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.
package/tuner.js CHANGED
@@ -1,149 +1,213 @@
1
- import { createKit, resolveConfig, triggersFor } from './lib/kit-ops.mjs'
2
- import { parseManagedBlocks } from './lib/tuner/tuner.mjs'
3
-
4
- export const name = 'context-kit-tuner'
5
- export const inject = ['tools']
6
-
7
- const k = (tokens) => `${Math.round(tokens / 1024)}K`
8
-
9
- function statusText(kit) {
10
- const state = kit.describe()
11
- const lines = [
12
- `profile: ${state.profileDir}(${state.profileVia})`,
13
- `补丁文件: ${state.patchPath}`,
14
- `上游来源: ${state.sources.join(' | ')}`,
15
- `上游预设: ${state.upstreamPresets.join(', ') || '<无>'}`,
16
- '',
17
- `已托管预设: ${state.managed.map((block) => `${block.presetId}@${block.sha}`).join(', ') || '<无>'}`,
18
- `压缩阈值: ${state.knobs.thresholdRatio}(${k(state.triggers.thresholdTokens)} 触发)` +
19
- ` / 保留 ${state.knobs.retainRatio}(${k(state.triggers.retainTokens)})`,
20
- ]
21
- for (const entry of state.entries) {
22
- const where = !entry.previousSha
23
- ? '未生成(需 sync)'
24
- : entry.drifted
25
- ? `上游已变 ${entry.previousSha}→${entry.upstreamSha},下次 sync 或启动时自动更新`
26
- : '已是最新'
27
- lines.push(` - ${entry.presetId}: ${where}`)
28
- }
29
- if (state.foreign.length > 0) {
30
- lines.push('', `! 补丁里有手写覆盖: ${state.foreign.map((item) => `${item.presetId} 第 ${item.line} 行`).join(', ')}`)
31
- lines.push(' 它们会让 sync 默认拒绝写入;需要接管时用 force + mode="replace"。')
32
- }
33
- if (state.problems.length > 0) {
34
- lines.push('', '问题:')
35
- for (const problem of state.problems) lines.push(` - ${problem}`)
36
- }
37
- lines.push('', '写盘后需要重启 DSH 生效;Settings → Context 面板可以直接改阈值。')
38
- return lines.join('\n')
39
- }
40
-
41
- export function apply(ctx, config = {}) {
42
- const settings = resolveConfig(config)
43
- const kit = createKit(config)
44
- const log = (level, message) => {
45
- try {
46
- ctx?.logger?.[level]?.(message)
47
- } catch {}
48
- }
49
-
50
- // 面板的 RPC 服务依赖 @deepseek-ai/dsh-typert-protocol;缺了只丢面板,
51
- // 工具与 CLI 必须照常工作(软失败)。
52
- import('./lib/remote.mjs')
53
- .then((module) => {
54
- ctx.plugin(module.ContextKitRemoteService, { kit })
55
- })
56
- .catch((error) => {
57
- log('warn', `context-kit: 面板服务未启动(${error?.message ?? error});工具与 CLI 不受影响`)
58
- })
59
-
60
- ctx.tools.register({
61
- name: 'preset_tuner',
62
- description:
63
- '调整 DSH 的 agent preset(预置)内部配置,例如把 compaction-basic 的自动压缩阈值提前,' +
64
- '或往 preset 的某个 group 里加插件。做法是:读运行中 app(app.asar)里 shipped 的 preset 声明原文,' +
65
- '原文逐字节保留、只插入你配置的少量行,生成托管块写进 profile 的 cordis.patch.yml。' +
66
- '因此不会像手写覆盖那样冻结上游——DSH 升级后会按上游重新生成。' +
67
- 'action=status 报告上游是否漂移;preview 只返回将要写入的文本;sync 真正落盘(需重启 DSH 生效);' +
68
- 'clear 移除托管块。若 profile 里已有手写的同 id 覆盖,sync 默认拒绝写入,需 force + mode="replace" 接管。',
69
- parameters: {
70
- type: 'object',
71
- properties: {
72
- action: {
73
- type: 'string',
74
- enum: ['status', 'preview', 'sync', 'clear'],
75
- description: 'status(只读报告)/ preview(只返回文本)/ sync(写盘)/ clear(移除托管块)',
76
- },
77
- force: {
78
- type: 'boolean',
79
- description: '与 mode="replace" 一起用:删除 profile 里手写的同 id preset 覆盖行,由本插件接管',
80
- },
81
- mode: {
82
- type: 'string',
83
- enum: ['append', 'replace'],
84
- description: 'force 时必须为 replace;否则默认 append(遇到手写覆盖就中止)',
85
- },
86
- },
87
- required: ['action'],
88
- },
89
- output: {
90
- schema: { type: 'string' },
91
- render: (_args, value) => [{ type: 'text', text: value }],
92
- },
93
- timeoutMs: 30000,
94
- isConcurrencySafe: () => false,
95
- async execute(args = {}) {
96
- const action = String(args.action ?? 'status')
97
- if (action === 'status') return statusText(kit)
98
- if (action === 'preview') {
99
- return [`将写入 ${kit.paths.patchPath}(预览,未落盘):`, '', kit.preview()].join('\n')
100
- }
101
- if (action === 'sync') {
102
- const result = kit.sync({ force: Boolean(args.force), mode: args.mode === 'replace' ? 'replace' : 'append' })
103
- if (!result.changed) return `已是最新,没有写入(${kit.paths.patchPath} 未变)。`
104
- const drift = result.entries.filter((entry) => entry.drifted)
105
- return [
106
- `已写入 ${kit.paths.patchPath}`,
107
- result.backup ? `备份: ${result.backup}` : '(原文件不存在,未产生备份)',
108
- result.removedForeign ? `已接管并移除手写覆盖 ${result.removedForeign} 处` : '',
109
- drift.length > 0
110
- ? `上游漂移已同步: ${drift.map((entry) => `${entry.presetId} ${entry.previousSha}→${entry.upstreamSha}`).join(', ')}`
111
- : '',
112
- '',
113
- '重启 DSH 后生效(已存在的会话在重启后也会用新的 preset 版本)。',
114
- ]
115
- .filter(Boolean)
116
- .join('\n')
117
- }
118
- if (action === 'clear') {
119
- const result = kit.clear()
120
- if (!result.changed) return '没有托管块,未改动文件。'
121
- return `已移除 ${result.removed} 个托管块。备份: ${result.backup ?? '<无>'}\n重启 DSH 后恢复上游默认行为。`
122
- }
123
- throw new Error(`未知 action: ${action}`)
124
- },
125
- })
126
-
127
- if (settings.autoSync) {
128
- queueMicrotask(() => {
129
- try {
130
- const active = kit.currentSettings()
131
- if (Object.keys(active.presetTweaks).length === 0) return
132
- const owned = new Set(parseManagedBlocks(kit.readPatch()).map((block) => block.presetId))
133
- const missing = Object.keys(active.presetTweaks).filter((presetId) => !owned.has(presetId))
134
- if (missing.length > 0) {
135
- log('info', `context-kit: ${missing.join(', ')} 还没有托管块,先运行 preset_tuner(action="sync");本次不自动写入`)
136
- return
137
- }
138
- const result = kit.sync()
139
- if (result.changed) {
140
- log('info', 'context-kit: 上游已变化,已按上游重新生成覆盖;重启后生效')
141
- }
142
- } catch (error) {
143
- log('warn', `context-kit: 自动同步跳过(${error?.message ?? error})`)
144
- }
145
- })
146
- }
147
- }
148
-
149
- export { triggersFor }
1
+ import { createKit, resolveConfig, triggersFor } from './lib/kit-ops.mjs'
2
+ import { parseManagedBlocks } from './lib/tuner/tuner.mjs'
3
+
4
+ export const name = 'context-kit-tuner'
5
+ export const inject = ['tools']
6
+
7
+ const k = (tokens) => `${Math.round(tokens / 1024)}K`
8
+
9
+ function statusText(kit) {
10
+ const state = kit.describe()
11
+ const lines = [
12
+ `profile: ${state.profileDir}(${state.profileVia})`,
13
+ `补丁文件: ${state.patchPath}`,
14
+ `上游来源: ${state.sources.join(' | ')}`,
15
+ `上游预设: ${state.upstreamPresets.join(', ') || '<无>'}`,
16
+ '',
17
+ `已托管预设: ${state.managed.map((block) => `${block.presetId}@${block.sha}`).join(', ') || '<无>'}`,
18
+ `压缩阈值: ${state.knobs.thresholdRatio}(${k(state.triggers.thresholdTokens)} 触发)` +
19
+ ` / 保留 ${state.knobs.retainRatio}(${k(state.triggers.retainTokens)})`,
20
+ ]
21
+ for (const entry of state.entries) {
22
+ const where = !entry.previousSha
23
+ ? '未生成(需 sync)'
24
+ : entry.drifted
25
+ ? `上游已变 ${entry.previousSha}→${entry.upstreamSha},下次 sync 或启动时自动更新`
26
+ : '已是最新'
27
+ lines.push(` - ${entry.presetId}: ${where}`)
28
+ }
29
+ if (state.foreign.length > 0) {
30
+ lines.push('', `! 补丁里有手写覆盖: ${state.foreign.map((item) => `${item.presetId} 第 ${item.line} 行`).join(', ')}`)
31
+ lines.push(' 它们会让 sync 默认拒绝写入;需要接管时用 force + mode="replace"。')
32
+ }
33
+ if (state.problems.length > 0) {
34
+ lines.push('', '问题:')
35
+ for (const problem of state.problems) lines.push(` - ${problem}`)
36
+ }
37
+ lines.push('', '写盘后需要重启 DSH 生效;Settings → Context 面板可以直接改阈值。')
38
+ return lines.join('\n')
39
+ }
40
+
41
+ const fmtTokens = (value) => (value >= 1e9 ? `${(value / 1e9).toFixed(2)}B` : value >= 1e6 ? `${(value / 1e6).toFixed(1)}M` : `${Math.round(value / 1e3)}K`)
42
+
43
+ function reportText(report) {
44
+ const t = report.totals
45
+ const savings = report.savings
46
+ const coverage = report.coverage || {}
47
+ const lines = [
48
+ `窗口: 最近 ${report.window.days} 天(自 ${report.window.since.slice(0, 10)})`,
49
+ `会话 ${t.sessions} 个 / ${t.steps} 步 / 压缩 ${t.compactions} 次`,
50
+ '',
51
+ '按观测到的压缩触发点分期(历史里可能混着旧阈值跑出来的会话):',
52
+ ]
53
+ for (const policy of report.policies || []) {
54
+ const label = policy.triggerTokens === null
55
+ ? '未发生压缩(无法判断策略)'
56
+ : `触发点 ≈${k(policy.triggerTokens)}${policy.thresholdRatio === null ? '(贴着上限)' : `(${policy.thresholdRatio.toFixed(2)})`}`
57
+ lines.push(
58
+ ` ${label}: ${policy.totals.sessions} 会话 / ${policy.totals.steps} 步 / 压缩 ${policy.totals.compactions} 次` +
59
+ (policy.isCurrent ? ' ← 当前阈值' : ''),
60
+ )
61
+ }
62
+ lines.push(
63
+ '',
64
+ '实测用量(全部会话,来自日志里的 usage):',
65
+ ` 缓存命中 ${fmtTokens(t.hit)} 未命中 ${fmtTokens(t.miss)} 输出 ${fmtTokens(t.out)}`,
66
+ ` 未命中占成本 ${t.missSharePct.toFixed(1)}% 平均上下文 ${k(t.promptAvg)} 峰值 ${k(t.promptMax)}`,
67
+ ` 成本(命中当量) ${fmtTokens(t.cost.total)}`,
68
+ )
69
+ if (coverage.currentThresholdRatio !== null && coverage.currentThresholdRatio !== undefined) {
70
+ lines.push(
71
+ ` 其中按当前阈值(${coverage.currentThresholdRatio})跑的实测: ${coverage.sessionsUnderCurrent} 会话 / ${coverage.stepsUnderCurrent} 步(${coverage.sharePct.toFixed(1)}%)`,
72
+ )
73
+ }
74
+ if (savings) {
75
+ lines.push(
76
+ '',
77
+ `节省估算(非实测,模型): ${savings.savedPct.toFixed(1)}%`,
78
+ ` 基线 ${savings.baseThresholdRatio}/${savings.baseRetainRatio} → 当前 ${savings.thresholdRatio}/${savings.retainRatio}`,
79
+ ` 做法:把历史每步增量按两种阈值各回放一次(压缩 ${savings.baseEvents} → ${savings.currentEvents} 次),假设工作量与价格比不变`,
80
+ )
81
+ if (coverage.isModelOnly) {
82
+ lines.push(' ! 当前阈值下的实测样本还太少,这个百分比只能当方向,不能当结论。')
83
+ }
84
+ }
85
+ lines.push(
86
+ '',
87
+ `返工信号: 重复调用 ${t.duplicates} 次 / 不同调用 ${t.distinctCalls} 个(${t.duplicatePct.toFixed(1)}%)`,
88
+ ' 重复高说明在重读/重跑——那是压缩压过头的第一信号。',
89
+ '',
90
+ `本次解压 ${(report.decompressedBytes / 1e6).toFixed(1)}MB;缓存 ${report.files.length} 个会话文件` +
91
+ (report.skipped.length > 0 ? `;跳过 ${report.skipped.length} 个` : ''),
92
+ report.privacy,
93
+ )
94
+ return lines.join('\n')
95
+ }
96
+
97
+ export function apply(ctx, config = {}) {
98
+ const settings = resolveConfig(config)
99
+ const kit = createKit(config)
100
+ const log = (level, message) => {
101
+ try {
102
+ ctx?.logger?.[level]?.(message)
103
+ } catch {}
104
+ }
105
+
106
+ // 面板的 RPC 服务依赖 @deepseek-ai/dsh-typert-protocol;缺了只丢面板,
107
+ // 工具与 CLI 必须照常工作(软失败)。
108
+ import('./lib/remote.mjs')
109
+ .then((module) => {
110
+ ctx.plugin(module.ContextKitRemoteService, { kit })
111
+ })
112
+ .catch((error) => {
113
+ log('warn', `context-kit: 面板服务未启动(${error?.message ?? error});工具与 CLI 不受影响`)
114
+ })
115
+
116
+ ctx.tools.register({
117
+ name: 'preset_tuner',
118
+ description:
119
+ '调整 DSH 的 agent preset(预置)内部配置,例如把 compaction-basic 的自动压缩阈值提前,' +
120
+ '或往 preset 的某个 group 里加插件。做法是:读运行中 app(app.asar)里 shipped 的 preset 声明原文,' +
121
+ '原文逐字节保留、只插入你配置的少量行,生成托管块写进 profile 的 cordis.patch.yml。' +
122
+ '因此不会像手写覆盖那样冻结上游——DSH 升级后会按上游重新生成。' +
123
+ 'action=status 报告上游是否漂移;preview 只返回将要写入的文本;sync 真正落盘(需重启 DSH 生效);' +
124
+ 'clear 移除托管块;report 统计最近几天在本机产生的真实用量与节省估算(只读本地会话日志)。' +
125
+ '若 profile 里已有手写的同 id 覆盖,sync 默认拒绝写入,需 force + mode="replace" 接管。',
126
+ parameters: {
127
+ type: 'object',
128
+ properties: {
129
+ action: {
130
+ type: 'string',
131
+ enum: ['status', 'preview', 'sync', 'clear', 'report'],
132
+ description: 'status(只读报告)/ preview(只返回文本)/ sync(写盘)/ clear(移除托管块)/ report(效果台账)',
133
+ },
134
+ days: {
135
+ type: 'number',
136
+ description: 'report 用:统计最近几天,默认 7',
137
+ },
138
+ force: {
139
+ type: 'boolean',
140
+ description: '与 mode="replace" 一起用:删除 profile 里手写的同 id preset 覆盖行,由本插件接管',
141
+ },
142
+ mode: {
143
+ type: 'string',
144
+ enum: ['append', 'replace'],
145
+ description: 'force 时必须为 replace;否则默认 append(遇到手写覆盖就中止)',
146
+ },
147
+ },
148
+ required: ['action'],
149
+ },
150
+ output: {
151
+ schema: { type: 'string' },
152
+ render: (_args, value) => [{ type: 'text', text: value }],
153
+ },
154
+ timeoutMs: 30000,
155
+ isConcurrencySafe: () => false,
156
+ async execute(args = {}) {
157
+ const action = String(args.action ?? 'status')
158
+ if (action === 'status') return statusText(kit)
159
+ if (action === 'preview') {
160
+ return [`将写入 ${kit.paths.patchPath}(预览,未落盘):`, '', kit.preview()].join('\n')
161
+ }
162
+ if (action === 'sync') {
163
+ const result = kit.sync({ force: Boolean(args.force), mode: args.mode === 'replace' ? 'replace' : 'append' })
164
+ if (!result.changed) return `已是最新,没有写入(${kit.paths.patchPath} 未变)。`
165
+ const drift = result.entries.filter((entry) => entry.drifted)
166
+ return [
167
+ `已写入 ${kit.paths.patchPath}`,
168
+ result.backup ? `备份: ${result.backup}` : '(原文件不存在,未产生备份)',
169
+ result.removedForeign ? `已接管并移除手写覆盖 ${result.removedForeign} 处` : '',
170
+ drift.length > 0
171
+ ? `上游漂移已同步: ${drift.map((entry) => `${entry.presetId} ${entry.previousSha}→${entry.upstreamSha}`).join(', ')}`
172
+ : '',
173
+ '',
174
+ '重启 DSH 后生效(已存在的会话在重启后也会用新的 preset 版本)。',
175
+ ]
176
+ .filter(Boolean)
177
+ .join('\n')
178
+ }
179
+ if (action === 'clear') {
180
+ const result = kit.clear()
181
+ if (!result.changed) return '没有托管块,未改动文件。'
182
+ return `已移除 ${result.removed} 个托管块。备份: ${result.backup ?? '<无>'}\n重启 DSH 后恢复上游默认行为。`
183
+ }
184
+ if (action === 'report') {
185
+ return reportText(await kit.report({ days: Number(args.days) || 7 }))
186
+ }
187
+ throw new Error(`未知 action: ${action}`)
188
+ },
189
+ })
190
+
191
+ if (settings.autoSync) {
192
+ queueMicrotask(() => {
193
+ try {
194
+ const active = kit.currentSettings()
195
+ if (Object.keys(active.presetTweaks).length === 0) return
196
+ const owned = new Set(parseManagedBlocks(kit.readPatch()).map((block) => block.presetId))
197
+ const missing = Object.keys(active.presetTweaks).filter((presetId) => !owned.has(presetId))
198
+ if (missing.length > 0) {
199
+ log('info', `context-kit: ${missing.join(', ')} 还没有托管块,先运行 preset_tuner(action="sync");本次不自动写入`)
200
+ return
201
+ }
202
+ const result = kit.sync()
203
+ if (result.changed) {
204
+ log('info', 'context-kit: 上游已变化,已按上游重新生成覆盖;重启后生效')
205
+ }
206
+ } catch (error) {
207
+ log('warn', `context-kit: 自动同步跳过(${error?.message ?? error})`)
208
+ }
209
+ })
210
+ }
211
+ }
212
+
213
+ export { triggersFor }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Arjun Barrett
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.