Skip to content

feat(session): 实现 context compress — token 预算模式的上下文压缩#12

Merged
uchouT merged 1 commit into
mainfrom
feat/context-compress
Mar 27, 2026
Merged

feat(session): 实现 context compress — token 预算模式的上下文压缩#12
uchouT merged 1 commit into
mainfrom
feat/context-compress

Conversation

@uchouT
Copy link
Copy Markdown
Collaborator

@uchouT uchouT commented Mar 27, 2026

Summary

  • 为 Session/MainSession 的 send()/stream() 添加基于 token 预算的上下文压缩能力
  • 应用层通过 contextWindow: { maxContextTokens, countTokens } 配置,适配不同 LLM 的上下文窗口和 tokenizer
  • 配置后 L2(memory/synthesis)作为摘要前缀注入上下文,L3 按剩余 token 预算从最近往前填充
  • 新增 trimRecords(keepRecent) 方法,支持 consolidate 后物理裁剪旧 L3
  • 不配置 contextWindow 时行为完全向后兼容

改动范围

模块 改动
types/functions.ts 新增 CountTokensFnContextWindowOptions,四个 Options 均添加 contextWindow?
types/storage.ts SessionStorage 新增 trimRecords()
types/session-api.ts / main-session-api.ts Session/MainSession 新增 trimRecords()
context-utils.ts 新文件 — 共享的上下文组装逻辑(selectHistoryByBudgetassembleSessionContextassembleMainSessionContext
create-session.ts / create-main-session.ts 重构 send()/stream() 使用共享上下文组装,添加 trimRecords 实现
in-memory-storage.ts 实现 trimRecords
pg-session-storage.ts 实现 trimRecords(SQL)

设计决策

  • 放宽 L2 可见性约束:配置 contextWindow 时,L2 作为压缩前缀注入子 Session 的 send() 上下文(原约束为「L2 对子 Session 不可见」)
  • 增量 token 计数:O(n) 算法,逐条累加而非 O(n²) 重新计数
  • countTokens 回调注入:不内置 tokenizer,应用层适配不同 LLM

Test plan

  • 现有 78 个测试全部通过(向后兼容)
  • 新增 15 个测试覆盖:trimRecords 存储操作、token 预算压缩、边界条件(负数/超预算/空历史)、consolidate+trim 工作流、MainSession 压缩、stream 压缩
  • session 包 build 通过(ESM + CJS + DTS)
  • core 包 build 通过

Session.send()/stream() 支持通过 contextWindow 配置按 token 预算压缩上下文:
- 新增 ContextWindowOptions(maxContextTokens + countTokens 回调)
- 配置后 L2 作为摘要前缀注入,L3 按剩余预算从最近往前填充
- 新增 trimRecords() 方法用于 consolidate 后物理裁剪旧 L3
- 不配置时行为完全向后兼容
@uchouT uchouT merged commit 3a2372d into main Mar 27, 2026
Difficult-Burger added a commit to Difficult-Burger/stello that referenced this pull request Mar 31, 2026
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant