dsh-context-kit 0.0.0-stage → 0.1.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.
@@ -0,0 +1,286 @@
1
+ // sources.cjs — 索引的两个数据来源:
2
+ // 1) 路径:read/write/edit/grep/glob 的 file_path / path 参数(只记路径,不记内容)
3
+ // 2) artifact:token-guard 的 manifest.jsonl 尾部 N 行(id/tool/mode/visibleChars)
4
+ //
5
+ // 安全不变式:
6
+ // - 任何命中脱敏表的路径整条丢弃(大小写不敏感,见 DENY_PATTERNS);
7
+ // - 绝对路径做展示折叠:工作区外且属于某个用户目录时,只保留尾部两段(`…\Documents\x.md`),
8
+ // 自家 home 折叠为 `~`,避免把用户名送进 system prompt(也省 token);
9
+ // - 不读取文件内容,只读路径字符串与 manifest 的元数据;
10
+ // - 任何异常返回空结果,不向上抛(失败开放)。
11
+ const fs = require('node:fs')
12
+ const os = require('node:os')
13
+ const path = require('node:path')
14
+
15
+ // 脱敏表:命中任一子串的路径整条丢弃。大小写不敏感。
16
+ // 'credentials' 覆盖 .credentials / .git-credentials / .aws\credentials / credentials.json。
17
+ const DENY_PATTERNS = [
18
+ '.credentials',
19
+ 'credentials',
20
+ '.env',
21
+ 'local-proxy',
22
+ 'secrets',
23
+ 'token',
24
+ '.ssh',
25
+ 'appdata',
26
+ '.kube',
27
+ 'kubeconfig',
28
+ '.npmrc',
29
+ 'id_rsa',
30
+ 'cookies',
31
+ ]
32
+
33
+ // 只跟踪这几种"触碰文件"的工具;其它工具(pwsh/web 等)不贡献路径。
34
+ const TRACKED_TOOLS = new Set(['read', 'write', 'edit', 'grep', 'glob'])
35
+
36
+ // 参数里可能承载路径的键,按优先级排列。
37
+ const PATH_KEYS = ['file_path', 'filePath', 'path', 'paths', 'files', 'file']
38
+
39
+ const MAX_PATH_CHARS = 320
40
+
41
+ // 某个用户目录(非工作区)绝对路径:只保留尾部两段
42
+ const USER_DIR_RE = /[\\/]Users[\\/][^\\/]+[\\/]/i
43
+
44
+ /** 路径是否命中脱敏规则(大小写不敏感)。 */
45
+ function isDeniedPath(raw) {
46
+ if (typeof raw !== 'string') return false
47
+ const lower = raw.toLowerCase()
48
+ return DENY_PATTERNS.some((needle) => lower.includes(needle))
49
+ }
50
+
51
+ /** abs 是否在 root 之内(root 为文件路径或目录)。 */
52
+ function isInside(root, abs) {
53
+ try {
54
+ if (!root) return false
55
+ const rel = path.relative(path.resolve(root), abs)
56
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))
57
+ } catch {
58
+ return false
59
+ }
60
+ }
61
+
62
+ /**
63
+ * 展示用路径:工作区内原样;自家 home 折叠成 `~`;
64
+ * 其它用户目录降级为尾部两段(避免泄露用户名)。
65
+ */
66
+ function displayPath(abs, options = {}) {
67
+ const { workspaceRoot = null, homeDir = null } = options
68
+ if (workspaceRoot && isInside(workspaceRoot, abs)) return abs
69
+ if (homeDir && isInside(homeDir, abs)) {
70
+ const rel = path.relative(homeDir, abs)
71
+ return rel ? `~${path.sep}${rel}` : '~'
72
+ }
73
+ if (USER_DIR_RE.test(abs)) {
74
+ const parts = abs.split(/[\\/]+/).filter(Boolean)
75
+ const tail = parts.slice(-2).join('\\')
76
+ return tail ? `…\\${tail}` : ''
77
+ }
78
+ return abs
79
+ }
80
+
81
+ /** 从工具名 + 参数里提取候选路径(未归一化、未脱敏)。 */
82
+ function extractPaths(toolName, args) {
83
+ if (!TRACKED_TOOLS.has(String(toolName ?? ''))) return []
84
+ if (!args || typeof args !== 'object') return []
85
+ const out = []
86
+ for (const key of PATH_KEYS) {
87
+ const value = args[key]
88
+ if (typeof value === 'string') {
89
+ out.push(value)
90
+ } else if (Array.isArray(value)) {
91
+ for (const item of value) {
92
+ if (typeof item === 'string') out.push(item)
93
+ else if (item && typeof item === 'object' && typeof item.path === 'string') out.push(item.path)
94
+ }
95
+ }
96
+ }
97
+ return out
98
+ }
99
+
100
+ /**
101
+ * 归一化 + 脱敏 + 展示折叠。返回可展示的路径字符串,或 null(表示丢弃)。
102
+ * cwd 用于把相对路径补全;workspaceRoot 用于判断"工作区内";homeDir 用于折叠用户名。
103
+ */
104
+ function normalizePath(raw, options = {}) {
105
+ const { cwd = process.cwd(), workspaceRoot = null, homeDir = os.homedir(), maxChars = MAX_PATH_CHARS } = options
106
+ try {
107
+ if (typeof raw !== 'string') return null
108
+ let p = raw.trim()
109
+ if (!p) return null
110
+ if (p.length > maxChars) return null
111
+ if (/[\r\n\t]/.test(p)) return null
112
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(p)) return null // URL 不是文件路径(也挡住 URL 里的 token)
113
+ if ((p.startsWith('"') && p.endsWith('"')) || (p.startsWith("'") && p.endsWith("'"))) p = p.slice(1, -1)
114
+ const abs = path.isAbsolute(p) ? path.normalize(p) : path.resolve(cwd, p)
115
+ const inWorkspace = workspaceRoot ? isInside(workspaceRoot, abs) : false
116
+ // 工作区自身的路径前缀(例如工作区恰好位于 AppData\Local\Temp)不算泄露;
117
+ // 但工作区内的相对部分命中敏感词仍整条丢弃。
118
+ if (isDeniedPath(p) || isDeniedPath(abs)) {
119
+ const rel = inWorkspace ? path.relative(path.resolve(workspaceRoot), abs) : null
120
+ if (!inWorkspace || (rel !== null && isDeniedPath(rel))) return null
121
+ }
122
+ const shown = displayPath(abs, { workspaceRoot, homeDir })
123
+ if (!shown) return null
124
+ if (!inWorkspace && isDeniedPath(shown)) return null
125
+ return shown
126
+ } catch {
127
+ return null
128
+ }
129
+ }
130
+
131
+ /**
132
+ * 读 JSONL 文件尾部最多 maxLines 行(不回扫整个大文件)。
133
+ * 返回 { records: [], total, size, mtimeMs },records 为"最近在前"。
134
+ * 文件不存在 / 读失败 → 空结果,绝不抛。
135
+ */
136
+ function readManifestTail(file, maxLines = 500, maxBytes = 256 * 1024) {
137
+ const empty = { records: [], total: 0, size: 0, mtimeMs: 0 }
138
+ try {
139
+ const st = fs.statSync(file)
140
+ if (!st.isFile() || st.size === 0) return { ...empty, size: st.size, mtimeMs: st.mtimeMs }
141
+ const limitLines = Math.max(1, Math.min(2000, Number(maxLines) || 500))
142
+ const bytes = Math.min(st.size, Math.max(4096, maxBytes))
143
+ const start = st.size - bytes
144
+ const fd = fs.openSync(file, 'r')
145
+ let text
146
+ try {
147
+ const buf = Buffer.allocUnsafe(bytes)
148
+ fs.readSync(fd, buf, 0, bytes, start)
149
+ text = buf.toString('utf8')
150
+ } finally {
151
+ fs.closeSync(fd)
152
+ }
153
+ let lines = text.split(/\r?\n/)
154
+ // 从中间截断时,首行可能是半行:丢掉
155
+ if (start > 0) lines = lines.slice(1)
156
+ lines = lines.filter((line) => line.trim())
157
+ const records = []
158
+ for (let i = lines.length - 1; i >= 0 && records.length < limitLines; i -= 1) {
159
+ try {
160
+ records.push(JSON.parse(lines[i]))
161
+ } catch {
162
+ // 单行坏了不影响其它行
163
+ }
164
+ }
165
+ return { records, total: lines.length, size: st.size, mtimeMs: st.mtimeMs }
166
+ } catch {
167
+ return empty
168
+ }
169
+ }
170
+
171
+ /** 人类可读体积:4.1K / 11.9K / 812。 */
172
+ function formatSize(chars) {
173
+ const n = Number(chars)
174
+ if (!Number.isFinite(n) || n <= 0) return '—'
175
+ if (n < 1024) return String(Math.round(n))
176
+ return `${(n / 1024).toFixed(1)}K`
177
+ }
178
+
179
+ // token-guard 落盘的溢出文件形如 ...\token-guard\artifacts\<sha16>.txt。
180
+ // 它是"原文副本"而不是工具的目标路径,当作目标展示会误导模型。
181
+ const SPILL_ARTIFACT_RE = /[\\/]artifacts[\\/][0-9a-f]{6,64}\.txt$/i
182
+
183
+ /** 从 manifest 记录里推断工具的目标路径;拿不到就返回空串。 */
184
+ function inferTarget(record) {
185
+ if (!record || typeof record !== 'object') return ''
186
+ const candidates = [record.target, record.path, record.file_path, record.filePath]
187
+ for (const candidate of candidates) {
188
+ if (typeof candidate === 'string' && candidate.trim()) return candidate.trim()
189
+ }
190
+ // artifact 字段:只有它不是 token-guard 自己的溢出副本时才作为目标
191
+ if (typeof record.artifact === 'string' && record.artifact.trim() && !SPILL_ARTIFACT_RE.test(record.artifact)) {
192
+ return record.artifact.trim()
193
+ }
194
+ return ''
195
+ }
196
+
197
+ // 状态语义(D1,2026-11-14 评审):
198
+ // mode:"unchanged" 表示这次只给了 99 字符的 `[未变 · 与 #N 相同]` 标记,
199
+ // visibleChars 才是模型当时真正看到的大小(实测 12,882 → 99)。
200
+ // 绝不能把它渲染成 "12.6K ok"——那会让模型以为原文已在上下文里。
201
+ function deriveStatus(record, { visibleChars, originalChars, mode }) {
202
+ if (record?.isError === true || record?.error) return 'err'
203
+ const marker = visibleChars > 0 && originalChars > 0 && visibleChars < originalChars * 0.5
204
+ // 截断/摘要:上下文里看到的是删节版 → trunc
205
+ if (mode === 'capped' || mode === 'summary') return 'trunc'
206
+ // 未变/差异:只有 visible 远小于原文时才说明"模型没见过原文" → need
207
+ if (mode === 'unchanged' || mode === 'delta') {
208
+ if (marker) return 'need'
209
+ return mode === 'delta' ? 'Δ' : 'same'
210
+ }
211
+ // 其它 mode(或没有 mode):保守处理
212
+ if (marker) return 'need'
213
+ return 'ok'
214
+ }
215
+
216
+ /** manifest 记录 → 索引里的 artifact 行;不是合法记录返回 null。 */
217
+ function summarizeArtifact(record) {
218
+ try {
219
+ if (!record || typeof record !== 'object') return null
220
+ const rawId = String(record.id ?? record.artifactId ?? '').trim()
221
+ if (!/^[0-9a-f]{6,64}$/i.test(rawId)) return null
222
+ const tool = typeof record.tool === 'string' && record.tool ? record.tool : '?'
223
+ const originalChars = Number(record.originalChars ?? record.chars ?? 0)
224
+ const hasVisible = record.visibleChars !== undefined && record.visibleChars !== null
225
+ const visibleParsed = hasVisible ? Number(record.visibleChars) : originalChars
226
+ const visibleChars = Number.isFinite(visibleParsed) && visibleParsed >= 0 ? visibleParsed : originalChars
227
+ const target = inferTarget(record)
228
+ if (target && isDeniedPath(target)) return null
229
+ const mode = typeof record.mode === 'string' ? record.mode : ''
230
+ const status = deriveStatus(record, { visibleChars, originalChars, mode })
231
+ const marker = visibleChars > 0 && originalChars > 0 && visibleChars < originalChars * 0.5
232
+ const size = marker
233
+ ? `${formatSize(visibleChars)} / full ${formatSize(originalChars)}`
234
+ : formatSize(visibleChars > 0 ? visibleChars : originalChars)
235
+ return {
236
+ id: rawId.slice(0, 6),
237
+ fullId: rawId.toLowerCase(),
238
+ tool,
239
+ target,
240
+ size,
241
+ status,
242
+ mode,
243
+ dup: 1,
244
+ originalChars: Number.isFinite(originalChars) ? originalChars : 0,
245
+ visibleChars: Number.isFinite(visibleChars) ? visibleChars : 0,
246
+ }
247
+ } catch {
248
+ return null
249
+ }
250
+ }
251
+
252
+ /** 批量转换,并按 id 去重(保留最近一条,重复次数进 dup 列,渲染成 `×N`)。 */
253
+ function summarizeArtifacts(records, limit = Infinity) {
254
+ const out = []
255
+ const seen = new Map()
256
+ if (!Array.isArray(records)) return out
257
+ for (const record of records) {
258
+ const item = summarizeArtifact(record)
259
+ if (!item) continue
260
+ const existing = seen.get(item.fullId)
261
+ if (existing) {
262
+ existing.dup += 1
263
+ continue
264
+ }
265
+ if (out.length >= limit) continue
266
+ seen.set(item.fullId, item)
267
+ out.push(item)
268
+ }
269
+ return out
270
+ }
271
+
272
+ module.exports = {
273
+ DENY_PATTERNS,
274
+ TRACKED_TOOLS,
275
+ extractPaths,
276
+ isDeniedPath,
277
+ isInside,
278
+ displayPath,
279
+ normalizePath,
280
+ readManifestTail,
281
+ formatSize,
282
+ inferTarget,
283
+ deriveStatus,
284
+ summarizeArtifact,
285
+ summarizeArtifacts,
286
+ }
@@ -0,0 +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 }
@@ -0,0 +1,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 { 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
+ }
package/lib/remote.mjs ADDED
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Settings 面板 <-> Host 的 RPC 服务。
3
+ * 客户端调用:ctx.connection.rpc.call('/api', 'contextKit/<method>', { args })
4
+ */
5
+
6
+ import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
7
+
8
+ /** 施加 Remote(name) 标记,兼容无装饰器的写法(与 dsh-memory-local 同款)。 */
9
+ export function markRemoteMethod(serviceClass, method, exportName = method) {
10
+ const instance = Object.create(serviceClass.prototype)
11
+ const decorate = Remote(exportName)
12
+ decorate(undefined, {
13
+ kind: 'method',
14
+ name: method,
15
+ static: false,
16
+ private: false,
17
+ addInitializer(fn) {
18
+ fn.call(instance)
19
+ },
20
+ })
21
+ }
22
+
23
+ export class ContextKitRemoteService extends TypertRemoteService {
24
+ static inject = []
25
+
26
+ constructor(ctx, config = {}) {
27
+ super(ctx, 'contextKit')
28
+ if (!config.kit) throw new Error('contextKit remote service requires a kit')
29
+ this.kit = config.kit
30
+ }
31
+
32
+ status() {
33
+ return this.kit.describe()
34
+ }
35
+
36
+ preview() {
37
+ return { text: this.kit.preview() }
38
+ }
39
+
40
+ save(presetId, thresholdRatio, retainRatio, auto, group) {
41
+ return this.kit.saveCompaction({ presetId, thresholdRatio, retainRatio, auto, group })
42
+ }
43
+
44
+ sync(force, mode) {
45
+ return this.kit.sync({ force: force === true, mode: mode === 'replace' ? 'replace' : 'append' })
46
+ }
47
+
48
+ clear() {
49
+ return this.kit.clear()
50
+ }
51
+ }
52
+
53
+ for (const method of ['status', 'preview', 'save', 'sync', 'clear']) {
54
+ markRemoteMethod(ContextKitRemoteService, method)
55
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * 面板可改的少量设置,存成 JSON(不碰 profile 的 YAML)。
3
+ * 位置:<profile>/dsh-context-kit/settings.json
4
+ */
5
+
6
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
7
+ import { join } from 'node:path'
8
+
9
+ export const SETTINGS_FILE = 'settings.json'
10
+ export const SETTINGS_DIR = 'dsh-context-kit'
11
+
12
+ export function settingsPath(profileDir) {
13
+ return join(profileDir, SETTINGS_DIR, SETTINGS_FILE)
14
+ }
15
+
16
+ export function readSettings(profileDir) {
17
+ const file = settingsPath(profileDir)
18
+ if (!existsSync(file)) return { presets: {} }
19
+ try {
20
+ const raw = readFileSync(file, 'utf8').replace(/^\uFEFF/, '')
21
+ const parsed = JSON.parse(raw)
22
+ const presets = {}
23
+ for (const [presetId, value] of Object.entries(parsed?.presets ?? {})) {
24
+ if (!value || typeof value !== 'object') continue
25
+ presets[presetId] = {
26
+ plugins: value.plugins && typeof value.plugins === 'object' ? value.plugins : {},
27
+ add: Array.isArray(value.add) ? value.add : [],
28
+ }
29
+ }
30
+ return { presets }
31
+ } catch {
32
+ // 坏文件当作没配置,绝不让面板/工具因此崩掉
33
+ return { presets: {} }
34
+ }
35
+ }
36
+
37
+ export function writeSettings(profileDir, settings) {
38
+ const dir = join(profileDir, SETTINGS_DIR)
39
+ mkdirSync(dir, { recursive: true })
40
+ const file = settingsPath(profileDir)
41
+ const payload = `${JSON.stringify({ presets: settings.presets ?? {} }, null, 2)}\n`
42
+ const temp = `${file}.tmp`
43
+ writeFileSync(temp, payload, 'utf8')
44
+ renameSync(temp, file)
45
+ return file
46
+ }
47
+
48
+ /** 把压缩阈值写进 presets[presetId].plugins['compaction-basic'],保留其它键。 */
49
+ export function setCompaction(settings, presetId, knobs, group = 'compaction') {
50
+ const next = {
51
+ presets: JSON.parse(JSON.stringify(settings.presets ?? {})),
52
+ }
53
+ const preset = next.presets[presetId] ?? { plugins: {}, add: [] }
54
+ const plugins = preset.plugins ?? {}
55
+ plugins['compaction-basic'] = {
56
+ ...(plugins['compaction-basic'] ?? {}),
57
+ group: group || 'compaction',
58
+ config: {
59
+ ...(plugins['compaction-basic']?.config ?? {}),
60
+ auto: knobs.auto !== false,
61
+ thresholdRatio: Number(knobs.thresholdRatio),
62
+ retainRatio: Number(knobs.retainRatio),
63
+ },
64
+ }
65
+ preset.plugins = plugins
66
+ preset.add = Array.isArray(preset.add) ? preset.add : []
67
+ next.presets[presetId] = preset
68
+ return next
69
+ }