dsh-lightweightcontext 0.1.2 → 0.3.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.
@@ -3,26 +3,389 @@ window.__ModuleLoader__.load({
3
3
  factory(require) {
4
4
  const React = require('react');
5
5
  const h = React.createElement;
6
- function 上下文入口() {
7
- return h('span', {
8
- title: '上下文由模型自动管理。输入 /context 查看用量、压缩块和可压缩范围。',
9
- 'aria-label': '上下文管理已启用',
10
- style: {
11
- display: 'inline-flex',
12
- alignItems: 'center',
13
- gap: '4px',
14
- color: 'var(--dsw-alias-text-secondary, currentColor)',
15
- fontSize: '12px',
16
- whiteSpace: 'nowrap',
17
- },
18
- }, '上下文');
6
+ const NS = 'settings.context';
7
+
8
+ const zh = {
9
+ title: '上下文',
10
+ description: '调节分层折叠、增长提醒、历史保护与摘要质量。保存后立即生效,无需重启。',
11
+ pluginSwitch: '启用或停用整个插件,请在插件管理页使用开关。此处编辑 26 项运行参数。',
12
+ loading: '正在读取上下文配置…',
13
+ unavailable: '上下文插件当前未加载,暂时无法配置。',
14
+ readOnly: '当前部署的配置为只读,仍可查看生效值。',
15
+ save: '保存', saving: '保存中…', discard: '放弃更改', defaults: '全部恢复默认',
16
+ saved: '设置已保存并即时生效。',
17
+ saveFailed: '配置未保存。它可能已在其他页面变更;草稿已保留,请核对后重试。',
18
+ saveError: '保存失败:', changedElsewhere: '配置已在其他页面更新。当前草稿未变,保存时仍会进行版本冲突检查。',
19
+ conflictTitle: '配置已在其他页面更新',
20
+ conflictWarning: '请核对差异。确认后仅覆盖下面列出的本次修改,其他字段保持最新值。',
21
+ confirmOverwrite: '以草稿覆盖最新配置', overwriteFields: '将覆盖',
22
+ overridden: '已覆盖', default: '默认', emptyList: '空列表', invalid: '请检查标出的字段。',
23
+ invalidNumber: '请输入数字。', required: '此项不能为空。',
24
+ range: '允许范围', stepError: '步长应为', relationPressure: '压力比例不能低于最低压力比例。',
25
+ relationEmergency: '紧急比例不能低于压力比例。', relationTiers: 'T3 触发数必须大于 T2 触发数。',
26
+ composer: '上下文由模型自动管理。输入 /context 查看状态;在设置 → 上下文中调节参数。',
27
+ attribution: '参数语义参考', upstream: 'billion-context / acp-kernel 上游配置',
28
+ enabled: '启用', disabled: '停用', listHint: '每行一个工具名,空行会被忽略。',
29
+ };
30
+ const en = {
31
+ title: 'Context',
32
+ description: 'Tune hierarchical folding, growth nudges, history protection, and summary quality. Changes apply immediately after saving.',
33
+ pluginSwitch: 'Use the switch on the Plugins page to enable or disable the whole plugin. This page edits 26 runtime parameters.',
34
+ loading: 'Loading context settings…',
35
+ unavailable: 'The context plugin is not loaded, so it cannot be configured right now.',
36
+ readOnly: 'This deployment stores settings read-only. Effective values remain visible.',
37
+ save: 'Save', saving: 'Saving…', discard: 'Discard changes', defaults: 'Reset all to defaults',
38
+ saved: 'Settings saved and applied immediately.',
39
+ saveFailed: 'Settings were not saved. They may have changed elsewhere; your draft is preserved for review.',
40
+ saveError: 'Save failed: ', changedElsewhere: 'Settings changed elsewhere. Your draft is intact and saving still uses a revision conflict check.',
41
+ conflictTitle: 'Settings changed elsewhere',
42
+ conflictWarning: 'Review the differences. Confirmation overwrites only the listed fields from this edit; every other field keeps its latest value.',
43
+ confirmOverwrite: 'Overwrite latest settings with my draft', overwriteFields: 'Fields to overwrite',
44
+ overridden: 'Overridden', default: 'Default', emptyList: 'Empty list', invalid: 'Check the highlighted fields.',
45
+ invalidNumber: 'Enter a number.', required: 'This field is required.',
46
+ range: 'Range', stepError: 'Step', relationPressure: 'Pressure ratio cannot be below minimum pressure ratio.',
47
+ relationEmergency: 'Emergency ratio cannot be below pressure ratio.', relationTiers: 'T3 trigger must be greater than T2 trigger.',
48
+ composer: 'The model manages context automatically. Use /context for status and Settings → Context for parameters.',
49
+ attribution: 'Parameter semantics follow the', upstream: 'billion-context / acp-kernel upstream configuration',
50
+ enabled: 'Enabled', disabled: 'Disabled', listHint: 'One tool name per line; blank lines are ignored.',
51
+ };
52
+
53
+ function numberField(key, label, enLabel, value, min, max, step, hint, enHint) {
54
+ return { key, kind: 'number', label: [label, enLabel], default: value, min, max, step, hint: [hint, enHint] };
55
+ }
56
+ function booleanField(key, label, enLabel, value, hint, enHint) {
57
+ return { key, kind: 'boolean', label: [label, enLabel], default: value, hint: [hint, enHint] };
58
+ }
59
+ function listField(key, label, enLabel, hint, enHint) {
60
+ return { key, kind: 'list', label: [label, enLabel], default: [], hint: [hint, enHint] };
61
+ }
62
+ function group(id, title, enTitle, fields) { return { id, title: [title, enTitle], fields }; }
63
+
64
+ // 默认值与 Host 配置.ts 保持一致;上游未移植的代理、absorb、CCR 参数不在此列出。
65
+ const groups = [
66
+ group('growth', '基础与增长', 'Basics and growth', [
67
+ numberField('defaultContextWindow', '默认上下文窗口', 'Default context window', 200000, 1000, null, 1000, '模型未提供窗口信息时使用的 token 数。', 'Fallback token window when the model reports none.'),
68
+ numberField('nudgeGrowthTokens', 'T1 增长步长', 'T1 growth step', 50000, 1000, null, 1000, 'T1 提醒的阈值与增长步长,单位为 token。', 'Threshold and growth interval for T1 nudges, in tokens.'),
69
+ numberField('minGrowthFloorTokens', '增长门限下限', 'Minimum growth floor', 20000, 0, null, 1000, '实际增长门限不会低于此 token 数。', 'The effective growth threshold never falls below this token count.'),
70
+ numberField('minGrowthRatio', '增长门限比例', 'Minimum growth ratio', 0.45, 0, null, 0.01, '增长门限相对增长步长的比例。', 'Minimum growth threshold as a share of the growth step.'),
71
+ ]),
72
+ group('pressure', '压力与分层', 'Pressure and tiers', [
73
+ numberField('pressureRatio', '压力比例', 'Pressure ratio', 0.75, 0.1, 1, 0.01, '窗口占用超过此比例后进入压力带。', 'Enter the pressure band above this window usage ratio.'),
74
+ numberField('minPressureRatio', '最低压力比例', 'Minimum pressure ratio', 0.45, 0, 1, 0.01, '首见积压或积压排空旁路所需的占用下限。', 'Usage floor for first-sight and drain bypasses.'),
75
+ numberField('emergencyRatio', '紧急比例', 'Emergency ratio', 0.95, 0.1, 1, 0.01, '达到此比例后优先选择可回收量最大的层。', 'Above this ratio, select the tier with the largest reclaimable mass.'),
76
+ numberField('truncateThreshold', '超窗告警线', 'Overflow warning ratio', 0.95, 0.1, 1, 0.01, '仅发出告警;DSH 原生模式不会据此截断内容。', 'Warning only; native DSH mode never truncates content at this line.'),
77
+ numberField('minPressureBenefitTokens', '压力带最小收益', 'Minimum pressure benefit', 0, 0, null, 1000, '单位为 token;0 表示按窗口大小自适应。', 'In tokens; 0 derives the benefit from the context window.'),
78
+ booleanField('requireUsageSampleForPressure', '压力判断要求真实用量', 'Require usage sample for pressure', true, '只有估算读数时暂缓压力提醒,避免幻影压力。', 'Hold pressure nudges on estimate-only readings to avoid phantom pressure.'),
79
+ numberField('maxEstimateHoldRounds', '估算读数最多推迟轮数', 'Maximum estimate hold rounds', 2, 0, null, 1, '超过该轮数后,即使仍无真实用量也照常判断。', 'After this many rounds, proceed even without a usage sample.'),
80
+ booleanField('tiersEnabled', '启用 T2/T3 分层', 'Enable T2/T3 tiers', true, '允许把旧摘要继续蒸馏为更高层摘要。', 'Allow older summaries to be distilled into higher tiers.'),
81
+ numberField('tier2GrowthMultiplier', 'T2/T3 质量阈值倍数', 'T2/T3 mass multiplier', 1.5, 1, null, 0.1, '高层摘要的 token 质量阈值 = 增长步长 × 此倍数。', 'Higher-tier token mass threshold = growth step × this multiplier.'),
82
+ numberField('tier2Trigger', 'T2 计数触发', 'T2 count trigger', 1000, 1, null, 1, '活动 T1 块达到此数量时触发 T2;大数值相当于关闭计数通道。', 'Trigger T2 at this many active T1 blocks; a large value effectively disables the count path.'),
83
+ numberField('tier3Trigger', 'T3 计数触发', 'T3 count trigger', 2000, 2, null, 1, '活动 T2 块达到此数量时触发 T3,且必须大于 T2 触发数。', 'Trigger T3 at this many active T2 blocks; must exceed the T2 trigger.'),
84
+ numberField('promotionThreshold', '旧块提升轮数', 'Old-block promotion threshold', 5, 1, null, 1, '活动块存活多少轮折叠后标记为 old。', 'Mark an active block old after it survives this many folds.'),
85
+ ]),
86
+ group('folding', '折叠与摘要', 'Folding and summaries', [
87
+ numberField('preserveRecentMessages', '最近消息保护条数', 'Protected recent messages', 3, 0, null, 1, '最近多少条消息不参与折叠。', 'Keep this many recent messages out of folds.'),
88
+ numberField('preserveRecentTokens', '最近 token 保护下限', 'Protected recent tokens', 5000, 0, null, 500, '与消息条数共同形成保护区,单位为 token。', 'Combine with the message count to form the protected tail, in tokens.'),
89
+ numberField('minCompressRange', '最小折叠范围', 'Minimum fold range', 5000, 0, null, 500, '单次折叠的原文字符数下限。', 'Minimum source characters required for one fold.'),
90
+ numberField('maxSummaryChars', '摘要字符上限', 'Maximum summary characters', 20000, 50, null, 500, '单个摘要允许的最大字符数。', 'Maximum characters allowed in one summary.'),
91
+ booleanField('enforceSummaryChecklist', '强制摘要清单校验', 'Enforce summary checklist', false, '开启后额外拒绝空指针与信息类别不足的摘要。', 'Reject pointer-only summaries and summaries with too few information categories.'),
92
+ numberField('minSummaryCategories', '摘要最少信息类别', 'Minimum summary categories', 2, 0, 6, 1, '仅在校验开启时生效,范围为 0–6 类。', 'Used only when checklist enforcement is on; accepts 0–6 categories.'),
93
+ numberField('maxPinnedFacts', '钉住事实条数上限', 'Pinned fact limit', 20, 0, null, 1, '0 表示不限制;降低后在下次钉住操作时裁剪。', '0 means unlimited; lowering trims on the next pin operation.'),
94
+ ]),
95
+ group('tools', '工具保护', 'Tool protection', [
96
+ listField('protectedTools', '整条保护的工具', 'Fully protected tools', '这些工具的调用与结果都不参与折叠。', 'Calls and results from these tools are never folded.'),
97
+ listField('protectedLatestTools', '只保护最后一次的工具', 'Latest-only protected tools', '只保留每种工具最近一次出现的完整内容。', 'Preserve only the latest complete occurrence of each listed tool.'),
98
+ listField('neverPreserveRecentTools', '不占最近保护区的工具', 'Tools excluded from recent protection', '大结果仍可见、可折叠,但不占最近窗口名额。', 'Large results stay visible and foldable without consuming recent-window slots.'),
99
+ ]),
100
+ ];
101
+ const fields = groups.flatMap(item => item.fields);
102
+ for (const item of groups) {
103
+ zh[`group.${item.id}`] = item.title[0];
104
+ en[`group.${item.id}`] = item.title[1];
105
+ for (const field of item.fields) {
106
+ zh[`field.${field.key}`] = field.label[0];
107
+ en[`field.${field.key}`] = field.label[1];
108
+ zh[`hint.${field.key}`] = field.hint[0];
109
+ en[`hint.${field.key}`] = field.hint[1];
110
+ }
111
+ }
112
+
113
+ const css = `
114
+ .dsh-context-settings{color:var(--dsw-alias-label-primary);font-size:13px;line-height:1.55;width:100%;max-width:760px}
115
+ .dsh-context-settings *{box-sizing:border-box}.dsh-context-intro{color:var(--dsw-alias-label-secondary);margin:0 0 8px}
116
+ .dsh-context-note{background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l1);border-radius:8px;color:var(--dsw-alias-label-secondary);padding:10px 12px;margin:12px 0 20px}
117
+ .dsh-context-group{padding:0 0 20px;margin:0 0 20px;border-bottom:1px solid var(--dsw-alias-border-l1)}
118
+ .dsh-context-group h3{font-size:15px;line-height:1.4;margin:0 0 12px;font-weight:600}
119
+ .dsh-context-row{display:grid;grid-template-columns:minmax(0,1fr) minmax(180px,240px);gap:32px;align-items:center;padding:12px 0}
120
+ .dsh-context-label{display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-weight:500;margin-bottom:3px}
121
+ .dsh-context-hint{color:var(--dsw-alias-label-secondary);font-size:12px}.dsh-context-default{margin-top:3px}
122
+ .dsh-context-badge{font-size:11px;font-weight:400;color:var(--dsw-alias-brand-primary);border:1px solid var(--dsw-alias-brand-primary);border-radius:4px;padding:0 4px}
123
+ .dsh-context-input,.dsh-context-list{width:100%;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);border:1px solid var(--dsw-alias-border-l2);border-radius:6px;padding:7px 9px;font:inherit;font-variant-numeric:tabular-nums}
124
+ .dsh-context-list{min-height:72px;resize:vertical;line-height:1.5}.dsh-context-input:focus,.dsh-context-list:focus{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
125
+ .dsh-context-input[aria-invalid="true"],.dsh-context-list[aria-invalid="true"]{border-color:var(--dsw-alias-state-error-primary)}
126
+ .dsh-context-error{color:var(--dsw-alias-state-error-primary);font-size:12px;margin-top:4px}.dsh-context-control{min-width:0}
127
+ .dsh-context-switch{justify-self:end;position:relative;width:38px;height:22px;border:1px solid var(--dsw-alias-border-l2);border-radius:12px;background:var(--dsw-alias-bg-layer-2);padding:2px;cursor:pointer}
128
+ .dsh-context-switch[aria-checked="true"]{background:var(--dsw-alias-brand-primary);border-color:var(--dsw-alias-brand-primary)}
129
+ .dsh-context-knob{display:block;width:16px;height:16px;border-radius:50%;background:var(--dsw-alias-label-primary);transition:transform 120ms ease}
130
+ .dsh-context-switch[aria-checked="true"] .dsh-context-knob{transform:translateX(16px);background:var(--dsw-alias-bg-base)}
131
+ .dsh-context-switch:focus-visible,.dsh-context-button:focus-visible,.dsh-context-attribution a:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:2px}
132
+ .dsh-context-switch:disabled,.dsh-context-button:disabled{cursor:not-allowed;opacity:.55}
133
+ .dsh-context-input[readonly],.dsh-context-list[readonly]{opacity:.65;cursor:default}
134
+ .dsh-context-boolean{display:flex;align-items:center;justify-content:flex-end;gap:8px}
135
+ .dsh-context-status{border-radius:6px;padding:9px 12px;margin:12px 0;color:var(--dsw-alias-label-secondary);background:var(--dsw-alias-bg-layer-2)}
136
+ .dsh-context-status[data-kind="success"]{color:var(--dsw-alias-state-success-primary)}.dsh-context-status[data-kind="error"]{color:var(--dsw-alias-state-error-primary)}
137
+ .dsh-context-actions{display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:12px 0 4px;position:sticky;bottom:0;background:var(--dsw-alias-bg-layer-1)}
138
+ .dsh-context-button{border:1px solid var(--dsw-alias-border-l2);border-radius:6px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font:inherit;font-weight:500;padding:7px 14px;cursor:pointer}
139
+ .dsh-context-button[data-primary="true"]{background:var(--dsw-alias-brand-primary);border-color:var(--dsw-alias-brand-primary);color:var(--dsw-alias-bg-base)}
140
+ .dsh-context-attribution{color:var(--dsw-alias-label-secondary);font-size:12px;margin:16px 0}.dsh-context-attribution a{color:var(--dsw-alias-brand-primary)}
141
+ @media(max-width:600px){.dsh-context-row{grid-template-columns:1fr;gap:8px}.dsh-context-switch,.dsh-context-boolean{justify-self:start;justify-content:flex-start}.dsh-context-actions{position:static}}
142
+ @media(prefers-reduced-motion:reduce){.dsh-context-knob{transition:none}}
143
+ `;
144
+
145
+ function draftFrom(value) {
146
+ const result = {};
147
+ for (const field of fields) {
148
+ const current = value?.[field.key] ?? field.default;
149
+ result[field.key] = field.kind === 'list' ? current.join('\n') : field.kind === 'number' ? String(current) : current;
150
+ }
151
+ return result;
152
+ }
153
+ function defaultDraft() { return draftFrom({}); }
154
+ function sameValue(left, right) { return JSON.stringify(left) === JSON.stringify(right); }
155
+ function parseField(field, text) {
156
+ if (field.kind === 'boolean') return text;
157
+ if (field.kind === 'list') return [...new Set(String(text).split(/\r?\n/).map(item => item.trim()).filter(Boolean))];
158
+ return Number(String(text).trim());
159
+ }
160
+ function changedFieldList(candidates, draft, baseline) {
161
+ return candidates.filter(field =>
162
+ !sameValue(parseField(field, draft[field.key]), parseField(field, baseline[field.key])));
163
+ }
164
+ function setOperations(candidates, draft) {
165
+ return candidates.map(field => ({
166
+ op: 'set', path: [field.key], value: parseField(field, draft[field.key]),
167
+ }));
168
+ }
169
+ function validate(field, draft, t) {
170
+ const text = draft[field.key];
171
+ if (field.kind !== 'number') return undefined;
172
+ if (String(text).trim() === '') return t('required');
173
+ const value = Number(text);
174
+ if (!Number.isFinite(value)) return t('invalidNumber');
175
+ if (field.min !== null && value < field.min || field.max !== null && value > field.max) {
176
+ return `${t('range')}: ${field.min ?? '−∞'}–${field.max ?? '∞'}`;
177
+ }
178
+ // step 同时用于输入框步进;整数字段的 Host 约束始终是 1,不能被界面步进值误收紧。
179
+ const requiredStep = field.step >= 1 ? 1 : field.step;
180
+ const steps = value / requiredStep;
181
+ if (Math.abs(steps - Math.round(steps)) > 1e-7) return `${t('stepError')} ${requiredStep}`;
182
+ return undefined;
183
+ }
184
+ function validateDraft(draft, t) {
185
+ const errors = {};
186
+ for (const field of fields) {
187
+ const error = validate(field, draft, t);
188
+ if (error !== undefined) errors[field.key] = error;
189
+ }
190
+ if (!errors.pressureRatio && !errors.minPressureRatio && Number(draft.pressureRatio) < Number(draft.minPressureRatio)) errors.pressureRatio = t('relationPressure');
191
+ if (!errors.emergencyRatio && !errors.pressureRatio && Number(draft.emergencyRatio) < Number(draft.pressureRatio)) errors.emergencyRatio = t('relationEmergency');
192
+ if (!errors.tier2Trigger && !errors.tier3Trigger && Number(draft.tier3Trigger) <= Number(draft.tier2Trigger)) errors.tier3Trigger = t('relationTiers');
193
+ return errors;
194
+ }
195
+
196
+ function Field({ field, draft, error, overridden, disabled, readOnly, onEdit, t }) {
197
+ const id = `dsh-context-${field.key}`;
198
+ const hintId = `${id}-hint`;
199
+ const errorId = `${id}-error`;
200
+ const label = h('div', { className: 'dsh-context-label' },
201
+ h('label', { htmlFor: id }, t(`field.${field.key}`)),
202
+ overridden ? h('span', { className: 'dsh-context-badge' }, t('overridden')) : null);
203
+ const hint = h('div', { className: 'dsh-context-hint', id: hintId },
204
+ h('div', null, t(`hint.${field.key}`)),
205
+ field.kind === 'list' ? h('div', null, t('listHint')) : null,
206
+ h('div', { className: 'dsh-context-default' }, `${t('default')}: ${field.kind === 'list' ? t('emptyList') : String(field.default)}`));
207
+ let control;
208
+ if (field.kind === 'boolean') {
209
+ control = h('div', { className: 'dsh-context-boolean' },
210
+ h('button', {
211
+ id, type: 'button', className: 'dsh-context-switch', role: 'switch',
212
+ 'aria-checked': draft[field.key], 'aria-label': t(`field.${field.key}`),
213
+ 'aria-describedby': hintId, disabled: disabled || readOnly,
214
+ onClick: () => onEdit(field.key, !draft[field.key]),
215
+ }, h('span', { className: 'dsh-context-knob' })),
216
+ h('span', null, draft[field.key] ? t('enabled') : t('disabled')));
217
+ } else if (field.kind === 'list') {
218
+ control = h('textarea', {
219
+ id, className: 'dsh-context-list', value: draft[field.key], rows: 3,
220
+ readOnly: disabled || readOnly,
221
+ 'aria-invalid': error !== undefined, 'aria-describedby': `${hintId}${error ? ` ${errorId}` : ''}`,
222
+ onChange: event => onEdit(field.key, event.target.value),
223
+ });
224
+ } else {
225
+ control = h('input', {
226
+ id, className: 'dsh-context-input', type: 'number', inputMode: 'decimal',
227
+ min: field.min ?? undefined, max: field.max ?? undefined, step: field.step,
228
+ value: draft[field.key], readOnly: disabled || readOnly,
229
+ 'aria-invalid': error !== undefined, 'aria-describedby': `${hintId}${error ? ` ${errorId}` : ''}`,
230
+ onChange: event => onEdit(field.key, event.target.value),
231
+ });
232
+ }
233
+ return h('div', { className: 'dsh-context-row' },
234
+ h('div', null, label, hint),
235
+ h('div', { className: 'dsh-context-control' }, control,
236
+ error ? h('div', { className: 'dsh-context-error', id: errorId, role: 'alert' }, error) : null));
237
+ }
238
+
239
+ function SettingsPage({ form, t, view }) {
240
+ const snapshot = React.useSyncExternalStore(listener => form.subscribe(listener), () => form.getSnapshot(), () => form.getSnapshot());
241
+ const [draft, setDraft] = React.useState(null);
242
+ const [baseline, setBaseline] = React.useState(null);
243
+ const [revision, setRevision] = React.useState();
244
+ const [saving, setSaving] = React.useState(false);
245
+ const [notice, setNotice] = React.useState(null);
246
+ const [needsOverwrite, setNeedsOverwrite] = React.useState(false);
247
+ const changedFields = draft === null || baseline === null ? [] : changedFieldList(fields, draft, baseline);
248
+ const dirty = changedFields.length > 0;
249
+
250
+ React.useEffect(() => {
251
+ if (snapshot.status !== 'ready' || snapshot.value === undefined || dirty) return;
252
+ const next = draftFrom(snapshot.value);
253
+ setDraft(next);
254
+ setBaseline(next);
255
+ setRevision(snapshot.revision);
256
+ setNeedsOverwrite(false);
257
+ }, [snapshot.status, snapshot.value, snapshot.revision, dirty]);
258
+
259
+ if (view === 'summary') return t('description');
260
+ if (snapshot.status === 'loading' || snapshot.status === 'ready' && (draft === null || baseline === null)) return h('div', { className: 'dsh-context-status', role: 'status' }, t('loading'));
261
+ if (snapshot.status === 'unavailable' || snapshot.value === undefined) return h('div', { className: 'dsh-context-status', role: 'status' }, t('unavailable'));
262
+
263
+ const errors = validateDraft(draft, t);
264
+ const invalid = Object.keys(errors).length > 0;
265
+ const disabled = saving || !snapshot.writable;
266
+ const externalChange = dirty && snapshot.revision !== revision;
267
+ const latestDraft = draftFrom(snapshot.value);
268
+ // 覆盖确认只列出草稿与“最新 Host 值”仍不同的字段;未触碰字段永不写入。
269
+ const overwriteFields = changedFieldList(changedFields, draft, latestDraft);
270
+ const edit = (key, value) => {
271
+ setDraft(current => ({ ...current, [key]: value }));
272
+ if (!dirty) setRevision(snapshot.revision);
273
+ setNotice(null);
274
+ };
275
+ const discard = () => {
276
+ const next = draftFrom(snapshot.value);
277
+ setDraft(next);
278
+ setBaseline(next);
279
+ setRevision(snapshot.revision);
280
+ setNeedsOverwrite(false);
281
+ setNotice(null);
282
+ };
283
+ const reset = () => {
284
+ setDraft(defaultDraft());
285
+ if (!dirty) setRevision(snapshot.revision);
286
+ setNotice(null);
287
+ };
288
+ const save = async (overwrite = false) => {
289
+ if (invalid || disabled || !dirty || needsOverwrite && !overwrite) return;
290
+ const targetFields = overwrite ? overwriteFields : changedFields;
291
+ if (targetFields.length === 0) {
292
+ const next = draftFrom(snapshot.value);
293
+ setDraft(next);
294
+ setBaseline(next);
295
+ setRevision(snapshot.revision);
296
+ setNeedsOverwrite(false);
297
+ setNotice({ kind: 'success', text: t('saved') });
298
+ return;
299
+ }
300
+ setSaving(true);
301
+ setNotice(null);
302
+ try {
303
+ // 内建默认值也是显式 set;unset 表示恢复继承值,不能用于普通保存或恢复默认。
304
+ const operations = setOperations(targetFields, draft);
305
+ const accepted = await form.mutate(operations, revision);
306
+ const latest = form.getSnapshot();
307
+ if (accepted) {
308
+ const next = draftFrom(latest.value);
309
+ setDraft(next);
310
+ setBaseline(next);
311
+ setRevision(latest.revision);
312
+ setNeedsOverwrite(false);
313
+ setNotice({ kind: 'success', text: t('saved') });
314
+ } else if (latest.revision !== undefined && latest.revision !== revision) {
315
+ // 只有确认区可以发起第二次写入;警告和字段差异在确认前始终保留。
316
+ setRevision(latest.revision);
317
+ setNeedsOverwrite(true);
318
+ } else {
319
+ setNotice({ kind: 'error', text: t('saveFailed') });
320
+ }
321
+ } catch (error) {
322
+ setNotice({ kind: 'error', text: `${t('saveError')}${error instanceof Error ? error.message : String(error)}` });
323
+ } finally {
324
+ setSaving(false);
325
+ }
326
+ };
327
+
328
+ return h('div', { className: 'dsh-context-settings' },
329
+ h('style', null, css),
330
+ h('p', { className: 'dsh-context-intro' }, t('description')),
331
+ h('div', { className: 'dsh-context-note' }, t('pluginSwitch')),
332
+ !snapshot.writable ? h('div', { className: 'dsh-context-status', role: 'status' }, t('readOnly')) : null,
333
+ externalChange ? h('div', { className: 'dsh-context-status', role: 'status' }, t('changedElsewhere')) : null,
334
+ notice ? h('div', { className: 'dsh-context-status', 'data-kind': notice.kind, role: notice.kind === 'error' ? 'alert' : 'status', 'aria-live': 'polite' }, notice.text) : null,
335
+ needsOverwrite ? h('div', { className: 'dsh-context-status', 'data-kind': 'error', role: 'alert' },
336
+ h('strong', null, t('conflictTitle')),
337
+ h('p', null, t('conflictWarning')),
338
+ h('p', null, `${t('overwriteFields')}: ${overwriteFields.map(field => t(`field.${field.key}`)).join('、')}`),
339
+ h('button', { type: 'button', className: 'dsh-context-button', 'data-primary': true, disabled: disabled || invalid, onClick: () => save(true) }, saving ? t('saving') : t('confirmOverwrite'))) : null,
340
+ groups.map(item => h('section', { className: 'dsh-context-group', key: item.id },
341
+ h('h3', null, t(`group.${item.id}`)),
342
+ item.fields.map(field => h(Field, {
343
+ key: field.key, field, draft, t, disabled: saving, readOnly: !snapshot.writable,
344
+ error: errors[field.key],
345
+ overridden: snapshot.user !== null && typeof snapshot.user === 'object' && Object.prototype.hasOwnProperty.call(snapshot.user, field.key),
346
+ onEdit: edit,
347
+ })))),
348
+ invalid && dirty ? h('div', { className: 'dsh-context-error' }, t('invalid')) : null,
349
+ h('div', { className: 'dsh-context-actions' },
350
+ h('button', { type: 'button', className: 'dsh-context-button', 'data-primary': true, disabled: disabled || !dirty || invalid || needsOverwrite, onClick: () => save(false) }, saving ? t('saving') : t('save')),
351
+ h('button', { type: 'button', className: 'dsh-context-button', disabled: saving || !dirty, onClick: discard }, t('discard')),
352
+ h('button', { type: 'button', className: 'dsh-context-button', disabled, onClick: reset }, t('defaults'))),
353
+ h('p', { className: 'dsh-context-attribution' }, `${t('attribution')} `,
354
+ h('a', { href: 'https://github.com/ranxianglei/billion-context', target: '_blank', rel: 'noreferrer', title: t('upstream') }, 'billion-context / acp-kernel'), '.'));
355
+ }
356
+
357
+ function ContextIcon({ size = 16 }) {
358
+ return h('svg', { width: size, height: size, viewBox: '0 0 20 20', fill: 'none', 'aria-hidden': true },
359
+ h('path', { d: 'M3 5.5 10 2l7 3.5-7 3.5-7-3.5Zm0 4L10 13l7-3.5M3 13.5 10 17l7-3.5', stroke: 'currentColor', 'stroke-width': 1.5, 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }));
19
360
  }
361
+
20
362
  return {
21
- inject: ['slots'],
363
+ inject: ['slots', 'locale', 'configForms'],
22
364
  apply(ctx) {
365
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'context: settings dictionaries');
366
+ const t = ctx.locale.bind(NS);
367
+ const form = ctx.configForms.get('context');
368
+ const page = props => h(SettingsPage, { ...props, form, t: props.t ?? t });
369
+ ctx.effect(() => ctx.configForms.whileServed(['context'], () => {
370
+ const disposers = [
371
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
372
+ name: 'settings.section', id: 'context', order: 25, label: () => t('title'), locale: NS,
373
+ }, page)),
374
+ ctx.slots.inject('settings.section.icon', () => ctx.slots.register({
375
+ name: 'settings.section.icon', id: 'context', locale: NS,
376
+ }, ContextIcon)),
377
+ ctx.slots.inject('plugins.row.config', () => ctx.slots.register({
378
+ name: 'plugins.row.config', key: 'dsh-lightweightcontext#context', locale: NS,
379
+ }, page)),
380
+ ];
381
+ return () => { for (const dispose of disposers) dispose(); };
382
+ }), 'context: settings pages');
23
383
  ctx.slots.inject('conversation.composer.dock', () => ctx.slots.register({
24
384
  name: 'conversation.composer.dock', id: 'context', order: 5,
25
- }, 上下文入口));
385
+ }, () => h('span', {
386
+ title: t('composer'), 'aria-label': t('title'),
387
+ style: { display: 'inline-flex', alignItems: 'center', gap: '4px', color: 'var(--dsw-alias-label-secondary)', fontSize: '12px', whiteSpace: 'nowrap' },
388
+ }, t('title'))));
26
389
  },
