dsh-context-compression-improved 0.7.0-beta.1 → 0.7.0-beta.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/.github/workflows/ci.yml +39 -39
- package/CHANGELOG.ja.md +217 -220
- package/CHANGELOG.ko.md +211 -214
- package/CHANGELOG.md +392 -376
- package/CHANGELOG.zh.md +196 -199
- package/README.md +97 -97
- package/README.zh.md +86 -86
- package/package.json +18 -17
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/client.js +733 -0
- package/packages/selector/lib/style.css +46 -46
- package/packages/selector/src/client/decode.ts +53 -53
- package/packages/selector/src/client/index.ts +30 -0
- package/packages/selector/src/client/locales/de.ts +98 -0
- package/packages/selector/src/client/locales/es.ts +98 -0
- package/packages/selector/src/client/locales/fr.ts +98 -0
- package/packages/selector/src/client/locales/it.ts +98 -0
- package/packages/selector/src/client/locales/ja.ts +98 -0
- package/packages/selector/src/client/locales/ko.ts +98 -0
- package/packages/selector/src/client/locales/ru.ts +98 -0
- package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
- package/packages/selector/src/preset-overlay.ts +629 -629
- package/packages/selector/src/profiles.ts +414 -414
- package/packages/selector/src/pruner/content.ts +198 -198
- package/packages/selector/src/pruner/state.ts +57 -57
- package/packages/selector/src/pruner.ts +2665 -2665
- package/packages/selector/src/runtime/audit.ts +303 -303
- package/packages/selector/src/runtime/config.ts +731 -731
- package/packages/selector/src/runtime/reducers.ts +1674 -1674
- package/packages/selector/src/runtime/summary-command.ts +133 -133
- package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -233
- package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -204
- package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -53
- package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -65
- package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -125
- package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -37
- package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
- package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +306 -306
- package/packages/selector/src/runtime/types.ts +358 -358
- package/packages/selector/tests/built/client-artifact.spec.ts +61 -61
- package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -15
- package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -41
- package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -647
- package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -78
- package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -234
- package/packages/selector/tests/host-preset-overlay.host.spec.ts +203 -203
- package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
- package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
- package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -62
- package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -156
- package/packages/selector/tests/runtime/summary-command.spec.ts +154 -154
- package/scripts/packed-components-smoke.mjs +734 -734
- package/tests/TEST_INVENTORY.md +41 -41
- package/tsconfig.tests.json +17 -17
- package/vitest.config.ts +57 -57
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { ContextCompressionLocaleKey } from '../locales.ts'
|
|
2
|
+
|
|
3
|
+
/** Russian copy matching every simplified Chinese selector key. */
|
|
4
|
+
export const ru = {
|
|
5
|
+
'nav': 'Выбор сжатия контекста',
|
|
6
|
+
'settings.title': 'Выбор сжатия контекста',
|
|
7
|
+
'settings.description': 'Выберите профиль сжатия для текущей сессии и настройте его параметры.',
|
|
8
|
+
'label': 'Сжатие контекста',
|
|
9
|
+
'status.loading': 'Загрузка',
|
|
10
|
+
'status.unavailable': 'Недоступно',
|
|
11
|
+
'status.presetUnavailable': 'Пресет этой сессии не предоставляет сжатие контекста, либо доступность пока не подтверждена.',
|
|
12
|
+
'status.minimalUnavailable': 'Минимальный режим не загружает сжатие контекста для этой сессии: селектор фактически выключен, действует нативное поведение Harness. Переключитесь на Standard, PTC / Coding, Creative или на поддерживающий её пользовательский пресет, чтобы настроить сжатие.',
|
|
13
|
+
'status.saveFailed': 'Не удалось сохранить. Повторите попытку.',
|
|
14
|
+
'pricing.disclosure': 'Официальные цены DeepSeek проверены 2026-08-25. Пиковые часы пн–пт 09:00–12:00 и 14:00–18:00 (Asia/Shanghai), остальное — непиковые. Для запросов на границе интервалов используется диапазон стоимости.',
|
|
15
|
+
'profile.balanced': 'Сбалансированный',
|
|
16
|
+
'profile.cache-strict': 'Cache Strict (защита префикса)',
|
|
17
|
+
'profile.savings': 'Экономия',
|
|
18
|
+
'profile.adaptive': 'Адаптивный (консервативная цена)',
|
|
19
|
+
'profile.tokenpilot-inspired': 'По мотивам TokenPilot',
|
|
20
|
+
'estimator.title': 'Оценщик (опционально)',
|
|
21
|
+
'estimator.description': 'Небольшая вспомогательная модель без примеров оценивает, вероятно ли старое чтение файла всё ещё востребовано; только рекомендация для старения истории. Без настройки или при сбое — режим только правил.',
|
|
22
|
+
'estimator.mode': 'Канал',
|
|
23
|
+
'estimator.mode.off': 'Выключен (только правила)',
|
|
24
|
+
'estimator.mode.host': 'Модель хоста (повторно использует настроенных провайдеров)',
|
|
25
|
+
'estimator.mode.direct': 'Прямой OpenAI-совместимый эндпоинт',
|
|
26
|
+
'estimator.inactive': 'Оценщик есть только у профиля «По мотивам TokenPilot»: пресет-опции этого профиля (указатели дедупликации, якоря резюме, семантика состояния чтения и канал оценщика) никогда не переносятся в другой профиль, поэтому у текущего профиля «{profile}» нет канала оценщика. Выберите «По мотивам TokenPilot» — в этом разделе появится выбор канала: настроенные провайдеры (модель хоста) или прямой OpenAI-совместимый эндпоинт.',
|
|
27
|
+
'estimator.provider': 'Провайдер',
|
|
28
|
+
'estimator.provider.placeholder': 'Пусто — следует модели по умолчанию сессии; выберите из списка или введите свой id',
|
|
29
|
+
'estimator.model.placeholder': 'Пусто — следует модели по умолчанию сессии; выберите из списка или введите свой id',
|
|
30
|
+
'estimator.hostReuse': 'Канал хоста повторно использует провайдеров и учётные данные, уже настроенные в DSH: ключ API не нужен — и здесь он не принимается.',
|
|
31
|
+
'estimator.hostRoute': 'Действующий маршрут: {route}.',
|
|
32
|
+
'estimator.hostUnresolved': 'пока не определено (выберите модель по умолчанию в настройках DSH или укажите здесь провайдера и модель)',
|
|
33
|
+
'estimator.baseUrl': 'Базовый URL эндпоинта (/v1)',
|
|
34
|
+
'estimator.model': 'Модель',
|
|
35
|
+
'estimator.apiKey': 'Ключ API (только запись, никогда не показывается)',
|
|
36
|
+
'estimator.apiKey.placeholder': 'Введите ключ эндпоинта; сохранение при выходе из поля',
|
|
37
|
+
'estimator.apiKey.set': 'Задан · введите новое значение, чтобы перезаписать',
|
|
38
|
+
'estimator.apiKey.clear': 'Очистить',
|
|
39
|
+
'estimator.apiKey.overwrite': 'Секрет сохранён; введите новое значение и выйдите из поля, чтобы перезаписать его.',
|
|
40
|
+
'detail.tokenpilot-inspired': 'Поверх «Сбалансированного»: указатели дедупликации, освобождение от восстановления, якоря резюме, стабилизация префикса и семантика состояния чтения; оценщику нужен отдельно настроенный эндпоинт',
|
|
41
|
+
'profile.custom': 'Пользовательский / Экспериментальный',
|
|
42
|
+
'profile.native': 'Нативная база',
|
|
43
|
+
'profile.off': 'Плагин выключен',
|
|
44
|
+
'profile.current': 'Текущий профиль',
|
|
45
|
+
'detail.balanced': 'Детерминированно сокращает свежие результаты инструментов; старые устаревают при высоком уровне заполнения',
|
|
46
|
+
'detail.cache-strict': 'Устаревание отправленной истории только при подтверждённой нехватке ёмкости; попадания в кэш провайдера остаются best-effort',
|
|
47
|
+
'detail.savings': 'Меньшие целевые значения и более раннее устаревание старых результатов инструментов; более дешёвый запрос не гарантирован',
|
|
48
|
+
'detail.adaptive': 'Использует Fresh/Aggregate «Сбалансированного»; история устаревает, только если соседний официальный usage и текущие официальные цены доказывают явную экономию',
|
|
49
|
+
'detail.custom': 'Выберите реализованные этапы и измеренные пороги для новых сессий',
|
|
50
|
+
'detail.native': 'Только нативная обрезка начала/конца Harness',
|
|
51
|
+
'detail.off': 'Отключает детерминированный селектор; нативный auto-compact настраивается отдельно',
|
|
52
|
+
'autoCompact.title': 'Уровень срабатывания Auto Compact',
|
|
53
|
+
'autoCompact.description': 'Управляемый моделью Auto Compact срабатывает, когда занятость запроса превышает этот уровень. Пороги History стандартного профиля, минимальное освобождение и недавний хвост следуют за уровнем; изменения касаются только новых сессий.',
|
|
54
|
+
'autoCompact.inputLabel': 'Порог Auto Compact (%)',
|
|
55
|
+
'autoCompact.sliderLabel': 'Ползунок порога Auto Compact',
|
|
56
|
+
'autoCompact.quick': 'Быстрые значения',
|
|
57
|
+
'autoCompact.riskLow': 'Ниже рекомендуемого диапазона: раннее срабатывание увеличивает вызовы резюмирования и перестройки префикса.',
|
|
58
|
+
'autoCompact.riskHigh': 'Выше рекомендуемого диапазона: ёмкость контекста делится между запросами и выводом, позднее срабатывание сокращает запас для одиночных больших выводов, рассуждений и схем инструментов.',
|
|
59
|
+
'autoCompact.invalid': 'Порог Auto Compact должен быть целым числом от 50 до 90.',
|
|
60
|
+
'autoCompact.save': 'Сохранить порог Auto Compact',
|
|
61
|
+
'autoCompact.summaryHint': 'Порог Auto Compact: {percent}%. Можно изменить в настройках.',
|
|
62
|
+
'codeSkeleton.title': 'Скелетное сжатие кода (по включению)',
|
|
63
|
+
'codeSkeleton.description': 'Отдельный переключатель, независимый от профилей выше. Когда включено, слишком большой свежий результат инструмента с исходным кодом сначала пробует скелет, сохраняющий импорты и объявления (тела опущены, строки ошибок сохранены), а при неудаче возвращается к исходной обрезке головы. Нужен точный токенизатор; касается только новых сессий.',
|
|
64
|
+
'codeSkeleton.enabled': 'Скелетное сжатие кода',
|
|
65
|
+
'codeSkeleton.enabled.on': 'Вкл',
|
|
66
|
+
'codeSkeleton.enabled.off': 'Выкл (по умолчанию)',
|
|
67
|
+
'custom.title': 'Пользовательская стратегия',
|
|
68
|
+
'custom.settingsHint': 'Подробные параметры — в «Настройки > Выбор сжатия контекста».',
|
|
69
|
+
'custom.sessionScope': 'Сохранённые изменения применяются, когда текущий runtime сжатия впервые наблюдает Session. Session, уже наблюдаемая этим runtime, сохраняет свою замороженную стратегию.',
|
|
70
|
+
'custom.measurement': 'Сначала точный токенизатор DeepSeek; иначе оценка токенизатором с калибровкой как запасной вариант. Никогда chars/4. Атрибуция кэша остаётся неизвестной.',
|
|
71
|
+
'custom.unit': 'Каноническая единица',
|
|
72
|
+
'custom.unit.tokens': 'Токены',
|
|
73
|
+
'custom.unit.contextPercent': 'Проценты контекста',
|
|
74
|
+
'custom.enabled': 'Включено',
|
|
75
|
+
'custom.enabled.on': 'Вкл',
|
|
76
|
+
'custom.enabled.off': 'Выкл',
|
|
77
|
+
'custom.fresh.enabled': 'Включить Fresh',
|
|
78
|
+
'custom.fresh.trigger': 'Порог Fresh',
|
|
79
|
+
'custom.fresh.target': 'Цель Fresh',
|
|
80
|
+
'custom.aggregate.enabled': 'Включить Aggregate',
|
|
81
|
+
'custom.aggregate.trigger': 'Порог Aggregate',
|
|
82
|
+
'custom.aggregate.target': 'Цель Aggregate',
|
|
83
|
+
'custom.history.enabled': 'Включить History',
|
|
84
|
+
'custom.history.trigger': 'Порог History',
|
|
85
|
+
'custom.history.keepRecentToolCalls': 'Защищённые недавние вызовы инструментов',
|
|
86
|
+
'custom.history.keepRecentTokens': 'Защищённый недавний хвост результатов инструментов',
|
|
87
|
+
'custom.history.minReclaim': 'Минимальное освобождение',
|
|
88
|
+
'custom.prefixPolicy': 'Политика отправленного префикса',
|
|
89
|
+
'custom.prefixPolicy.preserve': 'Сохранять до нехватки ёмкости',
|
|
90
|
+
'custom.prefixPolicy.pressureBreak': 'Разрешить обычное старение истории',
|
|
91
|
+
'custom.experimental': 'Экспериментально: эти настройки только для пользовательского профиля и никогда не добавляются в стандартные.',
|
|
92
|
+
'custom.tailTrim.enabled': 'Включить TailTrim (экспериментально)',
|
|
93
|
+
'custom.tailTrim.trigger': 'Порог TailTrim',
|
|
94
|
+
'custom.tailTrim.warning': 'TailTrim требует точный токенизатор и заменяет максимум одну полную, завершённую, без ошибок группу только из инструментов на восстанавливаемую ссылку. Он использует общие с History защищённые недавние вызовы инструментов, защищённый недавний хвост результатов инструментов и минимальное освобождение. Он переписывает отправленный префикс и может снизить попадания в кэш.',
|
|
95
|
+
'custom.save': 'Сохранить пользовательскую стратегию',
|
|
96
|
+
'custom.reset': 'Сбросить пользовательскую стратегию',
|
|
97
|
+
'custom.invalid': 'Значения пользовательской стратегии недопустимы.',
|
|
98
|
+
} satisfies Record<ContextCompressionLocaleKey, string>
|
|
@@ -1,205 +1,205 @@
|
|
|
1
|
-
/** Offline DeepSeek tokenizers backed by pinned official Hugging Face assets. */
|
|
2
|
-
|
|
3
|
-
import { createHash } from 'node:crypto'
|
|
4
|
-
import { readFileSync } from 'node:fs'
|
|
5
|
-
import { Tokenizer } from '@huggingface/tokenizers'
|
|
6
|
-
import type { ExactTokenizerTokenCount } from './runtime/token-count.ts'
|
|
7
|
-
|
|
8
|
-
const TOKENIZER_ID = 'deepseek-ai/DeepSeek-V4-Pro'
|
|
9
|
-
const TOKENIZER_REVISION = '0e1a0e5e52aea73055f50fef6f2423db370265b6'
|
|
10
|
-
const TOKENIZER_SHA256 = '8f9f37ca37fdc4f5fd36d5cf4d3b0e8392edb4e894fd10cc0d70b4957c8633cf'
|
|
11
|
-
const CONFIG_SHA256 = '6ac8c8dc065ed118161d02dd532749ae3f52c243deac27872134fae2f50d8547'
|
|
12
|
-
const VISION_TOKENIZER_ID = 'deepseek-ai/DeepSeek-V4-Flash-Vision-Exp'
|
|
13
|
-
const VISION_TOKENIZER_REVISION = '6821d6ad3681a4b137b066b76094fa82ebd0a380'
|
|
14
|
-
const VISION_TOKENIZER_SHA256 = 'c90dfa01249db1be4245780a052ede752e1361c612ac6d08e2bdada7d599476b'
|
|
15
|
-
const VISION_CONFIG_SHA256 = '6ac8c8dc065ed118161d02dd532749ae3f52c243deac27872134fae2f50d8547'
|
|
16
|
-
|
|
17
|
-
/** Auditable origin and compatibility mapping for one bundled tokenizer. */
|
|
18
|
-
export interface DeepSeekTokenizerArtifactOrigin {
|
|
19
|
-
/** Hugging Face repository the assets were pinned from. */
|
|
20
|
-
readonly repository: string
|
|
21
|
-
/** Immutable commit revision the assets were pinned from. */
|
|
22
|
-
readonly revision: string
|
|
23
|
-
/** Upstream license of the repository. */
|
|
24
|
-
readonly license: string
|
|
25
|
-
/** Exact API wire model ids served by this artifact. */
|
|
26
|
-
readonly modelIds: readonly string[]
|
|
27
|
-
readonly tokenizerSha256: string
|
|
28
|
-
readonly tokenizerConfigSha256: string
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/** Auditable origin and compatibility mapping for the bundled V4 Pro tokenizer. */
|
|
32
|
-
export const DEEPSEEK_V4_TOKENIZER_ARTIFACT: DeepSeekTokenizerArtifactOrigin = Object.freeze({
|
|
33
|
-
repository: TOKENIZER_ID,
|
|
34
|
-
revision: TOKENIZER_REVISION,
|
|
35
|
-
license: 'MIT',
|
|
36
|
-
tokenizerSha256: TOKENIZER_SHA256,
|
|
37
|
-
tokenizerConfigSha256: CONFIG_SHA256,
|
|
38
|
-
modelIds: Object.freeze(['deepseek-v4-flash', 'deepseek-v4-pro']),
|
|
39
|
-
})
|
|
40
|
-
|
|
41
|
-
/**
|
|
42
|
-
* Auditable origin and compatibility mapping for the bundled V4 Flash Vision
|
|
43
|
-
* tokenizer. The vision repository ships a distinct `tokenizer.json` (it adds
|
|
44
|
-
* the `<|deepseek_image|>` special token), so the vision model must never be
|
|
45
|
-
* mapped onto the V4 Pro tokenizer as an alias.
|
|
46
|
-
*/
|
|
47
|
-
export const DEEPSEEK_VISION_TOKENIZER_ARTIFACT: DeepSeekTokenizerArtifactOrigin = Object.freeze({
|
|
48
|
-
repository: VISION_TOKENIZER_ID,
|
|
49
|
-
revision: VISION_TOKENIZER_REVISION,
|
|
50
|
-
license: 'MIT',
|
|
51
|
-
tokenizerSha256: VISION_TOKENIZER_SHA256,
|
|
52
|
-
tokenizerConfigSha256: VISION_CONFIG_SHA256,
|
|
53
|
-
modelIds: Object.freeze(['deepseek-v4-flash-vision-exp']),
|
|
54
|
-
})
|
|
55
|
-
|
|
56
|
-
/** Synchronous exact counter backed only by the verified local V4 artifacts. */
|
|
57
|
-
export interface DeepSeekV4TextTokenizer {
|
|
58
|
-
/** Count one fully determined text value with the official tokenizer. */
|
|
59
|
-
countText(text: string): ExactTokenizerTokenCount
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
/** Integrity tuple for one tokenizer JSON asset. @internal */
|
|
63
|
-
export interface DeepSeekV4TokenizerAssetDescriptor {
|
|
64
|
-
readonly bytes: number
|
|
65
|
-
readonly sha256: string
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/** Injectable integrity manifest used by negative loader tests. @internal */
|
|
69
|
-
export interface DeepSeekV4TokenizerAssetIntegrity {
|
|
70
|
-
readonly tokenizer: DeepSeekV4TokenizerAssetDescriptor
|
|
71
|
-
readonly config: DeepSeekV4TokenizerAssetDescriptor
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
interface TokenizerArtifact {
|
|
75
|
-
readonly origin: DeepSeekTokenizerArtifactOrigin
|
|
76
|
-
readonly assetRoot: URL
|
|
77
|
-
readonly integrity: DeepSeekV4TokenizerAssetIntegrity
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* Every bundled artifact is registered with independent asset roots, integrity
|
|
82
|
-
* manifests, and cache entries: one corrupted artifact must never disable the
|
|
83
|
-
* tokenizer serving the other model family.
|
|
84
|
-
*/
|
|
85
|
-
const ARTIFACTS: readonly TokenizerArtifact[] = Object.freeze([
|
|
86
|
-
Object.freeze({
|
|
87
|
-
origin: DEEPSEEK_V4_TOKENIZER_ARTIFACT,
|
|
88
|
-
assetRoot: new URL('../assets/deepseek-v4/', import.meta.url),
|
|
89
|
-
integrity: Object.freeze({
|
|
90
|
-
tokenizer: Object.freeze({ bytes: 6_367_146, sha256: TOKENIZER_SHA256 }),
|
|
91
|
-
config: Object.freeze({ bytes: 801, sha256: CONFIG_SHA256 }),
|
|
92
|
-
}),
|
|
93
|
-
}),
|
|
94
|
-
Object.freeze({
|
|
95
|
-
origin: DEEPSEEK_VISION_TOKENIZER_ARTIFACT,
|
|
96
|
-
assetRoot: new URL('../assets/deepseek-v4-vision-exp/', import.meta.url),
|
|
97
|
-
integrity: Object.freeze({
|
|
98
|
-
tokenizer: Object.freeze({ bytes: 6_367_257, sha256: VISION_TOKENIZER_SHA256 }),
|
|
99
|
-
config: Object.freeze({ bytes: 801, sha256: VISION_CONFIG_SHA256 }),
|
|
100
|
-
}),
|
|
101
|
-
}),
|
|
102
|
-
])
|
|
103
|
-
|
|
104
|
-
interface ArtifactCacheEntry {
|
|
105
|
-
readonly tokenizer?: DeepSeekV4TextTokenizer
|
|
106
|
-
readonly failure?: string
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
const registryCache = new Map<DeepSeekTokenizerArtifactOrigin, ArtifactCacheEntry>()
|
|
110
|
-
|
|
111
|
-
function artifactForModel(modelId: string): TokenizerArtifact | undefined {
|
|
112
|
-
return ARTIFACTS.find(artifact => (artifact.origin.modelIds).includes(modelId))
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
/**
|
|
116
|
-
* Resolve the shared offline tokenizer for one compatible API model.
|
|
117
|
-
* Unknown models and a cached asset/runtime failure return `undefined`; callers
|
|
118
|
-
* must report unavailable instead of manufacturing a character estimate.
|
|
119
|
-
* @param modelId - exact DeepSeek API wire model id.
|
|
120
|
-
* @returns the shared verified tokenizer, or undefined when unsupported/unavailable.
|
|
121
|
-
*/
|
|
122
|
-
export function deepSeekV4TokenizerForModel(modelId: string): DeepSeekV4TextTokenizer | undefined {
|
|
123
|
-
const artifact = artifactForModel(modelId)
|
|
124
|
-
if (artifact === undefined) return undefined
|
|
125
|
-
const cached = registryCache.get(artifact.origin)
|
|
126
|
-
if (cached !== undefined) return cached.tokenizer
|
|
127
|
-
let entry: ArtifactCacheEntry
|
|
128
|
-
try {
|
|
129
|
-
const tokenizer = createDeepSeekV4TokenizerFromAssets(artifact.assetRoot, artifact.integrity, artifact.origin)
|
|
130
|
-
entry = { tokenizer }
|
|
131
|
-
} catch (error: unknown) {
|
|
132
|
-
entry = { failure: error instanceof Error ? error.message : String(error) }
|
|
133
|
-
}
|
|
134
|
-
registryCache.set(artifact.origin, entry)
|
|
135
|
-
return entry.tokenizer
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
/**
|
|
139
|
-
* Read the cached initialization diagnostic for provider registration.
|
|
140
|
-
* @param modelId - optional exact model id; defaults to the V4 Pro artifact.
|
|
141
|
-
* @returns the first initialization failure for that artifact, or undefined.
|
|
142
|
-
*/
|
|
143
|
-
export function deepSeekV4TokenizerFailureReason(modelId?: string): string | undefined {
|
|
144
|
-
const artifact = modelId === undefined ? ARTIFACTS[0] : artifactForModel(modelId)
|
|
145
|
-
if (artifact === undefined) return undefined
|
|
146
|
-
return registryCache.get(artifact.origin)?.failure
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
/** Complete pinned artifact inventory, in stable registration order. */
|
|
150
|
-
export function deepSeekTokenizerArtifacts(): readonly DeepSeekTokenizerArtifactOrigin[] {
|
|
151
|
-
return ARTIFACTS.map(artifact => artifact.origin)
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
/**
|
|
155
|
-
* Build a tokenizer from one local asset directory after byte/hash validation.
|
|
156
|
-
* This provider-private seam exists so tests can prove every failure branch
|
|
157
|
-
* without mutating the committed artifact.
|
|
158
|
-
* @param assetRoot - local URL containing tokenizer.json and tokenizer_config.json.
|
|
159
|
-
* @param integrity - expected byte length and SHA-256 for both files.
|
|
160
|
-
* @param origin - auditable identity recorded on every returned count.
|
|
161
|
-
* @returns a synchronous exact text counter.
|
|
162
|
-
* @internal
|
|
163
|
-
*/
|
|
164
|
-
export function createDeepSeekV4TokenizerFromAssets(
|
|
165
|
-
assetRoot: URL,
|
|
166
|
-
integrity: DeepSeekV4TokenizerAssetIntegrity,
|
|
167
|
-
origin: DeepSeekTokenizerArtifactOrigin = DEEPSEEK_V4_TOKENIZER_ARTIFACT,
|
|
168
|
-
): DeepSeekV4TextTokenizer {
|
|
169
|
-
const tokenizerJson = readVerifiedJson(assetRoot, 'tokenizer.json', integrity.tokenizer)
|
|
170
|
-
const tokenizerConfig = readVerifiedJson(assetRoot, 'tokenizer_config.json', integrity.config)
|
|
171
|
-
const runtime = new Tokenizer(tokenizerJson, tokenizerConfig)
|
|
172
|
-
return Object.freeze({
|
|
173
|
-
countText(text: string): ExactTokenizerTokenCount {
|
|
174
|
-
const tokens = runtime.encode(text, { add_special_tokens: false }).ids.length
|
|
175
|
-
return Object.freeze({
|
|
176
|
-
kind: 'exact-tokenizer',
|
|
177
|
-
tokens,
|
|
178
|
-
tokenizerId: origin.repository,
|
|
179
|
-
tokenizerRevision: origin.revision,
|
|
180
|
-
})
|
|
181
|
-
},
|
|
182
|
-
})
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
function readVerifiedJson(
|
|
186
|
-
assetRoot: URL,
|
|
187
|
-
name: string,
|
|
188
|
-
descriptor: DeepSeekV4TokenizerAssetDescriptor,
|
|
189
|
-
): Record<string, unknown> {
|
|
190
|
-
const bytes = readFileSync(new URL(name, assetRoot))
|
|
191
|
-
if (bytes.byteLength !== descriptor.bytes) {
|
|
192
|
-
throw new Error(
|
|
193
|
-
`DeepSeek tokenizer asset ${name} has ${String(bytes.byteLength)} bytes; expected ${String(descriptor.bytes)}`,
|
|
194
|
-
)
|
|
195
|
-
}
|
|
196
|
-
const actualSha256 = createHash('sha256').update(bytes).digest('hex')
|
|
197
|
-
if (actualSha256 !== descriptor.sha256) {
|
|
198
|
-
throw new Error(`DeepSeek tokenizer asset ${name} failed SHA-256 verification`)
|
|
199
|
-
}
|
|
200
|
-
const parsed: unknown = JSON.parse(bytes.toString('utf8'))
|
|
201
|
-
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
|
202
|
-
throw new Error(`DeepSeek tokenizer asset ${name} must contain a JSON object`)
|
|
203
|
-
}
|
|
204
|
-
return parsed as Record<string, unknown>
|
|
205
|
-
}
|
|
1
|
+
/** Offline DeepSeek tokenizers backed by pinned official Hugging Face assets. */
|
|
2
|
+
|
|
3
|
+
import { createHash } from 'node:crypto'
|
|
4
|
+
import { readFileSync } from 'node:fs'
|
|
5
|
+
import { Tokenizer } from '@huggingface/tokenizers'
|
|
6
|
+
import type { ExactTokenizerTokenCount } from './runtime/token-count.ts'
|
|
7
|
+
|
|
8
|
+
const TOKENIZER_ID = 'deepseek-ai/DeepSeek-V4-Pro'
|
|
9
|
+
const TOKENIZER_REVISION = '0e1a0e5e52aea73055f50fef6f2423db370265b6'
|
|
10
|
+
const TOKENIZER_SHA256 = '8f9f37ca37fdc4f5fd36d5cf4d3b0e8392edb4e894fd10cc0d70b4957c8633cf'
|
|
11
|
+
const CONFIG_SHA256 = '6ac8c8dc065ed118161d02dd532749ae3f52c243deac27872134fae2f50d8547'
|
|
12
|
+
const VISION_TOKENIZER_ID = 'deepseek-ai/DeepSeek-V4-Flash-Vision-Exp'
|
|
13
|
+
const VISION_TOKENIZER_REVISION = '6821d6ad3681a4b137b066b76094fa82ebd0a380'
|
|
14
|
+
const VISION_TOKENIZER_SHA256 = 'c90dfa01249db1be4245780a052ede752e1361c612ac6d08e2bdada7d599476b'
|
|
15
|
+
const VISION_CONFIG_SHA256 = '6ac8c8dc065ed118161d02dd532749ae3f52c243deac27872134fae2f50d8547'
|
|
16
|
+
|
|
17
|
+
/** Auditable origin and compatibility mapping for one bundled tokenizer. */
|
|
18
|
+
export interface DeepSeekTokenizerArtifactOrigin {
|
|
19
|
+
/** Hugging Face repository the assets were pinned from. */
|
|
20
|
+
readonly repository: string
|
|
21
|
+
/** Immutable commit revision the assets were pinned from. */
|
|
22
|
+
readonly revision: string
|
|
23
|
+
/** Upstream license of the repository. */
|
|
24
|
+
readonly license: string
|
|
25
|
+
/** Exact API wire model ids served by this artifact. */
|
|
26
|
+
readonly modelIds: readonly string[]
|
|
27
|
+
readonly tokenizerSha256: string
|
|
28
|
+
readonly tokenizerConfigSha256: string
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Auditable origin and compatibility mapping for the bundled V4 Pro tokenizer. */
|
|
32
|
+
export const DEEPSEEK_V4_TOKENIZER_ARTIFACT: DeepSeekTokenizerArtifactOrigin = Object.freeze({
|
|
33
|
+
repository: TOKENIZER_ID,
|
|
34
|
+
revision: TOKENIZER_REVISION,
|
|
35
|
+
license: 'MIT',
|
|
36
|
+
tokenizerSha256: TOKENIZER_SHA256,
|
|
37
|
+
tokenizerConfigSha256: CONFIG_SHA256,
|
|
38
|
+
modelIds: Object.freeze(['deepseek-v4-flash', 'deepseek-v4-pro']),
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Auditable origin and compatibility mapping for the bundled V4 Flash Vision
|
|
43
|
+
* tokenizer. The vision repository ships a distinct `tokenizer.json` (it adds
|
|
44
|
+
* the `<|deepseek_image|>` special token), so the vision model must never be
|
|
45
|
+
* mapped onto the V4 Pro tokenizer as an alias.
|
|
46
|
+
*/
|
|
47
|
+
export const DEEPSEEK_VISION_TOKENIZER_ARTIFACT: DeepSeekTokenizerArtifactOrigin = Object.freeze({
|
|
48
|
+
repository: VISION_TOKENIZER_ID,
|
|
49
|
+
revision: VISION_TOKENIZER_REVISION,
|
|
50
|
+
license: 'MIT',
|
|
51
|
+
tokenizerSha256: VISION_TOKENIZER_SHA256,
|
|
52
|
+
tokenizerConfigSha256: VISION_CONFIG_SHA256,
|
|
53
|
+
modelIds: Object.freeze(['deepseek-v4-flash-vision-exp']),
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
/** Synchronous exact counter backed only by the verified local V4 artifacts. */
|
|
57
|
+
export interface DeepSeekV4TextTokenizer {
|
|
58
|
+
/** Count one fully determined text value with the official tokenizer. */
|
|
59
|
+
countText(text: string): ExactTokenizerTokenCount
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Integrity tuple for one tokenizer JSON asset. @internal */
|
|
63
|
+
export interface DeepSeekV4TokenizerAssetDescriptor {
|
|
64
|
+
readonly bytes: number
|
|
65
|
+
readonly sha256: string
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Injectable integrity manifest used by negative loader tests. @internal */
|
|
69
|
+
export interface DeepSeekV4TokenizerAssetIntegrity {
|
|
70
|
+
readonly tokenizer: DeepSeekV4TokenizerAssetDescriptor
|
|
71
|
+
readonly config: DeepSeekV4TokenizerAssetDescriptor
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
interface TokenizerArtifact {
|
|
75
|
+
readonly origin: DeepSeekTokenizerArtifactOrigin
|
|
76
|
+
readonly assetRoot: URL
|
|
77
|
+
readonly integrity: DeepSeekV4TokenizerAssetIntegrity
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Every bundled artifact is registered with independent asset roots, integrity
|
|
82
|
+
* manifests, and cache entries: one corrupted artifact must never disable the
|
|
83
|
+
* tokenizer serving the other model family.
|
|
84
|
+
*/
|
|
85
|
+
const ARTIFACTS: readonly TokenizerArtifact[] = Object.freeze([
|
|
86
|
+
Object.freeze({
|
|
87
|
+
origin: DEEPSEEK_V4_TOKENIZER_ARTIFACT,
|
|
88
|
+
assetRoot: new URL('../assets/deepseek-v4/', import.meta.url),
|
|
89
|
+
integrity: Object.freeze({
|
|
90
|
+
tokenizer: Object.freeze({ bytes: 6_367_146, sha256: TOKENIZER_SHA256 }),
|
|
91
|
+
config: Object.freeze({ bytes: 801, sha256: CONFIG_SHA256 }),
|
|
92
|
+
}),
|
|
93
|
+
}),
|
|
94
|
+
Object.freeze({
|
|
95
|
+
origin: DEEPSEEK_VISION_TOKENIZER_ARTIFACT,
|
|
96
|
+
assetRoot: new URL('../assets/deepseek-v4-vision-exp/', import.meta.url),
|
|
97
|
+
integrity: Object.freeze({
|
|
98
|
+
tokenizer: Object.freeze({ bytes: 6_367_257, sha256: VISION_TOKENIZER_SHA256 }),
|
|
99
|
+
config: Object.freeze({ bytes: 801, sha256: VISION_CONFIG_SHA256 }),
|
|
100
|
+
}),
|
|
101
|
+
}),
|
|
102
|
+
])
|
|
103
|
+
|
|
104
|
+
interface ArtifactCacheEntry {
|
|
105
|
+
readonly tokenizer?: DeepSeekV4TextTokenizer
|
|
106
|
+
readonly failure?: string
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const registryCache = new Map<DeepSeekTokenizerArtifactOrigin, ArtifactCacheEntry>()
|
|
110
|
+
|
|
111
|
+
function artifactForModel(modelId: string): TokenizerArtifact | undefined {
|
|
112
|
+
return ARTIFACTS.find(artifact => (artifact.origin.modelIds).includes(modelId))
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Resolve the shared offline tokenizer for one compatible API model.
|
|
117
|
+
* Unknown models and a cached asset/runtime failure return `undefined`; callers
|
|
118
|
+
* must report unavailable instead of manufacturing a character estimate.
|
|
119
|
+
* @param modelId - exact DeepSeek API wire model id.
|
|
120
|
+
* @returns the shared verified tokenizer, or undefined when unsupported/unavailable.
|
|
121
|
+
*/
|
|
122
|
+
export function deepSeekV4TokenizerForModel(modelId: string): DeepSeekV4TextTokenizer | undefined {
|
|
123
|
+
const artifact = artifactForModel(modelId)
|
|
124
|
+
if (artifact === undefined) return undefined
|
|
125
|
+
const cached = registryCache.get(artifact.origin)
|
|
126
|
+
if (cached !== undefined) return cached.tokenizer
|
|
127
|
+
let entry: ArtifactCacheEntry
|
|
128
|
+
try {
|
|
129
|
+
const tokenizer = createDeepSeekV4TokenizerFromAssets(artifact.assetRoot, artifact.integrity, artifact.origin)
|
|
130
|
+
entry = { tokenizer }
|
|
131
|
+
} catch (error: unknown) {
|
|
132
|
+
entry = { failure: error instanceof Error ? error.message : String(error) }
|
|
133
|
+
}
|
|
134
|
+
registryCache.set(artifact.origin, entry)
|
|
135
|
+
return entry.tokenizer
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Read the cached initialization diagnostic for provider registration.
|
|
140
|
+
* @param modelId - optional exact model id; defaults to the V4 Pro artifact.
|
|
141
|
+
* @returns the first initialization failure for that artifact, or undefined.
|
|
142
|
+
*/
|
|
143
|
+
export function deepSeekV4TokenizerFailureReason(modelId?: string): string | undefined {
|
|
144
|
+
const artifact = modelId === undefined ? ARTIFACTS[0] : artifactForModel(modelId)
|
|
145
|
+
if (artifact === undefined) return undefined
|
|
146
|
+
return registryCache.get(artifact.origin)?.failure
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Complete pinned artifact inventory, in stable registration order. */
|
|
150
|
+
export function deepSeekTokenizerArtifacts(): readonly DeepSeekTokenizerArtifactOrigin[] {
|
|
151
|
+
return ARTIFACTS.map(artifact => artifact.origin)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Build a tokenizer from one local asset directory after byte/hash validation.
|
|
156
|
+
* This provider-private seam exists so tests can prove every failure branch
|
|
157
|
+
* without mutating the committed artifact.
|
|
158
|
+
* @param assetRoot - local URL containing tokenizer.json and tokenizer_config.json.
|
|
159
|
+
* @param integrity - expected byte length and SHA-256 for both files.
|
|
160
|
+
* @param origin - auditable identity recorded on every returned count.
|
|
161
|
+
* @returns a synchronous exact text counter.
|
|
162
|
+
* @internal
|
|
163
|
+
*/
|
|
164
|
+
export function createDeepSeekV4TokenizerFromAssets(
|
|
165
|
+
assetRoot: URL,
|
|
166
|
+
integrity: DeepSeekV4TokenizerAssetIntegrity,
|
|
167
|
+
origin: DeepSeekTokenizerArtifactOrigin = DEEPSEEK_V4_TOKENIZER_ARTIFACT,
|
|
168
|
+
): DeepSeekV4TextTokenizer {
|
|
169
|
+
const tokenizerJson = readVerifiedJson(assetRoot, 'tokenizer.json', integrity.tokenizer)
|
|
170
|
+
const tokenizerConfig = readVerifiedJson(assetRoot, 'tokenizer_config.json', integrity.config)
|
|
171
|
+
const runtime = new Tokenizer(tokenizerJson, tokenizerConfig)
|
|
172
|
+
return Object.freeze({
|
|
173
|
+
countText(text: string): ExactTokenizerTokenCount {
|
|
174
|
+
const tokens = runtime.encode(text, { add_special_tokens: false }).ids.length
|
|
175
|
+
return Object.freeze({
|
|
176
|
+
kind: 'exact-tokenizer',
|
|
177
|
+
tokens,
|
|
178
|
+
tokenizerId: origin.repository,
|
|
179
|
+
tokenizerRevision: origin.revision,
|
|
180
|
+
})
|
|
181
|
+
},
|
|
182
|
+
})
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function readVerifiedJson(
|
|
186
|
+
assetRoot: URL,
|
|
187
|
+
name: string,
|
|
188
|
+
descriptor: DeepSeekV4TokenizerAssetDescriptor,
|
|
189
|
+
): Record<string, unknown> {
|
|
190
|
+
const bytes = readFileSync(new URL(name, assetRoot))
|
|
191
|
+
if (bytes.byteLength !== descriptor.bytes) {
|
|
192
|
+
throw new Error(
|
|
193
|
+
`DeepSeek tokenizer asset ${name} has ${String(bytes.byteLength)} bytes; expected ${String(descriptor.bytes)}`,
|
|
194
|
+
)
|
|
195
|
+
}
|
|
196
|
+
const actualSha256 = createHash('sha256').update(bytes).digest('hex')
|
|
197
|
+
if (actualSha256 !== descriptor.sha256) {
|
|
198
|
+
throw new Error(`DeepSeek tokenizer asset ${name} failed SHA-256 verification`)
|
|
199
|
+
}
|
|
200
|
+
const parsed: unknown = JSON.parse(bytes.toString('utf8'))
|
|
201
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
|
202
|
+
throw new Error(`DeepSeek tokenizer asset ${name} must contain a JSON object`)
|
|
203
|
+
}
|
|
204
|
+
return parsed as Record<string, unknown>
|
|
205
|
+
}
|