@magic6/dsh-compaction-policy-engine 0.0.0-stage → 0.5.4

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.
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "dsh-standard-compaction-policy-example",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "description": "Example bundle: override the DSH standard preset to use dsh-compaction-policy-engine.",
7
+ "dsh": {
8
+ "bundle": {
9
+ "patch": "./cordis.patch.yml"
10
+ }
11
+ }
12
+ }
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Client-safe policy view for `dsh-compaction-policy-engine`.
3
+ *
4
+ * The session-header indicator answers "which policy is this conversation under,
5
+ * and where will it fire?" from data the browser genuinely has: the resolved
6
+ * settings document and the session's `contextPressure`/`modelSelection`
7
+ * projections. That is a *view*, not the host's resolver — and `client.js` is
8
+ * served verbatim and cannot import, so this module is inlined there (see the
9
+ * drift test in `test/client-policy.test.js`).
10
+ *
11
+ * @module dsh-compaction-policy-engine/client-policy
12
+ */
13
+
14
+ /** The only keys a policy layer may carry, in the order the panel lists them. */
15
+ export const LAYER_FIELDS = [
16
+ 'threshold',
17
+ 'thresholdTokens',
18
+ 'retain',
19
+ 'retainTokens',
20
+ 'headroomTokens',
21
+ 'maxTokens',
22
+ 'summarizationModel',
23
+ 'summarizationFallback',
24
+ ];
25
+
26
+ /** The literal `auto` sentinel, meaning "inherit the conversation's own model". */
27
+ export const AUTO = 'auto';
28
+
29
+ /** `compaction-basic`'s own default trigger ratio, shown when no layer states one. */
30
+ export const ENGINE_DEFAULT_THRESHOLD = 0.8;
31
+
32
+ /** `compaction-basic`'s own default retention ratio. */
33
+ export const ENGINE_DEFAULT_RETAIN = 0.16;
34
+
35
+ /**
36
+ * Minimum room a compaction must free, mirrored from the host's `policy.js`.
37
+ */
38
+ export const MIN_COMPACT_GAP_TOKENS = 8192;
39
+
40
+ /** True for a plain object (not null, not an array). */
41
+ function isPlainObject(value) {
42
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
43
+ }
44
+
45
+ /**
46
+ * The routed target a conversation is using, from its projection: the latest
47
+ * durable request wins, falling back to the session's selected model.
48
+ */
49
+ export function routeOf(modelSelection) {
50
+ const candidate = modelSelection?.lastUsed ?? modelSelection?.next;
51
+ if (!isPlainObject(candidate)) return undefined;
52
+ const { provider, model } = candidate;
53
+ if (typeof provider !== 'string' || provider.length === 0) return undefined;
54
+ if (typeof model !== 'string' || model.length === 0) return undefined;
55
+ return { provider, model };
56
+ }
57
+
58
+ /**
59
+ * Split one resolved settings document into the override layers, most specific
60
+ * first (`models[]` → `providers{}` → `default`), keeping only layers that
61
+ * actually state a field.
62
+ */
63
+ export function layersOf(value, user, target) {
64
+ const override = Array.isArray(value?.models)
65
+ ? value.models.find((entry) => entry?.provider === target?.provider && entry?.model === target?.model)
66
+ : undefined;
67
+ const userOverride = Array.isArray(user?.models)
68
+ ? user.models.find((entry) => entry?.provider === target?.provider && entry?.model === target?.model)
69
+ : undefined;
70
+ const routeName = target?.provider;
71
+ const route = routeName === undefined ? undefined : value?.providers?.[routeName];
72
+ const userRoute = routeName === undefined ? undefined : user?.providers?.[routeName];
73
+ return {
74
+ routeName,
75
+ layers: [
76
+ { kind: 'model', layer: override, user: userOverride !== undefined },
77
+ { kind: 'provider', layer: route, user: userRoute !== undefined },
78
+ { kind: 'default', layer: value?.default, user: user?.default !== undefined },
79
+ ],
80
+ };
81
+ }
82
+
83
+ /**
84
+ * Resolve the effective policy for one target out of a resolved settings
85
+ * document, field by field (`models[]` → `providers{}` → `default`).
86
+ *
87
+ * `used` names the winning declared value, while `overridden` says whether a user
88
+ * layer (not the composition base) supplied it — the card shows both.
89
+ */
90
+ export function resolveView(value, user, target) {
91
+ const { routeName, layers } = layersOf(value, user, target);
92
+ const pick = (field) => {
93
+ for (const candidate of layers) {
94
+ const declared = candidate.layer?.[field];
95
+ if (declared !== undefined) {
96
+ return { value: declared, source: candidate.kind, overridden: candidate.user };
97
+ }
98
+ }
99
+ return { value: undefined, source: 'engine', overridden: false };
100
+ };
101
+ /** The winning declaration of a field that may be stated in either unit. */
102
+ const pickForm = (ratioKey, tokensKey) => {
103
+ for (const candidate of layers) {
104
+ const layer = candidate.layer;
105
+ if (layer === undefined) continue;
106
+ if (layer[tokensKey] !== undefined) {
107
+ return { value: layer[tokensKey], unit: 'tokens', source: candidate.kind, overridden: candidate.user };
108
+ }
109
+ if (layer[ratioKey] !== undefined) {
110
+ return { value: layer[ratioKey], unit: 'ratio', source: candidate.kind, overridden: candidate.user };
111
+ }
112
+ }
113
+ return { value: undefined, unit: 'ratio', source: 'engine', overridden: false };
114
+ };
115
+
116
+ const threshold = pickForm('threshold', 'thresholdTokens');
117
+ const retain = pickForm('retain', 'retainTokens');
118
+ const maxTokens = pick('maxTokens');
119
+ const summarization = pick('summarizationModel');
120
+ const fallback = pick('summarizationFallback');
121
+ // Its own field, not a second name for the derived `gapTokens` below: this is
122
+ // the engine's reserve *below the threshold*, and an operator who set it needs
123
+ // to see it. The gap is computed from the two budgets and means something else
124
+ // entirely, which is why the derived one was renamed.
125
+ const headroom = pick('headroomTokens');
126
+
127
+ return {
128
+ target,
129
+ routeName,
130
+ auto: value?.auto !== false,
131
+ thresholdRatio: threshold.unit === 'ratio' ? threshold.value : undefined,
132
+ retainRatio: retain.unit === 'ratio' ? retain.value : undefined,
133
+ thresholdTokens: threshold.unit === 'tokens' ? threshold.value : undefined,
134
+ retainTokens: retain.unit === 'tokens' ? retain.value : undefined,
135
+ /** The winning declarations themselves, units included. */
136
+ declared: { threshold, retain },
137
+ maxTokens: maxTokens.value,
138
+ summarizationModel: summarization.value ?? AUTO,
139
+ /** The winning layer's ordered chain, or empty when no layer states one. */
140
+ summarizationFallback: fallback.value ?? [],
141
+ headroomTokens: headroom.value,
142
+ source: {
143
+ threshold: threshold.source,
144
+ retain: retain.source,
145
+ maxTokens: maxTokens.source,
146
+ summarizationModel: summarization.source,
147
+ summarizationFallback: fallback.source,
148
+ headroomTokens: headroom.source,
149
+ },
150
+ /** Per-field provenance, including whether the user layer stated it. */
151
+ fields: {
152
+ threshold,
153
+ retain,
154
+ maxTokens,
155
+ summarizationModel: summarization,
156
+ summarizationFallback: fallback,
157
+ headroomTokens: headroom,
158
+ },
159
+ /** Whether any layer for this target came from the user document. */
160
+ overridden: layers.some((candidate) => candidate.user),
161
+ };
162
+ }
163
+
164
+ /**
165
+ * Token budgets implied by a view plus a context window, or null when either is
166
+ * unknown: a ratio is a fraction of the adapter-declared window, not of the
167
+ * conversation.
168
+ */
169
+ export function budgetsOf(view, contextWindow) {
170
+ const window = typeof contextWindow === 'number' && Number.isFinite(contextWindow) ? contextWindow : undefined;
171
+ const tokensOf = (absolute, ratio, fallbackRatio) => {
172
+ if (typeof absolute === 'number') return absolute;
173
+ if (window === undefined) return null;
174
+ const effective = typeof ratio === 'number' ? ratio : fallbackRatio;
175
+ return Math.floor(window * effective);
176
+ };
177
+ const thresholdTokens = tokensOf(view.thresholdTokens, view.thresholdRatio, ENGINE_DEFAULT_THRESHOLD);
178
+ const retainTokens = tokensOf(view.retainTokens, view.retainRatio, ENGINE_DEFAULT_RETAIN);
179
+ return {
180
+ thresholdTokens,
181
+ retainTokens,
182
+ /**
183
+ * What a compaction would free. Below `MIN_COMPACT_GAP_TOKENS` the summary can
184
+ * end up no smaller than what it replaces, so the view says so.
185
+ *
186
+ * Named `gapTokens`, not `headroomTokens`: the engine's own `headroomTokens` is
187
+ * the reserve *below the threshold* and is a configurable knob, so sharing the
188
+ * name would make the panel's derived number indistinguishable from a setting.
189
+ */
190
+ gapTokens: thresholdTokens === null || retainTokens === null ? null : thresholdTokens - retainTokens,
191
+ };
192
+ }