dsh-context-compression-improved 0.2.2 → 0.2.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.
- package/.github/workflows/ci.yml +39 -39
- package/CHANGELOG.md +137 -135
- package/README.md +112 -103
- package/package.json +142 -138
- package/packages/selector/README.md +31 -26
- package/packages/selector/README.zh.md +31 -26
- package/packages/selector/dsh.plugin.json +16 -16
- package/packages/selector/lib/client.d.ts +228 -228
- package/packages/selector/lib/client.js +1462 -1462
- package/packages/selector/lib/config.js +856 -842
- package/packages/selector/lib/index.d.ts +37 -37
- package/packages/selector/lib/index.js +693 -645
- package/packages/selector/lib/invariant.js +70 -70
- package/packages/selector/lib/pruner.d.ts +728 -683
- package/packages/selector/lib/pruner.js +4765 -3807
- package/packages/selector/lib/style.css +46 -46
- package/packages/selector/lib/tail-trim.js +136 -136
- package/packages/selector/package.json +15 -7
- package/packages/selector/src/client/index.ts +111 -111
- package/packages/selector/src/preset-overlay.ts +60 -1
- package/packages/selector/src/pruner/content.ts +18 -5
- package/packages/selector/src/pruner/types.ts +23 -5
- package/packages/selector/src/pruner.ts +164 -154
- package/packages/selector/src/runtime/adaptive-cost.ts +23 -12
- package/packages/selector/src/runtime/audit.ts +18 -2
- package/packages/selector/src/runtime/config.ts +30 -1
- package/packages/selector/src/runtime/measurement.ts +31 -2
- package/packages/selector/src/runtime/reducers.ts +1115 -97
- package/packages/selector/src/runtime/tokenpilot/dedup.ts +1 -1
- package/packages/selector/src/runtime/tokenpilot/locator.ts +1 -1
- package/packages/selector/src/runtime/tokenpilot/read-state.ts +23 -2
- package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +275 -0
- package/packages/selector/src/runtime/toolclass.ts +103 -0
- package/packages/selector/src/runtime/types.ts +16 -0
- package/packages/selector/tests/preset-overlay.host.spec.ts +256 -243
- package/packages/selector/tests/runtime/adaptive-cost.spec.ts +7 -7
- package/packages/selector/tests/runtime/audit.spec.ts +44 -1
- package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
- package/packages/selector/tests/runtime/code-skeleton.spec.ts +14 -3
- package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
- package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
- package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
- package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
- package/packages/selector/tests/runtime/public/public-runtime.spec.ts +198 -27
- package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
- package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
- package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
- package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
- package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +24 -0
- package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
- package/packages/selector/tests/standing-generation.host.spec.ts +642 -631
- package/scripts/toolclass-corpus-replay.mjs +273 -0
|
@@ -1,111 +1,111 @@
|
|
|
1
|
-
import type {} from '@deepseek-ai/dsh-client-locale/client'
|
|
2
|
-
import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'
|
|
3
|
-
import type {} from '@deepseek-ai/dsh-client-ui-settings/client'
|
|
4
|
-
import type {} from '@deepseek-ai/dsh-client-ui-workspace/client'
|
|
5
|
-
import {
|
|
6
|
-
isCustomCompressionPolicy,
|
|
7
|
-
ContextCompressionSettingsSection,
|
|
8
|
-
type CompressionSelectorInjected, type ContextCompressionSettings,
|
|
9
|
-
} from './CompressionProfileSelector.tsx'
|
|
10
|
-
import { DEFAULT_CUSTOM_COMPRESSION_POLICY } from '../profiles.ts'
|
|
11
|
-
import { decodeSettings } from './decode.ts'
|
|
12
|
-
import { en, zh } from './locales.ts'
|
|
13
|
-
import { mergePresetOptionsPatch, presetOptionsEqual } from './preset-options.ts'
|
|
14
|
-
|
|
15
|
-
export const inject = ['slots', 'locale', 'settingsScope']
|
|
16
|
-
const NS = 'context-compression'
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
function sameCustomPolicy(
|
|
20
|
-
left: ContextCompressionSettings['custom'],
|
|
21
|
-
right: ContextCompressionSettings['custom'],
|
|
22
|
-
): boolean {
|
|
23
|
-
if (left.version !== 3 || right.version !== 3) return false
|
|
24
|
-
return left.version === right.version
|
|
25
|
-
&& left.unit === right.unit
|
|
26
|
-
&& left.prefixPolicy === right.prefixPolicy
|
|
27
|
-
&& left.fresh.enabled === right.fresh.enabled
|
|
28
|
-
&& left.fresh.trigger === right.fresh.trigger
|
|
29
|
-
&& left.fresh.target === right.fresh.target
|
|
30
|
-
&& left.aggregate.enabled === right.aggregate.enabled
|
|
31
|
-
&& left.aggregate.trigger === right.aggregate.trigger
|
|
32
|
-
&& left.aggregate.target === right.aggregate.target
|
|
33
|
-
&& left.history.enabled === right.history.enabled
|
|
34
|
-
&& left.history.trigger === right.history.trigger
|
|
35
|
-
&& left.history.keepRecentToolCalls === right.history.keepRecentToolCalls
|
|
36
|
-
&& left.history.keepRecentTokens === right.history.keepRecentTokens
|
|
37
|
-
&& left.history.minReclaim === right.history.minReclaim
|
|
38
|
-
&& left.tailTrim.enabled === right.tailTrim.enabled
|
|
39
|
-
&& left.tailTrim.trigger === right.tailTrim.trigger
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
export function apply(ctx: ClientContext): void {
|
|
43
|
-
ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-context-compression: dictionaries')
|
|
44
|
-
const scope = ctx.settingsScope.bind<ContextCompressionSettings>({ namespace: NS, decode: decodeSettings })
|
|
45
|
-
const writeAndConfirm = async (
|
|
46
|
-
write: () => Promise<void>,
|
|
47
|
-
accepts: (settings: ContextCompressionSettings) => boolean,
|
|
48
|
-
): Promise<void> => {
|
|
49
|
-
const beforeRevision = scope.getSnapshot().revision
|
|
50
|
-
await write()
|
|
51
|
-
const after = scope.getSnapshot()
|
|
52
|
-
if (
|
|
53
|
-
after.status !== 'ready'
|
|
54
|
-
|| after.value === undefined
|
|
55
|
-
|| after.revision === beforeRevision
|
|
56
|
-
|| !accepts(after.value)
|
|
57
|
-
) {
|
|
58
|
-
throw new Error('Context compression settings were not saved.')
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
const injected = (): CompressionSelectorInjected => ({
|
|
62
|
-
hooks: { compression: scope },
|
|
63
|
-
select: profile => writeAndConfirm(
|
|
64
|
-
() => scope.set('profile', profile),
|
|
65
|
-
settings => settings.profile === profile,
|
|
66
|
-
),
|
|
67
|
-
saveCustom: custom => writeAndConfirm(
|
|
68
|
-
() => scope.set('custom', custom),
|
|
69
|
-
settings => isCustomCompressionPolicy(settings.custom)
|
|
70
|
-
&& sameCustomPolicy(settings.custom, custom),
|
|
71
|
-
),
|
|
72
|
-
resetCustom: () => writeAndConfirm(
|
|
73
|
-
() => scope.set('custom', structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY)),
|
|
74
|
-
settings => isCustomCompressionPolicy(settings.custom)
|
|
75
|
-
&& sameCustomPolicy(settings.custom, DEFAULT_CUSTOM_COMPRESSION_POLICY),
|
|
76
|
-
),
|
|
77
|
-
saveAutoCompact: thresholdPercent => writeAndConfirm(
|
|
78
|
-
() => scope.set('autoCompact', { thresholdPercent }),
|
|
79
|
-
settings => settings.autoCompact.thresholdPercent === thresholdPercent,
|
|
80
|
-
),
|
|
81
|
-
saveCodeSkeleton: enabled => writeAndConfirm(
|
|
82
|
-
() => scope.set('codeSkeleton', { enabled }),
|
|
83
|
-
settings => settings.codeSkeleton.enabled === enabled,
|
|
84
|
-
),
|
|
85
|
-
savePresetOptions: options => {
|
|
86
|
-
// The section root is replaced by whatever is written there, so merge the
|
|
87
|
-
// patch over the stored document: writing the bare patch deleted
|
|
88
|
-
// estimatorMode (and every other override) on the next field edit.
|
|
89
|
-
const current = scope.getSnapshot().value?.presetOptions
|
|
90
|
-
const next = mergePresetOptionsPatch(current, options)
|
|
91
|
-
if (presetOptionsEqual(current, next)) return Promise.resolve()
|
|
92
|
-
return writeAndConfirm(
|
|
93
|
-
() => scope.set('presetOptions', next),
|
|
94
|
-
settings => presetOptionsEqual(settings.presetOptions, next),
|
|
95
|
-
)
|
|
96
|
-
},
|
|
97
|
-
})
|
|
98
|
-
ctx.slots.inject('settings.section', () => ctx.slots.register({
|
|
99
|
-
name: 'settings.section',
|
|
100
|
-
id: 'context-compression',
|
|
101
|
-
order: 17,
|
|
102
|
-
label: () => ctx.locale.bind(NS)('nav'),
|
|
103
|
-
locale: NS,
|
|
104
|
-
inject: injected,
|
|
105
|
-
}, ContextCompressionSettingsSection))
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
export type {
|
|
109
|
-
CompressionProfile, CompressionProfileSelectorProps, CompressionSelectorInjected,
|
|
110
|
-
ContextCompressionSettings,
|
|
111
|
-
} from './CompressionProfileSelector.tsx'
|
|
1
|
+
import type {} from '@deepseek-ai/dsh-client-locale/client'
|
|
2
|
+
import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'
|
|
3
|
+
import type {} from '@deepseek-ai/dsh-client-ui-settings/client'
|
|
4
|
+
import type {} from '@deepseek-ai/dsh-client-ui-workspace/client'
|
|
5
|
+
import {
|
|
6
|
+
isCustomCompressionPolicy,
|
|
7
|
+
ContextCompressionSettingsSection,
|
|
8
|
+
type CompressionSelectorInjected, type ContextCompressionSettings,
|
|
9
|
+
} from './CompressionProfileSelector.tsx'
|
|
10
|
+
import { DEFAULT_CUSTOM_COMPRESSION_POLICY } from '../profiles.ts'
|
|
11
|
+
import { decodeSettings } from './decode.ts'
|
|
12
|
+
import { en, zh } from './locales.ts'
|
|
13
|
+
import { mergePresetOptionsPatch, presetOptionsEqual } from './preset-options.ts'
|
|
14
|
+
|
|
15
|
+
export const inject = ['slots', 'locale', 'settingsScope']
|
|
16
|
+
const NS = 'context-compression'
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
function sameCustomPolicy(
|
|
20
|
+
left: ContextCompressionSettings['custom'],
|
|
21
|
+
right: ContextCompressionSettings['custom'],
|
|
22
|
+
): boolean {
|
|
23
|
+
if (left.version !== 3 || right.version !== 3) return false
|
|
24
|
+
return left.version === right.version
|
|
25
|
+
&& left.unit === right.unit
|
|
26
|
+
&& left.prefixPolicy === right.prefixPolicy
|
|
27
|
+
&& left.fresh.enabled === right.fresh.enabled
|
|
28
|
+
&& left.fresh.trigger === right.fresh.trigger
|
|
29
|
+
&& left.fresh.target === right.fresh.target
|
|
30
|
+
&& left.aggregate.enabled === right.aggregate.enabled
|
|
31
|
+
&& left.aggregate.trigger === right.aggregate.trigger
|
|
32
|
+
&& left.aggregate.target === right.aggregate.target
|
|
33
|
+
&& left.history.enabled === right.history.enabled
|
|
34
|
+
&& left.history.trigger === right.history.trigger
|
|
35
|
+
&& left.history.keepRecentToolCalls === right.history.keepRecentToolCalls
|
|
36
|
+
&& left.history.keepRecentTokens === right.history.keepRecentTokens
|
|
37
|
+
&& left.history.minReclaim === right.history.minReclaim
|
|
38
|
+
&& left.tailTrim.enabled === right.tailTrim.enabled
|
|
39
|
+
&& left.tailTrim.trigger === right.tailTrim.trigger
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function apply(ctx: ClientContext): void {
|
|
43
|
+
ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-context-compression: dictionaries')
|
|
44
|
+
const scope = ctx.settingsScope.bind<ContextCompressionSettings>({ namespace: NS, decode: decodeSettings })
|
|
45
|
+
const writeAndConfirm = async (
|
|
46
|
+
write: () => Promise<void>,
|
|
47
|
+
accepts: (settings: ContextCompressionSettings) => boolean,
|
|
48
|
+
): Promise<void> => {
|
|
49
|
+
const beforeRevision = scope.getSnapshot().revision
|
|
50
|
+
await write()
|
|
51
|
+
const after = scope.getSnapshot()
|
|
52
|
+
if (
|
|
53
|
+
after.status !== 'ready'
|
|
54
|
+
|| after.value === undefined
|
|
55
|
+
|| after.revision === beforeRevision
|
|
56
|
+
|| !accepts(after.value)
|
|
57
|
+
) {
|
|
58
|
+
throw new Error('Context compression settings were not saved.')
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const injected = (): CompressionSelectorInjected => ({
|
|
62
|
+
hooks: { compression: scope },
|
|
63
|
+
select: profile => writeAndConfirm(
|
|
64
|
+
() => scope.set('profile', profile),
|
|
65
|
+
settings => settings.profile === profile,
|
|
66
|
+
),
|
|
67
|
+
saveCustom: custom => writeAndConfirm(
|
|
68
|
+
() => scope.set('custom', custom),
|
|
69
|
+
settings => isCustomCompressionPolicy(settings.custom)
|
|
70
|
+
&& sameCustomPolicy(settings.custom, custom),
|
|
71
|
+
),
|
|
72
|
+
resetCustom: () => writeAndConfirm(
|
|
73
|
+
() => scope.set('custom', structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY)),
|
|
74
|
+
settings => isCustomCompressionPolicy(settings.custom)
|
|
75
|
+
&& sameCustomPolicy(settings.custom, DEFAULT_CUSTOM_COMPRESSION_POLICY),
|
|
76
|
+
),
|
|
77
|
+
saveAutoCompact: thresholdPercent => writeAndConfirm(
|
|
78
|
+
() => scope.set('autoCompact', { thresholdPercent }),
|
|
79
|
+
settings => settings.autoCompact.thresholdPercent === thresholdPercent,
|
|
80
|
+
),
|
|
81
|
+
saveCodeSkeleton: enabled => writeAndConfirm(
|
|
82
|
+
() => scope.set('codeSkeleton', { enabled }),
|
|
83
|
+
settings => settings.codeSkeleton.enabled === enabled,
|
|
84
|
+
),
|
|
85
|
+
savePresetOptions: options => {
|
|
86
|
+
// The section root is replaced by whatever is written there, so merge the
|
|
87
|
+
// patch over the stored document: writing the bare patch deleted
|
|
88
|
+
// estimatorMode (and every other override) on the next field edit.
|
|
89
|
+
const current = scope.getSnapshot().value?.presetOptions
|
|
90
|
+
const next = mergePresetOptionsPatch(current, options)
|
|
91
|
+
if (presetOptionsEqual(current, next)) return Promise.resolve()
|
|
92
|
+
return writeAndConfirm(
|
|
93
|
+
() => scope.set('presetOptions', next),
|
|
94
|
+
settings => presetOptionsEqual(settings.presetOptions, next),
|
|
95
|
+
)
|
|
96
|
+
},
|
|
97
|
+
})
|
|
98
|
+
ctx.slots.inject('settings.section', () => ctx.slots.register({
|
|
99
|
+
name: 'settings.section',
|
|
100
|
+
id: 'context-compression',
|
|
101
|
+
order: 17,
|
|
102
|
+
label: () => ctx.locale.bind(NS)('nav'),
|
|
103
|
+
locale: NS,
|
|
104
|
+
inject: injected,
|
|
105
|
+
}, ContextCompressionSettingsSection))
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export type {
|
|
109
|
+
CompressionProfile, CompressionProfileSelectorProps, CompressionSelectorInjected,
|
|
110
|
+
ContextCompressionSettings,
|
|
111
|
+
} from './CompressionProfileSelector.tsx'
|
|
@@ -116,6 +116,16 @@ export function standingStampMs(identity: string): number {
|
|
|
116
116
|
return standingStampMsAtWindow(identity, 0)
|
|
117
117
|
}
|
|
118
118
|
|
|
119
|
+
/**
|
|
120
|
+
* True for the filesystem errors a concurrent publish can raise on Windows:
|
|
121
|
+
* `MoveFileEx` reports a lost race — or a reader holding the destination open —
|
|
122
|
+
* as EPERM/EBUSY/EACCES, where POSIX `rename` simply replaces the destination.
|
|
123
|
+
*/
|
|
124
|
+
function isPublishRace(error: unknown): boolean {
|
|
125
|
+
const code = (error as { code?: unknown } | null)?.code
|
|
126
|
+
return code === 'EPERM' || code === 'EBUSY' || code === 'EACCES' || code === 'EEXIST'
|
|
127
|
+
}
|
|
128
|
+
|
|
119
129
|
const COMPRESSION_IDS = new Set([
|
|
120
130
|
'compaction',
|
|
121
131
|
'compaction-basic',
|
|
@@ -224,7 +234,7 @@ class PresetOverlayStore {
|
|
|
224
234
|
// still private. No reader can observe a colliding {mtimeMs,size}
|
|
225
235
|
// between rename and a later corrective utimes call.
|
|
226
236
|
await this.disambiguateStamp(staging, identity)
|
|
227
|
-
await
|
|
237
|
+
await this.publish(staging, path)
|
|
228
238
|
} catch (error) {
|
|
229
239
|
// A failed publish must not leak its staging file into the store; the
|
|
230
240
|
// cleanup must never mask the original failure either.
|
|
@@ -238,6 +248,55 @@ class PresetOverlayStore {
|
|
|
238
248
|
return { ...preset, path }
|
|
239
249
|
}
|
|
240
250
|
|
|
251
|
+
/** In-flight publish chains, one per destination path. */
|
|
252
|
+
private readonly publishChains = new Map<string, Promise<void>>()
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Publish one stamped staging file to its final path, serialized per path.
|
|
256
|
+
*
|
|
257
|
+
* POSIX `rename` replaces an existing destination atomically, so concurrent
|
|
258
|
+
* composers of one identity are naturally idempotent there. Windows
|
|
259
|
+
* `MoveFileEx` instead fails the loser of that race with EPERM/EBUSY, which
|
|
260
|
+
* surfaced as `standingKeyFor()` throwing during concurrent composition.
|
|
261
|
+
* Every composer of one identity writes identical bytes and re-derives the
|
|
262
|
+
* same deterministic identity stamp, so a destination that already observes
|
|
263
|
+
* this staging file's {mtimeMs, size} key IS the intended end state: confirm
|
|
264
|
+
* it and treat the lost race as success. Every other outcome still throws, so
|
|
265
|
+
* a silently reused generation stays forbidden, and the caller still removes
|
|
266
|
+
* the staging file when this rejects.
|
|
267
|
+
*/
|
|
268
|
+
private publish(staging: string, path: string): Promise<void> {
|
|
269
|
+
const previous = this.publishChains.get(path) ?? Promise.resolve()
|
|
270
|
+
const queued = previous.catch(() => undefined).then(async () => {
|
|
271
|
+
try {
|
|
272
|
+
await rename(staging, path)
|
|
273
|
+
return
|
|
274
|
+
} catch (error) {
|
|
275
|
+
if (!isPublishRace(error)) throw error
|
|
276
|
+
try {
|
|
277
|
+
const intended = await this.metadataIo.read(staging)
|
|
278
|
+
const published = await this.metadataIo.read(path)
|
|
279
|
+
// Sub-second precision survives a wrapped seconds field, but NTFS
|
|
280
|
+
// rounds it to 100ns, so compare the standing key within that
|
|
281
|
+
// rounding rather than by exact float equality.
|
|
282
|
+
if (published.size === intended.size
|
|
283
|
+
&& Math.abs(published.mtimeMs - intended.mtimeMs) < 2) {
|
|
284
|
+
await rm(staging, { force: true })
|
|
285
|
+
return
|
|
286
|
+
}
|
|
287
|
+
} catch {
|
|
288
|
+
// The destination is unreadable: report the original publish failure.
|
|
289
|
+
}
|
|
290
|
+
throw error
|
|
291
|
+
}
|
|
292
|
+
})
|
|
293
|
+
const tracked = queued.finally(() => {
|
|
294
|
+
if (this.publishChains.get(path) === tracked) this.publishChains.delete(path)
|
|
295
|
+
})
|
|
296
|
+
this.publishChains.set(path, tracked)
|
|
297
|
+
return tracked
|
|
298
|
+
}
|
|
299
|
+
|
|
241
300
|
/** Observed {mtimeMs,size} keys published by this store, per identity. */
|
|
242
301
|
private readonly standingKeys = new Map<string, string>()
|
|
243
302
|
|
|
@@ -70,8 +70,11 @@ function unavailableCount(reason: string): TokenCount {
|
|
|
70
70
|
|
|
71
71
|
// ── Recovery markers ────────────────────────────────────────────────────
|
|
72
72
|
|
|
73
|
-
function recoveryMarker(sourceRef: string, label: string): string {
|
|
74
|
-
|
|
73
|
+
function recoveryMarker(sourceRef: string, label: string, startLine?: number): string {
|
|
74
|
+
const hint = startLine === undefined
|
|
75
|
+
? 'use context_compression_retrieve if needed'
|
|
76
|
+
: `retrieve with context_compression_retrieve({"ref":"${sourceRef}","start_line":${String(startLine)},"max_lines":80})`
|
|
77
|
+
return `\n\n[... ${label}; source=${sourceRef}; ${hint} ...]\n\n`
|
|
75
78
|
}
|
|
76
79
|
|
|
77
80
|
// ── Content measurement ─────────────────────────────────────────────────
|
|
@@ -124,11 +127,11 @@ function nativePruneContent(
|
|
|
124
127
|
thresholdChars: number,
|
|
125
128
|
headChars: number,
|
|
126
129
|
tailChars: number,
|
|
127
|
-
marker: string = PRUNE_MARKER,
|
|
130
|
+
marker: string | ((startLine: number) => string) = PRUNE_MARKER,
|
|
128
131
|
): ContentBlock[] | null {
|
|
129
132
|
const totalChars = measureContent(blocks)
|
|
130
133
|
if (totalChars <= thresholdChars) return null
|
|
131
|
-
const markerChars = codePointLength(marker)
|
|
134
|
+
const markerChars = codePointLength(typeof marker === 'function' ? marker(1) : marker)
|
|
132
135
|
const safeHead = Math.max(0, Math.min(headChars, thresholdChars - markerChars))
|
|
133
136
|
const safeTail = Math.max(0, Math.min(tailChars, thresholdChars - markerChars - safeHead))
|
|
134
137
|
const removedStart = safeHead
|
|
@@ -136,9 +139,14 @@ function nativePruneContent(
|
|
|
136
139
|
const pruned: ContentBlock[] = []
|
|
137
140
|
let consumed = 0
|
|
138
141
|
let markerInserted = false
|
|
142
|
+
// '\n' count in the RAW event text before the current block (retrieve scans
|
|
143
|
+
// the original event; blocks are joined with '\n'). Line numbers therefore
|
|
144
|
+
// never depend on what the pruning removed.
|
|
145
|
+
let newlinesBefore = 0
|
|
139
146
|
for (const block of blocks) {
|
|
140
147
|
if (block.type !== 'text') {
|
|
141
148
|
pruned.push(block)
|
|
149
|
+
newlinesBefore += 1
|
|
142
150
|
continue
|
|
143
151
|
}
|
|
144
152
|
const points = Array.from(block.text)
|
|
@@ -147,10 +155,15 @@ function nativePruneContent(
|
|
|
147
155
|
const headEnd = Math.min(points.length, Math.max(0, removedStart - blockStart))
|
|
148
156
|
const tailStart = Math.min(points.length, Math.max(0, removedEnd - blockStart))
|
|
149
157
|
const intersectsRemoved = blockStart < removedEnd && blockEnd > removedStart
|
|
150
|
-
|
|
158
|
+
// The elided region starts on the event line after the retained head.
|
|
159
|
+
const headText = points.slice(0, headEnd).join('')
|
|
160
|
+
const insertion = intersectsRemoved && !markerInserted && typeof marker === 'function'
|
|
161
|
+
? marker(1 + newlinesBefore + headText.split('\n').length - 1)
|
|
162
|
+
: intersectsRemoved && !markerInserted ? marker : ''
|
|
151
163
|
if (insertion !== '') markerInserted = true
|
|
152
164
|
const text = points.slice(0, headEnd).join('') + insertion + points.slice(tailStart).join('')
|
|
153
165
|
if (text !== '') pruned.push({ ...block, text })
|
|
166
|
+
newlinesBefore += block.text.split('\n').length - 1 + 1
|
|
154
167
|
consumed = blockEnd
|
|
155
168
|
}
|
|
156
169
|
if (!markerInserted) return null
|
|
@@ -20,11 +20,16 @@ export interface SnapshotCandidate {
|
|
|
20
20
|
readonly seq: number
|
|
21
21
|
readonly event: SessionEvent<'tool/result'>
|
|
22
22
|
readonly call: ToolCallInfo
|
|
23
|
-
/** Authoritative same-revision exact canonical content count. */
|
|
23
|
+
/** Authoritative same-revision exact canonical content count (telemetry only). */
|
|
24
24
|
readonly count: TokenCount
|
|
25
25
|
/** Same-revision legacy heuristic price used only by bounded projections. */
|
|
26
26
|
readonly shadowedHeuristicTokenCount: number
|
|
27
|
-
/**
|
|
27
|
+
/**
|
|
28
|
+
* Authoritative decision metric: character pressure in Unicode code points.
|
|
29
|
+
* Every eligibility and acceptance gate decides on this number so the plugin
|
|
30
|
+
* never depends on the routed model id owning a bundled exact tokenizer;
|
|
31
|
+
* `count` is retained as diagnostic telemetry only.
|
|
32
|
+
*/
|
|
28
33
|
readonly characterPressure: number
|
|
29
34
|
}
|
|
30
35
|
|
|
@@ -40,19 +45,32 @@ export interface PlannedReplacement {
|
|
|
40
45
|
readonly charsAfter: number
|
|
41
46
|
readonly tokensBefore: number
|
|
42
47
|
readonly tokensAfter: number
|
|
48
|
+
/**
|
|
49
|
+
* Which measurement produced this plan's decision: 'exact-tokenizer' when
|
|
50
|
+
* both sides of the reduction carry one bundled tokenizer identity,
|
|
51
|
+
* 'characters' when the proof ran on code points alone.
|
|
52
|
+
*/
|
|
53
|
+
readonly measurementBasis: 'exact-tokenizer' | 'characters'
|
|
43
54
|
readonly tokenizerId: string
|
|
44
55
|
readonly tokenizerRevision: string
|
|
56
|
+
/**
|
|
57
|
+
* Original-event lines the reducer elided (task_4c/G7 telemetry, from
|
|
58
|
+
* `ReducerOutput.elidedLines`). Rides the rewrite AUDIT record only — it is
|
|
59
|
+
* never printed into replacement content.
|
|
60
|
+
*/
|
|
61
|
+
readonly elidedLines?: number
|
|
45
62
|
}
|
|
46
63
|
|
|
47
64
|
/**
|
|
48
65
|
* Discriminated History planning outcome: every skip path carries its own
|
|
49
66
|
* reason instead of collapsing into one merged "no eligible minimum reclaim"
|
|
50
|
-
* audit, so operators can tell a protected working set from
|
|
51
|
-
*
|
|
67
|
+
* audit, so operators can tell a protected working set from an unreachable
|
|
68
|
+
* reclaim target. The former 'exact-tokenizer-unavailable' member is gone:
|
|
69
|
+
* planning decides on the character basis and can no longer refuse for a
|
|
70
|
+
* missing exact count.
|
|
52
71
|
*/
|
|
53
72
|
export type HistoryPlanOutcome =
|
|
54
73
|
| { readonly kind: 'planned', readonly plans: PlannedReplacement[] }
|
|
55
|
-
| { readonly kind: 'exact-tokenizer-unavailable' }
|
|
56
74
|
| { readonly kind: 'below-profile-trigger' }
|
|
57
75
|
| { readonly kind: 'no-safe-candidates' }
|
|
58
76
|
| { readonly kind: 'protected-working-set' }
|