dsh-context-truth 0.0.0-stage → 0.1.2
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 +29 -0
- package/LICENSE +21 -0
- package/README-en.md +137 -0
- package/README.md +144 -2
- package/cordis.patch.yml +27 -0
- package/lib/index.js +618 -0
- package/package.json +56 -4
- package/scripts/build.sh +18 -0
- package/test/index.test.js +331 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,618 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-context-truth — the model's only authority on its own context pressure.
|
|
3
|
+
*
|
|
4
|
+
* WHY THIS EXISTS
|
|
5
|
+
* ---------------
|
|
6
|
+
* Nothing in the harness ever tells the model how full its context is, so the
|
|
7
|
+
* model guesses from the conversation's length. On a long session it guesses
|
|
8
|
+
* "context is nearly exhausted", stops doing write work, and hands off to a
|
|
9
|
+
* subagent — while the host's own meter reads 17% of a 1M window. Worse, the
|
|
10
|
+
* claim lands in the transcript, the next compaction folds it into a summary as
|
|
11
|
+
* "established background", and the false belief survives every later
|
|
12
|
+
* compaction. The model never gets a correction because no correction exists.
|
|
13
|
+
*
|
|
14
|
+
* TWO CAPABILITIES, ONE BELIEF TO KILL
|
|
15
|
+
* ------------------------------------
|
|
16
|
+
* 1. MEASUREMENT IN (default on). One dynamic runtime-context line, refreshed
|
|
17
|
+
* from the host's own token meter, re-injected only when the reading moves a
|
|
18
|
+
* display step. It adds no tool, no message, and no per-step noise — one
|
|
19
|
+
* stable paragraph that changes about a dozen times per compaction cycle.
|
|
20
|
+
* 2. CLAIM FILTERING (default on). The compaction summarizer is told not to
|
|
21
|
+
* record the assistant's own guesses about its remaining budget, so the
|
|
22
|
+
* false belief stops being re-injected as established background.
|
|
23
|
+
*
|
|
24
|
+
* HOW IT PLUGS IN
|
|
25
|
+
* ---------------
|
|
26
|
+
* `systemPrompt.variable()` is evaluated on every prompt assembly with the
|
|
27
|
+
* agent in hand (the same seam the harness uses for `{{model}}` / `{{cwd}}`),
|
|
28
|
+
* and `systemPrompt.context()` contributes the rendered text to the dynamic
|
|
29
|
+
* runtime-context snapshot. The agent loop commits a new "Current runtime
|
|
30
|
+
* context" message only when that rendered snapshot differs byte-for-byte from
|
|
31
|
+
* the retained one, which is why the reading is quantized: identical text costs
|
|
32
|
+
* nothing, drifted text appends.
|
|
33
|
+
*
|
|
34
|
+
* The summarizer directive is the final user message of the `purpose:
|
|
35
|
+
* 'compaction'` call. That call is not an agent-loop request (the loop's own
|
|
36
|
+
* requests are frozen and log-verified), so its tail can be extended through
|
|
37
|
+
* the public `llm/stream` waterfall. Only the tail changes: the replayed
|
|
38
|
+
* conversation prefix — the part the provider caches — stays byte-identical.
|
|
39
|
+
*
|
|
40
|
+
* WHAT IT MEASURES
|
|
41
|
+
* ----------------
|
|
42
|
+
* Primary: `tokenMeter.measure(session).totalTokens` — the host's price for the
|
|
43
|
+
* next request, and the exact number automatic compaction compares against.
|
|
44
|
+
* Fallback: the `contextPressure` projection (provider-reported prompt usage),
|
|
45
|
+
* which is the same figure the Web UI's context ring renders. The auto-compaction
|
|
46
|
+
* point is derived the way `dsh-compaction-basic` derives it:
|
|
47
|
+
* `min(window * thresholdRatio, window - reservedCompletion - headroom)`.
|
|
48
|
+
*
|
|
49
|
+
* NO IMPORTS, NO BUILD: this file is dependency-free ESM on purpose, so the
|
|
50
|
+
* plugin installs into any profile without a node_modules copy or a toolchain.
|
|
51
|
+
* It is both the source and the runtime artifact (`lib/index.js`).
|
|
52
|
+
*/
|
|
53
|
+
|
|
54
|
+
/** Stable cordis plugin name (loader diagnostics, and the runtime-context section name). */
|
|
55
|
+
export const name = 'context-truth'
|
|
56
|
+
|
|
57
|
+
/** Prompt context name; must be unique per layer. */
|
|
58
|
+
export const CONTEXT_NAME = 'context-truth'
|
|
59
|
+
|
|
60
|
+
/** Prompt variable carrying the rendered line. */
|
|
61
|
+
export const VARIABLE_NAME = 'context_occupancy'
|
|
62
|
+
|
|
63
|
+
/** Service required before the contribution can register. */
|
|
64
|
+
export const inject = ['systemPrompt']
|
|
65
|
+
|
|
66
|
+
/** Orders the line first inside the runtime-context block (sandbox is 110, approval 115). */
|
|
67
|
+
const DEFAULT_ORDER = 100
|
|
68
|
+
|
|
69
|
+
/** Substring that identifies the compaction engine's directive wherever `purpose` is absent. */
|
|
70
|
+
const COMPACTION_INSTRUCTION_MARKER = 'acting as a compaction engine'
|
|
71
|
+
|
|
72
|
+
/** Default rules appended to the compaction directive. Keep the first one first: it is the idempotence marker. */
|
|
73
|
+
const DEFAULT_COMPACTION_RULES = [
|
|
74
|
+
"- Never record the assistant's own statements about its remaining context, token budget, or context-window pressure (for example \"context is nearly exhausted\", \"running out of budget\", \"hand off before context runs out\"). Those readings are measured by the host and delivered separately; a model's guess about them is not a durable fact.",
|
|
75
|
+
'- Never record a plan to stop, defer, or hand off work whose only justification was context pressure. Record the actual task state instead.',
|
|
76
|
+
]
|
|
77
|
+
|
|
78
|
+
const DEFAULT_OPTIONS = {
|
|
79
|
+
/** Master switch for the measured line; `false` mounts no context contribution. */
|
|
80
|
+
enabled: true,
|
|
81
|
+
/** Where the line sits among runtime-context contributions. */
|
|
82
|
+
order: DEFAULT_ORDER,
|
|
83
|
+
/** Text language: 'en' | 'zh'. */
|
|
84
|
+
language: 'en',
|
|
85
|
+
/** Emit the auto-compaction point and the headroom left before it. */
|
|
86
|
+
showAutoCompactionPoint: true,
|
|
87
|
+
/**
|
|
88
|
+
* Mirror of `dsh-compaction-basic`'s policy. Keep these equal to the profile's
|
|
89
|
+
* compaction config; the line only reports the point, it never enforces it.
|
|
90
|
+
*/
|
|
91
|
+
thresholdRatio: 0.8,
|
|
92
|
+
headroomTokens: 65536,
|
|
93
|
+
/** Reserved completion tokens; `null` reads the routed request's own maxTokens. */
|
|
94
|
+
reservedCompletionTokens: null,
|
|
95
|
+
/** Band edges as a fraction of the auto-compaction point. */
|
|
96
|
+
moderateAt: 0.5,
|
|
97
|
+
tightAt: 0.85,
|
|
98
|
+
/** Fraction of the compaction point a reading must fall back below to leave a band. */
|
|
99
|
+
hysteresis: 0.05,
|
|
100
|
+
/**
|
|
101
|
+
* Display quantum as a percentage of the window. The rendered text changes
|
|
102
|
+
* only when the reading crosses a quantum, which is what keeps re-injection
|
|
103
|
+
* (and therefore cache churn) rare. 0 disables quantization — do not: the
|
|
104
|
+
* snapshot would then be re-committed on every single step.
|
|
105
|
+
*/
|
|
106
|
+
quantumPercent: 5,
|
|
107
|
+
/** Append the "this line is the only authority" clause. */
|
|
108
|
+
authoritative: true,
|
|
109
|
+
/** Add the explicit "earlier claims are stale" clause to the calm band. */
|
|
110
|
+
staleClaimClause: true,
|
|
111
|
+
/** Log each band change through ctx.logger, when a logger is present. */
|
|
112
|
+
logBandChanges: true,
|
|
113
|
+
/** Append `compactionRules` to the summarizer directive. */
|
|
114
|
+
patchCompactionPrompt: true,
|
|
115
|
+
/** Rules appended to the summarizer directive; `[]` disables the append. */
|
|
116
|
+
compactionRules: DEFAULT_COMPACTION_RULES,
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Clamp a numeric option, falling back when it is not a finite number. */
|
|
120
|
+
function num(value, fallback) {
|
|
121
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : fallback
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Merge user config over the defaults with light validation. */
|
|
125
|
+
function resolveOptions(config) {
|
|
126
|
+
const raw = config !== null && typeof config === 'object' ? config : {}
|
|
127
|
+
const merged = { ...DEFAULT_OPTIONS, ...raw }
|
|
128
|
+
const rules = Array.isArray(merged.compactionRules)
|
|
129
|
+
? merged.compactionRules.filter((rule) => typeof rule === 'string' && rule.trim().length > 0)
|
|
130
|
+
: DEFAULT_COMPACTION_RULES
|
|
131
|
+
return {
|
|
132
|
+
...merged,
|
|
133
|
+
order: num(merged.order, DEFAULT_ORDER),
|
|
134
|
+
language: merged.language === 'zh' ? 'zh' : 'en',
|
|
135
|
+
thresholdRatio: num(merged.thresholdRatio, DEFAULT_OPTIONS.thresholdRatio),
|
|
136
|
+
headroomTokens: Math.max(0, num(merged.headroomTokens, DEFAULT_OPTIONS.headroomTokens)),
|
|
137
|
+
reservedCompletionTokens:
|
|
138
|
+
merged.reservedCompletionTokens === null || merged.reservedCompletionTokens === undefined
|
|
139
|
+
? null
|
|
140
|
+
: Math.max(0, num(merged.reservedCompletionTokens, 0)),
|
|
141
|
+
moderateAt: num(merged.moderateAt, DEFAULT_OPTIONS.moderateAt),
|
|
142
|
+
tightAt: num(merged.tightAt, DEFAULT_OPTIONS.tightAt),
|
|
143
|
+
hysteresis: Math.max(0, num(merged.hysteresis, DEFAULT_OPTIONS.hysteresis)),
|
|
144
|
+
quantumPercent: Math.max(0, num(merged.quantumPercent, DEFAULT_OPTIONS.quantumPercent)),
|
|
145
|
+
compactionRules: rules,
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Compact token count: 172437 -> "172K", 1000000 -> "1.00M". */
|
|
150
|
+
function formatTokens(value) {
|
|
151
|
+
if (!Number.isFinite(value) || value < 0) return '?'
|
|
152
|
+
if (value >= 1e6) return `${(value / 1e6).toFixed(2)}M`
|
|
153
|
+
if (value >= 1e3) return `${Math.round(value / 1e3)}K`
|
|
154
|
+
return String(Math.round(value))
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Percentage of `total`, rounded to a whole number. */
|
|
158
|
+
function percentOf(value, total) {
|
|
159
|
+
if (!Number.isFinite(value) || !Number.isFinite(total) || total <= 0) return null
|
|
160
|
+
return Math.round((value / total) * 100)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Resolve a service that may or may not be mounted, without ever throwing. */
|
|
164
|
+
function safeGet(ctx, key) {
|
|
165
|
+
try {
|
|
166
|
+
return ctx.get(key)
|
|
167
|
+
} catch {
|
|
168
|
+
return undefined
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Read the host's own occupancy figure for one session.
|
|
174
|
+
* @returns `{ used, window, reserved, threshold }`; any field may be `undefined`.
|
|
175
|
+
*/
|
|
176
|
+
function readOccupancy(ctx, session, options) {
|
|
177
|
+
const result = {}
|
|
178
|
+
let used
|
|
179
|
+
let window_
|
|
180
|
+
|
|
181
|
+
const meter = safeGet(ctx, 'tokenMeter')
|
|
182
|
+
if (meter !== undefined && typeof meter.measure === 'function') {
|
|
183
|
+
try {
|
|
184
|
+
const measured = meter.measure(session)
|
|
185
|
+
if (measured !== undefined && Number.isFinite(measured.totalTokens)) used = measured.totalTokens
|
|
186
|
+
} catch {
|
|
187
|
+
used = undefined // a broken meter replay is the meter's business, not the model's
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
try {
|
|
192
|
+
const context = typeof session.requestContext === 'function' ? session.requestContext() : undefined
|
|
193
|
+
if (context !== undefined && context !== null && Number.isFinite(context.contextWindow)) {
|
|
194
|
+
window_ = context.contextWindow
|
|
195
|
+
}
|
|
196
|
+
} catch {
|
|
197
|
+
window_ = undefined
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
if (used === undefined || window_ === undefined) {
|
|
201
|
+
const projections = safeGet(ctx, 'sessionProjections')
|
|
202
|
+
if (projections !== undefined && typeof projections.stateOf === 'function') {
|
|
203
|
+
try {
|
|
204
|
+
const state = projections.stateOf(session, 'contextPressure')
|
|
205
|
+
if (state !== null && typeof state === 'object') {
|
|
206
|
+
if (used === undefined && Number.isFinite(state.pressureTokens)) {
|
|
207
|
+
used = Math.max(
|
|
208
|
+
0,
|
|
209
|
+
state.pressureTokens +
|
|
210
|
+
(Number.isFinite(state.surfaceTokens) ? state.surfaceTokens : 0) -
|
|
211
|
+
(Number.isFinite(state.sampledSurfaceTokens) ? state.sampledSurfaceTokens : 0),
|
|
212
|
+
)
|
|
213
|
+
}
|
|
214
|
+
if (window_ === undefined && Number.isFinite(state.contextWindow)) window_ = state.contextWindow
|
|
215
|
+
}
|
|
216
|
+
} catch {
|
|
217
|
+
// keep whatever was already resolved
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
result.used = used
|
|
223
|
+
result.window = window_
|
|
224
|
+
|
|
225
|
+
let reserved = options.reservedCompletionTokens
|
|
226
|
+
if (reserved === null) {
|
|
227
|
+
try {
|
|
228
|
+
const header = typeof session.requestHeader === 'function' ? session.requestHeader() : undefined
|
|
229
|
+
const declared = header?.config?.maxTokens
|
|
230
|
+
reserved = Number.isFinite(declared) ? declared : 0
|
|
231
|
+
} catch {
|
|
232
|
+
reserved = 0
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
result.reserved = reserved
|
|
236
|
+
|
|
237
|
+
if (options.showAutoCompactionPoint && Number.isFinite(window_)) {
|
|
238
|
+
const budget = window_ - reserved - options.headroomTokens
|
|
239
|
+
const threshold = Math.floor(Math.min(window_ * options.thresholdRatio, budget))
|
|
240
|
+
if (threshold > 0 && threshold < window_) result.threshold = threshold
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
return result
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Bands from calmest to most urgent. */
|
|
247
|
+
const BANDS = ['ample', 'moderate', 'tight', 'critical']
|
|
248
|
+
|
|
249
|
+
/** Lower edge of a band, as a fraction of the auto-compaction point. */
|
|
250
|
+
function bandFloor(band, options) {
|
|
251
|
+
switch (band) {
|
|
252
|
+
case 'moderate':
|
|
253
|
+
return options.moderateAt
|
|
254
|
+
case 'tight':
|
|
255
|
+
return options.tightAt
|
|
256
|
+
case 'critical':
|
|
257
|
+
return 1
|
|
258
|
+
default:
|
|
259
|
+
return 0
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Raw band for a reading, before hysteresis. */
|
|
264
|
+
function rawBand(ratio, options) {
|
|
265
|
+
if (ratio >= 1) return 'critical'
|
|
266
|
+
if (ratio >= options.tightAt) return 'tight'
|
|
267
|
+
if (ratio >= options.moderateAt) return 'moderate'
|
|
268
|
+
return 'ample'
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Apply hysteresis so a reading hovering on an edge does not flip the published
|
|
273
|
+
* text back and forth (each flip would append a runtime-context message).
|
|
274
|
+
*/
|
|
275
|
+
function settleBand(ratio, previous, options) {
|
|
276
|
+
const raw = rawBand(ratio, options)
|
|
277
|
+
if (previous === undefined) return raw
|
|
278
|
+
// Rising urgency is immediate: the model must hear about pressure at once.
|
|
279
|
+
if (BANDS.indexOf(raw) >= BANDS.indexOf(previous)) return raw
|
|
280
|
+
// Calm returns only once the reading falls clear of the previous band's floor.
|
|
281
|
+
return ratio <= bandFloor(previous, options) - options.hysteresis ? raw : previous
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** The display step for one window, in tokens. */
|
|
285
|
+
function displayStep(window_, options) {
|
|
286
|
+
return options.quantumPercent > 0 && Number.isFinite(window_) && window_ > 0
|
|
287
|
+
? Math.max(1000, Math.round((options.quantumPercent / 100) * window_))
|
|
288
|
+
: 1
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Quantize a reading DOWN so identical states render byte-identical text. */
|
|
292
|
+
function quantize(used, window_, options) {
|
|
293
|
+
if (!Number.isFinite(used)) return undefined
|
|
294
|
+
const step = displayStep(window_, options)
|
|
295
|
+
return Math.floor(used / step) * step
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Quantize the remaining headroom DOWN on a step that tightens as the room runs
|
|
300
|
+
* out. Two rules meet here: the reading must never promise more room than the
|
|
301
|
+
* session has (so it always rounds down), and it must stay useful to within a
|
|
302
|
+
* few thousand tokens once compaction is close (so the step shrinks near zero).
|
|
303
|
+
* Every step is a function of the reading, so a whole display bucket renders to
|
|
304
|
+
* one identical string.
|
|
305
|
+
*/
|
|
306
|
+
function quantizeHeadroom(headroom, window_, options) {
|
|
307
|
+
if (!Number.isFinite(headroom) || headroom < 0) return undefined
|
|
308
|
+
const coarse = displayStep(window_, options)
|
|
309
|
+
const tiers = [
|
|
310
|
+
coarse,
|
|
311
|
+
Math.max(1000, Math.round(coarse * 0.4)),
|
|
312
|
+
Math.max(1000, Math.round(coarse * 0.1)),
|
|
313
|
+
2000,
|
|
314
|
+
]
|
|
315
|
+
let step = tiers[tiers.length - 1]
|
|
316
|
+
for (const tier of tiers) {
|
|
317
|
+
if (headroom >= 4 * tier) {
|
|
318
|
+
step = tier
|
|
319
|
+
break
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
return Math.floor(headroom / step) * step
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** The clause that closes every variant. */
|
|
326
|
+
function authorityClause(language) {
|
|
327
|
+
return language === 'zh'
|
|
328
|
+
? '本行由宿主实测,是上下文压力的唯一权威——不要凭对话长度或轮数自行估计。'
|
|
329
|
+
: "This host-measured line is the only authority on context pressure; never estimate it from the conversation's length."
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** The clause that retires claims inherited from earlier turns and checkpoints. */
|
|
333
|
+
function staleClause(language) {
|
|
334
|
+
return language === 'zh'
|
|
335
|
+
? '此前任何"上下文快满了"的说法(含压缩检查点里的)都已作废。'
|
|
336
|
+
: 'Earlier claims that context is nearly exhausted — including ones inside compacted checkpoints — are stale.'
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** Render the reading for one band. Pure: same inputs, same bytes. */
|
|
340
|
+
function render(band, reading, options) {
|
|
341
|
+
const zh = options.language === 'zh'
|
|
342
|
+
const parts = []
|
|
343
|
+
if (options.authoritative) parts.push(authorityClause(options.language))
|
|
344
|
+
if (band === 'ample' && options.staleClaimClause) parts.push(staleClause(options.language))
|
|
345
|
+
const tail = parts.length === 0 ? '' : ` ${parts.join(' ')}`
|
|
346
|
+
|
|
347
|
+
if (band === 'unknown') {
|
|
348
|
+
return zh
|
|
349
|
+
? `上下文实况:本会话尚未取到用量读数。不要据此声称上下文紧张。${tail}`
|
|
350
|
+
: `Context occupancy: no reading yet in this session. Do not claim context is scarce on that basis.${tail}`
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const used = formatTokens(reading.quantized)
|
|
354
|
+
const window_ = formatTokens(reading.window)
|
|
355
|
+
const percent = reading.percent
|
|
356
|
+
const head = reading.headroom
|
|
357
|
+
const point = Number.isFinite(reading.threshold)
|
|
358
|
+
? zh
|
|
359
|
+
? ` 自动压缩阈值 ${formatTokens(reading.threshold)}(窗口的 ${percentOf(reading.threshold, reading.window)}%)。`
|
|
360
|
+
: ` Automatic compaction fires at ${formatTokens(reading.threshold)} (${percentOf(reading.threshold, reading.window)}% of the window).`
|
|
361
|
+
: ''
|
|
362
|
+
const remaining =
|
|
363
|
+
head !== undefined
|
|
364
|
+
? zh
|
|
365
|
+
? ` 距阈值还有约 ${head === 0 && reading.headroomRaw > 0 ? '不足 1K' : formatTokens(head)} tokens。`
|
|
366
|
+
: ` About ${head === 0 && reading.headroomRaw > 0 ? 'less than 1K' : formatTokens(head)} tokens of headroom remain before it.`
|
|
367
|
+
: ''
|
|
368
|
+
const head0 = zh
|
|
369
|
+
? `上下文实况(宿主实测):已用 ${used} / ${window_}(${percent}%)。`
|
|
370
|
+
: `Context occupancy (host-measured): ${used} / ${window_} tokens used (${percent}%).`
|
|
371
|
+
|
|
372
|
+
switch (band) {
|
|
373
|
+
case 'ample':
|
|
374
|
+
return zh
|
|
375
|
+
? `${head0}${point}${remaining} 上下文不紧张——不要因为"上下文不够"而收尾、交接子代理或缩小范围。${tail}`
|
|
376
|
+
: `${head0}${point}${remaining} Context is NOT scarce — do not wrap up, hand off to a subagent, or narrow scope for context reasons.${tail}`
|
|
377
|
+
case 'moderate':
|
|
378
|
+
return zh
|
|
379
|
+
? `${head0}${point}${remaining} 仍有充足余量,继续推进即可,顺手把关键状态写进文档或提交。${tail}`
|
|
380
|
+
: `${head0}${point}${remaining} There is still real headroom — keep going, and keep durable notes or commits current as you work.${tail}`
|
|
381
|
+
case 'tight':
|
|
382
|
+
return zh
|
|
383
|
+
? `${head0}${point}${remaining} 余量确实不多了——收完当前这一步、把状态落到磁盘,再考虑交接。${tail}`
|
|
384
|
+
: `${head0}${point}${remaining} Headroom is genuinely small — finish the current step, land durable state, then hand off.${tail}`
|
|
385
|
+
default:
|
|
386
|
+
return zh
|
|
387
|
+
? `${head0}${point} 已到或越过自动压缩点——接下来可能发生压缩折叠,别让关键状态只存在于本窗口。${tail}`
|
|
388
|
+
: `${head0}${point} At or past the automatic compaction point — expect earlier turns to be folded; keep nothing critical only in this window.${tail}`
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** The line used before any measurement exists (and whenever one cannot be taken). */
|
|
393
|
+
function renderUnknown(options) {
|
|
394
|
+
return render('unknown', {}, options)
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** Concatenate the text blocks of one LLM message, or `undefined` when it has none. */
|
|
398
|
+
function messageText(message) {
|
|
399
|
+
const content = message?.content
|
|
400
|
+
if (!Array.isArray(content)) return undefined
|
|
401
|
+
const parts = []
|
|
402
|
+
for (const block of content) {
|
|
403
|
+
if (block !== null && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string') {
|
|
404
|
+
parts.push(block.text)
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
return parts.length === 0 ? undefined : parts.join('\n')
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* Extend one compaction directive with the extra rules.
|
|
412
|
+
* @param text - the directive's full text.
|
|
413
|
+
* @param rules - rules to append; an empty list patches nothing.
|
|
414
|
+
* @returns the extended text, or `undefined` when no patch is due.
|
|
415
|
+
*/
|
|
416
|
+
function patchCompactionInstruction(text, rules) {
|
|
417
|
+
if (typeof text !== 'string' || !text.includes(COMPACTION_INSTRUCTION_MARKER)) return undefined
|
|
418
|
+
if (rules.length === 0) return undefined
|
|
419
|
+
if (text.includes(rules[0])) return undefined // already patched: stay idempotent
|
|
420
|
+
return `${text}\n${rules.join('\n')}`
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* Test whether one LLM request is the compaction summarization call.
|
|
425
|
+
* @param options - request envelope observed at the `llm/stream` waterfall.
|
|
426
|
+
* @returns whether the request carries the compaction directive.
|
|
427
|
+
*/
|
|
428
|
+
function isCompactionRequest(options) {
|
|
429
|
+
if (options === null || typeof options !== 'object') return false
|
|
430
|
+
const messages = options.messages
|
|
431
|
+
if (!Array.isArray(messages) || messages.length === 0) return false
|
|
432
|
+
const text = messageText(messages[messages.length - 1])
|
|
433
|
+
if (text === undefined || !text.includes(COMPACTION_INSTRUCTION_MARKER)) return false
|
|
434
|
+
return options.purpose === undefined || options.purpose === 'compaction'
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* Patch one compaction request in place by replacing its trailing directive.
|
|
439
|
+
* @param options - request envelope observed at the `llm/stream` waterfall.
|
|
440
|
+
* @param rules - rules to append.
|
|
441
|
+
* @returns whether the request now carries the rules.
|
|
442
|
+
*/
|
|
443
|
+
function patchCompactionRequest(options, rules) {
|
|
444
|
+
if (!isCompactionRequest(options)) return false
|
|
445
|
+
const messages = options.messages
|
|
446
|
+
const last = messages[messages.length - 1]
|
|
447
|
+
const text = messageText(last)
|
|
448
|
+
const patched = patchCompactionInstruction(text, rules)
|
|
449
|
+
if (patched === undefined) return text !== undefined && rules.length > 0 && text.includes(rules[0])
|
|
450
|
+
try {
|
|
451
|
+
options.messages = [...messages.slice(0, -1), { ...last, content: [{ type: 'text', text: patched }] }]
|
|
452
|
+
} catch {
|
|
453
|
+
return false
|
|
454
|
+
}
|
|
455
|
+
const applied = messageText(options.messages[options.messages.length - 1])
|
|
456
|
+
return applied !== undefined && applied.includes(rules[0])
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* Mount both contributions for the lifetime of `ctx`.
|
|
461
|
+
*
|
|
462
|
+
* Mounting twice in one scope is a supported outcome, not a crash: a deployment
|
|
463
|
+
* that both lists the package as a bundle and injects it at runtime mounts two
|
|
464
|
+
* instances of the same layer, and the second one cannot own the same prompt
|
|
465
|
+
* context and variable. The first instance keeps serving and the second stays
|
|
466
|
+
* inert, so the duplicate never turns into a failed plugin row.
|
|
467
|
+
*
|
|
468
|
+
* @param ctx - plugin context; registrations and listeners are disposed with it.
|
|
469
|
+
* @param config - optional overrides of the defaults documented above.
|
|
470
|
+
*/
|
|
471
|
+
export function apply(ctx, config) {
|
|
472
|
+
const options = resolveOptions(config)
|
|
473
|
+
|
|
474
|
+
if (options.enabled) {
|
|
475
|
+
try {
|
|
476
|
+
installContextLine(ctx, options)
|
|
477
|
+
} catch (error) {
|
|
478
|
+
if (isAlreadyRegistered(error)) {
|
|
479
|
+
const logger = ctx.logger
|
|
480
|
+
if (logger !== undefined && typeof logger.info === 'function') {
|
|
481
|
+
logger.info('context-truth: another instance already owns the context line in this scope; staying inert')
|
|
482
|
+
}
|
|
483
|
+
return
|
|
484
|
+
}
|
|
485
|
+
throw error
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
installCompactionPatch(ctx, options)
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** Whether a registration failed because the name is already taken in this layer. */
|
|
493
|
+
function isAlreadyRegistered(error) {
|
|
494
|
+
return error instanceof Error && error.message.includes('already registered')
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/** Install the `llm/stream` listener that extends the summarizer directive. */
|
|
498
|
+
function installCompactionPatch(ctx, options) {
|
|
499
|
+
if (!options.patchCompactionPrompt || options.compactionRules.length === 0) return
|
|
500
|
+
let warned = false
|
|
501
|
+
ctx.on('llm/stream', (request, next) => {
|
|
502
|
+
try {
|
|
503
|
+
if (!patchCompactionRequest(request, options.compactionRules) && isCompactionRequest(request) && !warned) {
|
|
504
|
+
warned = true
|
|
505
|
+
const logger = ctx.logger
|
|
506
|
+
if (logger !== undefined && typeof logger.warn === 'function') {
|
|
507
|
+
logger.warn('context-truth: could not extend the compaction directive (request envelope is immutable in this deployment)')
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
} catch {
|
|
511
|
+
// Interception must never break a model call.
|
|
512
|
+
}
|
|
513
|
+
return next()
|
|
514
|
+
})
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** Install the dynamic runtime-context line. */
|
|
518
|
+
function installContextLine(ctx, options) {
|
|
519
|
+
/** Last band published per session (hysteresis memory); never rendered. */
|
|
520
|
+
const bands = new WeakMap()
|
|
521
|
+
/** Last text handed out, so a failed read degrades to the previous line. */
|
|
522
|
+
let lastText = renderUnknown(options)
|
|
523
|
+
|
|
524
|
+
const line = (assembly) => {
|
|
525
|
+
try {
|
|
526
|
+
const session = assembly?.agent?.session
|
|
527
|
+
if (session === undefined || session === null) return lastText
|
|
528
|
+
|
|
529
|
+
const reading = readOccupancy(ctx, session, options)
|
|
530
|
+
const window_ = reading.window
|
|
531
|
+
const ratio =
|
|
532
|
+
Number.isFinite(reading.used) && Number.isFinite(window_) && window_ > 0
|
|
533
|
+
? reading.used / window_
|
|
534
|
+
: undefined
|
|
535
|
+
|
|
536
|
+
let band
|
|
537
|
+
if (ratio === undefined) band = 'unknown'
|
|
538
|
+
else if (Number.isFinite(reading.threshold) && reading.threshold > 0) {
|
|
539
|
+
band = settleBand(reading.used / reading.threshold, bands.get(session), options)
|
|
540
|
+
} else {
|
|
541
|
+
band = settleBand(ratio, bands.get(session), options)
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
if (band !== bands.get(session)) {
|
|
545
|
+
const previous = bands.get(session)
|
|
546
|
+
bands.set(session, band)
|
|
547
|
+
if (options.logBandChanges && band !== 'unknown') {
|
|
548
|
+
const logger = ctx.logger
|
|
549
|
+
if (logger !== undefined && typeof logger.info === 'function') {
|
|
550
|
+
logger.info(
|
|
551
|
+
'context-truth: %s -> %s (used=%s window=%s compactionAt=%s)',
|
|
552
|
+
previous ?? 'none',
|
|
553
|
+
band,
|
|
554
|
+
reading.used,
|
|
555
|
+
window_,
|
|
556
|
+
reading.threshold,
|
|
557
|
+
)
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
const quantized = band === 'unknown' ? undefined : quantize(reading.used, window_, options)
|
|
563
|
+
const headroomRaw =
|
|
564
|
+
Number.isFinite(reading.threshold) && Number.isFinite(reading.used)
|
|
565
|
+
? Math.max(0, reading.threshold - reading.used)
|
|
566
|
+
: undefined
|
|
567
|
+
const headroom =
|
|
568
|
+
band === 'unknown' || headroomRaw === undefined
|
|
569
|
+
? undefined
|
|
570
|
+
: quantizeHeadroom(headroomRaw, window_, options)
|
|
571
|
+
lastText = render(
|
|
572
|
+
band,
|
|
573
|
+
{
|
|
574
|
+
quantized,
|
|
575
|
+
headroom,
|
|
576
|
+
headroomRaw,
|
|
577
|
+
used: reading.used,
|
|
578
|
+
window: window_,
|
|
579
|
+
threshold: reading.threshold,
|
|
580
|
+
percent: Number.isFinite(quantized) ? percentOf(quantized, window_) : percentOf(reading.used, window_),
|
|
581
|
+
},
|
|
582
|
+
options,
|
|
583
|
+
)
|
|
584
|
+
return lastText
|
|
585
|
+
} catch {
|
|
586
|
+
// A prompt assembly must never fail because a reading failed.
|
|
587
|
+
return lastText
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
ctx.systemPrompt.variable(VARIABLE_NAME, (assembly) => line(assembly))
|
|
592
|
+
ctx.systemPrompt.context({
|
|
593
|
+
name: CONTEXT_NAME,
|
|
594
|
+
order: options.order,
|
|
595
|
+
text: `{{${VARIABLE_NAME}}}`,
|
|
596
|
+
})
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/** Test-only surface: the pure helpers, so the suite can exercise them directly. */
|
|
600
|
+
export const internals = {
|
|
601
|
+
DEFAULT_OPTIONS,
|
|
602
|
+
DEFAULT_COMPACTION_RULES,
|
|
603
|
+
resolveOptions,
|
|
604
|
+
formatTokens,
|
|
605
|
+
percentOf,
|
|
606
|
+
readOccupancy,
|
|
607
|
+
rawBand,
|
|
608
|
+
settleBand,
|
|
609
|
+
quantize,
|
|
610
|
+
quantizeHeadroom,
|
|
611
|
+
displayStep,
|
|
612
|
+
render,
|
|
613
|
+
renderUnknown,
|
|
614
|
+
messageText,
|
|
615
|
+
patchCompactionInstruction,
|
|
616
|
+
patchCompactionRequest,
|
|
617
|
+
isCompactionRequest,
|
|
618
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-context-truth",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.2",
|
|
4
|
+
"description": "DeepSeek Harness plugin: tells the model its real, host-measured context occupancy every turn — and keeps compaction summaries from carrying false \"context is nearly exhausted\" claims.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"deepseek-harness",
|
|
7
|
+
"dsh",
|
|
8
|
+
"dsh-plugin",
|
|
9
|
+
"context",
|
|
10
|
+
"context-window",
|
|
11
|
+
"token-meter",
|
|
12
|
+
"compaction",
|
|
13
|
+
"runtime-context",
|
|
14
|
+
"agent"
|
|
15
|
+
],
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"author": "deepseekv41flash<monkey321478965@outlook.com>",
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/deepseekv41flash/dsh-context-truth.git"
|
|
21
|
+
},
|
|
22
|
+
"homepage": "https://github.com/deepseekv41flash/dsh-context-truth#readme",
|
|
23
|
+
"bugs": {
|
|
24
|
+
"url": "https://github.com/deepseekv41flash/dsh-context-truth/issues"
|
|
25
|
+
},
|
|
26
|
+
"type": "module",
|
|
27
|
+
"main": "./lib/index.js",
|
|
28
|
+
"exports": {
|
|
29
|
+
".": "./lib/index.js",
|
|
30
|
+
"./package.json": "./package.json"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"lib",
|
|
34
|
+
"scripts",
|
|
35
|
+
"test",
|
|
36
|
+
"cordis.patch.yml",
|
|
37
|
+
"README.md",
|
|
38
|
+
"README-en.md",
|
|
39
|
+
"CHANGELOG.md",
|
|
40
|
+
"LICENSE"
|
|
41
|
+
],
|
|
42
|
+
"engines": {
|
|
43
|
+
"node": ">=20"
|
|
44
|
+
},
|
|
45
|
+
"dsh": {
|
|
46
|
+
"bundle": {
|
|
47
|
+
"patch": "./cordis.patch.yml"
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
"scripts": {
|
|
51
|
+
"test": "node --test \"test/*.test.js\"",
|
|
52
|
+
"build": "bash scripts/build.sh",
|
|
53
|
+
"check": "node --input-type=module -e \"await import('./lib/index.js')\""
|
|
54
|
+
},
|
|
55
|
+
"publishConfig": {
|
|
56
|
+
"access": "public"
|
|
57
|
+
}
|
|
58
|
+
}
|