27
390
  };
28
391
  },
@@ -1,43 +1,123 @@
1
1
  # 上下文(dsh-lightweightcontext)
2
2
 
3
- 完全内置于 DeepSeek Harness 的**模型驱动分层上下文管理**插件。较早且已消费的历史会被折叠成摘要,原始事件继续留在 DSH 会话日志里,随时可以检索和分页恢复——没有代理进程、没有独立会话库、没有端口监听、没有 `fetch` 改写。
3
+ 一个只服务 DeepSeek Harness(DSH)的**轻量上下文管理插件**:较早、已消费的历史折叠成摘要,原文继续留在 DSH 会话日志里,可检索、分页、逐层恢复。没有代理进程、没有独立会话库、没有端口监听、没有 `fetch` 改写。
4
4
 
5
5
  > 改编自 [billion-context](https://github.com/ranxianglei/billion-context) 与 [acp-kernel](https://github.com/ranxianglei/billion-context/tree/master/kernel)(MIT,Copyright (c) 2026 ranxianglei)。本项目与上游、与 DeepSeek 均无隶属关系。上游带一条**附加署名条款**:任何终端用户可见的产品在使用其内核时须显著说明使用了 billion-context 并附链接;分发衍生作品时请保留本段署名。完整许可与出处见 [`许可与来源.md`](许可与来源.md)。
6
6
 
7
+ ## 设计理念:把通用层剪掉,只留 DSH 需要的
8
+
9
+ 上游 billion-context 是一个**通用项目**:面向多种宿主与 Agent,必须自带一整套跨环境的基础设施才能在任何地方跑起来。通用性来自这些层,重量也来自这些层。
10
+
11
+ 本项目走反方向:**只认 DSH 一个宿主**。DSH 本身已经提供了会话日志、compaction 事务、Session Projection、TokenMeter 与 surface replacement——通用方案要自己实现的东西,在这里都是现成的原生能力。于是我们把那一层整体剥掉,插件直接长在 DSH 原生接口上:
12
+
13
+ | 通用方案常见做法 | 本项目做法 |
14
+ |---|---|
15
+ | 独立代理进程转发请求 | 无进程、无子进程,作为 bundle 装进 profile |
16
+ | 另存一份原文数据库 | 原文仍由 DSH 会话日志持有,插件只派生压缩块、层级与统计 |
17
+ | 监听端口、拦截网络 | 不开端口、不生成 CA、不改写 `fetch` 或 WebSocket、不发任何网络请求 |
18
+ | 显式管理压缩时机 | 增长提醒与 DSH 原生自动 compaction 共用同一条事务链,默认无感 |
19
+
20
+ 两条原则:
21
+
22
+ - **轻量**:不新增任何常驻设施。发布包只有 10 个文件,装进 profile 即随 DSH 一起运行。
23
+ - **无感**:装完新开会话即生效,日常不需要手动压缩。折叠走 DSH 原生的 `compaction/start → summary → surface replace → end` 事务,和宿主自己的 compaction 共用块谱系。模型看到的是变小的可见历史,用户看到的是照常运行的会话。
24
+
25
+ 代价也说清楚:这是**针对 DSH `0.2.2-rc.5` 的适配**,不是跨宿主通用方案。DSH 升级后必须重跑原生事务、重放与激活测试。
26
+
27
+ ## 它解决什么
28
+
29
+ 长会话里,较早且已被模型消费的历史会持续占用上下文预算。插件把这些历史折叠成分层摘要(T1 → T2 → T3),同时保留原文:
30
+
31
+ - 摘要只是 DSH 可见 surface 上的派生视图,**原文不会被删除**;
32
+ - `context_search` 在摘要和原文里检索,`context_decompress` 按块号取回原文,支持 `offset/limit` 分页与逐层展开;
33
+ - 最近用户消息和最小范围受保护,非法范围不会写入折叠事件。
34
+
7
35
  ## 安装
8
36
 
9
- 在 DSH 里让 Agent 调用 `plugin_manager install_bundle`,target 填 `dsh-lightweightcontext@0.1.0`;或在 Web 界面的 Plugins 页面安装。装完**新开会话**生效。
37
+ 在 DSH 里让 Agent 调用 `plugin_manager install_bundle`,target 填 `dsh-lightweightcontext@0.3.0`;或在 Web 界面的 Plugins 页面安装。装完**新开会话**生效——已打开的会话不会追溯改变插件修订。
10
38
 
11
39
  要求 DSH `0.2.2-rc.5`(`engines.dsh: ^0.2.2-rc.5`)与 Node `>=22`。这是开发验证的版本边界,不是营销话术:插件用的是 DSH 的 compaction 事务、Session Projection 与 TokenMeter,跨版本升级前要重跑原生事务测试。
12
40
 
13
41
  ## 用起来是什么样
14
42
 
15
- 安装并在新会话启用后,模型自动获得四个工具:
43
+ 新开会话后,模型自动获得五个工具,用户不需要改变任何使用习惯:
16
44
 
17
45
  | 工具 | 作用 |
18
46
  |---|---|
19
47
  | `context_compress` | 把较早的一段历史折叠成摘要块,支持 T1/T2 分层、范围保护 |
20
48
  | `context_decompress` | 按块号取回原文,支持 `offset/limit` 分页与逐层展开 |
21
49
  | `context_search` | 在压缩摘要和保留的原文里做关键词检索,返回块号与片段 |
22
- | `context_status` | 当前用量、活动块、可压缩范围 |
23
-
24
- 外加一条 `/context` 斜杠命令。
25
-
26
- 日常不需要手动压缩:增长提醒与 DSH 原生自动 compaction 共存,两者共用同一套 `compaction/start → summary → surface replace → end` 事务和块谱系。
50
+ | `context_status` | 当前用量、活动块、钉住事实、可压缩范围 |
51
+ | `context_pin` | 钉住不参与折叠的长期事实(目标、已确认路径、已排除假设) |
52
+
53
+ 外加一条 `/context` 斜杠命令查看状态。
54
+
55
+ 日常不需要手动压缩:增长提醒与 DSH 原生自动 compaction 共存,两者共用同一套事务和块谱系。它只在后台把旧历史折起来,需要时原文还能找回来——这就是“无感”。
56
+
57
+ ## 配置
58
+
59
+ 打开 **设置 → 上下文** 即可调节参数;也可以从 **Plugins → 上下文 → context 行 → 配置** 进入同一页面。页面按「基础与增长、压力与分层、折叠与摘要、工具保护」分组,支持草稿校验、统一保存、放弃更改和全部恢复默认。除 `enabled` 外的 **26 项参数保存后立即生效**,无需重启;整个插件的启停仍使用插件管理页的开关。
60
+
61
+ 参数语义对照上游 `billion-context@0.1.218` 的 [`kernel/src/config.ts`](https://github.com/ranxianglei/billion-context/blob/5d7dbbd3c5fee9cc755091cbe9e539e42724e764/kernel/src/config.ts) 与[配置参考](https://github.com/ranxianglei/billion-context/blob/5d7dbbd3c5fee9cc755091cbe9e539e42724e764/docs/configuration.md)。未移植的代理、网络、`absorb`、`CCR` 和规则提取参数不会出现在页面中。
62
+
63
+ 保存由 DSH 的 Settings / ConfigEditor 统一完成,带修订冲突检查;发生冲突或写入失败时保留草稿。每次仅写入相对 baseline 实际变化的字段,未修改字段的用户覆盖与继承关系保持不变。「全部恢复默认」表示显式写入内建默认值,不是 `unset` 恢复继承值。若其他页面已更新配置,必须先在差异确认区点击「以草稿覆盖最新配置」,且只覆盖本次编辑的字段。比例字段使用 `0–1` 小数,工具列表每行填写一个工具名。`promotionThreshold` 在投影外派生,配置变化不会把可变引用带入日志回放。
64
+
65
+ | 键 | 默认 | 说明 |
66
+ |---|---|---|
67
+ | `enabled` | `true` | 关掉后不注册工具、不注入提示词、不发提醒;由插件管理开关控制,不在热更新页内 |
68
+ | `defaultContextWindow` | `200000` | 模型未提供窗口信息时使用的默认 token 窗口 |
69
+ | `nudgeGrowthTokens` | `50000` | T1 阈值与增长步长;增长下限另由 `minGrowthFloorTokens`/`minGrowthRatio` 决定 |
70
+ | `minGrowthFloorTokens` | `20000` | 增长门限下限:实际门限为 `max(20000, 0.45×增长步)`,默认 22500 |
71
+ | `minGrowthRatio` | `0.45` | 增长门限相对增长步的比例 |
72
+ | `pressureRatio` | `0.75` | 窗口占用超过该比例进入压力带(跳过增长门限,按最大待压缩选层) |
73
+ | `minPressureRatio` | `0.45` | 首见积压/积压排空旁路所需的占用下限 |
74
+ | `emergencyRatio` | `0.95` | 紧急带,忽略层级优先级、取待压缩最大的层 |
75
+ | `minPressureBenefitTokens` | `0` | 压力带的最小可回收量;`0` 表示按 `max(5000, 窗口×1%)` 自适应 |
76
+ | `tier2GrowthMultiplier` | `1.5` | T2/T3 的质量阈值 = 增长步 × 该倍数(默认 75000) |
77
+ | `tiersEnabled` | `true` | 是否允许 T2/T3 蒸馏与凝练 |
78
+ | `tier2Trigger` | `1000` | 活动 T1 块达到该数量时按计数触发 T2 |
79
+ | `tier3Trigger` | `2000` | 活动 T2 块达到该数量时按计数触发 T3 |
80
+ | `requireUsageSampleForPressure` | `true` | 仅有估算读数时推迟压力注入(幻影压力守卫) |
81
+ | `maxEstimateHoldRounds` | `2` | 估算读数最多推迟几轮,超过后照常注入 |
82
+ | `truncateThreshold` | `0.95` | 超窗告警线;DSH 原生模式不做内容截断,仅提示 |
83
+ | `promotionThreshold` | `5` | 块存活到第几轮转为 `old` |
84
+ | `preserveRecentMessages` | `3` | 保护区条数(最近消息不参与折叠) |
85
+ | `preserveRecentTokens` | `5000` | 保护区 token 下限,与条数取并集 |
86
+ | `protectedTools` | `[]` | 整条保护的工具名(调用与结果都不折叠) |
87
+ | `protectedLatestTools` | `[]` | 只保护最后一次出现的工具名 |
88
+ | `neverPreserveRecentTools` | `[]` | 不占最近窗口名额的大结果工具(仍可见、可折叠) |
89
+ | `minCompressRange` | `5000` | 单次折叠的最小原文字符数;低于它的范围不推荐也拒绝 |
90
+ | `maxSummaryChars` | `20000` | 摘要长度上限 |
91
+ | `minSummaryCategories` | `2` | 摘要清单校验要求覆盖的信息类别数(仅在开启校验时生效) |
92
+ | `enforceSummaryChecklist` | `false` | 默认关闭以对齐上游“只校验长度”;开启后额外拒绝空指针与信息不足的摘要 |
93
+ | `maxPinnedFacts` | `20` | 钉住事实条数上限,`0` 表示不限制 |
94
+
95
+ ## 摘要为什么不会丢结论
96
+
97
+ 摘要仍然由模型撰写(与上游一致),但三处机制保证它不能写成空指针:
98
+
99
+ 1. **常驻规则**:系统提示里带完整的压缩哲学、KEEP / DROP / PRIORITY 清单、T2 蒸馏与 T3 凝练格式(含 `Open objectives` 结转、MEDIA REFS、`[SUPERSEDED]` 标记、语言保持)——与上游 `compression-rules.ts` 逐条对齐;
100
+ 2. **提醒文案**:每次催促只放“现在该做什么”、层级目标与候选范围(T1 消息范围或 T2/T3 块范围),规则本身常驻;
101
+ 3. **可选清单校验**:`enforceSummaryChecklist` 默认关闭(上游只校验长度);开启后检查摘要是否覆盖至少 `minSummaryCategories` 类信息,并拒绝「见 b00003」这类空指针,失败时给出按方向可执行的补救指令;
102
+ 4. **钉住区**:`context_pin` 记录的条目(用户目标、已确认路径、已排除假设)不进入摘要,每次 `context_status` 与压缩提醒原样带出,因此完全不受摘要质量影响。
27
103
 
28
104
  ## 数据与限制
29
105
 
30
106
  - 摘要由模型生成,可能漏细节;**原文不会被删除**,检索和分页恢复都在。
31
107
  - 插件只改变 DSH 的可见 surface,不缩小宿主日志文件。
32
- - 折叠是记录在会话日志里的事件,重放(`Session.create()`)与分叉(`buildForkSeed()`)后模型可见历史、块层级与恢复文本一致。
33
- - 已覆盖内存重放与分叉,但未做磁盘持久化后的进程级崩溃注入;未用真实在线模型评估摘要质量与节费比例。
108
+ - 折叠是记录在会话日志里的事件,重放(`Session.create()`)与分叉(`buildForkSeed()`)后模型可见历史、块层级与恢复文本一致;提醒状态也从日志里的提醒消息恢复,重启不会重复催。
34
109
  - 不读取模型凭据,不发起任何网络请求。
110
+ - 内容级截断(上游 `truncate`)是代理模式能力:DSH 原生模式下由宿主溢出恢复处理,插件只在越过 `truncateThreshold` 且无可折叠内容时给出显式告警。
111
+ - `absorb`、`CCR`(`acp_retrieve`)、`rules` 规则提取未移植:它们依赖代理侧工具注入与结果重写,且上游默认关闭。
112
+ - “失败压缩调用保护”与“不可恢复媒体保护”未单独实现:DSH 的附件是持久引用(可恢复),且 compaction 失败不携带调用号,按上游语义无可保护对象。
113
+ - 依赖 DSH `0.2.2-rc.5` 的 compaction 事务实现;升级 DSH 必须重跑原生事务、重放与激活测试。
114
+ - 未做磁盘持久化后的进程级崩溃注入;未用真实在线模型评估摘要质量与节费比例。
35
115
 
36
116
  ## 开发
37
117
 
38
118
  ```bash
39
119
  npm install
40
- npm run verify # check + build + test(19 项)
120
+ npm run verify # check + build + test(47 项)
41
121
  npm run build # tsup → 产物/
42
122
  npm test
43
123
  npm pack --dry-run
@@ -47,12 +127,16 @@ npm pack --dry-run
47
127
 
48
128
  ## 包内文件
49
129
 
50
- - `入口.ts` / `客户端.js`:Host 插件入口与 Web 客户端补丁
51
- - `内核/`:分层压缩内核(层级、叶子、摘要、数据模型)
52
- - `测试/`:19 项 `node:test`
130
+ - `产物/`:构建后的 Host 入口(含 DSH 原生事务代码)
131
+ - `客户端.js`:设置页、插件配置页与 Web 状态入口
132
+ - `配置.ts`:26 项热更新字段、默认值与运行时配置外观
53
133
  - `cordis.patch.yml`:bundle 补丁,插入 `id: context` 一行
134
+ - `内核/`:分层压缩内核(层级、叶子、摘要、数据模型、提醒决策、分层待压缩)
135
+ - `消息.ts`、`保护.ts`、`范围.ts`:消息口径、保护区与候选范围推荐
136
+ - `钉住.ts`:跨折叠常驻事实区(目标、路径、已排除假设)
137
+ - `测试/`:47 项 `node:test`
54
138
  - `图标.svg`、`许可与来源.md`、`验收报告.md`
55
139
 
56
140
  ## 许可
57
141
 
58
- MIT,见 [LICENSE](LICENSE)。
142
+ MIT,见 [LICENSE](LICENSE)。上游署名与第三方许可见 [许可与来源.md](许可与来源.md)。