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/client/panel.js CHANGED
@@ -1,302 +1,437 @@
1
- // dsh-context-kit 的 Settings 面板(Web 客户端插件)。
2
- // 通过 ctx.connection.rpc 调宿主 contextKit 服务:status / save / sync / preview / clear。
3
- window.__ModuleLoader__.load({
4
- id: 'dsh-context-kit',
5
- factory(require) {
6
- const React = require('react')
7
- const h = React.createElement
8
-
9
- const EN = {
10
- label: 'Context',
11
- title: 'Context & Compaction',
12
- subtitle: 'Save tokens by compacting earlier, without freezing the preset.',
13
- threshold: 'Compact at',
14
- retain: 'Keep after compact',
15
- auto: 'Automatic compaction',
16
- save: 'Save',
17
- sync: 'Apply to profile',
18
- preview: 'Preview',
19
- clear: 'Remove override',
20
- refresh: 'Refresh',
21
- restart: 'Restart DSH to apply. Existing sessions pick up the new preset after restart.',
22
- saved: 'Saved. Apply + restart to take effect.',
23
- synced: 'Written to the profile patch.',
24
- unchanged: 'Already up to date; nothing written.',
25
- cleared: 'Override removed. Restart to fall back to upstream defaults.',
26
- drift: 'Upstream preset changed',
27
- upToDate: 'Upstream in sync',
28
- missing: 'Not generated yet',
29
- foreign: 'A hand-written override exists in your patch; remove it before applying.',
30
- ofWindow: 'of the context window',
31
- triggers: 'Compaction triggers at',
32
- keeps: 'then keeps about',
33
- profile: 'Profile',
34
- patch: 'Patch file',
35
- upstream: 'Upstream',
36
- busy: 'Working…',
37
- error: 'Error',
38
- }
39
-
40
- const ZH = {
41
- label: '上下文',
42
- title: '上下文与压缩',
43
- subtitle: '早点压缩来省 token,同时不冻结预设。',
44
- threshold: '压缩触发于',
45
- retain: '压缩后保留',
46
- auto: '启用自动压缩',
47
- save: '保存',
48
- sync: '写入 profile',
49
- preview: '预览',
50
- clear: '移除覆盖',
51
- refresh: '刷新',
52
- restart: '重启 DSH 后生效;已存在的会话也会在重启后使用新的预设版本。',
53
- saved: '已保存。写入并重启后生效。',
54
- synced: '已写入 profile 补丁。',
55
- unchanged: '已是最新,没有写入。',
56
- cleared: '已移除覆盖,重启后回到上游默认。',
57
- drift: '上游预设已变化',
58
- upToDate: '与上游一致',
59
- missing: '尚未生成',
60
- foreign: '补丁里存在手写覆盖,请先移除再写入。',
61
- ofWindow: '占上下文窗口',
62
- triggers: '压缩触发点',
63
- keeps: '压缩后约保留',
64
- profile: 'Profile',
65
- patch: '补丁文件',
66
- upstream: '上游',
67
- busy: '处理中…',
68
- error: '出错',
69
- }
70
-
71
- const CSS = `
72
- .ck_wrap { display: flex; flex-direction: column; gap: 14px; }
73
- .ck_head h2 { margin: 0 0 4px; font-size: 15px; }
74
- .ck_head p { margin: 0; opacity: .7; font-size: 12px; }
75
- .ck_card { border: 1px solid rgba(127,127,127,.25); border-radius: 10px; padding: 12px; display: flex; flex-direction: column; gap: 10px; }
76
- .ck_row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
77
- .ck_row label { min-width: 110px; font-size: 12px; opacity: .8; }
78
- .ck_row input[type=range] { flex: 1 1 160px; }
79
- .ck_val { font-variant-numeric: tabular-nums; min-width: 72px; text-align: right; font-size: 12px; }
80
- .ck_btns { display: flex; gap: 8px; flex-wrap: wrap; }
81
- .ck_btn { border: 1px solid rgba(127,127,127,.35); background: transparent; border-radius: 8px; padding: 6px 12px; cursor: pointer; font-size: 12px; }
82
- .ck_btn.primary { background: #2563eb; border-color: #2563eb; color: #fff; }
83
- .ck_btn:disabled { opacity: .5; cursor: default; }
84
- .ck_meta { font-size: 11px; opacity: .65; word-break: break-all; }
85
- .ck_state { font-size: 12px; padding: 6px 8px; border-radius: 8px; background: rgba(127,127,127,.12); }
86
- .ck_warn { color: #d97706; }
87
- .ck_err { color: #dc2626; }
88
- .ck_pre { max-height: 220px; overflow: auto; font-size: 11px; background: rgba(127,127,127,.12); padding: 8px; border-radius: 8px; white-space: pre-wrap; }
89
- `
90
-
91
- function makeT(ctx) {
92
- try {
93
- ctx.locale.register('context-kit', { en: EN, zh: ZH })
94
- } catch {}
95
- let bound
96
- try {
97
- bound = ctx.locale.bind('context-kit')
98
- } catch {}
99
- return function t(key, fallback) {
100
- try {
101
- if (typeof bound === 'function') {
102
- const value = bound(key)
103
- if (typeof value === 'string' && value) return value
104
- } else if (bound && typeof bound[key] === 'string') {
105
- return bound[key]
106
- }
107
- } catch {}
108
- let id = 'en'
109
- try { id = ctx.locale.getLocale().id } catch {}
110
- const dict = id === 'zh' ? ZH : EN
111
- return dict[key] || fallback || key
112
- }
113
- }
114
-
115
- function makeApi(ctx) {
116
- function call(method, args) {
117
- return ctx.connection.rpc.call('/api', `contextKit/${method}`, { args: args || {} }, undefined).then(function (response) {
118
- if (response && response.ok) return response.value
119
- const message = response && response.error ? response.error.message : 'context kit remote call failed'
120
- const error = new Error(message)
121
- error.code = response && response.error ? response.error.code : 'REMOTE_FAILED'
122
- throw error
123
- })
124
- }
125
- return {
126
- status: function () { return call('status', {}) },
127
- save: function (input) {
128
- return call('save', {
129
- presetId: input.presetId,
130
- thresholdRatio: input.thresholdRatio,
131
- retainRatio: input.retainRatio,
132
- auto: input.auto,
133
- group: input.group,
134
- })
135
- },
136
- sync: function () { return call('sync', { force: false, mode: 'append' }) },
137
- preview: function () { return call('preview', {}) },
138
- clear: function () { return call('clear', {}) },
139
- }
140
- }
141
-
142
- const fmtK = function (tokens) {
143
- if (!Number.isFinite(tokens)) return '—'
144
- if (tokens >= 1024 * 1024) return (tokens / (1024 * 1024)).toFixed(1) + 'M'
145
- return Math.round(tokens / 1024) + 'K'
146
- }
147
- const pct = function (ratio) { return Math.round(Number(ratio) * 1000) / 10 + '%' }
148
-
149
- function Panel(props) {
150
- const t = props.t
151
- const api = props.api
152
- const [state, setState] = React.useState(null)
153
- const [threshold, setThreshold] = React.useState(0.5)
154
- const [retain, setRetain] = React.useState(0.16)
155
- const [busy, setBusy] = React.useState(false)
156
- const [message, setMessage] = React.useState('')
157
- const [error, setError] = React.useState('')
158
- const [pre, setPre] = React.useState('')
159
-
160
- const load = React.useCallback(function () {
161
- return api.status().then(function (next) {
162
- setState(next)
163
- if (next && next.knobs) {
164
- setThreshold(Number(next.knobs.thresholdRatio) || 0.5)
165
- setRetain(Number(next.knobs.retainRatio) || 0.16)
166
- }
167
- }).catch(function (cause) { setError(String(cause && cause.message ? cause.message : cause)) })
168
- }, [api])
169
-
170
- React.useEffect(function () { load() }, [load])
171
-
172
- const run = function (label, task) {
173
- setBusy(true)
174
- setError('')
175
- setMessage('')
176
- return task().then(function (result) {
177
- if (label) setMessage(label)
178
- return result
179
- }).catch(function (cause) {
180
- setError(String(cause && cause.message ? cause.message : cause))
181
- }).then(function () { setBusy(false) })
182
- }
183
-
184
- const presetId = state && state.presets && state.presets.length ? state.presets[0] : 'cordis'
185
- const window2 = state && state.triggers ? state.triggers.contextWindow : 1048576
186
- const triggerTokens = Math.floor(window2 * threshold)
187
- const retainTokens = Math.floor(window2 * retain)
188
-
189
- const entry = state && state.entries ? state.entries[0] : null
190
- const stateText = !entry
191
- ? t('missing')
192
- : entry.drifted
193
- ? t('drift') + ' · ' + entry.previousSha + ' → ' + entry.upstreamSha
194
- : entry.previousSha
195
- ? t('upToDate') + ' · ' + entry.upstreamSha
196
- : t('missing')
197
-
198
- return h('div', { className: 'ck_wrap' },
199
- h('div', { className: 'ck_head' },
200
- h('h2', null, t('title')),
201
- h('p', null, t('subtitle'))),
202
-
203
- h('div', { className: 'ck_card' },
204
- h('div', { className: 'ck_row' },
205
- h('label', null, t('threshold')),
206
- h('input', {
207
- type: 'range', min: 0.2, max: 0.85, step: 0.01, value: threshold,
208
- disabled: busy,
209
- onChange: function (event) { setThreshold(Number(event.target.value)) },
210
- }),
211
- h('span', { className: 'ck_val' }, fmtK(triggerTokens)),
212
- h('span', { className: 'ck_meta' }, pct(threshold) + ' ' + t('ofWindow'))),
213
- h('div', { className: 'ck_row' },
214
- h('label', null, t('retain')),
215
- h('input', {
216
- type: 'range', min: 0.04, max: Math.max(0.05, threshold - 0.02), step: 0.01, value: retain,
217
- disabled: busy,
218
- onChange: function (event) { setRetain(Number(event.target.value)) },
219
- }),
220
- h('span', { className: 'ck_val' }, fmtK(retainTokens)),
221
- h('span', { className: 'ck_meta' }, pct(retain) + ' ' + t('ofWindow'))),
222
- h('div', { className: 'ck_meta' },
223
- t('triggers') + ' ' + fmtK(triggerTokens) + ' · ' + t('keeps') + ' ' + fmtK(retainTokens)),
224
- h('div', { className: 'ck_btns' },
225
- h('button', {
226
- className: 'ck_btn primary', type: 'button', disabled: busy,
227
- onClick: function () {
228
- return run(t('saved'), function () {
229
- return api.save({ presetId: presetId, thresholdRatio: threshold, retainRatio: retain, auto: true, group: 'compaction' })
230
- .then(load)
231
- })
232
- },
233
- }, t('save')),
234
- h('button', {
235
- className: 'ck_btn', type: 'button', disabled: busy,
236
- onClick: function () {
237
- return run('', function () {
238
- return api.sync().then(function (result) {
239
- setMessage(result && result.changed ? t('synced') : t('unchanged'))
240
- return load()
241
- })
242
- })
243
- },
244
- }, t('sync')),
245
- h('button', {
246
- className: 'ck_btn', type: 'button', disabled: busy,
247
- onClick: function () {
248
- return run('', function () {
249
- return api.preview().then(function (result) { setPre(result && result.text ? result.text : '') })
250
- })
251
- },
252
- }, t('preview')),
253
- h('button', {
254
- className: 'ck_btn', type: 'button', disabled: busy,
255
- onClick: function () {
256
- return run(t('cleared'), function () { return api.clear().then(load) })
257
- },
258
- }, t('clear')),
259
- h('button', {
260
- className: 'ck_btn', type: 'button', disabled: busy,
261
- onClick: function () { return load() },
262
- }, t('refresh')))),
263
-
264
- state ? h('div', { className: 'ck_state' }, stateText) : null,
265
- state && state.foreign && state.foreign.length ? h('div', { className: 'ck_state ck_warn' }, t('foreign')) : null,
266
- message ? h('div', { className: 'ck_meta' }, message) : null,
267
- error ? h('div', { className: 'ck_meta ck_err' }, t('error') + ': ' + error) : null,
268
- state ? h('div', { className: 'ck_meta' }, t('profile') + ': ' + state.profileDir + ' · ' + t('patch') + ': ' + state.patchPath) : null,
269
- state ? h('div', { className: 'ck_meta' }, t('upstream') + ': ' + (state.sources || []).join(' | ')) : null,
270
- state && state.managed && state.managed.length
271
- ? h('div', { className: 'ck_meta' }, state.managed.map(function (block) { return block.presetId + '@' + block.sha }).join(', '))
272
- : null,
273
- h('div', { className: 'ck_meta' }, t('restart')),
274
- pre ? h('pre', { className: 'ck_pre' }, pre) : null)
275
- }
276
-
277
- return {
278
- inject: ['slots', 'connection', 'locale'],
279
- apply(ctx) {
280
- const style = document.createElement('style')
281
- style.dataset.plugin = 'dsh-context-kit'
282
- style.textContent = CSS
283
- document.head.appendChild(style)
284
- ctx.effect(function () {
285
- return function () { style.remove() }
286
- })
287
-
288
- const t = makeT(ctx)
289
- const api = makeApi(ctx)
290
- ctx.slots.inject('settings.section', function () {
291
- return ctx.slots.register({
292
- name: 'settings.section',
293
- id: 'context-kit',
294
- order: 46,
295
- label: function () { return t('label', 'Context') },
296
- inject: function () { return { api: api, t: t } },
297
- }, Panel)
298
- })
299
- },
300
- }
301
- },
302
- })
1
+ // dsh-context-kit 的 Settings 面板(Web 客户端插件)。
2
+ // 通过 ctx.connection.rpc 调宿主 contextKit 服务:status / save / sync / preview / clear / report。
3
+ window.__ModuleLoader__.load({
4
+ id: 'dsh-context-kit',
5
+ factory(require) {
6
+ const React = require('react')
7
+ const h = React.createElement
8
+
9
+ const EN = {
10
+ label: 'Context',
11
+ title: 'Context & Compaction',
12
+ subtitle: 'Save tokens by compacting earlier, without freezing the preset.',
13
+ threshold: 'Compact at',
14
+ retain: 'Keep after compact',
15
+ save: 'Save',
16
+ sync: 'Apply to profile',
17
+ preview: 'Preview',
18
+ clear: 'Remove override',
19
+ refresh: 'Refresh',
20
+ restart: 'Restart DSH to apply. Existing sessions pick up the new preset after restart.',
21
+ saved: 'Saved. Apply + restart to take effect.',
22
+ synced: 'Written to the profile patch.',
23
+ unchanged: 'Already up to date; nothing written.',
24
+ cleared: 'Override removed. Restart to fall back to upstream defaults.',
25
+ drift: 'Upstream preset changed',
26
+ upToDate: 'Upstream in sync',
27
+ missing: 'Not generated yet',
28
+ foreign: 'A hand-written override exists in your patch; remove it before applying.',
29
+ ofWindow: 'of the context window',
30
+ triggers: 'Compaction triggers at',
31
+ keeps: 'then keeps about',
32
+ profile: 'Profile',
33
+ patch: 'Patch file',
34
+ upstream: 'Upstream',
35
+ busy: 'Working…',
36
+ error: 'Error',
37
+ effectTitle: 'Measured effect',
38
+ effectHint: "Reads this machine's session logs. Nothing leaves the device.",
39
+ effectRun: 'Measure last 7 days',
40
+ effectRunning: 'Reading session logs…',
41
+ effectEmpty: 'Measuring… the first run decompresses recent sessions and may take a few seconds. Less than 7 days of history is fine — the window is capped at 7 days, not required.',
42
+ effectSessions: 'sessions',
43
+ effectSteps: 'steps',
44
+ effectCompactions: 'compactions',
45
+ effectHit: 'cache hit',
46
+ effectMiss: 'cache miss',
47
+ effectOut: 'output',
48
+ effectMissShare: 'miss share of cost',
49
+ effectContext: 'context (avg / peak)',
50
+ effectCost: 'cost (hit-equivalents)',
51
+ effectSavings: 'Estimated saving',
52
+ effectSavingsNote: 'estimate: replays your real per-step growth against the shipped default; not a bill',
53
+ effectRework: 'Rework signal',
54
+ effectReworkNote: 'repeated identical calls — the first sign compaction went too deep',
55
+ effectSkipped: 'skipped files',
56
+ effectWindow: 'window',
57
+ effectFiles: 'session logs read',
58
+ effectAt: 'measured at',
59
+ effectPolicies: 'observed policies',
60
+ effectCurrent: 'current',
61
+ effectCoverage: 'data under the current threshold',
62
+ effectModelOnly: 'Too few steps ran under the current threshold — treat the estimate as a direction, not a result.',
63
+ }
64
+
65
+ const ZH = {
66
+ label: '上下文',
67
+ title: '上下文与压缩',
68
+ subtitle: '早点压缩来省 token,同时不冻结预设。',
69
+ threshold: '压缩触发于',
70
+ retain: '压缩后保留',
71
+ save: '保存',
72
+ sync: '写入 profile',
73
+ preview: '预览',
74
+ clear: '移除覆盖',
75
+ refresh: '刷新',
76
+ restart: '重启 DSH 后生效;已存在的会话也会在重启后使用新的预设版本。',
77
+ saved: '已保存。写入并重启后生效。',
78
+ synced: '已写入 profile 补丁。',
79
+ unchanged: '已是最新,没有写入。',
80
+ cleared: '已移除覆盖,重启后回到上游默认。',
81
+ drift: '上游预设已变化',
82
+ upToDate: '与上游一致',
83
+ missing: '尚未生成',
84
+ foreign: '补丁里存在手写覆盖,请先移除再写入。',
85
+ ofWindow: '占上下文窗口',
86
+ triggers: '压缩触发点',
87
+ keeps: '压缩后约保留',
88
+ profile: 'Profile',
89
+ patch: '补丁文件',
90
+ upstream: '上游',
91
+ busy: '处理中…',
92
+ error: '出错',
93
+ effectTitle: '实测效果',
94
+ effectHint: '只读本机会话日志,数据不出设备。',
95
+ effectRun: '统计最近 7 天',
96
+ effectRunning: '正在读会话日志…',
97
+ effectEmpty: '正在统计… 第一次要解压最近的会话,可能需要几秒。用不满 7 天也能统计 —— 7 天是窗口上限,不是前提。',
98
+ effectSessions: '个会话',
99
+ effectSteps: '步',
100
+ effectCompactions: '次压缩',
101
+ effectHit: '缓存命中',
102
+ effectMiss: '未命中',
103
+ effectOut: '输出',
104
+ effectMissShare: '未命中占成本',
105
+ effectContext: '上下文(均值 / 峰值)',
106
+ effectCost: '成本(命中当量)',
107
+ effectSavings: '估算节省',
108
+ effectSavingsNote: '估算:用你的真实每步增量回放官方默认阈值,不等于账单',
109
+ effectRework: '返工信号',
110
+ effectReworkNote: '重复的相同调用 —— 压缩压过头的第一信号',
111
+ effectSkipped: '跳过文件',
112
+ effectWindow: '窗口',
113
+ effectFiles: '个会话日志',
114
+ effectAt: '统计时间',
115
+ effectPolicies: '观测到的策略',
116
+ effectCurrent: '当前',
117
+ effectCoverage: '当前阈值下的实测',
118
+ effectModelOnly: '当前阈值下实际跑过的步数还太少 —— 这个估算只能当方向,不能当结论。',
119
+ }
120
+
121
+ const CSS = [
122
+ '.ck_wrap { display: flex; flex-direction: column; gap: 14px; }',
123
+ '.ck_head h2 { margin: 0 0 4px; font-size: 15px; }',
124
+ '.ck_head p { margin: 0; opacity: .7; font-size: 12px; }',
125
+ '.ck_card { border: 1px solid rgba(127,127,127,.25); border-radius: 10px; padding: 12px; display: flex; flex-direction: column; gap: 10px; }',
126
+ '.ck_row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }',
127
+ '.ck_row label { min-width: 110px; font-size: 12px; opacity: .8; }',
128
+ '.ck_row input[type=range] { flex: 1 1 160px; }',
129
+ '.ck_val { font-variant-numeric: tabular-nums; min-width: 72px; text-align: right; font-size: 12px; }',
130
+ '.ck_btns { display: flex; gap: 8px; flex-wrap: wrap; }',
131
+ '.ck_btn { border: 1px solid rgba(127,127,127,.35); background: transparent; border-radius: 8px; padding: 6px 12px; cursor: pointer; font-size: 12px; }',
132
+ '.ck_btn.primary { background: #2563eb; border-color: #2563eb; color: #fff; }',
133
+ '.ck_btn:disabled { opacity: .5; cursor: default; }',
134
+ '.ck_meta { font-size: 11px; opacity: .65; word-break: break-all; }',
135
+ '.ck_state { font-size: 12px; padding: 6px 8px; border-radius: 8px; background: rgba(127,127,127,.12); }',
136
+ '.ck_warn { color: #d97706; }',
137
+ '.ck_err { color: #dc2626; }',
138
+ '.ck_pre { max-height: 220px; overflow: auto; font-size: 11px; background: rgba(127,127,127,.12); padding: 8px; border-radius: 8px; white-space: pre-wrap; }',
139
+ ].join('\n')
140
+
141
+ const fmtK = (tokens) => {
142
+ if (!Number.isFinite(tokens)) return '—'
143
+ if (tokens >= 1024 * 1024) return (tokens / (1024 * 1024)).toFixed(1) + 'M'
144
+ return Math.round(tokens / 1024) + 'K'
145
+ }
146
+ const fmtBig = (value) => {
147
+ if (!Number.isFinite(value)) return '—'
148
+ if (value >= 1e9) return (value / 1e9).toFixed(2) + 'B'
149
+ if (value >= 1e6) return (value / 1e6).toFixed(1) + 'M'
150
+ if (value >= 1e3) return Math.round(value / 1e3) + 'K'
151
+ return String(Math.round(value))
152
+ }
153
+ const pct = (ratio) => Math.round(Number(ratio) * 1000) / 10 + '%'
154
+ const meta = (value) => h('div', { className: 'ck_meta' }, value)
155
+
156
+ function makeT(ctx) {
157
+ try {
158
+ ctx.locale.register('context-kit', { en: EN, zh: ZH })
159
+ } catch {}
160
+ let bound
161
+ try {
162
+ bound = ctx.locale.bind('context-kit')
163
+ } catch {}
164
+ return function t(key, fallback) {
165
+ try {
166
+ if (typeof bound === 'function') {
167
+ const value = bound(key)
168
+ if (typeof value === 'string' && value) return value
169
+ } else if (bound && typeof bound[key] === 'string') {
170
+ return bound[key]
171
+ }
172
+ } catch {}
173
+ let id = 'en'
174
+ try {
175
+ id = ctx.locale.getLocale().id
176
+ } catch {}
177
+ const dict = id === 'zh' ? ZH : EN
178
+ return dict[key] || fallback || key
179
+ }
180
+ }
181
+
182
+ function makeApi(ctx) {
183
+ function call(method, args) {
184
+ return ctx.connection.rpc.call('/api', 'contextKit/' + method, { args: args || {} }, undefined).then(function (response) {
185
+ if (response && response.ok) return response.value
186
+ const message = response && response.error ? response.error.message : 'context kit remote call failed'
187
+ const error = new Error(message)
188
+ error.code = response && response.error ? response.error.code : 'REMOTE_FAILED'
189
+ throw error
190
+ })
191
+ }
192
+ return {
193
+ status: () => call('status', {}),
194
+ preview: () => call('preview', {}),
195
+ clear: () => call('clear', {}),
196
+ sync: () => call('sync', { force: false, mode: 'append' }),
197
+ report: (days) => call('report', { days: days }),
198
+ save: (input) =>
199
+ call('save', {
200
+ presetId: input.presetId,
201
+ thresholdRatio: input.thresholdRatio,
202
+ retainRatio: input.retainRatio,
203
+ auto: input.auto,
204
+ group: input.group,
205
+ }),
206
+ }
207
+ }
208
+
209
+ function EffectCard(props) {
210
+ const t = props.t
211
+ const report = props.report
212
+ const rows = []
213
+ if (report) {
214
+ const total = report.totals
215
+ rows.push(meta(total.sessions + ' ' + t('effectSessions') + ' · ' + total.steps + ' ' + t('effectSteps') + ' · ' + total.compactions + ' ' + t('effectCompactions')))
216
+ if (report.policies && report.policies.length) {
217
+ rows.push(meta(t('effectPolicies')))
218
+ for (const policy of report.policies) {
219
+ const label = policy.triggerTokens === null ? '—' : fmtK(policy.triggerTokens)
220
+ rows.push(meta(' ' + label + ': ' + policy.totals.sessions + ' ' + t('effectSessions') + ' / ' + policy.totals.steps + ' ' + t('effectSteps') + (policy.isCurrent ? ' ← ' + t('effectCurrent') : '')))
221
+ }
222
+ }
223
+ if (report.coverage) {
224
+ rows.push(meta(t('effectCoverage') + ': ' + report.coverage.stepsUnderCurrent + ' ' + t('effectSteps') + ' (' + pct(report.coverage.sharePct / 100) + ')'))
225
+ }
226
+ rows.push(
227
+ h('div', { className: 'ck_row' },
228
+ meta(t('effectHit') + ' ' + fmtBig(total.hit)),
229
+ meta(t('effectMiss') + ' ' + fmtBig(total.miss)),
230
+ meta(t('effectOut') + ' ' + fmtBig(total.out))),
231
+ )
232
+ rows.push(
233
+ h('div', { className: 'ck_row' },
234
+ meta(t('effectMissShare') + ' ' + pct(total.missSharePct / 100)),
235
+ meta(t('effectContext') + ' ' + fmtK(total.promptAvg) + ' / ' + fmtK(total.promptMax)),
236
+ meta(t('effectCost') + ' ' + fmtBig(total.cost.total))),
237
+ )
238
+ if (report.savings) {
239
+ rows.push(
240
+ h('div', { className: 'ck_row' },
241
+ h('span', { className: 'ck_val' }, '−' + report.savings.savedPct.toFixed(1) + '%'),
242
+ meta(t('effectSavings') + ' · ' + t('effectSavingsNote'))),
243
+ )
244
+ if (report.coverage && report.coverage.isModelOnly) {
245
+ rows.push(h('div', { className: 'ck_meta ck_warn' }, t('effectModelOnly')))
246
+ }
247
+ }
248
+ rows.push(meta(t('effectRework') + ' ' + total.duplicates + ' / ' + total.distinctCalls + ' (' + pct(total.duplicatePct / 100) + ') · ' + t('effectReworkNote')))
249
+ if (report.skipped && report.skipped.length) rows.push(h('div', { className: 'ck_meta ck_warn' }, t('effectSkipped') + ': ' + report.skipped.length))
250
+ rows.push(meta(report.privacy))
251
+ } else {
252
+ rows.push(meta(t('effectEmpty')))
253
+ }
254
+ return h('div', { className: 'ck_card' },
255
+ h('div', { className: 'ck_row' },
256
+ h('label', null, t('effectTitle')),
257
+ meta(t('effectHint')),
258
+ h('button', { className: 'ck_btn', type: 'button', disabled: props.busy, onClick: props.onRun },
259
+ props.busy ? t('effectRunning') : t('effectRun'))),
260
+ ...rows)
261
+ }
262
+
263
+ function SliderRow(props) {
264
+ return h('div', { className: 'ck_row' },
265
+ h('label', null, props.label),
266
+ h('input', {
267
+ type: 'range',
268
+ min: props.min,
269
+ max: props.max,
270
+ step: 0.01,
271
+ value: props.value,
272
+ disabled: props.disabled,
273
+ onChange: function (event) { props.onChange(Number(event.target.value)) },
274
+ }),
275
+ h('span', { className: 'ck_val' }, fmtK(props.tokens)),
276
+ h('span', { className: 'ck_meta' }, pct(props.value) + ' ' + props.ofWindow))
277
+ }
278
+
279
+ function Panel(props) {
280
+ const t = props.t
281
+ const api = props.api
282
+ const [state, setState] = React.useState(null)
283
+ const [threshold, setThreshold] = React.useState(0.5)
284
+ const [retain, setRetain] = React.useState(0.16)
285
+ const [busy, setBusy] = React.useState(false)
286
+ const [message, setMessage] = React.useState('')
287
+ const [error, setError] = React.useState('')
288
+ const [pre, setPre] = React.useState('')
289
+ const [report, setReport] = React.useState(null)
290
+
291
+ const load = React.useCallback(function () {
292
+ return api.status().then(function (next) {
293
+ setState(next)
294
+ if (next && next.knobs) {
295
+ setThreshold(Number(next.knobs.thresholdRatio) || 0.5)
296
+ setRetain(Number(next.knobs.retainRatio) || 0.16)
297
+ }
298
+ }).catch(function (cause) {
299
+ setError(String(cause && cause.message ? cause.message : cause))
300
+ })
301
+ }, [api])
302
+
303
+ React.useEffect(function () { load() }, [load])
304
+
305
+ const run = function (label, task) {
306
+ setBusy(true)
307
+ setError('')
308
+ setMessage('')
309
+ return task().then(function (result) {
310
+ if (label) setMessage(label)
311
+ return result
312
+ }).catch(function (cause) {
313
+ setError(String(cause && cause.message ? cause.message : cause))
314
+ }).then(function () { setBusy(false) })
315
+ }
316
+
317
+ const presetId = state && state.presets && state.presets.length ? state.presets[0] : 'cordis'
318
+ const windowSize = state && state.triggers ? state.triggers.contextWindow : 1048576
319
+ const triggerTokens = Math.floor(windowSize * threshold)
320
+ const retainTokens = Math.floor(windowSize * retain)
321
+ const entry = state && state.entries ? state.entries[0] : null
322
+ const stateText = !entry
323
+ ? t('missing')
324
+ : entry.drifted
325
+ ? t('drift') + ' · ' + entry.previousSha + ' → ' + entry.upstreamSha
326
+ : entry.previousSha
327
+ ? t('upToDate') + ' · ' + entry.upstreamSha
328
+ : t('missing')
329
+
330
+ const configCard = h('div', { className: 'ck_card' },
331
+ h(SliderRow, {
332
+ label: t('threshold'), min: 0.2, max: 0.85, value: threshold,
333
+ tokens: triggerTokens, ofWindow: t('ofWindow'), disabled: busy,
334
+ onChange: setThreshold,
335
+ }),
336
+ h(SliderRow, {
337
+ label: t('retain'), min: 0.04, max: Math.max(0.05, threshold - 0.02), value: retain,
338
+ tokens: retainTokens, ofWindow: t('ofWindow'), disabled: busy,
339
+ onChange: setRetain,
340
+ }),
341
+ meta(t('triggers') + ' ' + fmtK(triggerTokens) + ' · ' + t('keeps') + ' ' + fmtK(retainTokens)),
342
+ h('div', { className: 'ck_btns' },
343
+ h('button', {
344
+ className: 'ck_btn primary', type: 'button', disabled: busy,
345
+ onClick: function () {
346
+ return run(t('saved'), function () {
347
+ return api.save({ presetId: presetId, thresholdRatio: threshold, retainRatio: retain, auto: true, group: 'compaction' }).then(load)
348
+ })
349
+ },
350
+ }, t('save')),
351
+ h('button', {
352
+ className: 'ck_btn', type: 'button', disabled: busy,
353
+ onClick: function () {
354
+ return run('', function () {
355
+ return api.sync().then(function (result) {
356
+ setMessage(result && result.changed ? t('synced') : t('unchanged'))
357
+ return load()
358
+ })
359
+ })
360
+ },
361
+ }, t('sync')),
362
+ h('button', {
363
+ className: 'ck_btn', type: 'button', disabled: busy,
364
+ onClick: function () {
365
+ return run('', function () {
366
+ return api.preview().then(function (result) { setPre(result && result.text ? result.text : '') })
367
+ })
368
+ },
369
+ }, t('preview')),
370
+ h('button', {
371
+ className: 'ck_btn', type: 'button', disabled: busy,
372
+ onClick: function () {
373
+ return run(t('cleared'), function () { return api.clear().then(load) })
374
+ },
375
+ }, t('clear')),
376
+ h('button', {
377
+ className: 'ck_btn', type: 'button', disabled: busy,
378
+ onClick: function () { return load() },
379
+ }, t('refresh'))))
380
+
381
+ const infoRows = []
382
+ if (state) infoRows.push(h('div', { className: 'ck_state' }, stateText))
383
+ if (state && state.foreign && state.foreign.length) infoRows.push(h('div', { className: 'ck_state ck_warn' }, t('foreign')))
384
+ if (message) infoRows.push(meta(message))
385
+ if (error) infoRows.push(h('div', { className: 'ck_meta ck_err' }, t('error') + ': ' + error))
386
+ if (state) infoRows.push(meta(t('profile') + ': ' + state.profileDir + ' · ' + t('patch') + ': ' + state.patchPath))
387
+ if (state) infoRows.push(meta(t('upstream') + ': ' + (state.sources || []).join(' | ')))
388
+ if (state && state.managed && state.managed.length) {
389
+ infoRows.push(meta(state.managed.map(function (block) { return block.presetId + '@' + block.sha }).join(', ')))
390
+ }
391
+ infoRows.push(meta(t('restart')))
392
+ if (pre) infoRows.push(h('pre', { className: 'ck_pre' }, pre))
393
+
394
+ return h('div', { className: 'ck_wrap' },
395
+ h('div', { className: 'ck_head' },
396
+ h('h2', null, t('title')),
397
+ h('p', null, t('subtitle'))),
398
+ configCard,
399
+ h(EffectCard, {
400
+ t: t,
401
+ report: report,
402
+ busy: busy,
403
+ onRun: function () {
404
+ return run('', function () {
405
+ return api.report(7).then(function (next) { setReport(next) })
406
+ })
407
+ },
408
+ }),
409
+ ...infoRows)
410
+ }
411
+
412
+ return {
413
+ inject: ['slots', 'connection', 'locale'],
414
+ apply(ctx) {
415
+ const style = document.createElement('style')
416
+ style.dataset.plugin = 'dsh-context-kit'
417
+ style.textContent = CSS
418
+ document.head.appendChild(style)
419
+ ctx.effect(function () {
420
+ return function () { style.remove() }
421
+ })
422
+
423
+ const t = makeT(ctx)
424
+ const api = makeApi(ctx)
425
+ ctx.slots.inject('settings.section', function () {
426
+ return ctx.slots.register({
427
+ name: 'settings.section',
428
+ id: 'context-kit',
429
+ order: 46,
430
+ label: function () { return t('label', 'Context') },
431
+ inject: function () { return { api: api, t: t } },
432
+ }, Panel)
433
+ })
434
+ },
435
+ }
436
+ },
437
+ })