dsh-context-kit 0.1.0 → 0.2.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.
@@ -1,48 +1,48 @@
1
- // tokens.cjs — 字符数近似 token 估算(确定性、零依赖,不引入 tokenizer)
2
- //
3
- // 口径(与设计草案 §3 一致):
4
- // 中文/全角字符:1 字 ≈ 1 token
5
- // ASCII/其它: 4 字符 ≈ 1 token
6
- // 这是保守上界:CJK 在主流 BPE 里通常 1~2 token/字,取 1 会低估个别模型,
7
- // 但索引页以 ASCII 路径/十六进制 id 为主,整体误差远小于"硬上限"的余量。
8
- //
9
- // 为什么不装 tiktoken:插件在 agent 每一步被调用,任何 native 依赖
10
- // 都会成为启动期风险;且这里只需要"裁剪到 ≤1,000 token"的量级判断。
11
-
12
- // 宽字符(CJK / 全角 / emoji)判定,用于 1 字≈1 token 的计数
13
- const WIDE_RANGES = [
14
- [0x1100, 0x115f], // Hangul Jamo
15
- [0x2e80, 0x303e], // CJK Radicals + Kangxi + CJK Symbols
16
- [0x3041, 0x33ff], // Hiragana / Katakana / CJK Compatibility
17
- [0x3400, 0x4dbf], // CJK Ext A
18
- [0x4e00, 0x9fff], // CJK Unified
19
- [0xa000, 0xa4cf], // Yi
20
- [0xac00, 0xd7a3], // Hangul Syllables
21
- [0xf900, 0xfaff], // CJK Compatibility Ideographs
22
- [0xfe30, 0xfe4f], // CJK Compatibility Forms
23
- [0xff00, 0xff60], // Fullwidth Forms
24
- [0xffe0, 0xffe6], // Fullwidth Signs
25
- [0x1f300, 0x1faff], // Emoji
26
- [0x20000, 0x3fffd], // CJK Ext B+
27
- ]
28
-
29
- function isWideChar(codePoint) {
30
- for (const [lo, hi] of WIDE_RANGES) {
31
- if (codePoint >= lo && codePoint <= hi) return true
32
- }
33
- return false
34
- }
35
-
36
- function estimateTokens(text) {
37
- if (typeof text !== 'string' || text.length === 0) return 0
38
- let wide = 0
39
- let ascii = 0
40
- for (const ch of text) {
41
- const cp = ch.codePointAt(0)
42
- if (isWideChar(cp)) wide += 1
43
- else ascii += 1
44
- }
45
- return wide + Math.ceil(ascii / 4)
46
- }
47
-
48
- module.exports = { estimateTokens, isWideChar, WIDE_RANGES }
1
+ // tokens.cjs — 字符数近似 token 估算(确定性、零依赖,不引入 tokenizer)
2
+ //
3
+ // 口径(与设计草案 §3 一致):
4
+ // 中文/全角字符:1 字 ≈ 1 token
5
+ // ASCII/其它: 4 字符 ≈ 1 token
6
+ // 这是保守上界:CJK 在主流 BPE 里通常 1~2 token/字,取 1 会低估个别模型,
7
+ // 但索引页以 ASCII 路径/十六进制 id 为主,整体误差远小于"硬上限"的余量。
8
+ //
9
+ // 为什么不装 tiktoken:插件在 agent 每一步被调用,任何 native 依赖
10
+ // 都会成为启动期风险;且这里只需要"裁剪到 ≤1,000 token"的量级判断。
11
+
12
+ // 宽字符(CJK / 全角 / emoji)判定,用于 1 字≈1 token 的计数
13
+ const WIDE_RANGES = [
14
+ [0x1100, 0x115f], // Hangul Jamo
15
+ [0x2e80, 0x303e], // CJK Radicals + Kangxi + CJK Symbols
16
+ [0x3041, 0x33ff], // Hiragana / Katakana / CJK Compatibility
17
+ [0x3400, 0x4dbf], // CJK Ext A
18
+ [0x4e00, 0x9fff], // CJK Unified
19
+ [0xa000, 0xa4cf], // Yi
20
+ [0xac00, 0xd7a3], // Hangul Syllables
21
+ [0xf900, 0xfaff], // CJK Compatibility Ideographs
22
+ [0xfe30, 0xfe4f], // CJK Compatibility Forms
23
+ [0xff00, 0xff60], // Fullwidth Forms
24
+ [0xffe0, 0xffe6], // Fullwidth Signs
25
+ [0x1f300, 0x1faff], // Emoji
26
+ [0x20000, 0x3fffd], // CJK Ext B+
27
+ ]
28
+
29
+ function isWideChar(codePoint) {
30
+ for (const [lo, hi] of WIDE_RANGES) {
31
+ if (codePoint >= lo && codePoint <= hi) return true
32
+ }
33
+ return false
34
+ }
35
+
36
+ function estimateTokens(text) {
37
+ if (typeof text !== 'string' || text.length === 0) return 0
38
+ let wide = 0
39
+ let ascii = 0
40
+ for (const ch of text) {
41
+ const cp = ch.codePointAt(0)
42
+ if (isWideChar(cp)) wide += 1
43
+ else ascii += 1
44
+ }
45
+ return wide + Math.ceil(ascii / 4)
46
+ }
47
+
48
+ module.exports = { estimateTokens, isWideChar, WIDE_RANGES }
package/lib/kit-ops.mjs CHANGED
@@ -1,230 +1,253 @@
1
- /**
2
- * dsh-context-kit 的操作层:
3
- * 把 settings.json、插件 config、profile 补丁与上游 preset 串成一个对象,
4
- * Host 工具(preset_tuner)、Settings 面板的 RPC 服务、CLI 都走这里。
5
- *
6
- * 路径解析是惰性的:只写 settings.json(面板保存、CLI set)时不需要 app。
7
- */
8
-
9
- import { existsSync, readFileSync } from 'node:fs'
10
- import { join } from 'node:path'
11
-
12
- import { commitSync, planSync } from './tuner/sync.mjs'
13
- import {
14
- findForeignRows,
15
- parseManagedBlocks,
16
- resolveAppSources,
17
- resolveProfileDir,
18
- spliceBlocks,
19
- writePatchFile,
20
- PATCH_FILE,
21
- } from './tuner/tuner.mjs'
22
- import { readSettings, setCompaction, writeSettings } from './settings.mjs'
23
-
24
- const KNOB_DEFAULTS = { auto: true, thresholdRatio: 0.5, retainRatio: 0.16 }
25
- const CONTEXT_DEFAULTS = { contextWindow: 1048576, maxOutputTokens: 256000, headroomTokens: 65536 }
26
-
27
- const text = (value, fallback = '') => (typeof value === 'string' && value.trim() ? value.trim() : fallback)
28
- const finite = (value) => (typeof value === 'number' && Number.isFinite(value) ? value : undefined)
29
-
30
- /** 规范化插件配置。 */
31
- export function resolveConfig(config = {}) {
32
- const presets = {}
33
- const raw = config.presets && typeof config.presets === 'object' ? config.presets : {}
34
- for (const [presetId, value] of Object.entries(raw)) {
35
- if (!value || typeof value !== 'object') continue
36
- presets[presetId] = {
37
- plugins: value.plugins && typeof value.plugins === 'object' ? value.plugins : {},
38
- add: Array.isArray(value.add) ? value.add : [],
39
- }
40
- }
41
- return {
42
- profileDir: text(config.profileDir),
43
- profile: text(config.profile, 'desktop'),
44
- appRoot: text(config.appRoot),
45
- autoSync: config.autoSync !== false,
46
- context: {
47
- contextWindow: finite(config.context?.contextWindow) ?? CONTEXT_DEFAULTS.contextWindow,
48
- maxOutputTokens: finite(config.context?.maxOutputTokens) ?? CONTEXT_DEFAULTS.maxOutputTokens,
49
- headroomTokens: finite(config.context?.headroomTokens) ?? CONTEXT_DEFAULTS.headroomTokens,
50
- },
51
- presetTweaks: presets,
52
- }
53
- }
54
-
55
- function resourcesPathOf() {
56
- const path = process.resourcesPath
57
- if (!path || typeof path !== 'string') return undefined
58
- if (existsSync(join(path, 'app.asar')) || existsSync(join(path, 'app'))) return path
59
- return undefined
60
- }
61
-
62
- export function resolveProfile(settings) {
63
- return resolveProfileDir({
64
- config: { profileDir: settings.profileDir, profile: settings.profile },
65
- moduleUrl: import.meta.url,
66
- })
67
- }
68
-
69
- export function resolvePaths(settings) {
70
- const profile = resolveProfile(settings)
71
- const sources = resolveAppSources({
72
- config: { appRoot: settings.appRoot },
73
- resourcesPath: resourcesPathOf(),
74
- execPath: process.execPath,
75
- })
76
- if (sources.length === 0) {
77
- throw new Error(
78
- '找不到 DSH app 的 resources 目录(app.asar / app)。' +
79
- '请用 --resources "<DSH 安装目录>/resources" 或插件配置里的 appRoot 指定',
80
- )
81
- }
82
- return { profile, sources, patchPath: join(profile.dir, PATCH_FILE) }
83
- }
84
-
85
- /** 把 contextWindow 与阈值换算成“多少 token 触发 / 保留多少”。 */
86
- export function triggersFor(settings, presetId = 'cordis') {
87
- const knob = settings.presetTweaks[presetId]?.plugins?.['compaction-basic']?.config ?? KNOB_DEFAULTS
88
- const { contextWindow, maxOutputTokens, headroomTokens } = settings.context
89
- const ratio = finite(knob.thresholdRatio) ?? KNOB_DEFAULTS.thresholdRatio
90
- const retain = finite(knob.retainRatio) ?? KNOB_DEFAULTS.retainRatio
91
- const byRatio = Math.floor(contextWindow * ratio)
92
- const byBudget = contextWindow - maxOutputTokens - headroomTokens
93
- return {
94
- thresholdRatio: ratio,
95
- retainRatio: retain,
96
- contextWindow,
97
- thresholdTokens: Math.min(byRatio, byBudget),
98
- retainTokens: Math.floor(contextWindow * retain),
99
- byBudget,
100
- }
101
- }
102
-
103
- export function createKit(config = {}) {
104
- const settings = resolveConfig(config)
105
- let cachedPaths
106
- let cachedProfile
107
-
108
- const profileOf = () => (cachedProfile ??= resolveProfile(settings))
109
- const pathsOf = () => (cachedPaths ??= resolvePaths(settings))
110
- const readPatch = (paths) => (existsSync(paths.patchPath) ? readFileSync(paths.patchPath, 'utf8') : '')
111
-
112
- /** settings.json 优先于插件 config:面板保存后不必重启就能被工具/CLI 看到。 */
113
- const currentSettings = () => {
114
- const paths = pathsOf()
115
- const stored = readSettings(paths.profile.dir)
116
- const merged = { ...settings, presetTweaks: { ...settings.presetTweaks } }
117
- for (const [presetId, value] of Object.entries(stored.presets ?? {})) {
118
- merged.presetTweaks[presetId] = {
119
- plugins: value.plugins && typeof value.plugins === 'object' ? value.plugins : {},
120
- add: Array.isArray(value.add) ? value.add : [],
121
- }
122
- }
123
- return merged
124
- }
125
-
126
- const plan = (active, patchText, paths) =>
127
- planSync({ sources: paths.sources, presetTweaks: active.presetTweaks, patchText })
128
-
129
- return {
130
- settings,
131
-
132
- get paths() {
133
- return pathsOf()
134
- },
135
-
136
- currentSettings,
137
-
138
- readPatch() {
139
- return readPatch(pathsOf())
140
- },
141
-
142
- describe() {
143
- const paths = pathsOf()
144
- const active = currentSettings()
145
- const patchText = readPatch(paths)
146
- const { entries, problems, upstream } = plan(active, patchText, paths)
147
- const managed = parseManagedBlocks(patchText)
148
- const presetIds = Object.keys(active.presetTweaks)
149
- const foreign = presetIds.flatMap((presetId) =>
150
- findForeignRows(patchText, presetId).map((line) => ({ presetId, line: line + 1 })),
151
- )
152
- const focus = presetIds[0] ?? 'cordis'
153
- return {
154
- profileDir: paths.profile.dir,
155
- profileVia: paths.profile.via,
156
- patchPath: paths.patchPath,
157
- sources: paths.sources.map((item) => `${item.kind}:${item.path}`),
158
- upstreamPresets: [...upstream.keys()].sort(),
159
- managed: managed.map((block) => ({ presetId: block.presetId, sha: block.sha, upstreamPath: block.upstreamPath })),
160
- entries,
161
- foreign,
162
- problems,
163
- presets: presetIds,
164
- triggers: triggersFor(active, focus),
165
- knobs: active.presetTweaks[focus]?.plugins?.['compaction-basic']?.config ?? KNOB_DEFAULTS,
166
- restartRequired: false,
167
- }
168
- },
169
-
170
- preview() {
171
- const paths = pathsOf()
172
- const active = currentSettings()
173
- const { blocks, problems } = plan(active, readPatch(paths), paths)
174
- if (problems.length > 0) throw new Error(problems.join('; '))
175
- return blocks.map((block) => block.join('\n')).join('\n\n')
176
- },
177
-
178
- sync({ force = false, mode = 'append' } = {}) {
179
- const paths = pathsOf()
180
- const active = currentSettings()
181
- const patchText = readPatch(paths)
182
- const presetIds = Object.keys(active.presetTweaks)
183
- if (presetIds.length === 0) throw new Error('还没有配置任何预设:先在面板里保存一次阈值,或运行 CLI set')
184
- const { blocks, entries, problems } = plan(active, patchText, paths)
185
- if (problems.length > 0) throw new Error(problems.join('; '))
186
- const result = commitSync({ profileDir: paths.profile.dir, blocks, presetIds, patchText, force, mode })
187
- return { ...result, entries, restartRequired: result.changed }
188
- },
189
-
190
- clear() {
191
- const paths = pathsOf()
192
- const patchText = readPatch(paths)
193
- const managed = parseManagedBlocks(patchText)
194
- if (managed.length === 0) return { changed: false, removed: 0, restartRequired: false }
195
- const result = writePatchFile(paths.profile.dir, spliceBlocks(patchText, []))
196
- return { ...result, removed: managed.length, restartRequired: result.changed }
197
- },
198
-
199
- /** 面板/CLI 保存:只写 settings.json(不写 YAML),返回最新状态。 */
200
- saveCompaction(input = {}) {
201
- const profile = profileOf()
202
- const stored = readSettings(profile.dir)
203
- const presetId = text(
204
- input.presetId,
205
- Object.keys(stored.presets ?? {})[0] ?? Object.keys(settings.presetTweaks)[0] ?? 'cordis',
206
- )
207
- const knobs = {
208
- auto: input.auto !== false,
209
- thresholdRatio: Number(input.thresholdRatio ?? KNOB_DEFAULTS.thresholdRatio),
210
- retainRatio: Number(input.retainRatio ?? KNOB_DEFAULTS.retainRatio),
211
- }
212
- if (!(knobs.thresholdRatio > 0 && knobs.thresholdRatio <= 1)) {
213
- throw new Error('thresholdRatio 必须在 (0,1] 之间')
214
- }
215
- if (!(knobs.retainRatio > 0 && knobs.retainRatio < knobs.thresholdRatio)) {
216
- throw new Error('retainRatio 必须 > 0 且小于 thresholdRatio')
217
- }
218
- const next = setCompaction(stored, presetId, knobs, text(input.group, 'compaction'))
219
- writeSettings(profile.dir, next)
220
- const merged = { ...settings, presetTweaks: { ...settings.presetTweaks, ...next.presets } }
221
- return {
222
- saved: true,
223
- presetId,
224
- knobs,
225
- settingsPath: join(profile.dir, 'dsh-context-kit', 'settings.json'),
226
- triggers: triggersFor(merged, presetId),
227
- }
228
- },
229
- }
230
- }
1
+ /**
2
+ * dsh-context-kit 的操作层:
3
+ * 把 settings.json、插件 config、profile 补丁与上游 preset 串成一个对象,
4
+ * Host 工具(preset_tuner)、Settings 面板的 RPC 服务、CLI 都走这里。
5
+ *
6
+ * 路径解析是惰性的:只写 settings.json(面板保存、CLI set)时不需要 app。
7
+ */
8
+
9
+ import { existsSync, readFileSync } from 'node:fs'
10
+ import { homedir } from 'node:os'
11
+ import { join } from 'node:path'
12
+
13
+ import { commitSync, planSync } from './tuner/sync.mjs'
14
+ import {
15
+ findForeignRows,
16
+ parseManagedBlocks,
17
+ resolveAppSources,
18
+ resolveProfileDir,
19
+ spliceBlocks,
20
+ writePatchFile,
21
+ PATCH_FILE,
22
+ } from './tuner/tuner.mjs'
23
+ import { readSettings, setCompaction, writeSettings } from './settings.mjs'
24
+ import { loadReportAsync } from './usage.mjs'
25
+
26
+ const KNOB_DEFAULTS = { auto: true, thresholdRatio: 0.5, retainRatio: 0.16 }
27
+ const CONTEXT_DEFAULTS = { contextWindow: 1048576, maxOutputTokens: 256000, headroomTokens: 65536 }
28
+
29
+ const text = (value, fallback = '') => (typeof value === 'string' && value.trim() ? value.trim() : fallback)
30
+ const finite = (value) => (typeof value === 'number' && Number.isFinite(value) ? value : undefined)
31
+
32
+ /** 规范化插件配置。 */
33
+ export function resolveConfig(config = {}) {
34
+ const presets = {}
35
+ const raw = config.presets && typeof config.presets === 'object' ? config.presets : {}
36
+ for (const [presetId, value] of Object.entries(raw)) {
37
+ if (!value || typeof value !== 'object') continue
38
+ presets[presetId] = {
39
+ plugins: value.plugins && typeof value.plugins === 'object' ? value.plugins : {},
40
+ add: Array.isArray(value.add) ? value.add : [],
41
+ }
42
+ }
43
+ return {
44
+ profileDir: text(config.profileDir),
45
+ profile: text(config.profile, 'desktop'),
46
+ appRoot: text(config.appRoot),
47
+ autoSync: config.autoSync !== false,
48
+ context: {
49
+ contextWindow: finite(config.context?.contextWindow) ?? CONTEXT_DEFAULTS.contextWindow,
50
+ maxOutputTokens: finite(config.context?.maxOutputTokens) ?? CONTEXT_DEFAULTS.maxOutputTokens,
51
+ headroomTokens: finite(config.context?.headroomTokens) ?? CONTEXT_DEFAULTS.headroomTokens,
52
+ },
53
+ presetTweaks: presets,
54
+ }
55
+ }
56
+
57
+ function resourcesPathOf() {
58
+ const path = process.resourcesPath
59
+ if (!path || typeof path !== 'string') return undefined
60
+ if (existsSync(join(path, 'app.asar')) || existsSync(join(path, 'app'))) return path
61
+ return undefined
62
+ }
63
+
64
+ export function resolveProfile(settings) {
65
+ return resolveProfileDir({
66
+ config: { profileDir: settings.profileDir, profile: settings.profile },
67
+ moduleUrl: import.meta.url,
68
+ })
69
+ }
70
+
71
+ export function resolvePaths(settings) {
72
+ const profile = resolveProfile(settings)
73
+ const sources = resolveAppSources({
74
+ config: { appRoot: settings.appRoot },
75
+ resourcesPath: resourcesPathOf(),
76
+ execPath: process.execPath,
77
+ })
78
+ if (sources.length === 0) {
79
+ throw new Error(
80
+ '找不到 DSH app 的 resources 目录(app.asar / app)。' +
81
+ '请用 --resources "<DSH 安装目录>/resources" 或插件配置里的 appRoot 指定',
82
+ )
83
+ }
84
+ return { profile, sources, patchPath: join(profile.dir, PATCH_FILE) }
85
+ }
86
+
87
+ /** 把 contextWindow 与阈值换算成“多少 token 触发 / 保留多少”。 */
88
+ export function triggersFor(settings, presetId = 'cordis') {
89
+ const knob = settings.presetTweaks[presetId]?.plugins?.['compaction-basic']?.config ?? KNOB_DEFAULTS
90
+ const { contextWindow, maxOutputTokens, headroomTokens } = settings.context
91
+ const ratio = finite(knob.thresholdRatio) ?? KNOB_DEFAULTS.thresholdRatio
92
+ const retain = finite(knob.retainRatio) ?? KNOB_DEFAULTS.retainRatio
93
+ const byRatio = Math.floor(contextWindow * ratio)
94
+ const byBudget = contextWindow - maxOutputTokens - headroomTokens
95
+ return {
96
+ thresholdRatio: ratio,
97
+ retainRatio: retain,
98
+ contextWindow,
99
+ thresholdTokens: Math.min(byRatio, byBudget),
100
+ retainTokens: Math.floor(contextWindow * retain),
101
+ byBudget,
102
+ }
103
+ }
104
+
105
+ export function createKit(config = {}) {
106
+ const settings = resolveConfig(config)
107
+ let cachedPaths
108
+ let cachedProfile
109
+
110
+ const profileOf = () => (cachedProfile ??= resolveProfile(settings))
111
+ const pathsOf = () => (cachedPaths ??= resolvePaths(settings))
112
+ const readPatch = (paths) => (existsSync(paths.patchPath) ? readFileSync(paths.patchPath, 'utf8') : '')
113
+
114
+ /** settings.json 优先于插件 config:面板保存后不必重启就能被工具/CLI 看到。 */
115
+ const currentSettings = () => {
116
+ // 只读 settings.json,不解析 app.asar:CLI 的 report / set 在 app 之外也要能跑
117
+ const profile = profileOf()
118
+ const stored = readSettings(profile.dir)
119
+ const merged = { ...settings, presetTweaks: { ...settings.presetTweaks } }
120
+ for (const [presetId, value] of Object.entries(stored.presets ?? {})) {
121
+ merged.presetTweaks[presetId] = {
122
+ plugins: value.plugins && typeof value.plugins === 'object' ? value.plugins : {},
123
+ add: Array.isArray(value.add) ? value.add : [],
124
+ }
125
+ }
126
+ return merged
127
+ }
128
+
129
+ const plan = (active, patchText, paths) =>
130
+ planSync({ sources: paths.sources, presetTweaks: active.presetTweaks, patchText })
131
+
132
+ return {
133
+ settings,
134
+
135
+ get paths() {
136
+ return pathsOf()
137
+ },
138
+
139
+ currentSettings,
140
+
141
+ readPatch() {
142
+ return readPatch(pathsOf())
143
+ },
144
+
145
+ describe() {
146
+ const paths = pathsOf()
147
+ const active = currentSettings()
148
+ const patchText = readPatch(paths)
149
+ const { entries, problems, upstream } = plan(active, patchText, paths)
150
+ const managed = parseManagedBlocks(patchText)
151
+ const presetIds = Object.keys(active.presetTweaks)
152
+ const foreign = presetIds.flatMap((presetId) =>
153
+ findForeignRows(patchText, presetId).map((line) => ({ presetId, line: line + 1 })),
154
+ )
155
+ const focus = presetIds[0] ?? 'cordis'
156
+ return {
157
+ profileDir: paths.profile.dir,
158
+ profileVia: paths.profile.via,
159
+ patchPath: paths.patchPath,
160
+ sources: paths.sources.map((item) => `${item.kind}:${item.path}`),
161
+ upstreamPresets: [...upstream.keys()].sort(),
162
+ managed: managed.map((block) => ({ presetId: block.presetId, sha: block.sha, upstreamPath: block.upstreamPath })),
163
+ entries,
164
+ foreign,
165
+ problems,
166
+ presets: presetIds,
167
+ triggers: triggersFor(active, focus),
168
+ knobs: active.presetTweaks[focus]?.plugins?.['compaction-basic']?.config ?? KNOB_DEFAULTS,
169
+ restartRequired: false,
170
+ }
171
+ },
172
+
173
+ preview() {
174
+ const paths = pathsOf()
175
+ const active = currentSettings()
176
+ const { blocks, problems } = plan(active, readPatch(paths), paths)
177
+ if (problems.length > 0) throw new Error(problems.join('; '))
178
+ return blocks.map((block) => block.join('\n')).join('\n\n')
179
+ },
180
+
181
+ sync({ force = false, mode = 'append' } = {}) {
182
+ const paths = pathsOf()
183
+ const active = currentSettings()
184
+ const patchText = readPatch(paths)
185
+ const presetIds = Object.keys(active.presetTweaks)
186
+ if (presetIds.length === 0) throw new Error('还没有配置任何预设:先在面板里保存一次阈值,或运行 CLI set')
187
+ const { blocks, entries, problems } = plan(active, patchText, paths)
188
+ if (problems.length > 0) throw new Error(problems.join('; '))
189
+ const result = commitSync({ profileDir: paths.profile.dir, blocks, presetIds, patchText, force, mode })
190
+ return { ...result, entries, restartRequired: result.changed }
191
+ },
192
+
193
+ clear() {
194
+ const paths = pathsOf()
195
+ const patchText = readPatch(paths)
196
+ const managed = parseManagedBlocks(patchText)
197
+ if (managed.length === 0) return { changed: false, removed: 0, restartRequired: false }
198
+ const result = writePatchFile(paths.profile.dir, spliceBlocks(patchText, []))
199
+ return { ...result, removed: managed.length, restartRequired: result.changed }
200
+ },
201
+
202
+ /**
203
+ * 效果台账:读本机会话日志统计真实用量,并回放“当前阈值 vs 默认阈值”的节省估算。
204
+ * 只读本地文件;缓存放在 profile 目录下,第二次调用不再重解压。
205
+ */
206
+ async report({ days = 7 } = {}) {
207
+ const profile = profileOf()
208
+ const active = currentSettings()
209
+ const focus = Object.keys(active.presetTweaks)[0] ?? 'cordis'
210
+ const knob = active.presetTweaks[focus]?.plugins?.['compaction-basic']?.config ?? {}
211
+ const home = text(process.env.DSH_HOME) || join(homedir(), '.dsh')
212
+ return loadReportAsync({
213
+ home,
214
+ cachePath: join(profile.dir, 'dsh-context-kit', 'usage-cache.json'),
215
+ days: Math.min(90, Math.max(1, Number(days) || 7)),
216
+ contextWindow: active.context.contextWindow,
217
+ thresholdRatio: finite(knob.thresholdRatio) ?? KNOB_DEFAULTS.thresholdRatio,
218
+ retainRatio: finite(knob.retainRatio) ?? KNOB_DEFAULTS.retainRatio,
219
+ })
220
+ },
221
+
222
+ /** 面板/CLI 保存:只写 settings.json(不写 YAML),返回最新状态。 */
223
+ saveCompaction(input = {}) {
224
+ const profile = profileOf()
225
+ const stored = readSettings(profile.dir)
226
+ const presetId = text(
227
+ input.presetId,
228
+ Object.keys(stored.presets ?? {})[0] ?? Object.keys(settings.presetTweaks)[0] ?? 'cordis',
229
+ )
230
+ const knobs = {
231
+ auto: input.auto !== false,
232
+ thresholdRatio: Number(input.thresholdRatio ?? KNOB_DEFAULTS.thresholdRatio),
233
+ retainRatio: Number(input.retainRatio ?? KNOB_DEFAULTS.retainRatio),
234
+ }
235
+ if (!(knobs.thresholdRatio > 0 && knobs.thresholdRatio <= 1)) {
236
+ throw new Error('thresholdRatio 必须在 (0,1] 之间')
237
+ }
238
+ if (!(knobs.retainRatio > 0 && knobs.retainRatio < knobs.thresholdRatio)) {
239
+ throw new Error('retainRatio 必须 > 0 且小于 thresholdRatio')
240
+ }
241
+ const next = setCompaction(stored, presetId, knobs, text(input.group, 'compaction'))
242
+ writeSettings(profile.dir, next)
243
+ const merged = { ...settings, presetTweaks: { ...settings.presetTweaks, ...next.presets } }
244
+ return {
245
+ saved: true,
246
+ presetId,
247
+ knobs,
248
+ settingsPath: join(profile.dir, 'dsh-context-kit', 'settings.json'),
249
+ triggers: triggersFor(merged, presetId),
250
+ }
251
+ },
252
+ }
253
+ }