npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

dsh-llm-context-guard

v1.0.0

Published

阻止 pi-ai 的上下文估算把 max_tokens 压成 1(模型只吐一个字就 finish_reason: length)。幂等自愈补丁,可跨 DSH 安装复用。

Readme

dsh-llm-context-guard

阻止 DSH 的 「模型只吐一个字就报 max token」 故障,做成可跨 DSH 安装复用的 cordis 插件。


症状

对话进行到一定长度后:

  • 模型只输出 一个字("The"、"This")就停下
  • 报 已达到输出 token 上限回答被截断
  • 发「继续」还是同样的错,永远无法完成任务
  • 日志里 outputTokens: 1、stopReason: "length"

根因

max_tokens 被压成了 1。

@earendil-works/pi-ai 的 dist/api/simple-options.js:

const MIN_MAX_TOKENS = 1;

export function clampMaxTokensToContext(model, context, maxTokens) {
    if (model.contextWindow <= 0) return Math.max(MIN_MAX_TOKENS, maxTokens);
    const available = model.contextWindow - estimateContextTokens(context).tokens - 4096;
    return Math.min(maxTokens, Math.max(MIN_MAX_TOKENS, available));
}

estimateContextTokens 是 字符数 / 4 的估算。当它超过 contextWindow - 4096, available 变成负数,Math.max(1, 负数) = 1 —— 于是向 provider 请求「只生成 1 个 token」。

为什么估算会虚高

pi-ai 的 dist/utils/estimate.js 本来有个「用真实 usage 锚定」的分支:

const usageAppliesToPrefix = assistant.timestamp >= latestPrefixTimestamp;
if (usageAppliesToPrefix &&
    assistant.stopReason !== "aborted" &&
    assistant.stopReason !== "error" &&
    calculateContextTokens(assistant.usage) > 0) {
    usageInfo = { usage: assistant.usage, index: i };
}

命中时,估算 = 最后一次真实 usage + 之后的增量,历史不再重复计费。

但 @deepseek-ai/dsh-llm-pi-ai 在重建历史时把每条 assistant 消息的 usage 清零了 (lib/index.js 的 foreignAssistant / replayedAssistant):

usage: emptyPiUsage(),   // totalTokens: 0
timestamp: 0,

calculateContextTokens(...) > 0 永远为假 → 锚点永不生效 → 退化成对整段历史做 char / 4,并且把每个 reasoning 块也算进去 (estimate.js:chars += block.thinking.length)。

在实测的故障会话里,reasoning 累计 451,143 字符 ≈ 112,786 个幻觉 token。

为什么「继续」也救不回来

历史没变 → 估算不变 → 永远 clamp 到 1。粘死。

而且压缩也救不了:压缩摘要本身也是一次 LLM 调用,被同一个估算 clamp (compaction-basic 默认 maxTokens: 8192),摘要写不完 → finishError 抛 summarization truncated at the token cap (incomplete checkpoint) → 整个压缩被丢弃 → 上下文永远不缩小。


修复

插件打两处补丁,幂等,每次启动重打 —— 所以 npm install 覆盖后会自动修回来, 不需要 fork,也不需要改 settings.yaml。

① 治本:把真实 usage 带回 replay 信封

dsh-llm-pi-ai 的 replay 信封多带一个可选 usage 字段:

  • 写:toPiReplayState 把 provider 的真实 usage 写进 response.usage
  • 读:replayedAssistant 用它还原 usage,而不是强制 emptyPiUsage()

锚点因此生效,估算从「整段历史 char/4」塌缩成「最后一次 usage + 尾部增量」。

实测(故障会话 eca5daaf @ seq 305):

| | 估算 | clamp @ 256K | |---|---|---| | 修复前 | 252,336 | 1 | | 修复后 | 183,709 | 68,195 |

对照 provider 真实 prompt(176,410),误差从 75,926 降到 7,299。

② 兜底:抬高「1 token」地板

const MIN_MAX_TOKENS = 1024; /* dsh-llm-context-guard */

即使某条路由的估算仍然溢出,模型也能输出约 1024 个 token 而不是 1 个字 —— 把「静默吐一个字」变成「诚实的截断」。


安装

# 方式一:bundle 通道(自动读 cordis.patch.yml)
dsh plugin --profile web add ./dsh-llm-context-guard

# 方式二:手工挂载 —— 把下面这行加进 profile 的 cordis.patch.yml
# - insert:
#     - id: dsh-llm-context-guard
#       name: 'dsh-llm-context-guard'

重启 DSH 生效。 补丁在插件加载时写入磁盘,而 Node 已经缓存了旧模块, 所以本次进程内不会立即改变行为。

验证

node tools/verify.mjs              # 只读:解析结果 + 补丁状态
node tools/verify.mjs --dry-run    # 预览将要改什么
node tools/verify.mjs --selftest   # 在临时副本上证明机制(不动线上安装)
node tools/verify.mjs --apply      # 直接打补丁(不启动 DSH)
node tools/verify.mjs --revert     # 从备份还原

--selftest 会把两个包复制到临时目录、只对副本打补丁、并对比 clamp 前后:

  clamp before patch              : 1   <- one token, the reported bug
  clamp after patch               : 1024
  estimator with zero usage       : 300003 tokens (anchor never engages)
  estimator with real usage       : 1050 tokens (anchor at index 1)
RESULT: PASS

配置

- id: dsh-llm-context-guard
  name: 'dsh-llm-context-guard'
  config:
    minMaxTokens: 1024          # 地板,默认 1024
    restoreReplayUsage: true    # 是否打 ①(治本),默认 true
    enabled: true               # false = 完全不动库文件

也可用环境变量 DSH_CONTEXT_GUARD_MIN_MAX_TOKENS 覆盖地板。


已知边界

  • 只对新消息生效。 ① 依赖消息自己的 replay 信封携带 usage; 已经写进日志的旧消息没有这个字段,会回落到 emptyPiUsage(), 因此在被压缩掉之前仍然虚高。想让存量会话立刻恢复,用 /compact 或另开新会话。
  • 补丁依赖上游文件形状。 每个锚点必须恰好出现一次,否则拒绝打补丁并记日志 (partial / anchor not found / anchor is ambiguous)—— 上游重构时会大声失败,而不是悄悄改坏文件。
  • 不改 settings.yaml。 把 contextWindow 调大能缓解,但那只是把墙往后挪; 估算虚高这个根因还在,窗口一改小就会复发。本插件不依赖任何 contextWindow 取值。
  • 备份文件后缀 .orig-ctxguard,--revert 会用它还原。

卸载

node tools/verify.mjs --revert
# 然后从 profile 的 cordis.patch.yml 移除对应条目并重启