@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/policy.js
ADDED
|
@@ -0,0 +1,608 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compaction policy resolution for dsh-compaction-policy-engine.
|
|
3
|
+
*
|
|
4
|
+
* Three layers (global default / per-provider / per-model) are merged leaf-wise,
|
|
5
|
+
* then resolved to one policy per routed target. Two units are accepted for the
|
|
6
|
+
* two budget fields: a ratio of the adapter-declared window, or an absolute token
|
|
7
|
+
* count. The token form is resolved through the window at apply time — which is
|
|
8
|
+
* why a route that declares no window cannot honor one, and why that is a loud
|
|
9
|
+
* failure rather than a silent fallback to the engine default.
|
|
10
|
+
*
|
|
11
|
+
* @module dsh-compaction-policy-engine/policy
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** The literal `auto` sentinel, meaning "inherit the conversation's own model". */
|
|
15
|
+
export const AUTO = 'auto';
|
|
16
|
+
|
|
17
|
+
/** Default threshold ratio when a layer states none; matches compaction-basic. */
|
|
18
|
+
export const DEFAULT_THRESHOLD_RATIO = 0.8;
|
|
19
|
+
|
|
20
|
+
/** Default retention ratio when a layer states none; matches compaction-basic. */
|
|
21
|
+
export const DEFAULT_RETAIN_RATIO = 0.16;
|
|
22
|
+
|
|
23
|
+
/** Default provider generation cap for the summarization call. */
|
|
24
|
+
export const DEFAULT_MAX_TOKENS = 8192;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Minimum room a compaction must free, in tokens: below this the summary can end
|
|
28
|
+
* up no smaller than what it replaces (`summary is not smaller than the shadowed
|
|
29
|
+
* content`), so the policy is reported as unworkable instead of tried forever.
|
|
30
|
+
*/
|
|
31
|
+
export const MIN_COMPACT_GAP_TOKENS = 8192;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The sentinel meaning "inherit the reasoning effort of the route's own model",
|
|
35
|
+
* used by the `summarizationModel` field.
|
|
36
|
+
*/
|
|
37
|
+
export const INHERIT_EFFORT = 'inherit';
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Summarizing is mechanical compression of text already in context, so the
|
|
41
|
+
* summarization call always runs with thinking off; `pickThinkingOff` resolves
|
|
42
|
+
* that from the route's own declared levels.
|
|
43
|
+
*/
|
|
44
|
+
export const THINKING_OFF = 'off';
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Aliases adapters use for the "do not think" level, in match order.
|
|
48
|
+
*/
|
|
49
|
+
const THINKING_OFF_ALIASES = ['off', 'none', 'disabled', 'no-thinking', 'nothinking'];
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Pick a route's "do not think" effort from the efforts it declares.
|
|
53
|
+
*
|
|
54
|
+
* @param efforts - `LlmReasoningEffortInfo[]` for the summarization route.
|
|
55
|
+
* @returns the matching effort id, or undefined when the route offers none.
|
|
56
|
+
*/
|
|
57
|
+
export function pickThinkingOff(efforts) {
|
|
58
|
+
if (!Array.isArray(efforts) || efforts.length === 0) return undefined;
|
|
59
|
+
for (const alias of THINKING_OFF_ALIASES) {
|
|
60
|
+
const match = efforts.find((effort) => effort?.id === alias);
|
|
61
|
+
if (match !== undefined) return match.id;
|
|
62
|
+
}
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* What the summarization call can actually be told about thinking, and what it
|
|
68
|
+
* will therefore do.
|
|
69
|
+
*
|
|
70
|
+
* `pickThinkingOff` answers only "which id do we send". This answers the question
|
|
71
|
+
* the operator cannot otherwise ask: *can this route be told not to think at
|
|
72
|
+
* all?* A hand-declared model with no `reasoningEfforts` (or
|
|
73
|
+
* `reasoningEfforts: false`) is treated as non-reasoning by the provider-d adapter,
|
|
74
|
+
* which then skips **every** thinking-control branch — including the off switch —
|
|
75
|
+
* so the route thinks at its own default and spends the summarization
|
|
76
|
+
* `maxTokens` on reasoning. Nothing in the log said so: the compaction succeeded,
|
|
77
|
+
* just slower and dearer. The four `control` values are the four answers, and
|
|
78
|
+
* the two that mean "it will think" are the ones the engine warns about.
|
|
79
|
+
*
|
|
80
|
+
* @param info - what `ctx.llm.resolveModelInfo(provider, model, signal)`
|
|
81
|
+
* resolved to. May be undefined, and may be any shape at all: a hand-written
|
|
82
|
+
* model entry is not schema-checked by the adapter.
|
|
83
|
+
* @returns the resolved effort, whether the route can be told not to think, and
|
|
84
|
+
* the level ids it declares in order. Never throws.
|
|
85
|
+
*/
|
|
86
|
+
export function resolveSummarizationEffort(info) {
|
|
87
|
+
// `unknown` is the one case where the route's own declaration cannot be read,
|
|
88
|
+
// so nothing at all can be said about it — not even that it has no levels.
|
|
89
|
+
if (info === undefined || info === null) {
|
|
90
|
+
return { effort: undefined, control: 'unknown', offered: [] };
|
|
91
|
+
}
|
|
92
|
+
const reasoning = info.reasoning;
|
|
93
|
+
// `reasoning: false` (a hand-declared model with no `reasoningEfforts`) and a
|
|
94
|
+
// catalog model whose `thinkingLevelMap.off` is null both land here: the
|
|
95
|
+
// adapter reports no reasoning capability, and its request builder then sends
|
|
96
|
+
// no thinking control whatsoever.
|
|
97
|
+
if (reasoning === undefined || reasoning === null || reasoning === false) {
|
|
98
|
+
return { effort: undefined, control: 'no-reasoning', offered: [] };
|
|
99
|
+
}
|
|
100
|
+
const efforts = reasoning.efforts;
|
|
101
|
+
if (!Array.isArray(efforts) || efforts.length === 0) {
|
|
102
|
+
return { effort: undefined, control: 'no-reasoning', offered: [] };
|
|
103
|
+
}
|
|
104
|
+
const offered = efforts.map((effort) => effort?.id).filter((id) => id !== undefined);
|
|
105
|
+
const effort = pickThinkingOff(efforts);
|
|
106
|
+
// Declared levels but no off-equivalent among them: the route *can* think and
|
|
107
|
+
// cannot be stopped, which is the other half of the same silent failure.
|
|
108
|
+
if (effort === undefined) {
|
|
109
|
+
return { effort: undefined, control: 'no-off-level', offered };
|
|
110
|
+
}
|
|
111
|
+
return { effort, control: 'off', offered };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The only keys a layer may carry; anything else is a typo, not a silent no-op. */
|
|
115
|
+
const LAYER_KEYS = new Set([
|
|
116
|
+
'threshold',
|
|
117
|
+
'thresholdTokens',
|
|
118
|
+
'summarizationModel',
|
|
119
|
+
'summarizationFallback',
|
|
120
|
+
'headroomTokens',
|
|
121
|
+
'retain',
|
|
122
|
+
'retainTokens',
|
|
123
|
+
'maxTokens',
|
|
124
|
+
'compactionRetries',
|
|
125
|
+
'maxOverflowRetries',
|
|
126
|
+
]);
|
|
127
|
+
|
|
128
|
+
/** The only keys the document root may carry. */
|
|
129
|
+
const ROOT_KEYS = new Set(['default', 'providers', 'models', 'auto']);
|
|
130
|
+
|
|
131
|
+
/** A configuration failure the operator can act on. */
|
|
132
|
+
export class CompactionConfigError extends Error {
|
|
133
|
+
/**
|
|
134
|
+
* @param message - actionable description naming the offending field.
|
|
135
|
+
*/
|
|
136
|
+
constructor(message) {
|
|
137
|
+
super(message);
|
|
138
|
+
this.name = 'CompactionConfigError';
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Assert a value is a plain object (not null, not an array). */
|
|
143
|
+
function isPlainObject(value) {
|
|
144
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Validate one policy layer's keys and field types.
|
|
149
|
+
* @param layer - candidate layer object.
|
|
150
|
+
* @param path - human-readable location used in error messages.
|
|
151
|
+
*/
|
|
152
|
+
/**
|
|
153
|
+
* A ratio must be a real number in (0, 1). A value at or above 1 is almost
|
|
154
|
+
* always a token budget typed into the ratio field, so the error names the
|
|
155
|
+
* token field to use instead.
|
|
156
|
+
* @param path - field location for the error message.
|
|
157
|
+
* @param value - candidate ratio.
|
|
158
|
+
*/
|
|
159
|
+
function assertRatio(path, value) {
|
|
160
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
161
|
+
throw new CompactionConfigError(`${path} must be a number`);
|
|
162
|
+
}
|
|
163
|
+
if (value <= 0 || value >= 1) {
|
|
164
|
+
const hint =
|
|
165
|
+
value >= 1
|
|
166
|
+
? `; for an absolute token budget use ${path}Tokens: ${value}`
|
|
167
|
+
: '';
|
|
168
|
+
throw new CompactionConfigError(`${path} must be greater than 0 and less than 1${hint}`);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* An absolute budget is a whole number of tokens. Fractions are rejected rather
|
|
174
|
+
* than rounded: the operator asked for a specific budget, and silently shifting
|
|
175
|
+
* it is worse than saying the value is not a token count.
|
|
176
|
+
* @param path - field location for the error message.
|
|
177
|
+
* @param value - candidate token budget.
|
|
178
|
+
*/
|
|
179
|
+
function assertTokenBudget(path, value) {
|
|
180
|
+
if (!Number.isInteger(value) || value < 1) {
|
|
181
|
+
throw new CompactionConfigError(`${path} must be a positive whole number of tokens`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Validate one budget field that has two units.
|
|
187
|
+
*
|
|
188
|
+
* Stating both in one layer is rejected (they are the same setting in two units);
|
|
189
|
+
* a shadowed sibling is reported, and a ratio must be in (0, 1).
|
|
190
|
+
*/
|
|
191
|
+
function assertBudgetUnit(path, ratioKey, tokensKey, layer) {
|
|
192
|
+
if (layer[tokensKey] !== undefined) {
|
|
193
|
+
assertTokenBudget(`${path}.${tokensKey}`, layer[tokensKey]);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
if (layer[ratioKey] !== undefined) assertRatio(`${path}.${ratioKey}`, layer[ratioKey]);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Assert a positive integer field. */
|
|
200
|
+
function assertPositiveInt(path, value) {
|
|
201
|
+
if (!Number.isInteger(value) || value < 1) {
|
|
202
|
+
throw new CompactionConfigError(`${path} must be a positive integer`);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Assert a non-negative integer field. */
|
|
207
|
+
function assertNonNegativeInt(path, value) {
|
|
208
|
+
if (!Number.isInteger(value) || value < 0) {
|
|
209
|
+
throw new CompactionConfigError(`${path} must be a non-negative integer`);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* A summarization model is either the `auto` sentinel or an explicit
|
|
215
|
+
* `provider/model`.
|
|
216
|
+
*/
|
|
217
|
+
function assertModelRef(path, value) {
|
|
218
|
+
if (typeof value !== 'string' || value.length === 0) {
|
|
219
|
+
throw new CompactionConfigError(`${path} must be a non-empty string`);
|
|
220
|
+
}
|
|
221
|
+
if (value === AUTO) return;
|
|
222
|
+
const slash = value.indexOf('/');
|
|
223
|
+
if (slash <= 0 || slash === value.length - 1) {
|
|
224
|
+
throw new CompactionConfigError(
|
|
225
|
+
`${path} must be "${AUTO}" or "provider/model", got "${value}"`,
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* A summarization fallback chain is an ordered list of `provider/model` refs.
|
|
232
|
+
*
|
|
233
|
+
* Validated as strictly as a single model ref, plus the two rules a chain can
|
|
234
|
+
* break that a bare list cannot express: an entry repeating the primary route is
|
|
235
|
+
* a no-op that costs a full re-send, and a repeated entry would retry a route
|
|
236
|
+
* that has already failed in the same attempt. Both are rejected rather than
|
|
237
|
+
* de-duplicated: the operator wrote them, and silently reordering a cost-bearing
|
|
238
|
+
* attempt list is worse than saying the list is wrong.
|
|
239
|
+
*
|
|
240
|
+
* @param path - field location for the error message.
|
|
241
|
+
* @param value - candidate chain.
|
|
242
|
+
*/
|
|
243
|
+
function assertFallbackChain(path, value) {
|
|
244
|
+
if (!Array.isArray(value)) {
|
|
245
|
+
throw new CompactionConfigError(`${path} must be a list of "provider/model" refs; got ${typeof value}`);
|
|
246
|
+
}
|
|
247
|
+
const seen = new Set();
|
|
248
|
+
for (const [index, entry] of value.entries()) {
|
|
249
|
+
const entryPath = `${path}[${index}]`;
|
|
250
|
+
if (typeof entry !== 'string' || entry.length === 0) {
|
|
251
|
+
throw new CompactionConfigError(`${entryPath} must be a non-empty string`);
|
|
252
|
+
}
|
|
253
|
+
assertModelRef(entryPath, entry);
|
|
254
|
+
if (entry === AUTO) {
|
|
255
|
+
throw new CompactionConfigError(
|
|
256
|
+
`${entryPath} is "${AUTO}"; a fallback must name an explicit "provider/model" — ` +
|
|
257
|
+
'"auto" means the conversation\'s own route, which is what the primary field is for.',
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
if (seen.has(entry)) {
|
|
261
|
+
throw new CompactionConfigError(
|
|
262
|
+
`${entryPath} repeats "${entry}"; a fallback chain is tried in order, so a repeat would ` +
|
|
263
|
+
're-send the whole summary prompt to a route that already failed in this attempt.',
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
seen.add(entry);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function validateLayer(layer, path) {
|
|
271
|
+
if (!isPlainObject(layer)) throw new CompactionConfigError(`${path} must be a mapping`);
|
|
272
|
+
for (const key of Object.keys(layer)) {
|
|
273
|
+
if (!LAYER_KEYS.has(key)) {
|
|
274
|
+
throw new CompactionConfigError(
|
|
275
|
+
`${path}: unknown field "${key}"; known fields are ${[...LAYER_KEYS].join(', ')}`,
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
assertBudgetUnit(path, 'threshold', 'thresholdTokens', layer);
|
|
280
|
+
assertBudgetUnit(path, 'retain', 'retainTokens', layer);
|
|
281
|
+
if (layer.maxTokens !== undefined) assertPositiveInt(`${path}.maxTokens`, layer.maxTokens);
|
|
282
|
+
if (layer.headroomTokens !== undefined) assertNonNegativeInt(`${path}.headroomTokens`, layer.headroomTokens);
|
|
283
|
+
if (layer.compactionRetries !== undefined) assertNonNegativeInt(`${path}.compactionRetries`, layer.compactionRetries);
|
|
284
|
+
if (layer.maxOverflowRetries !== undefined) assertNonNegativeInt(`${path}.maxOverflowRetries`, layer.maxOverflowRetries);
|
|
285
|
+
if (layer.summarizationModel !== undefined) assertModelRef(`${path}.summarizationModel`, layer.summarizationModel);
|
|
286
|
+
if (layer.summarizationFallback !== undefined) assertFallbackChain(`${path}.summarizationFallback`, layer.summarizationFallback);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Validate the whole document and freeze it.
|
|
291
|
+
* @param config - untrusted plugin configuration.
|
|
292
|
+
* @returns a detached, deeply frozen config document.
|
|
293
|
+
*/
|
|
294
|
+
export function resolveConfig(config = {}) {
|
|
295
|
+
if (!isPlainObject(config)) throw new CompactionConfigError('compaction-control config must be a mapping');
|
|
296
|
+
for (const key of Object.keys(config)) {
|
|
297
|
+
if (!ROOT_KEYS.has(key)) {
|
|
298
|
+
throw new CompactionConfigError(
|
|
299
|
+
`unknown top-level field "${key}"; known fields are ${[...ROOT_KEYS].join(', ')}`,
|
|
300
|
+
);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
if (config.auto !== undefined && typeof config.auto !== 'boolean') {
|
|
304
|
+
throw new CompactionConfigError('auto must be a boolean');
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const defaults = config.default ?? {};
|
|
308
|
+
validateLayer(defaults, 'default');
|
|
309
|
+
|
|
310
|
+
const providers = config.providers ?? {};
|
|
311
|
+
if (!isPlainObject(providers)) throw new CompactionConfigError('providers must be a mapping of route name to policy');
|
|
312
|
+
for (const [route, layer] of Object.entries(providers)) validateLayer(layer, `providers.${route}`);
|
|
313
|
+
|
|
314
|
+
const models = config.models ?? [];
|
|
315
|
+
if (!Array.isArray(models)) throw new CompactionConfigError('models must be a list');
|
|
316
|
+
const seenTargets = new Set();
|
|
317
|
+
models.forEach((entry, index) => {
|
|
318
|
+
const path = `models[${index}]`;
|
|
319
|
+
if (!isPlainObject(entry)) throw new CompactionConfigError(`${path} must be a mapping`);
|
|
320
|
+
if (typeof entry.provider !== 'string' || entry.provider.length === 0) {
|
|
321
|
+
throw new CompactionConfigError(`${path}.provider must be a non-empty string`);
|
|
322
|
+
}
|
|
323
|
+
if (typeof entry.model !== 'string' || entry.model.length === 0) {
|
|
324
|
+
throw new CompactionConfigError(`${path}.model must be a non-empty string`);
|
|
325
|
+
}
|
|
326
|
+
const rest = { ...entry };
|
|
327
|
+
delete rest.provider;
|
|
328
|
+
delete rest.model;
|
|
329
|
+
validateLayer(rest, path);
|
|
330
|
+
const key = `${entry.provider}\u0000${entry.model}`;
|
|
331
|
+
if (seenTargets.has(key)) {
|
|
332
|
+
throw new CompactionConfigError(`${path}: duplicate override for ${entry.provider}/${entry.model}`);
|
|
333
|
+
}
|
|
334
|
+
seenTargets.add(key);
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
return deepFreeze({
|
|
338
|
+
auto: config.auto ?? true,
|
|
339
|
+
default: { ...defaults },
|
|
340
|
+
providers: { ...providers },
|
|
341
|
+
models: models.map((entry) => ({ ...entry })),
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** Recursively freeze a value so callers cannot mutate resolved policy. */
|
|
346
|
+
function deepFreeze(value) {
|
|
347
|
+
if (value === null || typeof value !== 'object' || Object.isFrozen(value)) return value;
|
|
348
|
+
Object.freeze(value);
|
|
349
|
+
for (const key of Object.keys(value)) deepFreeze(value[key]);
|
|
350
|
+
return value;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Find the layer stack that applies to one routed target, highest precedence first.
|
|
355
|
+
* @param config - resolved config document.
|
|
356
|
+
* @param target - routed provider and model.
|
|
357
|
+
* @returns the override layer, the route layer, and the global default.
|
|
358
|
+
*/
|
|
359
|
+
function layersFor(config, target) {
|
|
360
|
+
const override = config.models.find(
|
|
361
|
+
(entry) => entry.provider === target.provider && entry.model === target.model,
|
|
362
|
+
);
|
|
363
|
+
return {
|
|
364
|
+
override,
|
|
365
|
+
route: config.providers[target.provider],
|
|
366
|
+
fallback: config.default,
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Resolve the first layer that states a given field.
|
|
372
|
+
* @param layers - precedence-ordered layers.
|
|
373
|
+
* @param key - field name to look up.
|
|
374
|
+
* @returns the winning value, or undefined when no layer states it.
|
|
375
|
+
*/
|
|
376
|
+
function pick(layers, key) {
|
|
377
|
+
for (const layer of [layers.override, layers.route, layers.fallback]) {
|
|
378
|
+
const value = layer?.[key];
|
|
379
|
+
if (value !== undefined) return value;
|
|
380
|
+
}
|
|
381
|
+
return undefined;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** The layer names, highest precedence first, for provenance reporting. */
|
|
385
|
+
const LAYER_NAMES = [
|
|
386
|
+
['override', 'model'],
|
|
387
|
+
['route', 'provider'],
|
|
388
|
+
['fallback', 'default'],
|
|
389
|
+
];
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* Resolve the first layer that states a field in *either* unit, returning both
|
|
393
|
+
* forms so callers can order and report them.
|
|
394
|
+
*/
|
|
395
|
+
function pickForm(layers, ratioKey, tokensKey) {
|
|
396
|
+
for (const [slot, name] of LAYER_NAMES) {
|
|
397
|
+
const layer = layers[slot];
|
|
398
|
+
if (layer === undefined) continue;
|
|
399
|
+
if (layer[tokensKey] !== undefined) return { value: layer[tokensKey], unit: 'tokens', layer: name };
|
|
400
|
+
if (layer[ratioKey] !== undefined) return { value: layer[ratioKey], unit: 'ratio', layer: name };
|
|
401
|
+
}
|
|
402
|
+
return { value: undefined, unit: 'ratio', layer: 'engine' };
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Report every layer that states one budget field in both units.
|
|
407
|
+
*/
|
|
408
|
+
function shadowedUnits(layers) {
|
|
409
|
+
const messages = [];
|
|
410
|
+
for (const [slot, name] of LAYER_NAMES) {
|
|
411
|
+
const layer = layers[slot];
|
|
412
|
+
if (layer === undefined) continue;
|
|
413
|
+
for (const [ratioKey, tokensKey] of [
|
|
414
|
+
['threshold', 'thresholdTokens'],
|
|
415
|
+
['retain', 'retainTokens'],
|
|
416
|
+
]) {
|
|
417
|
+
if (layer[ratioKey] === undefined || layer[tokensKey] === undefined) continue;
|
|
418
|
+
messages.push(
|
|
419
|
+
`${name}: ${tokensKey} (${layer[tokensKey]}) wins over ${ratioKey} (${layer[ratioKey]}); ` +
|
|
420
|
+
'the two are the same setting in two units, so remove the one you did not mean',
|
|
421
|
+
);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
return messages;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Overlay one settings section on the composition document, leaf-wise and
|
|
429
|
+
* per-field: a layer the section does not restate (a profile's per-model row)
|
|
430
|
+
* survives the user's first edit instead of being dropped. Arrays replace whole.
|
|
431
|
+
*/
|
|
432
|
+
export function overlayDocument(base, section) {
|
|
433
|
+
if (section === undefined) return base;
|
|
434
|
+
if (!isPlainObject(base) || !isPlainObject(section)) return section;
|
|
435
|
+
const merged = { ...base };
|
|
436
|
+
for (const [key, value] of Object.entries(section)) {
|
|
437
|
+
merged[key] = key in merged ? overlayDocument(merged[key], value) : value;
|
|
438
|
+
}
|
|
439
|
+
return merged;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* Parse a model reference into an explicit provider/model pair.
|
|
444
|
+
* @param value - `auto`, an explicit `provider/model`, or undefined.
|
|
445
|
+
* @returns the explicit pair, or undefined for `auto`/absent (inherit the conversation's route).
|
|
446
|
+
*/
|
|
447
|
+
function modelRefToTarget(value) {
|
|
448
|
+
if (value === undefined || value === AUTO) return undefined;
|
|
449
|
+
const slash = value.indexOf('/');
|
|
450
|
+
return { provider: value.slice(0, slash), model: value.slice(slash + 1) };
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Resolve the effective policy for one routed conversation target: per-model
|
|
455
|
+
* beats per-provider beats global, per field, in either unit.
|
|
456
|
+
*/
|
|
457
|
+
export function resolvePolicy(config, target, contextWindow) {
|
|
458
|
+
const layers = layersFor(config, target);
|
|
459
|
+
const window = Number.isFinite(contextWindow) && contextWindow > 0 ? contextWindow : undefined;
|
|
460
|
+
|
|
461
|
+
const threshold = pickForm(layers, 'threshold', 'thresholdTokens');
|
|
462
|
+
const retain = pickForm(layers, 'retain', 'retainTokens');
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* Express one declared field as both units, so the ordering check compares like
|
|
466
|
+
* with like.
|
|
467
|
+
*/
|
|
468
|
+
const deferred = [];
|
|
469
|
+
const budgetOf = (declaration, defaultRatio, tokensKey) => {
|
|
470
|
+
if (declaration.unit === 'tokens') {
|
|
471
|
+
if (window === undefined) {
|
|
472
|
+
deferred.push(tokensKey);
|
|
473
|
+
return { ratio: defaultRatio, tokens: undefined };
|
|
474
|
+
}
|
|
475
|
+
return { ratio: declaration.value / window, tokens: declaration.value };
|
|
476
|
+
}
|
|
477
|
+
const ratio = declaration.value ?? defaultRatio;
|
|
478
|
+
return { ratio, tokens: window === undefined ? undefined : Math.floor(window * ratio) };
|
|
479
|
+
};
|
|
480
|
+
|
|
481
|
+
const thresholdBudget = budgetOf(threshold, DEFAULT_THRESHOLD_RATIO, 'thresholdTokens');
|
|
482
|
+
const retainBudget = budgetOf(retain, DEFAULT_RETAIN_RATIO, 'retainTokens');
|
|
483
|
+
|
|
484
|
+
// Compared in whichever unit is exact: tokens once the window is known, the
|
|
485
|
+
// declared ratios otherwise. A deferred absolute budget is not comparable at
|
|
486
|
+
// all — `applyPolicy` refuses it where the window is supposed to be known, so
|
|
487
|
+
// the comparison is deferred to the same place as the value.
|
|
488
|
+
if (deferred.length === 0) {
|
|
489
|
+
const describe = (budget) =>
|
|
490
|
+
budget.tokens === undefined ? `${budget.ratio}` : `${budget.tokens} tokens (${budget.ratio})`;
|
|
491
|
+
const inverted =
|
|
492
|
+
window === undefined
|
|
493
|
+
? retainBudget.ratio >= thresholdBudget.ratio
|
|
494
|
+
: retainBudget.tokens >= thresholdBudget.tokens;
|
|
495
|
+
if (inverted) {
|
|
496
|
+
throw new CompactionConfigError(
|
|
497
|
+
`retain (${describe(retainBudget)}) must be less than threshold (${describe(thresholdBudget)}) for ${target.provider}/${target.model}`,
|
|
498
|
+
);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* The headroom a compaction needs to be able to succeed. Reported, not
|
|
504
|
+
* enforced; see {@link MIN_COMPACT_GAP_TOKENS}.
|
|
505
|
+
*/
|
|
506
|
+
const warnings = [];
|
|
507
|
+
if (window !== undefined) {
|
|
508
|
+
const gap = thresholdBudget.tokens - retainBudget.tokens;
|
|
509
|
+
if (gap < MIN_COMPACT_GAP_TOKENS) {
|
|
510
|
+
warnings.push(
|
|
511
|
+
`threshold (${thresholdBudget.tokens}) leaves only ${gap} tokens above retain (${retainBudget.tokens}), ` +
|
|
512
|
+
`below the ${MIN_COMPACT_GAP_TOKENS}-token minimum a summary needs to be smaller than the region it replaces`,
|
|
513
|
+
);
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
for (const shadow of shadowedUnits(layers)) warnings.push(shadow);
|
|
517
|
+
|
|
518
|
+
const summarizationModel = pick(layers, 'summarizationModel') ?? AUTO;
|
|
519
|
+
const summarizationTarget = modelRefToTarget(summarizationModel);
|
|
520
|
+
// The chain is resolved against the *primary* route, not against the layer's
|
|
521
|
+
// own text: `summarizationModel: "auto"` resolves to the conversation's route,
|
|
522
|
+
// which differs per target, so an entry repeating it can only be caught here.
|
|
523
|
+
// Such an entry is a no-op that re-sends the entire summary prompt at full
|
|
524
|
+
// cold-read price to a route that just failed — the most expensive way to
|
|
525
|
+
// accomplish nothing, and the one mistake a hand-written chain actually makes.
|
|
526
|
+
let summarizationFallback = (pick(layers, 'summarizationFallback') ?? []).map(modelRefToTarget);
|
|
527
|
+
// What the primary actually resolves to. `auto` means "the conversation's own
|
|
528
|
+
// route", which the parent reads from the latest routed request — so under
|
|
529
|
+
// `auto` the primary *is* this target, and an entry naming it is the same
|
|
530
|
+
// mistake as naming an explicit primary.
|
|
531
|
+
const primary = summarizationTarget ?? { provider: target.provider, model: target.model };
|
|
532
|
+
// Remove redundant primary entries rather than disable all compaction. A
|
|
533
|
+
// repeated route is a no-op: retrying the route that just failed re-sends
|
|
534
|
+
// the whole summary prompt for nothing. Keep the remaining chain order.
|
|
535
|
+
summarizationFallback = summarizationFallback.filter((entry, index) => {
|
|
536
|
+
const isPrimary = entry.provider === primary.provider && entry.model === primary.model;
|
|
537
|
+
if (isPrimary) {
|
|
538
|
+
warnings.push(
|
|
539
|
+
`summarizationFallback[${index}] (${entry.provider}/${entry.model}) is the primary summarization route; it was skipped, ` +
|
|
540
|
+
'because retrying the route that just failed re-sends the whole summary prompt for nothing.',
|
|
541
|
+
);
|
|
542
|
+
}
|
|
543
|
+
return !isPrimary;
|
|
544
|
+
});
|
|
545
|
+
|
|
546
|
+
return deepFreeze({
|
|
547
|
+
target: { provider: target.provider, model: target.model },
|
|
548
|
+
window,
|
|
549
|
+
thresholdRatio: thresholdBudget.ratio,
|
|
550
|
+
retainRatio: retainBudget.ratio,
|
|
551
|
+
thresholdTokens: thresholdBudget.tokens,
|
|
552
|
+
retainTokens: retainBudget.tokens,
|
|
553
|
+
/** Which units the winning layers stated, and where they came from. */
|
|
554
|
+
absolute: { threshold: threshold.unit === 'tokens', retain: retain.unit === 'tokens' },
|
|
555
|
+
/** Absolute fields that could not be converted for want of a window. */
|
|
556
|
+
deferred,
|
|
557
|
+
warnings,
|
|
558
|
+
maxTokens: pick(layers, 'maxTokens') ?? DEFAULT_MAX_TOKENS,
|
|
559
|
+
/** Left undefined when no layer states one, so the parent's own default stands. */
|
|
560
|
+
headroomTokens: pick(layers, 'headroomTokens'),
|
|
561
|
+
compactionRetries: pick(layers, 'compactionRetries') ?? 1,
|
|
562
|
+
maxOverflowRetries: pick(layers, 'maxOverflowRetries') ?? 1,
|
|
563
|
+
summarizationTarget,
|
|
564
|
+
summarizationModel,
|
|
565
|
+
/** Ordered fallback routes, already checked against `summarizationTarget`. */
|
|
566
|
+
summarizationFallback,
|
|
567
|
+
source: {
|
|
568
|
+
override: layers.override !== undefined,
|
|
569
|
+
route: layers.route !== undefined,
|
|
570
|
+
fallback: true,
|
|
571
|
+
threshold: { layer: threshold.layer, unit: threshold.unit },
|
|
572
|
+
retain: { layer: retain.layer, unit: retain.unit },
|
|
573
|
+
},
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* Translate one resolved policy into the flat shape the parent engine consumes,
|
|
579
|
+
* naming only the fields this plugin owns (the caller seeds the rest from the
|
|
580
|
+
* parent's own resolved defaults).
|
|
581
|
+
*/
|
|
582
|
+
export function toBasicConfig(policy) {
|
|
583
|
+
const config = {
|
|
584
|
+
maxTokens: policy.maxTokens,
|
|
585
|
+
compactionRetries: policy.compactionRetries,
|
|
586
|
+
maxOverflowRetries: policy.maxOverflowRetries,
|
|
587
|
+
summarizationProvider: policy.summarizationTarget?.provider ?? '',
|
|
588
|
+
summarizationModel: policy.summarizationTarget?.model ?? '',
|
|
589
|
+
};
|
|
590
|
+
// Named only when a layer stated one: the field is in the parent's schema with
|
|
591
|
+
// its own default, and writing `undefined` over it would make the loader treat
|
|
592
|
+
// the key as present-but-empty rather than absent.
|
|
593
|
+
if (policy.headroomTokens !== undefined) config.headroomTokens = policy.headroomTokens;
|
|
594
|
+
if (policy.absolute.threshold && policy.window !== undefined) {
|
|
595
|
+
config.thresholdRatio = (policy.thresholdTokens + 0.5) / policy.window;
|
|
596
|
+
} else {
|
|
597
|
+
config.thresholdRatio = policy.thresholdRatio;
|
|
598
|
+
}
|
|
599
|
+
// Exactly one retention unit, because the parent treats the two as mutually
|
|
600
|
+
// exclusive. A deferred absolute retention has no token value to send, and
|
|
601
|
+
// `applyPolicy` has already refused that policy by the time this is reached.
|
|
602
|
+
if (policy.absolute.retain && policy.retainTokens !== undefined) {
|
|
603
|
+
config.retainTokens = policy.retainTokens;
|
|
604
|
+
} else {
|
|
605
|
+
config.retainRatio = policy.retainRatio;
|
|
606
|
+
}
|
|
607
|
+
return config;
|
|
608
|
+
}
|