@magic6/dsh-compaction-policy-engine 0.0.0-stage → 0.5.3
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/CHANGELOG.md +67 -0
- package/LICENSE +21 -0
- package/README.md +353 -2
- package/README.zh-CN.md +308 -0
- package/cordis.patch.yml +61 -0
- package/docs/DESIGN.md +161 -0
- package/examples/standard-with-policy/cordis.patch.yml +139 -0
- package/examples/standard-with-policy/package.json +12 -0
- package/lib/client-policy.js +192 -0
- package/lib/client.js +1791 -0
- package/lib/companion.js +13 -0
- package/lib/engine.js +19 -0
- package/lib/index.js +1384 -0
- package/lib/policy.js +608 -0
- package/lib/settings-file.js +396 -0
- package/lib/settings.js +138 -0
- package/package.json +70 -4
package/lib/client.js
ADDED
|
@@ -0,0 +1,1791 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser half of dsh-compaction-policy-engine: the policy card in the settings page
|
|
3
|
+
* and the in-session indicator beside the composer.
|
|
4
|
+
*
|
|
5
|
+
* The server half publishes the `compaction-control` settings section; this file
|
|
6
|
+
* renders it. It is served verbatim (no build step), so the client-safe policy
|
|
7
|
+
* view is inlined below and must stay textually identical to
|
|
8
|
+
* `lib/client-policy.js` — `test/client-policy.test.js` fails if it drifts.
|
|
9
|
+
*
|
|
10
|
+
* @module dsh-compaction-policy-engine/client
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
window.__ModuleLoader__.load({
|
|
14
|
+
id: 'dsh-compaction-policy-engine',
|
|
15
|
+
factory: (require) => {
|
|
16
|
+
var module = { exports: {} };
|
|
17
|
+
var exports = module.exports;
|
|
18
|
+
|
|
19
|
+
const react = require('react');
|
|
20
|
+
const jsx = require('react/jsx-runtime');
|
|
21
|
+
|
|
22
|
+
/** Settings namespace owned by the host half of this plugin. */
|
|
23
|
+
const NS = 'compaction-control';
|
|
24
|
+
|
|
25
|
+
/** Copy for both locales the Web client ships. */
|
|
26
|
+
const zh = {
|
|
27
|
+
title: '压缩策略',
|
|
28
|
+
hint: '上下文达到触发比例时自动压缩;也可以直接填固定 token 数(≥1 的整数)。留白表示沿用部署配置的默认值。',
|
|
29
|
+
threshold: '触发阈值',
|
|
30
|
+
retain: '保留比例',
|
|
31
|
+
maxTokens: '摘要长度上限',
|
|
32
|
+
model: '压缩用模型',
|
|
33
|
+
auto: 'auto(沿用当前会话的模型)',
|
|
34
|
+
reset: '重置',
|
|
35
|
+
save: '保存',
|
|
36
|
+
invalid: '请输入 0–1 之间的比例,或 ≥1 的整数 token 数',
|
|
37
|
+
retainAbove: '保留比例必须小于触发阈值',
|
|
38
|
+
unavailable: '设置服务不可用,当前策略来自部署配置。',
|
|
39
|
+
memoryNote: '这个浏览器不是环回地址(例如用局域网 IP 打开),dsh 只给它内存态视图:读不到主机上真正生效的压缩策略,写也不会保存。下面输入框里的提示数字是插件默认值,不是实际阈值——百分比请以本机 127.0.0.1 打开的界面为准。',
|
|
40
|
+
writeRefused: '写入未被主机接受:这台浏览器是内存态,改动不会保存。',
|
|
41
|
+
enable: '自动压缩',
|
|
42
|
+
enableHint: '关闭后上下文不再被自动压缩,超长会话将直接撞上模型窗口。',
|
|
43
|
+
modelAuto: 'auto(沿用当前会话的模型)',
|
|
44
|
+
modelLoading: '正在读取模型列表…',
|
|
45
|
+
modelEmpty: '当前没有可用的模型路由,只能选 auto。',
|
|
46
|
+
modelFailed: '模型列表读取失败,只能选 auto。',
|
|
47
|
+
// ── 摘要模型的回退链与安全余量 ────────────────────────────────
|
|
48
|
+
headroom: '安全余量(token)',
|
|
49
|
+
headroomHint: '留空沿用下层',
|
|
50
|
+
fallback: '回退链',
|
|
51
|
+
fallbackOrder: '按顺序尝试:强免费 → 弱免费 → 收费。留空表示不重试。',
|
|
52
|
+
fallbackNone: '还没有回退路由。主模型失败时压缩会直接报错。',
|
|
53
|
+
fallbackPick: '选择一个路由…',
|
|
54
|
+
fallbackAdd: '添加',
|
|
55
|
+
fallbackRemove: '移除',
|
|
56
|
+
fallbackUp: '上移',
|
|
57
|
+
fallbackDown: '下移',
|
|
58
|
+
fallbackNoChoices: '没有更多可添加的路由(不能是主模型,也不能重复)。',
|
|
59
|
+
// ── 策略层(全局默认 / 按供应商 / 按模型)──────────────────────
|
|
60
|
+
layer: '策略层',
|
|
61
|
+
layerRemove: '移除这一层',
|
|
62
|
+
layerAdd: '按供应商新增覆盖',
|
|
63
|
+
layerAddButton: '新增',
|
|
64
|
+
layerAddHint: '选中一层后,下面的输入框改的就是那一层;留白表示继承下一层。',
|
|
65
|
+
layerRoute: '供应商路由名',
|
|
66
|
+
layerPick: '选择供应商…',
|
|
67
|
+
layerOther: '手填路由名…',
|
|
68
|
+
// ── 会话内策略指示器 ──────────────────────────────────────────
|
|
69
|
+
badgeOff: '压缩已关',
|
|
70
|
+
badgeAria: '当前会话压缩策略',
|
|
71
|
+
badgeTitle: '当前会话的压缩策略',
|
|
72
|
+
badgeUnknown: '策略未读到',
|
|
73
|
+
badgeUnknownHint: '这个浏览器读不到主机上的压缩策略(它不是环回地址,dsh 只给它内存态视图),所以徽标不再猜数字。要看真实阈值请用本机 127.0.0.1 打开。',
|
|
74
|
+
pEffective: '生效值',
|
|
75
|
+
pLayerDefault: '全局默认',
|
|
76
|
+
pLayerProvider: '按供应商',
|
|
77
|
+
pLayerModel: '按模型',
|
|
78
|
+
pLayerEngine: '引擎内置(未被任何层覆盖)',
|
|
79
|
+
pUser: '你设置的',
|
|
80
|
+
pThreshold: '触发阈值',
|
|
81
|
+
pThresholdHint: '达到上下文窗口的这一比例即自动压缩',
|
|
82
|
+
pRetain: '保留尾部',
|
|
83
|
+
pRetainHint: '压缩时原样保留的最近内容比例',
|
|
84
|
+
pGap: '可压缩空间',
|
|
85
|
+
pGapWarn: '触发点与保留尾部之间空隙太小,摘要无法比被压缩的内容更短:压缩会被拒绝,门限会反复触发。建议至少留 8K。',
|
|
86
|
+
pSummary: '压缩用模型',
|
|
87
|
+
pFallback: '模型回退链',
|
|
88
|
+
pFallbackHint: '主模型失败时按顺序尝试,依次消耗更强/更弱的免费额度,最后才用收费模型',
|
|
89
|
+
pFallbackNone: '无(主模型失败即报错)',
|
|
90
|
+
pEffort: '压缩思考等级',
|
|
91
|
+
pEffortHint: '摘要只是对已有上下文做机械压缩,不需要思考',
|
|
92
|
+
pEffortFixed: '不思考(写死)',
|
|
93
|
+
pMaxTokens: '摘要上限',
|
|
94
|
+
pMaxTokensUnit: 'tokens',
|
|
95
|
+
pWindow: '上下文窗口',
|
|
96
|
+
pWindowUnknown: '会话尚未报告窗口(还没发过请求)',
|
|
97
|
+
pTriggerAt: '约在',
|
|
98
|
+
pAuto: '自动压缩',
|
|
99
|
+
pOn: '开',
|
|
100
|
+
pOff: '关',
|
|
101
|
+
pOffHint: '自动压缩已关闭,超长会话会直接撞上模型窗口。',
|
|
102
|
+
pUnits: 'tokens',
|
|
103
|
+
pModelAuto: 'auto(沿用本会话模型)',
|
|
104
|
+
pTarget: '适用路由',
|
|
105
|
+
pTargetNone: '本会话还没确定路由,按全局默认显示',
|
|
106
|
+
pEdit: '改这里:设置 → 模型 → 压缩策略,或直接编辑 settings.yaml。',
|
|
107
|
+
// ── 最近一次压缩:谁做的、哪条路由写的 ────────────────────────
|
|
108
|
+
lastSummary: '最近摘要',
|
|
109
|
+
lastSummaryNone: '还没有压缩过',
|
|
110
|
+
lastSummaryHint: '最近一次压缩实际用来写摘要的路由——回退链成功后会改成真正写成功的那条,和策略里配置的那条可能不是同一个。',
|
|
111
|
+
lastManual: '手动',
|
|
112
|
+
lastAuto: '自动',
|
|
113
|
+
lastCount: '压缩了',
|
|
114
|
+
lastTokens: 'tokens',
|
|
115
|
+
};
|
|
116
|
+
const en = {
|
|
117
|
+
title: 'Compaction policy',
|
|
118
|
+
hint: 'Compact once the session reaches this fraction of the context window — or type a whole token count (1 or more). Blank inherits the deployment default.',
|
|
119
|
+
threshold: 'Threshold',
|
|
120
|
+
retain: 'Retain',
|
|
121
|
+
maxTokens: 'Summary cap',
|
|
122
|
+
model: 'Summarization model',
|
|
123
|
+
auto: 'auto (reuse the conversation model)',
|
|
124
|
+
reset: 'Reset',
|
|
125
|
+
save: 'Save',
|
|
126
|
+
invalid: 'Enter a ratio between 0 and 1, or a whole number of tokens (1 or more)',
|
|
127
|
+
retainAbove: 'Retain must be below the threshold',
|
|
128
|
+
unavailable: 'Settings service unavailable; the policy comes from deployment config.',
|
|
129
|
+
memoryNote: 'This browser is not loopback (opened via a LAN address), so dsh gives it a memory-only view: it cannot read the host\'s effective policy and cannot save a change. The hint numbers below are plugin defaults, not your threshold — check the real value from the host at 127.0.0.1.',
|
|
130
|
+
writeRefused: 'The host refused the write: this browser is in memory mode, so changes are not saved.',
|
|
131
|
+
enable: 'Automatic compaction',
|
|
132
|
+
enableHint: 'When off, context is never compacted automatically and a long session runs into the model window.',
|
|
133
|
+
modelAuto: 'auto (reuse the conversation model)',
|
|
134
|
+
modelLoading: 'Reading the model list…',
|
|
135
|
+
modelEmpty: 'No model route is currently available, so only auto can be chosen.',
|
|
136
|
+
modelFailed: 'The model list could not be read, so only auto can be chosen.',
|
|
137
|
+
// ── Summarization fallback chain and reserve ──────────────────
|
|
138
|
+
headroom: 'Reserve (tokens)',
|
|
139
|
+
headroomHint: 'blank inherits the layer below',
|
|
140
|
+
fallback: 'Fallback chain',
|
|
141
|
+
fallbackOrder: 'Tried in order: strongest free → weaker free → paid. Empty means no retry.',
|
|
142
|
+
fallbackNone: 'No fallback route yet. A failing primary aborts the compaction.',
|
|
143
|
+
fallbackPick: 'Choose a route…',
|
|
144
|
+
fallbackAdd: 'Add',
|
|
145
|
+
fallbackRemove: 'Remove',
|
|
146
|
+
fallbackUp: 'Move up',
|
|
147
|
+
fallbackDown: 'Move down',
|
|
148
|
+
fallbackNoChoices: 'No further route can be added (not the primary, and no repeats).',
|
|
149
|
+
// ── Policy layers (global default / per provider / per model) ──
|
|
150
|
+
layer: 'Policy layer',
|
|
151
|
+
layerRemove: 'Remove this layer',
|
|
152
|
+
layerAdd: 'Add a per-provider override',
|
|
153
|
+
layerAddButton: 'Add',
|
|
154
|
+
layerAddHint: 'The fields below edit the selected layer; a blank field inherits the layer under it.',
|
|
155
|
+
layerRoute: 'Provider route id',
|
|
156
|
+
layerPick: 'Choose a provider…',
|
|
157
|
+
layerOther: 'Type a route id…',
|
|
158
|
+
// ── In-session policy indicator ──────────────────────────────
|
|
159
|
+
badgeOff: 'Compaction off',
|
|
160
|
+
badgeAria: 'Current compaction policy',
|
|
161
|
+
badgeTitle: 'Compaction policy for this session',
|
|
162
|
+
badgeUnknown: 'policy unreadable',
|
|
163
|
+
badgeUnknownHint: 'This browser cannot read the host policy (it is not loopback, so dsh gives it a memory-only view), so the badge stops guessing numbers. Check the real threshold from the host at 127.0.0.1.',
|
|
164
|
+
pEffective: 'Effective',
|
|
165
|
+
pLayerDefault: 'Global default',
|
|
166
|
+
pLayerProvider: 'Per provider',
|
|
167
|
+
pLayerModel: 'Per model',
|
|
168
|
+
pLayerEngine: 'Engine default (no layer sets it)',
|
|
169
|
+
pUser: 'yours',
|
|
170
|
+
pThreshold: 'Threshold',
|
|
171
|
+
pThresholdHint: 'Compact once the context reaches this share of the window',
|
|
172
|
+
pRetain: 'Retained tail',
|
|
173
|
+
pRetainHint: 'Recent content kept verbatim across a compaction',
|
|
174
|
+
pGap: 'Compactable room',
|
|
175
|
+
pGapWarn: 'Too little room between the trigger and the retained tail for a summary to be shorter than the region it replaces: the compaction would be rejected and the trigger would fire again. Leave at least 8K.',
|
|
176
|
+
pSummary: 'Summarization model',
|
|
177
|
+
pFallback: 'Model fallback chain',
|
|
178
|
+
pFallbackHint: 'tried in order when the primary fails, spending free quota before paid credit',
|
|
179
|
+
pFallbackNone: 'none (a failing primary aborts the compaction)',
|
|
180
|
+
pEffort: 'Summarization thinking',
|
|
181
|
+
pEffortHint: 'the summary only compresses text already in context, so it need not think',
|
|
182
|
+
pEffortFixed: 'off (fixed)',
|
|
183
|
+
pMaxTokens: 'Summary cap',
|
|
184
|
+
pMaxTokensUnit: 'tokens',
|
|
185
|
+
pWindow: 'Context window',
|
|
186
|
+
pWindowUnknown: 'this session has not reported a window yet (no request sent)',
|
|
187
|
+
pTriggerAt: 'fires at',
|
|
188
|
+
pAuto: 'Automatic compaction',
|
|
189
|
+
pOn: 'on',
|
|
190
|
+
pOff: 'off',
|
|
191
|
+
pOffHint: 'Automatic compaction is off; a long session will run into the model window.',
|
|
192
|
+
pUnits: 'tokens',
|
|
193
|
+
pModelAuto: 'auto (reuse this session’s model)',
|
|
194
|
+
pTarget: 'Applies to',
|
|
195
|
+
pTargetNone: 'no route known for this session yet; showing the global default',
|
|
196
|
+
pEdit: 'Edit it in Settings → Models → Compaction policy, or in settings.yaml.',
|
|
197
|
+
// ── The last compaction: who did it, which route wrote it ──────
|
|
198
|
+
lastSummary: 'Last summary',
|
|
199
|
+
lastSummaryNone: 'no compaction yet',
|
|
200
|
+
lastSummaryHint: 'the route that actually wrote the most recent summary — once the fallback chain succeeds it is the route that won, which need not be the one the policy names.',
|
|
201
|
+
lastManual: 'manual',
|
|
202
|
+
lastAuto: 'automatic',
|
|
203
|
+
lastCount: 'compacted',
|
|
204
|
+
lastTokens: 'tokens',
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Shared config-card kit (`cc*` classes) — the plugin-form layout vocabulary
|
|
209
|
+
* for settings pages, expressed only in `--dsw-alias-*` theme tokens.
|
|
210
|
+
*
|
|
211
|
+
* Provenance: grown inside dsh-compaction-policy-engine's card, promoted to the
|
|
212
|
+
* shared standard (WorkSpaces/ui-unification-plan-2026-10-26.md). This exact
|
|
213
|
+
* text is vendored into every hand-written client that renders a config
|
|
214
|
+
* card; `plugin-devkit/ui-kit/check.mjs` fails when a copy drifts. The
|
|
215
|
+
* injector is idempotent on the shared `data-plugin-css="dsh-ui-kit"` id, so
|
|
216
|
+
* the first client to boot owns the single <style> tag and the rest no-op —
|
|
217
|
+
* no plugin may grow a runtime dependency on another plugin's stylesheet.
|
|
218
|
+
*/
|
|
219
|
+
const UI_KIT_CSS = [
|
|
220
|
+
'.ccWrap{display:flex;flex-direction:column;gap:8px;padding:12px 0}',
|
|
221
|
+
'.ccTitle{color:var(--dsw-alias-label-primary);font-size:13px;font-weight:500}',
|
|
222
|
+
'.ccHint{color:var(--dsw-alias-label-tertiary);margin:0;font-size:12px;line-height:1.5}',
|
|
223
|
+
'.ccRow{display:flex;align-items:center;gap:10px}',
|
|
224
|
+
'.ccLabel{color:var(--dsw-alias-label-secondary);flex:1;font-size:13px}',
|
|
225
|
+
'.ccInput{border:.5px solid var(--dsw-alias-border-l4);background:var(--dsw-alias-bg-layer-3);height:32px;font:inherit;color:var(--dsw-alias-label-primary);border-radius:8px;padding:0 10px;width:104px;font-size:13px;font-variant-numeric:tabular-nums}',
|
|
226
|
+
'.ccInput:focus-visible{border-color:var(--dsw-alias-brand-primary);outline:none}',
|
|
227
|
+
'.ccInputInvalid{border-color:var(--dsw-alias-label-error)}',
|
|
228
|
+
'.ccInputWide{width:170px}',
|
|
229
|
+
'.ccReset{font:inherit;color:var(--dsw-alias-label-secondary);cursor:pointer;background:0 0;border:none;padding:0;font-size:12px}',
|
|
230
|
+
'.ccReset:hover:not(:disabled){color:var(--dsw-alias-label-primary)}',
|
|
231
|
+
'.ccReset:disabled{cursor:default;opacity:.5}',
|
|
232
|
+
'.ccError{color:var(--dsw-alias-label-error);margin:0;font-size:12px}',
|
|
233
|
+
'.ccReadonly{color:var(--dsw-alias-label-secondary);font-size:13px}',
|
|
234
|
+
'.ccSelect{border:.5px solid var(--dsw-alias-border-l4);background:var(--dsw-alias-bg-layer-3);height:32px;font:inherit;color:var(--dsw-alias-label-primary);border-radius:8px;padding:0 8px;max-width:240px;font-size:13px;cursor:pointer}',
|
|
235
|
+
'.ccSelect:focus-visible{border-color:var(--dsw-alias-brand-primary);outline:none}',
|
|
236
|
+
'.ccSelect:disabled{cursor:default;opacity:.6}',
|
|
237
|
+
'.ccCheck{width:16px;height:16px;accent-color:var(--dsw-alias-brand-primary);cursor:pointer;flex:none;margin:0}',
|
|
238
|
+
'.ccSubHint{color:var(--dsw-alias-label-tertiary);margin:0;font-size:12px;line-height:1.5;padding-left:26px}',
|
|
239
|
+
'.ccList{margin:0;padding-left:1.2em;max-height:9em;overflow:auto;color:var(--dsw-alias-label-secondary);font-size:12px;line-height:1.5}',
|
|
240
|
+
// 回退链是一张有序表,缩进让它读起来像“主模型之下的第 1、2、3 选择”,
|
|
241
|
+
// 而不是一组与阈值平级的设置。
|
|
242
|
+
'.ccChain{display:flex;flex-direction:column;gap:6px;border-left:2px solid var(--dsw-alias-border-l4);padding-left:10px;margin:4px 0}',
|
|
243
|
+
'.ccChainRow{gap:8px}',
|
|
244
|
+
'.ccChainIndex{color:var(--dsw-alias-label-tertiary);font-size:12px;min-width:14px}',
|
|
245
|
+
'.ccChainValue{flex:1;font-size:13px;color:var(--dsw-alias-label-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
|
|
246
|
+
].join('');
|
|
247
|
+
|
|
248
|
+
if (
|
|
249
|
+
typeof document !== 'undefined' &&
|
|
250
|
+
document.querySelector('style[data-plugin-css="dsh-ui-kit"]') === null
|
|
251
|
+
) {
|
|
252
|
+
const uiKitTag = document.createElement('style');
|
|
253
|
+
uiKitTag.dataset.pluginCss = 'dsh-ui-kit';
|
|
254
|
+
uiKitTag.textContent = UI_KIT_CSS;
|
|
255
|
+
document.head.appendChild(uiKitTag);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Session-header badge and flyout — compaction-specific surfaces, stay with this plugin. */
|
|
259
|
+
const css = [
|
|
260
|
+
// ── 会话头部指示器 ────────────────────────────────────────────
|
|
261
|
+
'.ccbRoot{display:inline-flex;position:relative;align-items:center}',
|
|
262
|
+
'.ccbBadge{display:inline-flex;align-items:center;gap:6px;height:26px;padding:0 9px;border-radius:999px;background:0 0;border:.5px solid var(--dsw-alias-border-l4);color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;line-height:1;cursor:pointer;white-space:nowrap;font-variant-numeric:tabular-nums}',
|
|
263
|
+
'.ccbBadge:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}',
|
|
264
|
+
'.ccbBadge:focus-visible{outline:none;border-color:var(--dsw-alias-brand-primary)}',
|
|
265
|
+
'.ccbDot{width:6px;height:6px;border-radius:999px;background:var(--dsw-alias-brand-primary);flex:none}',
|
|
266
|
+
'.ccbOff{background:var(--dsw-alias-label-tertiary)}',
|
|
267
|
+
'.ccbStrong{color:var(--dsw-alias-label-primary);font-weight:500}',
|
|
268
|
+
// The badge's second segment: the route that actually wrote the last
|
|
269
|
+
// summary. Muted and clipped, because it is the answer to a question the
|
|
270
|
+
// operator asks *after* a compaction, not the state they read every time
|
|
271
|
+
// they look up — the policy headline beside it stays the primary face.
|
|
272
|
+
'.ccbLast{color:var(--dsw-alias-label-tertiary);font-size:11px;max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
|
|
273
|
+
'.ccbPanel{position:absolute;top:calc(100% + 8px);right:0;z-index:100;box-sizing:border-box;width:286px;background:var(--dsw-specific-menu);--dsw-elevation-stroke-color:var(--dsw-alias-border-l1);box-shadow:var(--dsw-elevation-prominent);color:var(--dsw-alias-label-secondary);border:0;border-radius:12px;padding:12px;font-size:12px;line-height:18px;text-align:left}',
|
|
274
|
+
'.ccbTitle{margin:0 0 2px;color:var(--dsw-alias-label-primary);font-size:12px;font-weight:500}',
|
|
275
|
+
'.ccbTarget{margin:0 0 10px;color:var(--dsw-alias-label-tertiary);font-size:11px;word-break:break-all}',
|
|
276
|
+
'.ccbRows{margin:0;display:flex;flex-direction:column;gap:6px}',
|
|
277
|
+
'.ccbRow{display:flex;align-items:baseline;gap:8px}',
|
|
278
|
+
'.ccbKey{color:var(--dsw-alias-label-secondary);flex:none;min-width:78px}',
|
|
279
|
+
'.ccbVal{margin-left:auto;color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums;text-align:right}',
|
|
280
|
+
'.ccbHint{color:var(--dsw-alias-label-tertiary);font-size:11px;margin:0}',
|
|
281
|
+
'.ccbSrc{color:var(--dsw-alias-label-tertiary);font-size:11px}',
|
|
282
|
+
'.ccbWarn{color:var(--dsw-alias-label-error);margin:8px 0 0;font-size:11px}',
|
|
283
|
+
'.ccbFoot{margin:10px 0 0;color:var(--dsw-alias-label-tertiary);font-size:11px;line-height:1.5}',
|
|
284
|
+
].join('');
|
|
285
|
+
|
|
286
|
+
if (
|
|
287
|
+
typeof document !== 'undefined' &&
|
|
288
|
+
document.querySelector('style[data-plugin-css="dsh-compaction-policy-engine"]') === null
|
|
289
|
+
) {
|
|
290
|
+
const tag = document.createElement('style');
|
|
291
|
+
tag.dataset.plugin = 'dsh-compaction-policy-engine';
|
|
292
|
+
tag.dataset.pluginCss = 'dsh-compaction-policy-engine';
|
|
293
|
+
tag.textContent = css;
|
|
294
|
+
document.head.appendChild(tag);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Whether a staged budget is neither a ratio in (0, 1) nor a whole token
|
|
299
|
+
* count. Blank means "inherit", which is always valid.
|
|
300
|
+
*
|
|
301
|
+
* The two units are told apart by shape rather than by a separate control:
|
|
302
|
+
* a value below 1 can only be a ratio, and a whole number of 1 or more can
|
|
303
|
+
* only be a token count. That keeps one input per setting — the same shape
|
|
304
|
+
* the setting has in `settings.yaml`.
|
|
305
|
+
*/
|
|
306
|
+
function budgetInvalid(text) {
|
|
307
|
+
if (text === '') return false;
|
|
308
|
+
const value = Number(text);
|
|
309
|
+
if (Number.isNaN(value)) return true;
|
|
310
|
+
if (value > 0 && value < 1) return false;
|
|
311
|
+
return !Number.isInteger(value) || value < 1;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** Which unit a staged value is written in. */
|
|
315
|
+
function unitOf(text) {
|
|
316
|
+
const value = Number(text);
|
|
317
|
+
return Number.isInteger(value) && value >= 1 ? 'tokens' : 'ratio';
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* One numeric policy field.
|
|
322
|
+
*
|
|
323
|
+
* Renders the effective value and whether the user layer overrides it,
|
|
324
|
+
* and reports edits upward. It never writes: the card owns the single
|
|
325
|
+
* commit point, so a half-typed number cannot reach the document.
|
|
326
|
+
*/
|
|
327
|
+
function RatioField(props) {
|
|
328
|
+
const { label, text, overridden, placeholder, invalid, disabled, onEdit, onReset, t } = props;
|
|
329
|
+
return jsx.jsxs('div', {
|
|
330
|
+
className: 'ccRow',
|
|
331
|
+
children: [
|
|
332
|
+
jsx.jsx('label', { className: 'ccLabel', children: label }),
|
|
333
|
+
overridden
|
|
334
|
+
? jsx.jsx('button', { type: 'button', className: 'ccReset', disabled, onClick: onReset, children: t('reset') })
|
|
335
|
+
: null,
|
|
336
|
+
jsx.jsx('input', {
|
|
337
|
+
className: invalid ? 'ccInput ccInputInvalid' : 'ccInput',
|
|
338
|
+
inputMode: 'decimal',
|
|
339
|
+
value: text,
|
|
340
|
+
placeholder: placeholder,
|
|
341
|
+
disabled,
|
|
342
|
+
'aria-label': label,
|
|
343
|
+
onChange: (event) => onEdit(event.target.value),
|
|
344
|
+
}),
|
|
345
|
+
],
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* Every key a policy layer can carry.
|
|
351
|
+
*
|
|
352
|
+
* Used by "remove this layer": the settings document has no
|
|
353
|
+
* "delete this mapping" op, so removing a layer means unsetting each of
|
|
354
|
+
* its fields. Listing them here — rather than only the fields this card
|
|
355
|
+
* renders — is what makes the button mean what it says for a layer
|
|
356
|
+
* hand-written with `compactionRetries` and the like.
|
|
357
|
+
*/
|
|
358
|
+
const LAYER_KEYS = [
|
|
359
|
+
'threshold',
|
|
360
|
+
'thresholdTokens',
|
|
361
|
+
'retain',
|
|
362
|
+
'retainTokens',
|
|
363
|
+
'headroomTokens',
|
|
364
|
+
'maxTokens',
|
|
365
|
+
'summarizationModel',
|
|
366
|
+
'summarizationFallback',
|
|
367
|
+
'compactionRetries',
|
|
368
|
+
'maxOverflowRetries',
|
|
369
|
+
];
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* The compaction policy card: the three override layers (global / per-provider /
|
|
373
|
+
* per-model), each editable in either unit, with the effective value per routed
|
|
374
|
+
* model shown as the host would resolve it.
|
|
375
|
+
*/
|
|
376
|
+
function CompactionCard(props) {
|
|
377
|
+
const { t, provider, useScope, useCatalog } = props;
|
|
378
|
+
const snapshot = useScope((value) => value);
|
|
379
|
+
const catalog = useCatalog();
|
|
380
|
+
const [draft, setDraft] = react.useState({});
|
|
381
|
+
const [error, setError] = react.useState(null);
|
|
382
|
+
/**
|
|
383
|
+
* The layer the fields below edit; `null` is the global default.
|
|
384
|
+
*
|
|
385
|
+
* A `provider` prop, when the host ever supplies one, only picks the
|
|
386
|
+
* starting layer — the selector can still move away from it.
|
|
387
|
+
*/
|
|
388
|
+
const [layer, setLayer] = react.useState(provider?.id ?? null);
|
|
389
|
+
/** Routes added in this session that the document does not carry yet. */
|
|
390
|
+
const [added, setAdded] = react.useState([]);
|
|
391
|
+
/** The route staged in the add control. */
|
|
392
|
+
const [candidate, setCandidate] = react.useState('');
|
|
393
|
+
/** The fallback route staged in the chain's add control. */
|
|
394
|
+
const [candidateSelection, setCandidateSelection] = react.useState('');
|
|
395
|
+
|
|
396
|
+
const resolvedProviders = snapshot?.value?.providers ?? {};
|
|
397
|
+
const userProviders = snapshot?.user?.providers ?? {};
|
|
398
|
+
/** Every route with a layer, plus the ones added in this session. */
|
|
399
|
+
const routes = [...new Set([...Object.keys(resolvedProviders), ...Object.keys(userProviders), ...added])];
|
|
400
|
+
const userKeysOf = (id) => Object.keys(userProviders[id] ?? {});
|
|
401
|
+
|
|
402
|
+
const layerPath = layer === null ? ['default'] : ['providers', layer];
|
|
403
|
+
const resolved = (layer === null ? snapshot?.value?.default : resolvedProviders[layer]) ?? {};
|
|
404
|
+
const user = (layer === null ? snapshot?.user?.default : userProviders[layer]) ?? {};
|
|
405
|
+
/**
|
|
406
|
+
* What a cleared field falls back to: the composition's own document for
|
|
407
|
+
* this namespace (`base`) — where the deployment states
|
|
408
|
+
* `default.threshold`/`default.retain`.
|
|
409
|
+
*
|
|
410
|
+
* The hints used to be the plugin's schema defaults (0.8/0.16), which only
|
|
411
|
+
* apply to a host that declares nothing. On this host, which declares 0.6,
|
|
412
|
+
* they advertised a number nothing like the effective trigger while the
|
|
413
|
+
* card's own copy ("blank inherits the deployment default") made it read
|
|
414
|
+
* as the real one.
|
|
415
|
+
*/
|
|
416
|
+
const base = (layer === null ? snapshot?.base?.default : snapshot?.base?.providers?.[layer]) ?? {};
|
|
417
|
+
const baseText = (field, fallback) => {
|
|
418
|
+
const raw = base[`${field}Tokens`] ?? base[field];
|
|
419
|
+
return typeof raw === 'number' ? String(raw) : fallback;
|
|
420
|
+
};
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* A remote browser is a `memory` client: the host never gives it the
|
|
424
|
+
* settings document and never accepts a write from it — by design, since
|
|
425
|
+
* the config plane has no authentication. Saying so plainly is the
|
|
426
|
+
* difference between "your threshold is 0.8" and "this browser cannot see
|
|
427
|
+
* your threshold".
|
|
428
|
+
*/
|
|
429
|
+
const locked = snapshot?.mode === 'memory' || snapshot?.status === 'unavailable';
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Move to another layer, discarding staged edits.
|
|
433
|
+
*
|
|
434
|
+
* A draft belongs to the layer it was typed on; carrying it over
|
|
435
|
+
* would silently write one layer's number into another.
|
|
436
|
+
*/
|
|
437
|
+
const selectLayer = (next) => {
|
|
438
|
+
setDraft({});
|
|
439
|
+
setError(null);
|
|
440
|
+
setLayer(next);
|
|
441
|
+
};
|
|
442
|
+
|
|
443
|
+
const addLayer = (id) => {
|
|
444
|
+
const route = id.trim();
|
|
445
|
+
if (route === '') return;
|
|
446
|
+
if (!routes.includes(route)) setAdded((current) => [...current, route]);
|
|
447
|
+
setCandidate('');
|
|
448
|
+
selectLayer(route);
|
|
449
|
+
};
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* Remove the selected route layer from the user document.
|
|
453
|
+
*
|
|
454
|
+
* Only the user layer: a route the *composition* declares stays, and
|
|
455
|
+
* the card then shows its inherited values again — which is the
|
|
456
|
+
* point of the button, not a failure.
|
|
457
|
+
*/
|
|
458
|
+
const removeLayer = async () => {
|
|
459
|
+
if (layer === null) return;
|
|
460
|
+
setError(null);
|
|
461
|
+
const ops = LAYER_KEYS.map((key) => ({ op: 'unset', path: [...layerPath, key] }));
|
|
462
|
+
try {
|
|
463
|
+
if (!(await props.mutate(ops))) throw new Error(t('writeRefused'));
|
|
464
|
+
setDraft({});
|
|
465
|
+
setAdded((current) => current.filter((entry) => entry !== layer));
|
|
466
|
+
setLayer(null);
|
|
467
|
+
} catch (failure) {
|
|
468
|
+
setError(failure?.message ?? String(failure));
|
|
469
|
+
}
|
|
470
|
+
};
|
|
471
|
+
|
|
472
|
+
/**
|
|
473
|
+
* The two keys one budget field can be stored under.
|
|
474
|
+
*
|
|
475
|
+
* A layer states a budget in one unit only — a ratio or an absolute
|
|
476
|
+
* token count — so an edit that changes the unit has to remove the
|
|
477
|
+
* form it replaces in the same commit. That keeps the file honest;
|
|
478
|
+
* the *merged* document can still carry both, because the settings
|
|
479
|
+
* provider overlays the user section on the composition base.
|
|
480
|
+
*/
|
|
481
|
+
const formsOf = (field) => [field, `${field}Tokens`];
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* Effective text for a field: the draft wins, then the resolved layer.
|
|
485
|
+
*
|
|
486
|
+
* Within a layer the token form is the effective one, matching the
|
|
487
|
+
* host's own precedence (`pickForm`) — so the number the card shows is
|
|
488
|
+
* the number the engine acts on even when the composition base left a
|
|
489
|
+
* ratio of the same setting in the merged document.
|
|
490
|
+
*/
|
|
491
|
+
const textOf = (field) => {
|
|
492
|
+
if (draft[field] !== undefined) return draft[field];
|
|
493
|
+
const raw = resolved[`${field}Tokens`] ?? resolved[field];
|
|
494
|
+
return typeof raw === 'number' ? String(raw) : '';
|
|
495
|
+
};
|
|
496
|
+
|
|
497
|
+
/** Whether the user layer overrides this field in either unit. */
|
|
498
|
+
const overriddenOf = (field) => formsOf(field).some((key) => user[key] !== undefined);
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* Move one chain entry one position, returning a new array.
|
|
502
|
+
*
|
|
503
|
+
* The chain's order *is* its meaning — strongest free first, paid last —
|
|
504
|
+
* so reordering has to be a first-class edit rather than "remove and
|
|
505
|
+
* re-add", which would also silently move the entry to the weakest slot.
|
|
506
|
+
*
|
|
507
|
+
* @param entries - the current chain.
|
|
508
|
+
* @param index - the entry to move.
|
|
509
|
+
* @param delta - -1 for one step earlier, +1 for one step later.
|
|
510
|
+
* @returns the reordered chain.
|
|
511
|
+
*/
|
|
512
|
+
const moveIn = (entries, index, delta) => {
|
|
513
|
+
const next = [...entries];
|
|
514
|
+
const [moved] = next.splice(index, 1);
|
|
515
|
+
next.splice(index + delta, 0, moved);
|
|
516
|
+
return next;
|
|
517
|
+
};
|
|
518
|
+
|
|
519
|
+
const thresholdInvalid = budgetInvalid(textOf('threshold'));
|
|
520
|
+
const retainInvalid = budgetInvalid(textOf('retain'));
|
|
521
|
+
// Only comparable within one unit: 200000 and 0.2 are not ordered by
|
|
522
|
+
// magnitude, so a mixed pair is left for the host, which compares them
|
|
523
|
+
// in tokens once it has the window.
|
|
524
|
+
const ordering =
|
|
525
|
+
!thresholdInvalid &&
|
|
526
|
+
!retainInvalid &&
|
|
527
|
+
textOf('threshold') !== '' &&
|
|
528
|
+
textOf('retain') !== '' &&
|
|
529
|
+
unitOf(textOf('threshold')) === unitOf(textOf('retain')) &&
|
|
530
|
+
Number(textOf('retain')) >= Number(textOf('threshold'));
|
|
531
|
+
const blocked = thresholdInvalid || retainInvalid || ordering;
|
|
532
|
+
const dirty = Object.keys(draft).length > 0;
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* Commit staged edits.
|
|
536
|
+
*
|
|
537
|
+
* One `mutate` rather than per-field writes, for two reasons: clearing
|
|
538
|
+
* an override must *remove* the key rather than write a value the user
|
|
539
|
+
* never chose, and a threshold change that also moves `retain` must
|
|
540
|
+
* land atomically — otherwise the intermediate document is one the
|
|
541
|
+
* host resolver rejects.
|
|
542
|
+
*/
|
|
543
|
+
const commit = async () => {
|
|
544
|
+
if (blocked) return;
|
|
545
|
+
const ops = [];
|
|
546
|
+
for (const field of ['threshold', 'retain']) {
|
|
547
|
+
const text = draft[field];
|
|
548
|
+
if (text === undefined) continue;
|
|
549
|
+
const forms = formsOf(field);
|
|
550
|
+
const keep = text === '' ? undefined : unitOf(text) === 'tokens' ? forms[1] : forms[0];
|
|
551
|
+
for (const key of forms) {
|
|
552
|
+
if (key === keep) ops.push({ op: 'set', path: [...layerPath, key], value: Number(text) });
|
|
553
|
+
// The other unit is removed even when this layer does not
|
|
554
|
+
// currently state it: it may come from the composition base,
|
|
555
|
+
// where leaving it would make the merged layer ambiguous.
|
|
556
|
+
else ops.push({ op: 'unset', path: [...layerPath, key] });
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
if (draft.maxTokens !== undefined) {
|
|
560
|
+
const text = draft.maxTokens;
|
|
561
|
+
if (text === '') ops.push({ op: 'unset', path: [...layerPath, 'maxTokens'] });
|
|
562
|
+
else ops.push({ op: 'set', path: [...layerPath, 'maxTokens'], value: Number(text) });
|
|
563
|
+
}
|
|
564
|
+
if (draft.headroomTokens !== undefined) {
|
|
565
|
+
const text = draft.headroomTokens;
|
|
566
|
+
// Blank removes the key rather than storing 0: 0 is a real policy
|
|
567
|
+
// ("no reserve"), while blank means "inherit the layer below".
|
|
568
|
+
if (text === '') ops.push({ op: 'unset', path: [...layerPath, 'headroomTokens'] });
|
|
569
|
+
else ops.push({ op: 'set', path: [...layerPath, 'headroomTokens'], value: Number(text) });
|
|
570
|
+
}
|
|
571
|
+
if (draft.summarizationModel !== undefined) {
|
|
572
|
+
// `auto` is a real stored value, not an absence: writing it back is
|
|
573
|
+
// what lets the user return to inheriting the conversation model
|
|
574
|
+
// without also losing the explicit override they had chosen before.
|
|
575
|
+
ops.push({ op: 'set', path: [...layerPath, 'summarizationModel'], value: draft.summarizationModel });
|
|
576
|
+
}
|
|
577
|
+
if (draft.summarizationFallback !== undefined) {
|
|
578
|
+
// An emptied chain is unset, not stored as `[]`: the host resolver
|
|
579
|
+
// treats a missing field as "no fallback" and an empty list the same,
|
|
580
|
+
// but leaving `[]` in the file would make the layer look like it
|
|
581
|
+
// overrides the chain when it means to inherit one.
|
|
582
|
+
if (draft.summarizationFallback.length === 0) ops.push({ op: 'unset', path: [...layerPath, 'summarizationFallback'] });
|
|
583
|
+
else ops.push({ op: 'set', path: [...layerPath, 'summarizationFallback'], value: [...draft.summarizationFallback] });
|
|
584
|
+
}
|
|
585
|
+
// The automatic-compaction switch is a *root* field shared by every
|
|
586
|
+
// layer, so it is written once at the document root rather than into
|
|
587
|
+
// the per-route layer the other rows edit.
|
|
588
|
+
if (draft.auto !== undefined) ops.push({ op: 'set', path: ['auto'], value: draft.auto });
|
|
589
|
+
if (ops.length === 0) return setDraft({});
|
|
590
|
+
setError(null);
|
|
591
|
+
try {
|
|
592
|
+
if (!(await props.mutate(ops))) throw new Error(t('writeRefused'));
|
|
593
|
+
setDraft({});
|
|
594
|
+
} catch (failure) {
|
|
595
|
+
setError(failure?.message ?? String(failure));
|
|
596
|
+
}
|
|
597
|
+
};
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* The fields that exist in two units, and so have two keys to clear.
|
|
601
|
+
*
|
|
602
|
+
* Only these may be expanded through `formsOf`. Applying it to every
|
|
603
|
+
* reset produced a bogus sibling for each single-unit field — resetting
|
|
604
|
+
* `maxTokens` also unset `maxTokensTokens`, and a chain reset would unset
|
|
605
|
+
* `summarizationFallbackTokens`. Unsetting a key that cannot exist is not
|
|
606
|
+
* harmless: it writes a path into the operator's document that the host
|
|
607
|
+
* resolver then has to reject or ignore.
|
|
608
|
+
*/
|
|
609
|
+
const UNIT_PAIRED = new Set(['threshold', 'retain']);
|
|
610
|
+
|
|
611
|
+
const resetField = async (field) => {
|
|
612
|
+
setError(null);
|
|
613
|
+
// Both units, because either may be the one this layer states.
|
|
614
|
+
const keys = UNIT_PAIRED.has(field) ? formsOf(field) : [field];
|
|
615
|
+
const ops = keys.map((key) => ({ op: 'unset', path: [...layerPath, key] }));
|
|
616
|
+
try {
|
|
617
|
+
if (!(await props.mutate(ops))) throw new Error(t('writeRefused'));
|
|
618
|
+
setDraft((current) => {
|
|
619
|
+
const next = { ...current };
|
|
620
|
+
delete next[field];
|
|
621
|
+
return next;
|
|
622
|
+
});
|
|
623
|
+
} catch (failure) {
|
|
624
|
+
setError(failure?.message ?? String(failure));
|
|
625
|
+
}
|
|
626
|
+
};
|
|
627
|
+
|
|
628
|
+
/**
|
|
629
|
+
* Edit the staged fallback chain.
|
|
630
|
+
*
|
|
631
|
+
* Staged rather than written: the chain is one array, so adding three
|
|
632
|
+
* routes should be one commit — three writes would put the document
|
|
633
|
+
* through two intermediate states, and each is a chain the host resolver
|
|
634
|
+
* could reject (a chain whose first entry is the primary route, say).
|
|
635
|
+
*
|
|
636
|
+
* @param change - receives the current chain, returns the next one.
|
|
637
|
+
*/
|
|
638
|
+
const editChain = (change) => setDraft((current) => ({ ...current, summarizationFallback: change(current.summarizationFallback ?? chain) }));
|
|
639
|
+
|
|
640
|
+
const model = resolved.summarizationModel;
|
|
641
|
+
// 与同组件的 chain / autoShown 一致:草稿优先,否则回读 resolved。
|
|
642
|
+
// 这样用户刚选中的值会立刻回显,且 resetField 删除草稿后仍会回到 resolved。
|
|
643
|
+
const modelText = draft.summarizationModel ?? (model === undefined || model === '' ? 'auto' : model);
|
|
644
|
+
/**
|
|
645
|
+
* The fallback chain shown in the editor: the draft while one is staged,
|
|
646
|
+
* otherwise the layer's resolved chain.
|
|
647
|
+
*
|
|
648
|
+
* Resolved (not just the user layer) so the row shows the chain this target
|
|
649
|
+
* will actually use, which is the whole point of showing it at all.
|
|
650
|
+
*/
|
|
651
|
+
const chain = draft.summarizationFallback ?? resolved.summarizationFallback ?? [];
|
|
652
|
+
const autoEnabled = snapshot?.value?.auto !== false;
|
|
653
|
+
const draftedAuto = draft.auto;
|
|
654
|
+
const autoShown = draftedAuto === undefined ? autoEnabled : draftedAuto;
|
|
655
|
+
|
|
656
|
+
/**
|
|
657
|
+
* The catalog's flat `provider/model` options.
|
|
658
|
+
*
|
|
659
|
+
* A group with no models still contributes its provider: an empty
|
|
660
|
+
* catalog is a route that can serve, and a route the user configured
|
|
661
|
+
* a summarization model for must not silently vanish from the list.
|
|
662
|
+
* The value's shape is the same one `policy.js` validates
|
|
663
|
+
* (`assertModelRef`), so the picker cannot produce a document the
|
|
664
|
+
* host rejects.
|
|
665
|
+
*/
|
|
666
|
+
const options = [];
|
|
667
|
+
for (const group of catalog?.groups ?? []) {
|
|
668
|
+
for (const entry of group.models ?? []) options.push({ value: `${group.id}/${entry.id}`, label: `${group.name} · ${entry.name}` });
|
|
669
|
+
if ((group.models ?? []).length === 0) options.push({ value: `${group.id}/`, label: group.name, disabled: true });
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
/**
|
|
673
|
+
* Routes the catalog knows that have no layer yet.
|
|
674
|
+
*
|
|
675
|
+
* The same catalog the model picker reads, so a route offered here
|
|
676
|
+
* is one this host can actually serve. While it is still loading —
|
|
677
|
+
* or when it cannot be read at all — the control falls back to a
|
|
678
|
+
* free-text id, because "the catalog failed" must not mean "you
|
|
679
|
+
* cannot configure a provider".
|
|
680
|
+
*/
|
|
681
|
+
const routeChoices = (catalog?.groups ?? [])
|
|
682
|
+
.map((group) => ({ id: group.id, label: group.name ?? group.id }))
|
|
683
|
+
.filter((choice) => !routes.includes(choice.id));
|
|
684
|
+
const stagedRoute = candidate.trim();
|
|
685
|
+
|
|
686
|
+
/**
|
|
687
|
+
* The route the primary summarization call will use, when this card can
|
|
688
|
+
* know it.
|
|
689
|
+
*
|
|
690
|
+
* An explicit `summarizationModel` names it outright. Under `auto` the
|
|
691
|
+
* primary is the *conversation's* routed model, which this settings card
|
|
692
|
+
* has no way to read — so the filter below is simply absent, and the host
|
|
693
|
+
* resolver stays the authority: it rejects a chain entry naming the
|
|
694
|
+
* resolved primary, and this card surfaces that as a save error. Hiding
|
|
695
|
+
* routes on a guess would be worse than letting the host speak.
|
|
696
|
+
*/
|
|
697
|
+
const primaryRoute = modelText === 'auto' ? undefined : modelText;
|
|
698
|
+
/** Catalog routes a chain entry may name: not the known primary, not already in the chain. */
|
|
699
|
+
const chainChoices = options.filter((option) => option.value !== primaryRoute && !chain.includes(option.value));
|
|
700
|
+
const stagedChainEntry = candidateSelection.trim();
|
|
701
|
+
const stagedChainValid =
|
|
702
|
+
stagedChainEntry.length > 0 && stagedChainEntry !== primaryRoute && !chain.includes(stagedChainEntry);
|
|
703
|
+
|
|
704
|
+
return jsx.jsxs('div', {
|
|
705
|
+
className: 'ccWrap',
|
|
706
|
+
children: [
|
|
707
|
+
jsx.jsx('span', { className: 'ccTitle', children: t('title') }),
|
|
708
|
+
jsx.jsx('p', { className: 'ccHint', children: t('hint') }),
|
|
709
|
+
locked ? jsx.jsx('p', { className: 'ccError', children: t('memoryNote') }) : null,
|
|
710
|
+
jsx.jsxs('div', {
|
|
711
|
+
className: 'ccRow',
|
|
712
|
+
children: [
|
|
713
|
+
jsx.jsx('input', {
|
|
714
|
+
type: 'checkbox',
|
|
715
|
+
className: 'ccCheck',
|
|
716
|
+
checked: autoShown,
|
|
717
|
+
'aria-label': t('enable'),
|
|
718
|
+
disabled: locked,
|
|
719
|
+
onChange: (event) => setDraft((current) => ({ ...current, auto: event.target.checked })),
|
|
720
|
+
}),
|
|
721
|
+
jsx.jsx('span', { className: 'ccLabel', children: t('enable') }),
|
|
722
|
+
],
|
|
723
|
+
}),
|
|
724
|
+
autoShown ? null : jsx.jsx('p', { className: 'ccSubHint', children: t('enableHint') }),
|
|
725
|
+
jsx.jsxs('div', {
|
|
726
|
+
className: 'ccRow',
|
|
727
|
+
children: [
|
|
728
|
+
jsx.jsx('span', { className: 'ccLabel', children: t('layer') }),
|
|
729
|
+
layer !== null && userKeysOf(layer).length > 0
|
|
730
|
+
? jsx.jsx('button', {
|
|
731
|
+
type: 'button',
|
|
732
|
+
className: 'ccReset',
|
|
733
|
+
onClick: () => void removeLayer(),
|
|
734
|
+
children: t('layerRemove'),
|
|
735
|
+
})
|
|
736
|
+
: null,
|
|
737
|
+
jsx.jsxs('select', {
|
|
738
|
+
className: 'ccSelect',
|
|
739
|
+
'aria-label': t('layer'),
|
|
740
|
+
value: layer ?? '',
|
|
741
|
+
onChange: (event) => selectLayer(event.target.value === '' ? null : event.target.value),
|
|
742
|
+
children: [
|
|
743
|
+
jsx.jsx('option', { value: '', children: t('pLayerDefault') }),
|
|
744
|
+
routes.map((id) =>
|
|
745
|
+
jsx.jsx(
|
|
746
|
+
'option',
|
|
747
|
+
{
|
|
748
|
+
value: id,
|
|
749
|
+
children: userKeysOf(id).length > 0 ? `${id} · ${t('pUser')}` : id,
|
|
750
|
+
},
|
|
751
|
+
id,
|
|
752
|
+
),
|
|
753
|
+
),
|
|
754
|
+
],
|
|
755
|
+
}),
|
|
756
|
+
],
|
|
757
|
+
}),
|
|
758
|
+
jsx.jsxs('div', {
|
|
759
|
+
className: 'ccRow',
|
|
760
|
+
children: [
|
|
761
|
+
jsx.jsx('span', { className: 'ccLabel', children: t('layerAdd') }),
|
|
762
|
+
routeChoices.length > 0
|
|
763
|
+
? jsx.jsxs('select', {
|
|
764
|
+
className: 'ccSelect',
|
|
765
|
+
'aria-label': t('layerAdd'),
|
|
766
|
+
value: '',
|
|
767
|
+
onChange: (event) => addLayer(event.target.value),
|
|
768
|
+
children: [
|
|
769
|
+
jsx.jsx('option', { value: '', children: t('layerPick') }),
|
|
770
|
+
routeChoices.map((choice) =>
|
|
771
|
+
jsx.jsx('option', { value: choice.id, children: choice.label }, choice.id),
|
|
772
|
+
),
|
|
773
|
+
],
|
|
774
|
+
})
|
|
775
|
+
: jsx.jsx('input', {
|
|
776
|
+
className: 'ccInput ccInputWide',
|
|
777
|
+
placeholder: t('layerRoute'),
|
|
778
|
+
value: candidate,
|
|
779
|
+
'aria-label': t('layerAdd'),
|
|
780
|
+
onChange: (event) => setCandidate(event.target.value),
|
|
781
|
+
}),
|
|
782
|
+
jsx.jsx('button', {
|
|
783
|
+
type: 'button',
|
|
784
|
+
className: 'ccReset',
|
|
785
|
+
disabled: stagedRoute === '',
|
|
786
|
+
onClick: () => addLayer(stagedRoute),
|
|
787
|
+
children: t('layerAddButton'),
|
|
788
|
+
}),
|
|
789
|
+
],
|
|
790
|
+
}),
|
|
791
|
+
jsx.jsx('p', { className: 'ccSubHint', children: t('layerAddHint') }),
|
|
792
|
+
jsx.jsx(RatioField, {
|
|
793
|
+
label: t('threshold'),
|
|
794
|
+
text: textOf('threshold'),
|
|
795
|
+
overridden: overriddenOf('threshold'),
|
|
796
|
+
placeholder: baseText('threshold', '0.8'),
|
|
797
|
+
disabled: locked,
|
|
798
|
+
invalid: thresholdInvalid,
|
|
799
|
+
onEdit: (text) => setDraft((current) => ({ ...current, threshold: text })),
|
|
800
|
+
onReset: () => void resetField('threshold'),
|
|
801
|
+
t,
|
|
802
|
+
}),
|
|
803
|
+
jsx.jsx(RatioField, {
|
|
804
|
+
label: t('retain'),
|
|
805
|
+
text: textOf('retain'),
|
|
806
|
+
overridden: overriddenOf('retain'),
|
|
807
|
+
placeholder: baseText('retain', '0.16'),
|
|
808
|
+
disabled: locked,
|
|
809
|
+
invalid: retainInvalid || ordering,
|
|
810
|
+
onEdit: (text) => setDraft((current) => ({ ...current, retain: text })),
|
|
811
|
+
onReset: () => void resetField('retain'),
|
|
812
|
+
t,
|
|
813
|
+
}),
|
|
814
|
+
jsx.jsx(RatioField, {
|
|
815
|
+
label: t('maxTokens'),
|
|
816
|
+
text: textOf('maxTokens'),
|
|
817
|
+
overridden: user.maxTokens !== undefined,
|
|
818
|
+
placeholder: baseText('maxTokens', '8192'),
|
|
819
|
+
disabled: locked,
|
|
820
|
+
invalid: false,
|
|
821
|
+
onEdit: (text) => setDraft((current) => ({ ...current, maxTokens: text })),
|
|
822
|
+
onReset: () => void resetField('maxTokens'),
|
|
823
|
+
t,
|
|
824
|
+
}),
|
|
825
|
+
jsx.jsx(RatioField, {
|
|
826
|
+
label: t('headroom'),
|
|
827
|
+
text: draft.headroomTokens ?? (typeof resolved.headroomTokens === 'number' ? String(resolved.headroomTokens) : ''),
|
|
828
|
+
overridden: user.headroomTokens !== undefined,
|
|
829
|
+
placeholder: t('headroomHint'),
|
|
830
|
+
disabled: locked,
|
|
831
|
+
invalid: draft.headroomTokens !== undefined && draft.headroomTokens !== '' && !/^\d+$/.test(draft.headroomTokens),
|
|
832
|
+
onEdit: (text) => setDraft((current) => ({ ...current, headroomTokens: text })),
|
|
833
|
+
onReset: () => void resetField('headroomTokens'),
|
|
834
|
+
t,
|
|
835
|
+
}),
|
|
836
|
+
jsx.jsxs('div', {
|
|
837
|
+
className: 'ccRow',
|
|
838
|
+
children: [
|
|
839
|
+
jsx.jsx('span', { className: 'ccLabel', children: t('model') }),
|
|
840
|
+
user.summarizationModel !== undefined
|
|
841
|
+
? jsx.jsx('button', { type: 'button', className: 'ccReset', onClick: () => void resetField('summarizationModel'), children: t('reset') })
|
|
842
|
+
: null,
|
|
843
|
+
jsx.jsxs('select', {
|
|
844
|
+
className: 'ccSelect',
|
|
845
|
+
'aria-label': t('model'),
|
|
846
|
+
disabled: locked,
|
|
847
|
+
value: modelText,
|
|
848
|
+
onChange: (event) => {
|
|
849
|
+
const value = event.target.value;
|
|
850
|
+
setDraft((current) => ({ ...current, summarizationModel: value }));
|
|
851
|
+
},
|
|
852
|
+
children: [
|
|
853
|
+
jsx.jsx('option', { value: 'auto', children: t('modelAuto') }),
|
|
854
|
+
options.map((option) =>
|
|
855
|
+
jsx.jsx('option', { value: option.value, disabled: option.disabled, children: option.label }, option.value),
|
|
856
|
+
),
|
|
857
|
+
// A stored model whose route has since disappeared must stay
|
|
858
|
+
// selectable, otherwise merely opening the card would look like
|
|
859
|
+
// an edit and saving would silently drop the operator's choice.
|
|
860
|
+
options.some((option) => option.value === modelText) || modelText === 'auto'
|
|
861
|
+
? null
|
|
862
|
+
: jsx.jsx('option', { value: modelText, children: `${modelText}(${t('modelEmpty')})` }),
|
|
863
|
+
],
|
|
864
|
+
}),
|
|
865
|
+
],
|
|
866
|
+
}),
|
|
867
|
+
catalog === undefined ? null : jsx.jsx('p', { className: 'ccSubHint', children: t('modelLoading') }),
|
|
868
|
+
// ── 摘要模型的 fallback 链 ────────────────────────────────
|
|
869
|
+
// 顺序即语义:从强到弱依次尝试,最强的免费大模型在前、收费的在后。
|
|
870
|
+
// 单向不可逆,所以每一行都给出上移/下移,而不是只让用户删了重加。
|
|
871
|
+
jsx.jsxs('div', {
|
|
872
|
+
className: 'ccChain',
|
|
873
|
+
children: [
|
|
874
|
+
jsx.jsxs('div', {
|
|
875
|
+
className: 'ccRow',
|
|
876
|
+
children: [
|
|
877
|
+
jsx.jsx('span', { className: 'ccLabel', children: t('fallback') }),
|
|
878
|
+
jsx.jsx('span', { className: 'ccSubHint', children: t('fallbackOrder') }),
|
|
879
|
+
user.summarizationFallback !== undefined
|
|
880
|
+
? jsx.jsx('button', { type: 'button', className: 'ccReset', onClick: () => void resetField('summarizationFallback'), children: t('reset') })
|
|
881
|
+
: null,
|
|
882
|
+
],
|
|
883
|
+
}),
|
|
884
|
+
chain.length === 0 ? jsx.jsx('p', { className: 'ccSubHint', children: t('fallbackNone') }) : null,
|
|
885
|
+
chain.map((entry, index) =>
|
|
886
|
+
jsx.jsxs(
|
|
887
|
+
'div',
|
|
888
|
+
{
|
|
889
|
+
className: 'ccRow ccChainRow',
|
|
890
|
+
children: [
|
|
891
|
+
jsx.jsx('span', { className: 'ccChainIndex', children: String(index + 1) }),
|
|
892
|
+
jsx.jsx('span', { className: 'ccChainValue', children: entry }),
|
|
893
|
+
jsx.jsx('button', {
|
|
894
|
+
type: 'button',
|
|
895
|
+
className: 'ccReset',
|
|
896
|
+
disabled: locked || index === 0,
|
|
897
|
+
'aria-label': t('fallbackUp'),
|
|
898
|
+
onClick: () => editChain((current) => moveIn(current, index, -1)),
|
|
899
|
+
children: '↑',
|
|
900
|
+
}),
|
|
901
|
+
jsx.jsx('button', {
|
|
902
|
+
type: 'button',
|
|
903
|
+
className: 'ccReset',
|
|
904
|
+
disabled: locked || index === chain.length - 1,
|
|
905
|
+
'aria-label': t('fallbackDown'),
|
|
906
|
+
onClick: () => editChain((current) => moveIn(current, index, 1)),
|
|
907
|
+
children: '↓',
|
|
908
|
+
}),
|
|
909
|
+
jsx.jsx('button', {
|
|
910
|
+
type: 'button',
|
|
911
|
+
className: 'ccReset',
|
|
912
|
+
disabled: locked,
|
|
913
|
+
'aria-label': t('fallbackRemove'),
|
|
914
|
+
onClick: () => editChain((current) => current.filter((_, position) => position !== index)),
|
|
915
|
+
children: t('fallbackRemove'),
|
|
916
|
+
}),
|
|
917
|
+
],
|
|
918
|
+
},
|
|
919
|
+
`${entry}-${index}`,
|
|
920
|
+
),
|
|
921
|
+
),
|
|
922
|
+
jsx.jsxs('div', {
|
|
923
|
+
className: 'ccRow',
|
|
924
|
+
children: [
|
|
925
|
+
jsx.jsxs('select', {
|
|
926
|
+
className: 'ccSelect',
|
|
927
|
+
'aria-label': t('fallbackAdd'),
|
|
928
|
+
disabled: locked || chainChoices.length === 0,
|
|
929
|
+
value: candidateSelection,
|
|
930
|
+
onChange: (event) => setCandidateSelection(event.target.value),
|
|
931
|
+
children: [
|
|
932
|
+
jsx.jsx('option', { value: '', children: t('fallbackPick') }),
|
|
933
|
+
chainChoices.map((option) =>
|
|
934
|
+
jsx.jsx('option', { value: option.value, children: option.label }, option.value),
|
|
935
|
+
),
|
|
936
|
+
],
|
|
937
|
+
}),
|
|
938
|
+
jsx.jsx('button', {
|
|
939
|
+
type: 'button',
|
|
940
|
+
className: 'ccReset',
|
|
941
|
+
disabled: locked || !stagedChainValid,
|
|
942
|
+
onClick: () => {
|
|
943
|
+
editChain((current) => [...current, stagedChainEntry]);
|
|
944
|
+
setCandidateSelection('');
|
|
945
|
+
},
|
|
946
|
+
children: t('fallbackAdd'),
|
|
947
|
+
}),
|
|
948
|
+
],
|
|
949
|
+
}),
|
|
950
|
+
chainChoices.length === 0 ? jsx.jsx('p', { className: 'ccSubHint', children: t('fallbackNoChoices') }) : null,
|
|
951
|
+
],
|
|
952
|
+
}),
|
|
953
|
+
thresholdInvalid || retainInvalid
|
|
954
|
+
? jsx.jsx('p', { className: 'ccError', children: t('invalid') })
|
|
955
|
+
: ordering
|
|
956
|
+
? jsx.jsx('p', { className: 'ccError', children: t('retainAbove') })
|
|
957
|
+
: null,
|
|
958
|
+
error === null ? null : jsx.jsx('p', { className: 'ccError', children: error }),
|
|
959
|
+
!dirty
|
|
960
|
+
? null
|
|
961
|
+
: jsx.jsx('button', {
|
|
962
|
+
type: 'button',
|
|
963
|
+
className: 'ccReset',
|
|
964
|
+
disabled: blocked || locked,
|
|
965
|
+
onClick: () => void commit(),
|
|
966
|
+
children: t('save'),
|
|
967
|
+
}),
|
|
968
|
+
],
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
// ── 会话头部指示器:当前会话正在跑什么压缩策略 ─────────────────────
|
|
973
|
+
//
|
|
974
|
+
// Inlined view of `lib/client-policy.js`: this file is served verbatim and
|
|
975
|
+
// cannot `import`. `test/client-policy.test.js` extracts these declarations and
|
|
976
|
+
// asserts they match the module AND agree with the host's `policy.js`, so this
|
|
977
|
+
// cannot silently drift from what the engine resolves.
|
|
978
|
+
|
|
979
|
+
/** The literal `auto` sentinel, meaning "inherit the conversation's own model". */
|
|
980
|
+
const AUTO = 'auto';
|
|
981
|
+
|
|
982
|
+
/** `compaction-basic`'s own default trigger ratio, shown when no layer states one. */
|
|
983
|
+
const ENGINE_DEFAULT_THRESHOLD = 0.8;
|
|
984
|
+
|
|
985
|
+
/** `compaction-basic`'s own default retention ratio. */
|
|
986
|
+
const ENGINE_DEFAULT_RETAIN = 0.16;
|
|
987
|
+
|
|
988
|
+
/**
|
|
989
|
+
* Minimum room a compaction must free, mirrored from the host's
|
|
990
|
+
* `policy.js` (which cannot be imported here — this bundle is served
|
|
991
|
+
* verbatim and has no module graph). The panel states the shortfall
|
|
992
|
+
* instead of leaving the operator to infer it from two numbers.
|
|
993
|
+
*/
|
|
994
|
+
const MIN_COMPACT_GAP_TOKENS = 8192;
|
|
995
|
+
|
|
996
|
+
function isPlainObject(value) {
|
|
997
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
function routeOf(modelSelection) {
|
|
1001
|
+
const candidate = modelSelection?.lastUsed ?? modelSelection?.next;
|
|
1002
|
+
if (!isPlainObject(candidate)) return undefined;
|
|
1003
|
+
const { provider, model } = candidate;
|
|
1004
|
+
if (typeof provider !== 'string' || provider.length === 0) return undefined;
|
|
1005
|
+
if (typeof model !== 'string' || model.length === 0) return undefined;
|
|
1006
|
+
return { provider, model };
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
function layersOf(value, user, target) {
|
|
1010
|
+
const override = Array.isArray(value?.models)
|
|
1011
|
+
? value.models.find((entry) => entry?.provider === target?.provider && entry?.model === target?.model)
|
|
1012
|
+
: undefined;
|
|
1013
|
+
const userOverride = Array.isArray(user?.models)
|
|
1014
|
+
? user.models.find((entry) => entry?.provider === target?.provider && entry?.model === target?.model)
|
|
1015
|
+
: undefined;
|
|
1016
|
+
const routeName = target?.provider;
|
|
1017
|
+
const route = routeName === undefined ? undefined : value?.providers?.[routeName];
|
|
1018
|
+
const userRoute = routeName === undefined ? undefined : user?.providers?.[routeName];
|
|
1019
|
+
return {
|
|
1020
|
+
routeName,
|
|
1021
|
+
layers: [
|
|
1022
|
+
{ kind: 'model', layer: override, user: userOverride !== undefined },
|
|
1023
|
+
{ kind: 'provider', layer: route, user: userRoute !== undefined },
|
|
1024
|
+
{ kind: 'default', layer: value?.default, user: user?.default !== undefined },
|
|
1025
|
+
],
|
|
1026
|
+
};
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
function resolveView(value, user, target) {
|
|
1030
|
+
const { routeName, layers } = layersOf(value, user, target);
|
|
1031
|
+
const pick = (field) => {
|
|
1032
|
+
for (const candidate of layers) {
|
|
1033
|
+
const declared = candidate.layer?.[field];
|
|
1034
|
+
if (declared !== undefined) {
|
|
1035
|
+
return { value: declared, source: candidate.kind, overridden: candidate.user };
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
return { value: undefined, source: 'engine', overridden: false };
|
|
1039
|
+
};
|
|
1040
|
+
/** The winning declaration of a field that may be stated in either unit. */
|
|
1041
|
+
const pickForm = (ratioKey, tokensKey) => {
|
|
1042
|
+
for (const candidate of layers) {
|
|
1043
|
+
const layer = candidate.layer;
|
|
1044
|
+
if (layer === undefined) continue;
|
|
1045
|
+
if (layer[tokensKey] !== undefined) {
|
|
1046
|
+
return { value: layer[tokensKey], unit: 'tokens', source: candidate.kind, overridden: candidate.user };
|
|
1047
|
+
}
|
|
1048
|
+
if (layer[ratioKey] !== undefined) {
|
|
1049
|
+
return { value: layer[ratioKey], unit: 'ratio', source: candidate.kind, overridden: candidate.user };
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
return { value: undefined, unit: 'ratio', source: 'engine', overridden: false };
|
|
1053
|
+
};
|
|
1054
|
+
|
|
1055
|
+
const threshold = pickForm('threshold', 'thresholdTokens');
|
|
1056
|
+
const retain = pickForm('retain', 'retainTokens');
|
|
1057
|
+
const maxTokens = pick('maxTokens');
|
|
1058
|
+
const summarization = pick('summarizationModel');
|
|
1059
|
+
const fallback = pick('summarizationFallback');
|
|
1060
|
+
// Its own field, not a second name for the derived `gapTokens` below: this is
|
|
1061
|
+
// the engine's reserve *below the threshold*, and an operator who set it needs
|
|
1062
|
+
// to see it. The gap is computed from the two budgets and means something else
|
|
1063
|
+
// entirely, which is why the derived one was renamed.
|
|
1064
|
+
const headroom = pick('headroomTokens');
|
|
1065
|
+
|
|
1066
|
+
return {
|
|
1067
|
+
target,
|
|
1068
|
+
routeName,
|
|
1069
|
+
auto: value?.auto !== false,
|
|
1070
|
+
thresholdRatio: threshold.unit === 'ratio' ? threshold.value : undefined,
|
|
1071
|
+
retainRatio: retain.unit === 'ratio' ? retain.value : undefined,
|
|
1072
|
+
thresholdTokens: threshold.unit === 'tokens' ? threshold.value : undefined,
|
|
1073
|
+
retainTokens: retain.unit === 'tokens' ? retain.value : undefined,
|
|
1074
|
+
/** The winning declarations themselves, units included. */
|
|
1075
|
+
declared: { threshold, retain },
|
|
1076
|
+
maxTokens: maxTokens.value,
|
|
1077
|
+
summarizationModel: summarization.value ?? AUTO,
|
|
1078
|
+
/** The winning layer's ordered chain, or empty when no layer states one. */
|
|
1079
|
+
summarizationFallback: fallback.value ?? [],
|
|
1080
|
+
headroomTokens: headroom.value,
|
|
1081
|
+
source: {
|
|
1082
|
+
threshold: threshold.source,
|
|
1083
|
+
retain: retain.source,
|
|
1084
|
+
maxTokens: maxTokens.source,
|
|
1085
|
+
summarizationModel: summarization.source,
|
|
1086
|
+
summarizationFallback: fallback.source,
|
|
1087
|
+
headroomTokens: headroom.source,
|
|
1088
|
+
},
|
|
1089
|
+
/** Per-field provenance, including whether the user layer stated it. */
|
|
1090
|
+
fields: {
|
|
1091
|
+
threshold,
|
|
1092
|
+
retain,
|
|
1093
|
+
maxTokens,
|
|
1094
|
+
summarizationModel: summarization,
|
|
1095
|
+
summarizationFallback: fallback,
|
|
1096
|
+
headroomTokens: headroom,
|
|
1097
|
+
},
|
|
1098
|
+
/** Whether any layer for this target came from the user document. */
|
|
1099
|
+
overridden: layers.some((candidate) => candidate.user),
|
|
1100
|
+
};
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
function budgetsOf(view, contextWindow) {
|
|
1104
|
+
const window = typeof contextWindow === 'number' && Number.isFinite(contextWindow) ? contextWindow : undefined;
|
|
1105
|
+
const tokensOf = (absolute, ratio, fallbackRatio) => {
|
|
1106
|
+
if (typeof absolute === 'number') return absolute;
|
|
1107
|
+
if (window === undefined) return null;
|
|
1108
|
+
const effective = typeof ratio === 'number' ? ratio : fallbackRatio;
|
|
1109
|
+
return Math.floor(window * effective);
|
|
1110
|
+
};
|
|
1111
|
+
const thresholdTokens = tokensOf(view.thresholdTokens, view.thresholdRatio, ENGINE_DEFAULT_THRESHOLD);
|
|
1112
|
+
const retainTokens = tokensOf(view.retainTokens, view.retainRatio, ENGINE_DEFAULT_RETAIN);
|
|
1113
|
+
return {
|
|
1114
|
+
thresholdTokens,
|
|
1115
|
+
retainTokens,
|
|
1116
|
+
/**
|
|
1117
|
+
* What a compaction would free. Below `MIN_COMPACT_GAP_TOKENS` the summary can
|
|
1118
|
+
* end up no smaller than what it replaces, so the view says so.
|
|
1119
|
+
*
|
|
1120
|
+
* Named `gapTokens`, not `headroomTokens`: the engine's own `headroomTokens` is
|
|
1121
|
+
* the reserve *below the threshold* and is a configurable knob, so sharing the
|
|
1122
|
+
* name would make the panel's derived number indistinguishable from a setting.
|
|
1123
|
+
*/
|
|
1124
|
+
gapTokens: thresholdTokens === null || retainTokens === null ? null : thresholdTokens - retainTokens,
|
|
1125
|
+
};
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
/** Count tokens the way the conversation's own meter does (K / M). */
|
|
1129
|
+
function tokenText(value) {
|
|
1130
|
+
if (value === null || value === undefined) return '—';
|
|
1131
|
+
if (value < 1000) return String(value);
|
|
1132
|
+
const scaled = (candidate) => (candidate >= 100 ? String(Math.round(candidate)) : String(Math.round(candidate * 10) / 10));
|
|
1133
|
+
if (value < 1e6) return `${scaled(value / 1e3)}K`;
|
|
1134
|
+
return `${scaled(value / 1e6)}M`;
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
/** `0.2` → `20%`, without trailing zeroes. */
|
|
1138
|
+
function ratioText(ratio) {
|
|
1139
|
+
if (typeof ratio !== 'number') return null;
|
|
1140
|
+
return `${Math.round(ratio * 1000) / 10}%`;
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
/** Panel copy for one policy field's winning layer. */
|
|
1144
|
+
function layerText(t, source, overridden) {
|
|
1145
|
+
const name =
|
|
1146
|
+
source === 'model'
|
|
1147
|
+
? t('pLayerModel')
|
|
1148
|
+
: source === 'provider'
|
|
1149
|
+
? t('pLayerProvider')
|
|
1150
|
+
: source === 'default'
|
|
1151
|
+
? t('pLayerDefault')
|
|
1152
|
+
: t('pLayerEngine');
|
|
1153
|
+
return overridden ? `${name} · ${t('pUser')}` : name;
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
/**
|
|
1157
|
+
* One panel row: label, effective value, and the layer that produced it.
|
|
1158
|
+
*
|
|
1159
|
+
* @param props - row content; `hint` renders under the label as the
|
|
1160
|
+
* explanation, `unit` as a muted suffix on the value.
|
|
1161
|
+
*/
|
|
1162
|
+
function PolicyRow(props) {
|
|
1163
|
+
const { label, value, source, hint, unit, t } = props;
|
|
1164
|
+
return jsx.jsxs('div', {
|
|
1165
|
+
className: 'ccbRow',
|
|
1166
|
+
children: [
|
|
1167
|
+
jsx.jsxs('span', {
|
|
1168
|
+
className: 'ccbKey',
|
|
1169
|
+
children: [
|
|
1170
|
+
label,
|
|
1171
|
+
hint === undefined ? null : jsx.jsx('span', { className: 'ccbHint', children: ` — ${hint}` }),
|
|
1172
|
+
],
|
|
1173
|
+
}),
|
|
1174
|
+
jsx.jsxs('span', {
|
|
1175
|
+
className: 'ccbVal',
|
|
1176
|
+
children: [
|
|
1177
|
+
value,
|
|
1178
|
+
unit === undefined ? null : jsx.jsx('span', { className: 'ccbHint', children: ` ${unit}` }),
|
|
1179
|
+
source === undefined ? null : jsx.jsx('span', { className: 'ccbSrc', children: ` · ${source}` }),
|
|
1180
|
+
],
|
|
1181
|
+
}),
|
|
1182
|
+
],
|
|
1183
|
+
});
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
/**
|
|
1187
|
+
* In-session indicator for the policy this conversation is actually running
|
|
1188
|
+
* under, resolved from the same document and the session's own projections.
|
|
1189
|
+
*/
|
|
1190
|
+
/**
|
|
1191
|
+
* Read one session projection with a plain subscription: the indicator must
|
|
1192
|
+
* follow the live session, not a snapshot taken when it mounted.
|
|
1193
|
+
*/
|
|
1194
|
+
function useSessionProjection(session, key) {
|
|
1195
|
+
const face = session?.projections?.faceOf(key);
|
|
1196
|
+
const [value, setValue] = react.useState(() => face?.getSnapshot());
|
|
1197
|
+
react.useEffect(() => {
|
|
1198
|
+
if (face === undefined || typeof face.subscribe !== 'function') return undefined;
|
|
1199
|
+
setValue(face.getSnapshot());
|
|
1200
|
+
return face.subscribe(() => setValue(face.getSnapshot()));
|
|
1201
|
+
}, [face]);
|
|
1202
|
+
return value;
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
/**
|
|
1206
|
+
* The route that actually wrote the most recent compaction's summary, read
|
|
1207
|
+
* live from the session's own event window.
|
|
1208
|
+
*
|
|
1209
|
+
* The `compaction/summary` event is the only durable answer to "which model
|
|
1210
|
+
* summarized this": `provider`/`model` are rewritten by the fallback chain
|
|
1211
|
+
* on success, so the recorded pair is the route that won and not merely the
|
|
1212
|
+
* one the policy asked for. Nothing here goes over the remote — the loaded
|
|
1213
|
+
* window is the source, which is what makes this cheap enough for a header
|
|
1214
|
+
* badge that re-renders on every streamed event.
|
|
1215
|
+
*
|
|
1216
|
+
* Deliberately defensive: a session stub, or a session whose event source
|
|
1217
|
+
* has not been wired up, must leave the badge at its current face rather
|
|
1218
|
+
* than throw. `undefined` means "no compaction record readable", which is
|
|
1219
|
+
* also the answer for an empty window.
|
|
1220
|
+
*
|
|
1221
|
+
* @param param0 - `{ session }`, the object `useSession()` returns.
|
|
1222
|
+
* @returns the last summary's route and cost, or `undefined`.
|
|
1223
|
+
*/
|
|
1224
|
+
function useLastCompaction({ session } = {}) {
|
|
1225
|
+
const source = session?.eventSource;
|
|
1226
|
+
const [value, setValue] = react.useState(() => lastCompactionOf(source));
|
|
1227
|
+
react.useEffect(() => {
|
|
1228
|
+
if (source === undefined || typeof source.subscribe !== 'function') return undefined;
|
|
1229
|
+
setValue(lastCompactionOf(source));
|
|
1230
|
+
return source.subscribe(() => setValue(lastCompactionOf(source)));
|
|
1231
|
+
}, [source]);
|
|
1232
|
+
return value;
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
/** Read the last `compaction/summary` entry out of one event window. */
|
|
1236
|
+
function lastCompactionOf(source) {
|
|
1237
|
+
const snapshot = typeof source?.getSnapshot === 'function' ? source.getSnapshot() : undefined;
|
|
1238
|
+
const entries = Array.isArray(snapshot?.entries) ? snapshot.entries : undefined;
|
|
1239
|
+
if (entries === undefined) return undefined;
|
|
1240
|
+
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
1241
|
+
const entry = entries[index];
|
|
1242
|
+
if (entry?.type !== 'event') continue;
|
|
1243
|
+
const event = entry.event;
|
|
1244
|
+
if (event?.type !== 'compaction/summary') continue;
|
|
1245
|
+
const data = event.data;
|
|
1246
|
+
if (!isPlainObject(data)) continue;
|
|
1247
|
+
const { provider, model } = data;
|
|
1248
|
+
if (typeof provider !== 'string' || provider.length === 0) continue;
|
|
1249
|
+
if (typeof model !== 'string' || model.length === 0) continue;
|
|
1250
|
+
const usage = isPlainObject(data.usage) ? data.usage : undefined;
|
|
1251
|
+
return {
|
|
1252
|
+
provider,
|
|
1253
|
+
model,
|
|
1254
|
+
// A `sourceCommandId` means the operator ran /compact; its absence
|
|
1255
|
+
// means the engine compacted on its own trigger.
|
|
1256
|
+
manual: data.sourceCommandId !== undefined && data.sourceCommandId !== null,
|
|
1257
|
+
itemCount: Array.isArray(data.shadowedSeqs) ? data.shadowedSeqs.length : null,
|
|
1258
|
+
tokenCount: typeof data.shadowedTokenCount === 'number' ? data.shadowedTokenCount : null,
|
|
1259
|
+
usage,
|
|
1260
|
+
time: typeof event.time === 'number' ? event.time : 0,
|
|
1261
|
+
};
|
|
1262
|
+
}
|
|
1263
|
+
return undefined;
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
/**
|
|
1267
|
+
* In-session indicator for the policy this conversation is actually
|
|
1268
|
+
* running under.
|
|
1269
|
+
*
|
|
1270
|
+
* The backend numbers and the frontend numbers come from two different
|
|
1271
|
+
* places and both are needed: the policy is the session-scoped settings
|
|
1272
|
+
* document (live — an edit on the settings page moves this badge in the
|
|
1273
|
+
* same commit), while the window and current occupancy come from the
|
|
1274
|
+
* session's own projections. Showing the ratio alone would be useless in
|
|
1275
|
+
* this deployment, because `measured` already contains the fixed system
|
|
1276
|
+
* prompt and tool catalog (~21k), so a ratio is not "percent of the
|
|
1277
|
+
* conversation" — the panel therefore also states the token budget the
|
|
1278
|
+
* ratio maps to once a window is known.
|
|
1279
|
+
*
|
|
1280
|
+
* The route matters: the policy table resolves per `provider/model`, so
|
|
1281
|
+
* the badge resolves against the session's last-used route rather than
|
|
1282
|
+
* the global default alone. Before the session has sent a request there
|
|
1283
|
+
* is no route, and the panel says so instead of implying a per-model
|
|
1284
|
+
* layer applied.
|
|
1285
|
+
*/
|
|
1286
|
+
function CompactionBadge(props) {
|
|
1287
|
+
const { t, usePolicy, useSession } = props;
|
|
1288
|
+
// State and ref are declared before the injected hooks on purpose: a
|
|
1289
|
+
// React hook's identity is its call position, so keeping the
|
|
1290
|
+
// component's own two seats first makes the hook order independent of
|
|
1291
|
+
// how many hooks the standard source happens to contribute.
|
|
1292
|
+
const [open, setOpen] = react.useState(false);
|
|
1293
|
+
const rootRef = react.useRef(null);
|
|
1294
|
+
const policy = usePolicy((value) => value);
|
|
1295
|
+
/**
|
|
1296
|
+
* Whether this client can see the host's policy at all.
|
|
1297
|
+
*
|
|
1298
|
+
* A remote browser gets a memory-mode form (`status: 'unavailable'`), so
|
|
1299
|
+
* `value` is empty. The badge used to fall through to
|
|
1300
|
+
* `ENGINE_DEFAULT_THRESHOLD` and render the plugin's own 0.8 as
|
|
1301
|
+
* "80% · 800K" — a number that reads exactly like a configured trigger and
|
|
1302
|
+
* is wrong by a factor the operator cannot see. Saying "unreadable" is the
|
|
1303
|
+
* only honest answer it can give.
|
|
1304
|
+
*/
|
|
1305
|
+
const policyKnown = policy !== undefined && policy !== null && policy.status !== 'unavailable';
|
|
1306
|
+
const session = useSession();
|
|
1307
|
+
const pressure = useSessionProjection(session, 'contextPressure');
|
|
1308
|
+
const selection = useSessionProjection(session, 'modelSelection');
|
|
1309
|
+
/**
|
|
1310
|
+
* Which route actually wrote the last summary, and whether the operator
|
|
1311
|
+
* asked for it. Read from the session's event window, so a compaction
|
|
1312
|
+
* that just landed moves this badge without a reload.
|
|
1313
|
+
*/
|
|
1314
|
+
const last = useLastCompaction({ session });
|
|
1315
|
+
|
|
1316
|
+
const view = resolveView(policy?.value, policy?.user, routeOf(selection));
|
|
1317
|
+
const contextWindow = pressure?.contextWindow;
|
|
1318
|
+
const budgets = budgetsOf(view, contextWindow);
|
|
1319
|
+
const used = pressure?.projectedTokens ?? pressure?.pressureTokens;
|
|
1320
|
+
|
|
1321
|
+
react.useEffect(() => {
|
|
1322
|
+
if (!open) return undefined;
|
|
1323
|
+
const onPointerDown = (event) => {
|
|
1324
|
+
if (event.target instanceof Node && rootRef.current?.contains(event.target) === true) return;
|
|
1325
|
+
setOpen(false);
|
|
1326
|
+
};
|
|
1327
|
+
const onKeyDown = (event) => {
|
|
1328
|
+
if (event.key === 'Escape') setOpen(false);
|
|
1329
|
+
};
|
|
1330
|
+
document.addEventListener('pointerdown', onPointerDown);
|
|
1331
|
+
document.addEventListener('keydown', onKeyDown);
|
|
1332
|
+
return () => {
|
|
1333
|
+
document.removeEventListener('pointerdown', onPointerDown);
|
|
1334
|
+
document.removeEventListener('keydown', onKeyDown);
|
|
1335
|
+
};
|
|
1336
|
+
}, [open]);
|
|
1337
|
+
|
|
1338
|
+
const thresholdText = !policyKnown
|
|
1339
|
+
? '—'
|
|
1340
|
+
: (ratioText(
|
|
1341
|
+
view.thresholdRatio ??
|
|
1342
|
+
(budgets.thresholdTokens === null ? undefined : budgets.thresholdTokens / contextWindow),
|
|
1343
|
+
) ?? ratioText(ENGINE_DEFAULT_THRESHOLD));
|
|
1344
|
+
const autoOn = view.auto;
|
|
1345
|
+
// Headline: what will happen, not what is configured. Without a window
|
|
1346
|
+
// the honest answer is the ratio; with one it is the token budget.
|
|
1347
|
+
const headline = !policyKnown
|
|
1348
|
+
? t('badgeUnknown')
|
|
1349
|
+
: autoOn
|
|
1350
|
+
? budgets.thresholdTokens === null
|
|
1351
|
+
? `${t('pThreshold')} ${thresholdText}`
|
|
1352
|
+
: `${thresholdText} · ${tokenText(budgets.thresholdTokens)}`
|
|
1353
|
+
: t('badgeOff');
|
|
1354
|
+
const aria = `${t('badgeAria')}: ${headline}`;
|
|
1355
|
+
|
|
1356
|
+
/**
|
|
1357
|
+
* The badge's second face segment: the route that actually wrote the last
|
|
1358
|
+
* summary, with how it was triggered.
|
|
1359
|
+
*
|
|
1360
|
+
* The policy face above answers "what will happen"; this answers "what just
|
|
1361
|
+
* happened, and who did it" — the one thing the operator cannot tell from
|
|
1362
|
+
* anywhere else in the chat, because the compaction marker's renderer is
|
|
1363
|
+
* dsh's own and a plugin cannot decorate it. The route is shown here, not
|
|
1364
|
+
* only in the popover, because the question it answers is the one asked
|
|
1365
|
+
* right after a compaction: the summary came out short, or in a voice that
|
|
1366
|
+
* is not the policy's model, and the cause is the fallback chain having
|
|
1367
|
+
* picked a different route.
|
|
1368
|
+
*
|
|
1369
|
+
* Without a compaction record there is nothing to say, and the segment is
|
|
1370
|
+
* omitted rather than replaced by a placeholder — a header badge that
|
|
1371
|
+
* reads "no compaction yet" on every fresh conversation is noise.
|
|
1372
|
+
*/
|
|
1373
|
+
const lastSummary = last === undefined ? undefined : `${last.provider}/${last.model}`;
|
|
1374
|
+
const lastSummaryText =
|
|
1375
|
+
lastSummary === undefined ? undefined : `${lastSummary} · ${last.manual ? t('lastManual') : t('lastAuto')}`;
|
|
1376
|
+
|
|
1377
|
+
/**
|
|
1378
|
+
* A budget as the panel states it: the ratio, and the token count it
|
|
1379
|
+
* maps to whenever that is knowable.
|
|
1380
|
+
*
|
|
1381
|
+
* Both units, always, because either can be the one the operator wrote
|
|
1382
|
+
* and either can be the one the engine acts on: a policy stated in
|
|
1383
|
+
* tokens has no ratio of its own until the window is known, and a
|
|
1384
|
+
* policy stated as a ratio has no token count without it. Showing one
|
|
1385
|
+
* number would let the configured value and the effective value drift
|
|
1386
|
+
* apart on screen.
|
|
1387
|
+
*/
|
|
1388
|
+
const budgetText = (ratio, tokens, fallback) => {
|
|
1389
|
+
if (!policyKnown) return '—';
|
|
1390
|
+
// A budget declared in tokens has no ratio of its own, but with a
|
|
1391
|
+
// window in hand the share it occupies is arithmetic, not a
|
|
1392
|
+
// guess — and it is the number that says how eager the trigger is.
|
|
1393
|
+
const shown =
|
|
1394
|
+
typeof ratio === 'number'
|
|
1395
|
+
? ratio
|
|
1396
|
+
: typeof tokens === 'number' && Number.isFinite(contextWindow) && contextWindow > 0
|
|
1397
|
+
? tokens / contextWindow
|
|
1398
|
+
: undefined;
|
|
1399
|
+
const ratioPart = ratioText(shown) ?? ratioText(fallback);
|
|
1400
|
+
return tokens === null ? ratioPart : `${ratioPart} · ${tokenText(tokens)}`;
|
|
1401
|
+
};
|
|
1402
|
+
|
|
1403
|
+
const rows = [
|
|
1404
|
+
{
|
|
1405
|
+
key: 'threshold',
|
|
1406
|
+
label: t('pThreshold'),
|
|
1407
|
+
hint: t('pThresholdHint'),
|
|
1408
|
+
value: budgetText(view.thresholdRatio, budgets.thresholdTokens, ENGINE_DEFAULT_THRESHOLD),
|
|
1409
|
+
source: layerText(t, view.fields.threshold.source, view.fields.threshold.overridden),
|
|
1410
|
+
},
|
|
1411
|
+
{
|
|
1412
|
+
key: 'retain',
|
|
1413
|
+
label: t('pRetain'),
|
|
1414
|
+
hint: t('pRetainHint'),
|
|
1415
|
+
value: budgetText(view.retainRatio, budgets.retainTokens, ENGINE_DEFAULT_RETAIN),
|
|
1416
|
+
source: layerText(t, view.fields.retain.source, view.fields.retain.overridden),
|
|
1417
|
+
},
|
|
1418
|
+
{
|
|
1419
|
+
key: 'summary',
|
|
1420
|
+
label: t('pSummary'),
|
|
1421
|
+
value: view.summarizationModel === AUTO ? t('pModelAuto') : view.summarizationModel,
|
|
1422
|
+
source: layerText(
|
|
1423
|
+
t,
|
|
1424
|
+
view.fields.summarizationModel.source,
|
|
1425
|
+
view.fields.summarizationModel.overridden,
|
|
1426
|
+
),
|
|
1427
|
+
},
|
|
1428
|
+
{
|
|
1429
|
+
// The chain is a row of its own rather than a suffix on the model: it
|
|
1430
|
+
// is a *sequence*, and the order is the whole point — a reader who
|
|
1431
|
+
// cannot see which route is tried first cannot reason about what a
|
|
1432
|
+
// failed summarization will cost.
|
|
1433
|
+
key: 'fallback',
|
|
1434
|
+
label: t('pFallback'),
|
|
1435
|
+
hint: t('pFallbackHint'),
|
|
1436
|
+
value:
|
|
1437
|
+
view.summarizationFallback.length === 0
|
|
1438
|
+
? t('pFallbackNone')
|
|
1439
|
+
: view.summarizationFallback.join(' → '),
|
|
1440
|
+
source:
|
|
1441
|
+
view.summarizationFallback.length === 0
|
|
1442
|
+
? undefined
|
|
1443
|
+
: layerText(t, view.fields.summarizationFallback.source, view.fields.summarizationFallback.overridden),
|
|
1444
|
+
},
|
|
1445
|
+
{
|
|
1446
|
+
// Not a setting either: the route that actually wrote the last
|
|
1447
|
+
// summary. The policy row above names the model that *will* be
|
|
1448
|
+
// asked; this one names the model that *did* the work, which the
|
|
1449
|
+
// fallback chain may have rewritten. The two disagreeing is the
|
|
1450
|
+
// whole reason the row exists.
|
|
1451
|
+
key: 'lastSummary',
|
|
1452
|
+
label: t('lastSummary'),
|
|
1453
|
+
hint: t('lastSummaryHint'),
|
|
1454
|
+
value:
|
|
1455
|
+
lastSummary === undefined
|
|
1456
|
+
? t('lastSummaryNone')
|
|
1457
|
+
: `${lastSummary} · ${last.manual ? t('lastManual') : t('lastAuto')}`,
|
|
1458
|
+
source: undefined,
|
|
1459
|
+
},
|
|
1460
|
+
{
|
|
1461
|
+
// What that compaction actually replaced. Stated because the route
|
|
1462
|
+
// alone does not say whether the summary had room to work: a
|
|
1463
|
+
// 55K-token shadowed region and an 85-node one are different kinds
|
|
1464
|
+
// of squeeze, and the number is what makes the difference visible
|
|
1465
|
+
// without opening the trajectory panel.
|
|
1466
|
+
key: 'lastCost',
|
|
1467
|
+
label: t('lastCount'),
|
|
1468
|
+
value:
|
|
1469
|
+
last?.tokenCount === null || last?.tokenCount === undefined
|
|
1470
|
+
? '—'
|
|
1471
|
+
: tokenText(last.tokenCount),
|
|
1472
|
+
unit: last?.tokenCount === null || last?.tokenCount === undefined ? undefined : t('lastTokens'),
|
|
1473
|
+
source: last?.itemCount === null || last?.itemCount === undefined ? undefined : `${last.itemCount}`,
|
|
1474
|
+
},
|
|
1475
|
+
{
|
|
1476
|
+
// Not a setting: summarizing is mechanical compression of text that
|
|
1477
|
+
// is already in context, so the engine always asks the route for its
|
|
1478
|
+
// "do not think" level. The row exists so the panel states that fact
|
|
1479
|
+
// rather than leaving the reader to wonder.
|
|
1480
|
+
key: 'effort',
|
|
1481
|
+
label: t('pEffort'),
|
|
1482
|
+
hint: t('pEffortHint'),
|
|
1483
|
+
value: t('pEffortFixed'),
|
|
1484
|
+
},
|
|
1485
|
+
{
|
|
1486
|
+
key: 'maxTokens',
|
|
1487
|
+
label: t('pMaxTokens'),
|
|
1488
|
+
value: view.maxTokens === undefined ? '—' : view.maxTokens,
|
|
1489
|
+
unit: view.maxTokens === undefined ? undefined : t('pMaxTokensUnit'),
|
|
1490
|
+
source: layerText(t, view.fields.maxTokens.source, view.fields.maxTokens.overridden),
|
|
1491
|
+
},
|
|
1492
|
+
];
|
|
1493
|
+
const triggerRow =
|
|
1494
|
+
budgets.thresholdTokens === null
|
|
1495
|
+
? null
|
|
1496
|
+
: {
|
|
1497
|
+
key: 'trigger',
|
|
1498
|
+
label: t('pTriggerAt'),
|
|
1499
|
+
value: `${tokenText(budgets.thresholdTokens)} / ${tokenText(contextWindow)}`,
|
|
1500
|
+
source: used === undefined ? undefined : `${tokenText(used)} ${t('pWindow')}`,
|
|
1501
|
+
};
|
|
1502
|
+
const windowRow =
|
|
1503
|
+
budgets.thresholdTokens === null
|
|
1504
|
+
? {
|
|
1505
|
+
key: 'window',
|
|
1506
|
+
label: t('pWindow'),
|
|
1507
|
+
value: t('pWindowUnknown'),
|
|
1508
|
+
source: undefined,
|
|
1509
|
+
}
|
|
1510
|
+
: null;
|
|
1511
|
+
/**
|
|
1512
|
+
* The room a compaction actually has to work with: everything between
|
|
1513
|
+
* the trigger and the retained tail.
|
|
1514
|
+
*
|
|
1515
|
+
* A summary has to come out *smaller* than the region it replaces or
|
|
1516
|
+
* the engine rejects the compaction, and the observed floor for a
|
|
1517
|
+
* structured summary is a few thousand tokens — so a policy whose gap
|
|
1518
|
+
* is a few hundred tokens fires, fails, and fires again. The engine
|
|
1519
|
+
* cannot refuse the document (a small window may make a small gap
|
|
1520
|
+
* unavoidable), so the panel is where the operator is told.
|
|
1521
|
+
*/
|
|
1522
|
+
const gap = budgets.gapTokens;
|
|
1523
|
+
const gapShort = gap !== null && gap < MIN_COMPACT_GAP_TOKENS;
|
|
1524
|
+
const gapRow =
|
|
1525
|
+
gap === null
|
|
1526
|
+
? null
|
|
1527
|
+
: {
|
|
1528
|
+
key: 'gap',
|
|
1529
|
+
label: t('pGap'),
|
|
1530
|
+
value: tokenText(gap),
|
|
1531
|
+
source: undefined,
|
|
1532
|
+
};
|
|
1533
|
+
|
|
1534
|
+
return jsx.jsxs('span', {
|
|
1535
|
+
ref: rootRef,
|
|
1536
|
+
className: 'ccbRoot',
|
|
1537
|
+
children: [
|
|
1538
|
+
jsx.jsxs('button', {
|
|
1539
|
+
type: 'button',
|
|
1540
|
+
className: 'ccbBadge',
|
|
1541
|
+
'aria-label': aria,
|
|
1542
|
+
'aria-haspopup': 'dialog',
|
|
1543
|
+
'aria-expanded': open,
|
|
1544
|
+
title: aria,
|
|
1545
|
+
onClick: () => setOpen(!open),
|
|
1546
|
+
children: [
|
|
1547
|
+
jsx.jsx('span', { className: autoOn ? 'ccbDot' : 'ccbDot ccbOff' }),
|
|
1548
|
+
jsx.jsx('span', { children: headline }),
|
|
1549
|
+
lastSummaryText === undefined
|
|
1550
|
+
? null
|
|
1551
|
+
: jsx.jsx('span', {
|
|
1552
|
+
className: 'ccbLast',
|
|
1553
|
+
// The route alone does not say who started it, and
|
|
1554
|
+
// "automatic" is the case worth seeing at a glance: an
|
|
1555
|
+
// automatic compaction is the one that lands mid-turn
|
|
1556
|
+
// and surprises the operator.
|
|
1557
|
+
title: `${t('pSummary')}: ${lastSummary} · ${last.manual ? t('lastManual') : t('lastAuto')}`,
|
|
1558
|
+
children: lastSummaryText,
|
|
1559
|
+
}),
|
|
1560
|
+
],
|
|
1561
|
+
}),
|
|
1562
|
+
!open
|
|
1563
|
+
? null
|
|
1564
|
+
: jsx.jsxs('div', {
|
|
1565
|
+
className: 'ccbPanel',
|
|
1566
|
+
role: 'dialog',
|
|
1567
|
+
'aria-label': t('badgeTitle'),
|
|
1568
|
+
children: [
|
|
1569
|
+
jsx.jsx('p', { className: 'ccbTitle', children: t('badgeTitle') }),
|
|
1570
|
+
jsx.jsx('p', {
|
|
1571
|
+
className: 'ccbTarget',
|
|
1572
|
+
children: `${t('pTarget')}: ${
|
|
1573
|
+
view.target === undefined
|
|
1574
|
+
? t('pTargetNone')
|
|
1575
|
+
: `${view.target.provider}/${view.target.model}`
|
|
1576
|
+
}`,
|
|
1577
|
+
}),
|
|
1578
|
+
jsx.jsxs('div', {
|
|
1579
|
+
className: 'ccbRows',
|
|
1580
|
+
children: [
|
|
1581
|
+
jsx.jsx(
|
|
1582
|
+
PolicyRow,
|
|
1583
|
+
{
|
|
1584
|
+
key: 'auto',
|
|
1585
|
+
label: t('pAuto'),
|
|
1586
|
+
value: autoOn ? t('pOn') : t('pOff'),
|
|
1587
|
+
t,
|
|
1588
|
+
},
|
|
1589
|
+
'auto',
|
|
1590
|
+
),
|
|
1591
|
+
...rows.map((row) => jsx.jsx(PolicyRow, { ...row, t }, row.key)),
|
|
1592
|
+
triggerRow === null ? null : jsx.jsx(PolicyRow, { ...triggerRow, t }),
|
|
1593
|
+
windowRow === null ? null : jsx.jsx(PolicyRow, { ...windowRow, t }),
|
|
1594
|
+
gapRow === null ? null : jsx.jsx(PolicyRow, { ...gapRow, t }),
|
|
1595
|
+
],
|
|
1596
|
+
}),
|
|
1597
|
+
autoOn ? null : jsx.jsx('p', { className: 'ccbWarn', children: t('pOffHint') }),
|
|
1598
|
+
!policyKnown ? jsx.jsx('p', { className: 'ccbWarn', children: t('badgeUnknownHint') }) : null,
|
|
1599
|
+
autoOn && gapShort ? jsx.jsx('p', { className: 'ccbWarn', children: t('pGapWarn') }) : null,
|
|
1600
|
+
jsx.jsx('p', { className: 'ccbFoot', children: t('pEdit') }),
|
|
1601
|
+
],
|
|
1602
|
+
}),
|
|
1603
|
+
],
|
|
1604
|
+
});
|
|
1605
|
+
}
|
|
1606
|
+
|
|
1607
|
+
/**
|
|
1608
|
+
* Register the policy card into the Models page's footer seat, and keep its
|
|
1609
|
+
* translation keys in sync with the locale bundle.
|
|
1610
|
+
*/
|
|
1611
|
+
function apply(ctx) {
|
|
1612
|
+
const t = ctx.locale.bind(NS);
|
|
1613
|
+
ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'compaction-control: card copy');
|
|
1614
|
+
|
|
1615
|
+
// 0.2.0 renamed the browser-side settings transport: the old
|
|
1616
|
+
// `ctx.settingsScope.bind({ namespace })` no longer exists (the service
|
|
1617
|
+
// was removed outright), and `ctx.configForms.get(entryId)` is its
|
|
1618
|
+
// replacement — same ConfigForm surface (getSnapshot/subscribe/mutate).
|
|
1619
|
+
// Injecting the old name leaves this entry `pending` forever, which the
|
|
1620
|
+
// browser reports as "Failed to load plugins".
|
|
1621
|
+
/**
|
|
1622
|
+
* The 0.2.0 settings document IS the profile patch: a form is keyed by the
|
|
1623
|
+
* profile **entry id** whose `Config` owns it (see `configForms.get`'s own
|
|
1624
|
+
* doc: "Unique Host plugin entry id"), not by a namespace the plugin
|
|
1625
|
+
* registers. 0.1.x's publish path (`ctx.settings.installSection`) is gone
|
|
1626
|
+
* from 0.2.0 outright, so `get('compaction-control')` answers
|
|
1627
|
+
* `unavailable` forever and this card quietly fell back to its own schema
|
|
1628
|
+
* defaults — the deployment said 0.6 while the panel advertised 0.8.
|
|
1629
|
+
*
|
|
1630
|
+
* The first entry must match the server's `PATCH_ENTRY_IDS[0]`: the panel
|
|
1631
|
+
* edits the first available form, while the engine reads the first patch
|
|
1632
|
+
* entry with a config. `compaction-control-host` is not exposed by this
|
|
1633
|
+
* deployment's settings plane (`settings/describe` exposes only
|
|
1634
|
+
* `compaction-control-settings`), so starting with it made the panel edit
|
|
1635
|
+
* an entry the engine never read — that divergence broke settings on
|
|
1636
|
+
* 2026-10-14. The remaining ids remain fallbacks for older profiles.
|
|
1637
|
+
*/
|
|
1638
|
+
const SETTINGS_ENTRIES = ['compaction-control-settings', 'compaction-control-host', 'compaction-control'];
|
|
1639
|
+
const forms = SETTINGS_ENTRIES.map((id) => ctx.configForms.get(id));
|
|
1640
|
+
/**
|
|
1641
|
+
* The first entry the Host actually serves.
|
|
1642
|
+
*
|
|
1643
|
+
* Resolved per read rather than once: these forms all start `loading`, so a
|
|
1644
|
+
* pick made at apply time would be a guess about which entry this profile
|
|
1645
|
+
* mounts. `unavailable` is the settled answer, so anything else may still
|
|
1646
|
+
* be right.
|
|
1647
|
+
*/
|
|
1648
|
+
const scopeOf = () => forms.find((form) => form.getSnapshot?.()?.status !== 'unavailable') ?? forms[0];
|
|
1649
|
+
const scope = {
|
|
1650
|
+
getSnapshot: () => scopeOf().getSnapshot(),
|
|
1651
|
+
subscribe: (listener) => {
|
|
1652
|
+
const disposers = forms.map((form) => form.subscribe(listener));
|
|
1653
|
+
return () => {
|
|
1654
|
+
for (const dispose of disposers) dispose();
|
|
1655
|
+
};
|
|
1656
|
+
},
|
|
1657
|
+
mutate: (ops, expectedRevision) => scopeOf().mutate(ops, expectedRevision),
|
|
1658
|
+
};
|
|
1659
|
+
|
|
1660
|
+
/**
|
|
1661
|
+
* The host's servable model catalog, loaded once per page.
|
|
1662
|
+
*
|
|
1663
|
+
* Read lazily — the first card that mounts starts the load — because
|
|
1664
|
+
* most visits to the Models page never open the compaction card's
|
|
1665
|
+
* picker, and this is the same Remote the conversation's model menu
|
|
1666
|
+
* uses, so it is cheap but not free.
|
|
1667
|
+
*
|
|
1668
|
+
* A failure is a fact the card must state, not a reason to render an
|
|
1669
|
+
* empty picker: `undefined` means "still loading", `null` means "the
|
|
1670
|
+
* read failed", and the card says so.
|
|
1671
|
+
*/
|
|
1672
|
+
let catalogState = { status: 'idle', value: undefined };
|
|
1673
|
+
const catalogListeners = new Set();
|
|
1674
|
+
const loadCatalog = () => {
|
|
1675
|
+
if (catalogState.status !== 'idle') return;
|
|
1676
|
+
catalogState = { status: 'loading', value: undefined };
|
|
1677
|
+
ctx.remote.session
|
|
1678
|
+
.modelCatalog()
|
|
1679
|
+
.then((response) => {
|
|
1680
|
+
if (!response.ok) throw new Error(`${response.error.code}: ${response.error.message}`);
|
|
1681
|
+
catalogState = { status: 'ready', value: response.value };
|
|
1682
|
+
})
|
|
1683
|
+
.catch(() => {
|
|
1684
|
+
catalogState = { status: 'failed', value: null };
|
|
1685
|
+
})
|
|
1686
|
+
.finally(() => {
|
|
1687
|
+
for (const listener of catalogListeners) listener();
|
|
1688
|
+
});
|
|
1689
|
+
};
|
|
1690
|
+
|
|
1691
|
+
const useCatalog = () => {
|
|
1692
|
+
const [value, setValue] = react.useState(() => catalogState.value);
|
|
1693
|
+
react.useEffect(() => {
|
|
1694
|
+
loadCatalog();
|
|
1695
|
+
const listener = () => setValue(catalogState.value);
|
|
1696
|
+
catalogListeners.add(listener);
|
|
1697
|
+
listener();
|
|
1698
|
+
return () => {
|
|
1699
|
+
catalogListeners.delete(listener);
|
|
1700
|
+
};
|
|
1701
|
+
}, []);
|
|
1702
|
+
return value;
|
|
1703
|
+
};
|
|
1704
|
+
|
|
1705
|
+
ctx.slots.inject('settings.models.footer', function* () {
|
|
1706
|
+
yield ctx.slots.register(
|
|
1707
|
+
{
|
|
1708
|
+
name: 'settings.models.footer',
|
|
1709
|
+
id: NS,
|
|
1710
|
+
locale: NS,
|
|
1711
|
+
inject: () => ({
|
|
1712
|
+
t,
|
|
1713
|
+
scope,
|
|
1714
|
+
useCatalog,
|
|
1715
|
+
useScope: (select) => {
|
|
1716
|
+
const [snapshot, setSnapshot] = react.useState(() => scope.getSnapshot());
|
|
1717
|
+
react.useEffect(() => scope.subscribe(() => setSnapshot(scope.getSnapshot())), []);
|
|
1718
|
+
return select(snapshot);
|
|
1719
|
+
},
|
|
1720
|
+
mutate: (ops) => scope.mutate(ops),
|
|
1721
|
+
}),
|
|
1722
|
+
},
|
|
1723
|
+
CompactionCard,
|
|
1724
|
+
);
|
|
1725
|
+
});
|
|
1726
|
+
|
|
1727
|
+
/**
|
|
1728
|
+
* The in-session indicator.
|
|
1729
|
+
*
|
|
1730
|
+
* Seat: `conversation.session.header.utilities` — a session-scoped
|
|
1731
|
+
* list slot rendered with no props (`renderSlot(name, {})`), beside
|
|
1732
|
+
* the header's other utilities. Session scope is what supplies
|
|
1733
|
+
* `sessionId` and the two standard keyed hooks: `useProjection`
|
|
1734
|
+
* (the `contextPressure` / `modelSelection` projections the chat
|
|
1735
|
+
* meter already reads) and `useSession`. It needs no `remote.*`
|
|
1736
|
+
* calls, which is what keeps it cheap enough for a header that
|
|
1737
|
+
* re-renders on every streamed event.
|
|
1738
|
+
*
|
|
1739
|
+
* The policy itself comes from the settings scope rather than the
|
|
1740
|
+
* projections, and that is the point: the scope is live, so an edit
|
|
1741
|
+
* on the Models page moves this badge in the same commit — the
|
|
1742
|
+
* answer to "did my change apply to the session I am looking at".
|
|
1743
|
+
*/
|
|
1744
|
+
const sessions = ctx.sessions;
|
|
1745
|
+
ctx.slots.inject('conversation.session.header.utilities', function* () {
|
|
1746
|
+
yield ctx.slots.register(
|
|
1747
|
+
{
|
|
1748
|
+
name: 'conversation.session.header.utilities',
|
|
1749
|
+
id: `${NS}-session-badge`,
|
|
1750
|
+
order: 20,
|
|
1751
|
+
locale: NS,
|
|
1752
|
+
inject: (sessionId) => {
|
|
1753
|
+
const binding = sessionId === undefined ? undefined : sessions.binding(sessionId);
|
|
1754
|
+
if (binding === undefined) {
|
|
1755
|
+
throw new Error(`compaction-control: session "${String(sessionId)}" is unavailable`);
|
|
1756
|
+
}
|
|
1757
|
+
return {
|
|
1758
|
+
useSession: () => binding.session,
|
|
1759
|
+
usePolicy: (select) => {
|
|
1760
|
+
const [snapshot, setSnapshot] = react.useState(() => scope.getSnapshot());
|
|
1761
|
+
react.useEffect(() => scope.subscribe(() => setSnapshot(scope.getSnapshot())), []);
|
|
1762
|
+
return select(snapshot);
|
|
1763
|
+
},
|
|
1764
|
+
};
|
|
1765
|
+
},
|
|
1766
|
+
},
|
|
1767
|
+
CompactionBadge,
|
|
1768
|
+
);
|
|
1769
|
+
});
|
|
1770
|
+
}
|
|
1771
|
+
|
|
1772
|
+
/**
|
|
1773
|
+
* Required client services (cordis fiber inject). Listed in one place so the
|
|
1774
|
+
* bundle's dependencies are auditable against the host's provided services.
|
|
1775
|
+
*/
|
|
1776
|
+
const inject = [
|
|
1777
|
+
'locale',
|
|
1778
|
+
'remote',
|
|
1779
|
+
'remote.session',
|
|
1780
|
+
'sessions',
|
|
1781
|
+
// 0.2.0:`settingsScope` 已不存在,settings 表单服务改名 `configForms`
|
|
1782
|
+
// (由 dsh-client-ui-settings 提供)。名字写错 = entry 永远 pending。
|
|
1783
|
+
'configForms',
|
|
1784
|
+
'slots',
|
|
1785
|
+
];
|
|
1786
|
+
|
|
1787
|
+
exports.apply = apply;
|
|
1788
|
+
exports.inject = inject;
|
|
1789
|
+
return module.exports;
|
|
1790
|
+
},
|
|
1791
|
+
});
|