iia-arg/dsh-plugins--packages-dsh-pamyat-nudzh ↗★ 2
dsh-pamyat-nudzh
Расходный учёт контекста агента DSH: занятость окна, честная нижняя оценка расхода и одно напоминание модели перед компактом · Context spend accounting for a DSH agent: window occupancy, an honest lower bound of spend and one reminder to the model before compaction
Install
This plugin has no verified bundle, or compatibility checks failed. Read the repository notes first. Read the full README ↗
README
Read the full README ↗Настройка · Configuration
Ключи блока config (схема Config в src/index.js). Схема знает только типы; границы проверяет apply при каждом вызове — и при старте, и при горячей загрузке настройки.
Keys of the config block (the Config schema in src/index.js). The schema only knows types; bounds are checked by apply on every call — both at start-up and on a hot reload of the settings.
| ключ · key | тип · type | умолчание · default | допуск · range | смысл · meaning |
|---|---|---|---|---|
predel | число · number | 0 | [0, ∞), конечное · [0, ∞), finite | окно модели в токенах провайдера; 0 — предел неизвестен: расход считается, но тревоги, отметок и вставок нет, при подъёме печатается «предел контекста НЕ ЗАДАН (predel: 0) …» · the model window in provider tokens; 0 — limit unknown: spend is counted, but there is no alarm, no marks and no insertions; at start-up it prints "предел контекста НЕ ЗАДАН (predel: 0) …" |
dolyaTrevogi | число · number | 0.8 | (0, 1] | доля предела, с которой пора подталкивать к компакту; порог = predel × dolyaTrevogi · the fraction of the limit from which to nudge towards compaction; threshold = predel × dolyaTrevogi |
otmetkiPuti | массив чисел · array of numbers | [] | каждое строго между 0 и 1 · each strictly between 0 and 1 | отметки на пути к порогу: на каждую пересечённую печатается одна строка-наблюдение за цикл; на тревогу не влияют · marks on the way to the threshold: one observation line per crossed mark per cycle; they do not affect the alarm |
Негодный predel или dolyaTrevogi (вне допуска, бесконечность) отклоняется строкой «ОТКЛОНЕНО: = … — вне допуска …; действует …»: действует прежнее годное значение, а если его нет — умолчание. null и отсутствие ключа дают умолчание. Негодные отметки отбрасываются строкой «ОТКЛОНЕНО: otmetkiPuti — … отброшены …; действуют …», годные сортируются по возрастанию. Подробно — docs/SETTINGS.md.
An invalid predel or dolyaTrevogi (out of range, infinity) is rejected with a line "ОТКЛОНЕНО: = … — вне допуска …; действует …": the previous valid value stays in force, or the default if there is none. null or a missing key gives the default. Invalid marks are dropped with a line "ОТКЛОНЕНО: otmetkiPuti — … отброшены …; действуют …"; valid ones are sorted ascending. Details — docs/SETTINGS.md.
Переменных окружения пакет не читает (process.env в коде нет), файлов настроек у него нет.
The package reads no environment variables (there is no process.env in the code) and has no settings files.
Две величины · Two quantities
- Занятость окна — вход последнего вызова модели, у которого было число от провайдера (
inputTokens + cacheReadTokens + cacheWriteTokens). Порог считается от неё; после компакта она падает. Строка тревоги: «пора подтолкнуть к компакту: занято … из … (порог …%)». - Window occupancy is the input of the model's last call that had a provider number (
inputTokens + cacheReadTokens + cacheWriteTokens). The threshold is computed from it; it drops after compaction. The alarm line: "пора подтолкнуть к компакту: занято … из … (порог …%)". - Сумма расхода — сколько токенов прошло через API за все учтённые вызовы (
neMenshe). Каждый вызов пересылает весь контекст, поэтому сумма растёт без предела и компакт её не уменьшает. Это нижняя оценка: сумма может быть только БОЛЬШЕ, потому что вызовы без числа (bezChisla) посчитать нельзя. - Total spend is how many tokens went through the API over all counted calls (
neMenshe). Every call resends the whole context, so the sum grows without bound and compaction does not reduce it. It is a lower bound: the sum can only be LARGER, because calls without a number (bezChisla) cannot be counted.
Служба и события · Service and events
Пакет публикует службу nudzhPamyati (ctx.provide):
The package publishes the nudzhPamyati service (ctx.provide):
| метод · method | что делает и возвращает · what it does and returns |
|---|---|
uchest(usage, session?) | учесть расход одного вызова; с сессией — только догнать её журнал, переданный usage не прибавляется (иначе то же событие считалось бы дважды) · count one call's spend; with a session — only catch up with its journal, the given usage is not added (otherwise the same event would be counted twice) |
itog(session?) | { neMenshe, zanyato, vhod, vyhod, izNihRassuzhdenie, uchtenoVyzovov, bezChisla, polnyj }; без сессии — сумма по всем известным состояниям, zanyato — у последнего тронутого; у слепой сессии zanyato: null · { neMenshe, zanyato, vhod, vyhod, izNihRassuzhdenie, uchtenoVyzovov, bezChisla, polnyj }; without a session — the sum over all known states, zanyato from the last one touched; a blind session gives zanyato: null |
hvatitLi(session?) | никогда не «хватает»: sostoyanie = porog-pereyden (с zanyato, neMenshe, predel, uchtenoVyzovov, bezChisla) или neizvestno (с pochemu и числами полноты; при predel: 0 — только uchtenoVyzovov, bezChisla; у слепой сессии — только pochemu) · never "enough": sostoyanie = porog-pereyden (with zanyato, neMenshe, predel, uchtenoVyzovov, bezChisla) or neizvestno (with pochemu and completeness numbers; with predel: 0 — only uchtenoVyzovov, bezChisla; for a blind session — only pochemu) |
raskhodVyzova(usage) | { vhod, vyhod, vsego, izNihRassuzhdenie } одного вызова, без накопления; негодное поле — исключение с именем поля · { vhod, vyhod, vsego, izNihRassuzhdenie } of one call, without accumulation; an invalid field throws, naming the field |
Подписки (ctx.on):
Subscriptions (ctx.on):
session/event— догоняет состояние сессии по её журналу. Журнал берётся у службыpamyat(ctx.get('pamyat').sobytiyaSessii(session), необязательна), иначеsession.snapshotEvents(), иначеsession.events; унаследованная от родителя часть (inheritedEventCount/seedLength) отрезается. Учитываютсяassistant/message(data.usage),compaction/summary(только в сумму, не в занятость),compaction/end(успешный компакт с известнымcompactionIdделает занятость неизвестной до свежегоusage),user/messageот самого пакета (напоминание уже в журнале — не повторять).session/event— catches the session state up with its journal. The journal comes from thepamyatservice (ctx.get('pamyat').sobytiyaSessii(session), optional), elsesession.snapshotEvents(), elsesession.events; the part inherited from the parent (inheritedEventCount/seedLength) is cut off. Counted areassistant/message(data.usage),compaction/summary(into the sum only, not into occupancy),compaction/end(a successful compaction with a knowncompactionIdmakes occupancy unknown until a freshusage), anduser/messagefrom the package itself (the reminder is already in the journal — do not repeat it).agent/pre-step— сначала решение остальных обработчиков (next()); приreject, оборванном шаге или слепой сессии решение не трогается; если вставка взведена — кmessagesдобавляется одно сообщение пользователя, собранноеcreateUserMessageсsource.kind: 'plugin:dsh-pamyat-nudzh', и решение получаетkind: 'enter'.agent/pre-step— first the decision of the other handlers (next()); onreject, an aborted step or a blind session the decision is left alone; if the insertion is armed, one user message built withcreateUserMessageandsource.kind: 'plugin:dsh-pamyat-nudzh'is appended tomessages, and the decision getskind: 'enter'.
Весь вывод — console.error с приставкой [dsh-pamyat-nudzh ], версия из своего package.json («версия неизвестна», если не прочёлся). ctx.logger не используется.
All output goes through console.error with the prefix [dsh-pamyat-nudzh ], the version taken from its own package.json ("версия неизвестна" if it could not be read). ctx.logger is not used.
Что настройкой НЕ является · What is NOT a setting
- Состав суммы. Три правила арифметики сняты с кода платформы (замер 03.09; способ — чтение типа
TokenUsageв@deepseek-ai/dsh-llmи функцииmapUsageадаптераdsh-llm-deepseek; см. шапкуsrc/schet.js): счётчики DISJOINT — вход =inputTokens + cacheReadTokens + cacheWriteTokens;reasoningTokensв сумму не идёт (это часть выхода, показывается справочно полемizNihRassuzhdenie); вызов безusage— не ноль, аbezChisla. - The composition of the sum. Three arithmetic rules are taken from the platform's code (measured 03.09; method — reading the
TokenUsagetype in@deepseek-ai/dsh-llmand themapUsagefunction of thedsh-llm-deepseekadapter; see the header ofsrc/schet.js): the counters are DISJOINT — input =inputTokens + cacheReadTokens + cacheWriteTokens;reasoningTokensdo not go into the sum (they are part of output, shown for reference in theizNihRassuzhdeniefield); a call withoutusageis not zero butbezChisla. - Запас недостоверности. Константа
NEVOZMOZHNO = 1.5: занятость больше1.5 × predelобъявляется недостоверной — строка «СЧЁТ ЗАНЯТОСТИ НЕДОСТОВЕРЕН», ни отметок, ни тревоги. - The non-credibility margin. The constant
NEVOZMOZHNO = 1.5: occupancy above1.5 × predelis declared non-credible — the line "СЧЁТ ЗАНЯТОСТИ НЕДОСТОВЕРЕН", no marks, no alarm. - Однократность. Тревога — одна за цикл, напоминание модели — одно за цикл; цикл кончается, когда занятость вернулась под порог или после успешного компакта.
- Once per cycle. One alarm per cycle, one reminder to the model per cycle; a cycle ends when occupancy is back below the threshold or after a successful compaction.
- Несимметричность ответа. Значения «хватает» у
hvatitLiнет ни при какой настройке. - The asymmetry of the answer.
hvatitLihas no "enough" value under any setting.