sage-mem 2.16.0 → 2.17.1
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/README.en.md +32 -2
- package/README.md +35 -3
- package/lib/assembly/index.js +3 -0
- package/lib/assembly/precompact-mount.js +217 -0
- package/lib/client.js +165 -0
- package/lib/index.js +16 -133
- package/lib/memory/experimental.js +77 -0
- package/lib/precompact/policy.js +161 -0
- package/lib/precompact/state.js +73 -0
- package/lib/precompact/text.js +95 -0
- package/lib/settings.js +175 -4
- package/lib/typert/schemas.js +670 -0
- package/lib/typert.host.js +15 -650
- package/package.json +1 -20
package/README.en.md
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
|
|
13
13
|
**Cross-session memory for DeepSeek Harness — plain markdown files, no database, no worker.**
|
|
14
14
|
|
|
15
|
-
**Current release: `2.
|
|
15
|
+
**Current release: `2.17.1`** — the npm badge above is the dynamic source of truth. **Contract baseline: `1.0.0`** — the first stable release, whose public commitments, the capability boundaries and the list of things it explicitly cannot do are frozen in the
|
|
16
16
|
[frozen contract](https://github.com/gezi-wen/sage-mem/blob/main/docs/1.0.0-contract.md).
|
|
17
17
|
|
|
18
18
|
If it is useful to you, a Star is the most direct feedback.
|
|
@@ -469,6 +469,36 @@ The two things are moved **differently**, spelled out:
|
|
|
469
469
|
|
|
470
470
|
⚠️ **The premise is that the shape matches.** The four-type division and the frontmatter are sage-mem's own conventions: if your memories in CC were already "one Markdown file per memory + frontmatter" (which is what ours were at the time), just copy them over; **if they were not** (if they were all piled into a single `CLAUDE.md`, say), you need to organize them first — and that job can perfectly well be handed to an agent: have it read the old material and lay it out as files under the four types.
|
|
471
471
|
|
|
472
|
+
## Memory Reminder Before Compaction (experimental · 2.17.0)
|
|
473
|
+
|
|
474
|
+
Late in a session the host condenses earlier turns into a summary — and the details it drops are gone for good. This switch makes sage-mem drop a reminder **before** that happens, so the model can write down what deserves to survive while it still remembers.
|
|
475
|
+
|
|
476
|
+
Where: Settings → Memory management → Lab → "Memory reminder before compaction". **Off by default.**
|
|
477
|
+
|
|
478
|
+
### The trigger is computed, not guessed
|
|
479
|
+
|
|
480
|
+
The host exposes no "about to compact" event, but its criterion is public — and the plugin uses the **same metering service**:
|
|
481
|
+
|
|
482
|
+
```
|
|
483
|
+
trigger = min( window × 0.8 , window − output reservation − compaction headroom )
|
|
484
|
+
```
|
|
485
|
+
|
|
486
|
+
The window comes from `ctx.tokenMeter.contextPressure()`, the output reservation from this request's `maxTokens`, and the headroom plus 0.8 from `ctx.compaction.config` (engine defaults of 65536 / 0.8 when unset).
|
|
487
|
+
|
|
488
|
+
For example: window `1048576`, output reservation `256000`, headroom `65536` → trigger = `1048576 − 256000 − 65536 = 727040` = **69.34%**, the same figure the dsh-context panel reports as "auto-compaction is expected to fire at 69.3% of the window". So a lead of 8 reminds at **61.3%** — both ends agree, rather than two competing estimates.
|
|
489
|
+
|
|
490
|
+
### Lead time
|
|
491
|
+
|
|
492
|
+
Default **8** (percentage points), configurable 3–20. Models with a large window and a large output reservation compact well below 80% (69% above), which is why the setting is "how many points early" rather than "remind at some absolute percentage" — the latter necessarily drifts once you switch models.
|
|
493
|
+
|
|
494
|
+
### It only reminds, it never writes
|
|
495
|
+
|
|
496
|
+
What to keep, and whether to keep anything, stays the model's call. The reminder says plainly that it can be ignored; if compaction happens on the very same step, the wording changes ("the details are already gone; if you cannot recall them, do not invent them").
|
|
497
|
+
|
|
498
|
+
Each tier fires once per session and re-arms after a compaction; **subagent sessions are skipped** (their writes would pollute the main memory, and they rarely outlive the turn).
|
|
499
|
+
|
|
500
|
+
**Cost**: when off it does nothing at all — it does not even measure the context. When on, each step reads a switch and a window projection (cheap); only past half the window does it take one precise measurement (on the same waterfall as the compaction engine, where the cache is already warm). **It cannot make the model comply** — it is a reminder, not a guarantee.
|
|
501
|
+
|
|
472
502
|
## To-do Board (experimental · since 2.11.0; wrapped up in 2.15.0)
|
|
473
503
|
|
|
474
504
|
`project_session-state.md` in the memory directory has always been a to-do list you keep for yourself: injected into every session, but you still have to open the file to see what is left. 2.11.0 puts it in the **right sidebar**: Settings → Memory management → Lab → enable "To-do board", and the sidebar's Start page gains a card that opens a tab.
|
|
@@ -593,7 +623,7 @@ sage-mem is a pure DSH plugin and declares its host requirement through **`engin
|
|
|
593
623
|
|
|
594
624
|
**Verified on DSH Go (the Android client).** After installing from the in-app plugin market, the settings section and sidebar panel render normally and the `sidebar.panellist` island opens; the memory directory keeps sage-mem's default `~/.sage-mem/memory`, no extra adaptation needed. 2.1.1 fixes the invisible primary-button label on the phone host (foreground token fallback).
|
|
595
625
|
|
|
596
|
-
Version-by-version compatibility record:
|
|
626
|
+
Version-by-version compatibility record (**historical list, not a declaration** — since 2.17.1 `package.json` no longer carries `dsh.compatibility`: hosts after 0.2.1-alpha.4 only read `engines.dsh`, so a row in this table cannot make the plugin compatible; adding one only makes people believe "one row = one verified run"):
|
|
597
627
|
|
|
598
628
|
| DSH version | Status |
|
|
599
629
|
| --- | --- |
|
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
|
|
15
15
|
> File-based cross-session memory for DeepSeek Harness — every memory is a plain markdown file you can open, edit and delete. No database, no worker, no port.
|
|
16
16
|
|
|
17
|
-
**当前发布版本:`2.
|
|
17
|
+
**当前发布版本:`2.17.1`** —— 顶部 npm 徽章是动态权威。**契约基线:`1.0.0`** —— 第一个稳定版,公开承诺、能力边界与「明确做不到」的清单冻结在
|
|
18
18
|
[契约冻结](https://github.com/gezi-wen/sage-mem/blob/main/docs/1.0.0-contract.md)。
|
|
19
19
|
|
|
20
20
|
如果它对你有用,给个 Star 是最直接的反馈。
|
|
@@ -200,7 +200,7 @@ SAGE_MEM_DIR=/path/to/your/memory
|
|
|
200
200
|
|
|
201
201
|
*库健康 —— 一屏回答「这个库有没有事」:**冲突队列在上**(要你裁决的有限队列:两条说法互斥,选哪一方作废),**体检在下**(索引悬空、漏索引、双链断链等结构问题按类报红)。「指向已归档」只作提示、不计入问题;也**不提供一键修补** —— 改哪条由你决定。体检只报告、不修改。2.10.1 起体检多两类体积审计:**超线体积**(单条 ≥ 40 KB 计入问题、16–40 KB 只列提示;这两条线 2.10.2 从 8/16 KB 抬上来)与**索引过长**(只报不改,见[体积治理](#体积治理超线了怎么办))。2.14.0 起再加两类**提示**(都不计入问题):**孤儿归档件**(切片所属的那条记忆已经没了、或两份归档件内容完全相同)与**索引瘦身提案**(悬空条目与超长行直接指到行号,改不改由你);同时补上原先「算进了问题却没有渲染位置」的两类 —— **索引有多份变体**与**超线体积**。真有事要处理时,徽标后面会多一颗**「复制修复提示词」**(2.6.0):把这一屏要处理的事整理成一段提示词放进剪贴板 —— **体检问题与待裁决冲突分两段写**(前者照清单修、后者只给建议),粘给智能体就能照着办;复制成功后下方弹一条提示,10 秒自收、换页签即收、也能自己关掉。*
|
|
202
202
|
|
|
203
|
-
*实验性(2.9.0,排在库健康之后)——
|
|
203
|
+
*实验性(2.9.0,排在库健康之后)—— 只给「会改变选出哪些记忆」的开关,默认全关。当前有 **MMR 去重**:注入名额被同一件事的多份记忆占满时,先扣掉候选与已选中那些的相似度再挑。它**只改挑哪几条**(不改打分、不改文件、不碰锁定的 baseline 记忆),候选不够名额时原样返回。为什么默认关:离线对照里它一次都没触发(证据门已把候选压到 10 条以内),而关掉证据门的压力测试中重复度只降 4.5%、误注入却涨了 24% —— 它只知道「不像」,不知道「不相关」。打开前请读那一页的三条声明;**若觉得记忆变少了,关掉它、重启即可恢复**。另一项是 2.17.0 的**压缩前记忆提醒**(默认关、改完立刻生效,触发线按引擎同一条公式算出来,见下文那一节)。*
|
|
204
204
|
|
|
205
205
|

|
|
206
206
|
|
|
@@ -306,6 +306,8 @@ baselinePriority: 10 # 可选:多条 baseline 之间谁先注入(越大越
|
|
|
306
306
|
|
|
307
307
|
宿主什么时候压缩上下文,插件控制不了 —— 所以**不承诺「压缩前保存」**。能做的是:如果 `<状态目录>/tasks/<任务 id>/WORKING.md` 存在,注入末尾会给一条短句柄,说清任务、revision 与去哪读。**压缩后账本归零会连去重一起清掉**,句柄因此重新出现 —— 这就是恢复路径。
|
|
308
308
|
|
|
309
|
+
> **2.17.0 更正**:上面那句只对了一半。宿主确实没有「即将压缩」的**事件**可挂,但压缩的**判据**是公开的,插件能用同一个 token 计量服务算出它会在哪一点动手 —— 见[压缩前记忆提醒](#压缩前记忆提醒实验性--2170)(默认关,打开后会在触发线之前若干个百分点提醒模型先把要紧的写下来)。「压缩之后怎么接着干」仍然靠下面这条 WORKING.md 句柄,两者互补。
|
|
310
|
+
|
|
309
311
|
任务 id 取 `SAGE_MEM_TASK_ID`(给跨会话的同一条任务用),否则用会话 id。**绝不用你的问题原文去决定读哪个目录。** 检查点里「已完成」的条目如果没有任何证据标记(路径、命令、测试结果),解析时会如实报出来 —— 格式完美、内容错误的交接材料仍然是错的。
|
|
310
312
|
|
|
311
313
|
## 写入安全
|
|
@@ -469,6 +471,36 @@ sage-mem 给记忆目录的写入加了**版本守卫**:写入前记下当前
|
|
|
469
471
|
|
|
470
472
|
⚠️ **前提是形状对得上。** 四类划分与 frontmatter 是 sage-mem 自己的约定:如果你在 CC 里的记忆本来就是「一条一个 Markdown + frontmatter」(我们当时是这种),拷过来即可;**如果不是**(比如都堆在一个 `CLAUDE.md` 里),需要先整理一遍 —— 这活儿正好可以交给一个 agent 做:让它读旧语料,按四类落成文件。
|
|
471
473
|
|
|
474
|
+
## 压缩前记忆提醒(实验性 · 2.17.0)
|
|
475
|
+
|
|
476
|
+
会话跑到后半程,宿主会把早先的对话压成摘要 —— 被压掉的具体细节,之后谁也看不见。这个开关让 sage-mem 在**压缩发生之前**往会话里放一条提醒:趁模型还记得,把该跨会话留下的东西先写进记忆。
|
|
477
|
+
|
|
478
|
+
位置:设置 → 记忆管理 → 实验性 → 「压缩前记忆提醒」。**默认关。**
|
|
479
|
+
|
|
480
|
+
### 触发线是算出来的,不是估的
|
|
481
|
+
|
|
482
|
+
宿主没有「即将压缩」这种事件可以挂钩,但它的判据是公开的,而且插件用的是**同一个计量服务**:
|
|
483
|
+
|
|
484
|
+
```
|
|
485
|
+
触发线 = min( 窗口 × 0.8 , 窗口 − 输出预留 − 压缩预留 )
|
|
486
|
+
```
|
|
487
|
+
|
|
488
|
+
窗口从 `ctx.tokenMeter.contextPressure()` 读,输出预留从本次请求的 `maxTokens` 读,压缩预留与 0.8 从 `ctx.compaction.config` 读(没配过就用引擎默认的 65536 / 0.8)。
|
|
489
|
+
|
|
490
|
+
举例:窗口 `1048576`、输出预留 `256000`、压缩预留 `65536` → 触发线 = `1048576 − 256000 − 65536 = 727040` = **69.34%**(`727040 / 1048576`),与 dsh-context 面板显示的「自动压缩预计在窗口的 69.3% 处触发」是同一个数。所以「提前量 8」就是在 **61.3%** 提醒 —— 两端一致,不是各算一套。
|
|
491
|
+
|
|
492
|
+
### 提前量
|
|
493
|
+
|
|
494
|
+
默认 **8**(个百分点),可设 3–20。窗口大、输出预留大的模型,触发线会明显低于 80%(上例只有 69%),这正是参数取「提前多少个百分点」而不是「到某个绝对百分比就提醒」的原因 —— 后者换个模型就必然错位。
|
|
495
|
+
|
|
496
|
+
### 它只提醒,不代写
|
|
497
|
+
|
|
498
|
+
写什么、写不写由模型自己判断。提醒里明说「没有要留的就忽略这条,继续手上的事」;如果压缩就在当前这一步发生,会换成另一套话(「被砍掉的内容你看不到了;记不清就别凭印象编」)。
|
|
499
|
+
|
|
500
|
+
同一档位每条会话只发一次,压缩之后重新武装;**子代理会话不提醒**(它的写入会污染主记忆,而且它通常活不过这一轮)。
|
|
501
|
+
|
|
502
|
+
**代价**:开关关着时它什么都不做 —— 连上下文都不测。打开后每步读一次开关与窗口投影(便宜),压力过半才做一次精确测量(与压缩引擎排在同一条 waterfall 上,缓存是热的)。**它不能让模型一定照做** —— 这是提醒,不是保证。
|
|
503
|
+
|
|
472
504
|
## 待办清单看板(实验性 · 2.11.0 起;2.15.0 收尾)
|
|
473
505
|
|
|
474
506
|
记忆目录里的 `project_session_state.md` 一直是「给自己看的代办清单」——每场会话都会注入,人却要打开文件才知道还剩什么。2.11.0 把它搬进**右侧栏**:设置 → 记忆管理 → 实验性 → 打开「待办清单看板」,右侧栏「开始」页就会多一张卡片,点开是一个页签。
|
|
@@ -595,7 +627,7 @@ sage-mem 是纯 DSH 插件,用 `package.json` 的 **`engines.dsh`** 声明宿
|
|
|
595
627
|
|
|
596
628
|
**已在 DSH Go(Android 客户端)上验证可用**:从 App 内插件市场安装后,设置分区与侧栏面板正常、`sidebar.panellist` 岛屿可打开;记忆目录用 `SAGE_MEM_DIR` 默认的 `~/.sage-mem/memory` 即可,不需要额外适配。2.1.1 修掉了手机宿主上主按钮文字不可见的问题(前景令牌兜底)。
|
|
597
629
|
|
|
598
|
-
|
|
630
|
+
逐版本兼容记录(**历史清单,不是声明** —— 2.17.1 起 `package.json` 不再带 `dsh.compatibility`:0.2.1-alpha.4 之后的宿主只看 `engines.dsh`,那张表写了也不会让插件真的 compatible,补进去只会让人以为「补一行 = 验过一次」):
|
|
599
631
|
|
|
600
632
|
| DSH 版本 | 状态 |
|
|
601
633
|
| --- | --- |
|
package/lib/assembly/index.js
CHANGED
|
@@ -11,3 +11,6 @@ export { mountAutodream } from './autodream-mount.js'
|
|
|
11
11
|
export { mountMemoryTools } from './tools-mount.js'
|
|
12
12
|
export { mountObserve } from './observe-mount.js'
|
|
13
13
|
export { mountWriteGate } from './write-gate-mount.js'
|
|
14
|
+
// 2.17.0:第五块挂载。它不参与上面四块的顺序语义(不碰写门、不碰工具注册窗口),
|
|
15
|
+
// 只是两条事件监听 —— 所以排在最后,坏了也不影响前面任何一块。
|
|
16
|
+
export { mountPreCompact } from './precompact-mount.js'
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 「压缩前记忆提醒」的挂载(2.17.0)。
|
|
3
|
+
*
|
|
4
|
+
* ## 接缝图(谁 import 谁,单向)
|
|
5
|
+
*
|
|
6
|
+
* memory/experimental.js 开关边界与生效值(唯一定义处)
|
|
7
|
+
* memory/util.js warnLog
|
|
8
|
+
* ↑
|
|
9
|
+
* precompact/policy.js 纯判据:触发线 / 两档线 / 该发哪档(零 IO、零 import)
|
|
10
|
+
* precompact/text.js 纯文案(import policy 的 fmtTokens / pct)
|
|
11
|
+
* precompact/state.js 会话账(WeakMap,无 IO)
|
|
12
|
+
* ↑
|
|
13
|
+
* assembly/precompact-mount.js ← 本文件:只接线,不写业务判据
|
|
14
|
+
* ↑
|
|
15
|
+
* assembly/index.js barrel
|
|
16
|
+
* index.js 构造函数里一行调用
|
|
17
|
+
*
|
|
18
|
+
* 判据只有 `policy.js` 一份、文案只有 `text.js` 一份、账只有 `state.js` 一份;
|
|
19
|
+
* 本文件除了「取数 → 问判据 → 交文案 → 造消息」之外不做别的。
|
|
20
|
+
*
|
|
21
|
+
* ## 为什么 `{ prepend: true }`
|
|
22
|
+
*
|
|
23
|
+
* 压缩就发生在 `agent/pre-step` 的同一条 waterfall 里(`dsh-compaction-basic`
|
|
24
|
+
* 的监听器)。`prepend` 把我们排到**它前面**,于是 `next()` 之前拿到的是
|
|
25
|
+
* **压缩前**的真实压力。排在后面就只能看到压缩后的低压力 —— 那时提醒已经没有
|
|
26
|
+
* 意义(要写的细节刚被砍掉)。这是整套设计成立的前提,不是性能优化。
|
|
27
|
+
*
|
|
28
|
+
* ## 为什么要两个监听器
|
|
29
|
+
*
|
|
30
|
+
* 一个测压提醒(pre-step),一个复位(session 事件里的 `compaction/start`)。
|
|
31
|
+
* 少了后者,一条长会话只会在头一次逼近触发线时提醒,之后再也不会 —— 因为账
|
|
32
|
+
* 一直挂着。压缩把压力砍回去了,账也该跟着清。
|
|
33
|
+
*
|
|
34
|
+
* ## 失败纪律
|
|
35
|
+
*
|
|
36
|
+
* 这是锦上添花的功能:任何异常都必须**回到 `next()` 的原有结果**上,绝不因为
|
|
37
|
+
* 提醒出问题而让某一步走不动。每类异常只 warn 一次(`logOnce`),免得一条会话
|
|
38
|
+
* 刷出几百行。
|
|
39
|
+
*/
|
|
40
|
+
import { randomUUID } from 'node:crypto'
|
|
41
|
+
import { EXPERIMENTAL_SPECS, liveExperimental } from '../memory/experimental.js'
|
|
42
|
+
import { warnLog } from '../memory/util.js'
|
|
43
|
+
import {
|
|
44
|
+
decideTier,
|
|
45
|
+
resolveLines,
|
|
46
|
+
resolveThreshold,
|
|
47
|
+
worthMeasuring,
|
|
48
|
+
} from '../precompact/policy.js'
|
|
49
|
+
import { armTier, isArmed, resetSession, stateOf } from '../precompact/state.js'
|
|
50
|
+
import {
|
|
51
|
+
NUDGE_SOURCE_KIND,
|
|
52
|
+
NUDGE_SUMMARY,
|
|
53
|
+
renderAfterCompaction,
|
|
54
|
+
renderNudge,
|
|
55
|
+
} from '../precompact/text.js'
|
|
56
|
+
|
|
57
|
+
/** 本插件注入的消息来源标识(会话里认它用)。 */
|
|
58
|
+
const SOURCE = Object.freeze({ kind: NUDGE_SOURCE_KIND, form: 'notice', summary: NUDGE_SUMMARY })
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 挂载压缩前提醒。
|
|
62
|
+
*
|
|
63
|
+
* @param {object} ctx — 宿主上下文
|
|
64
|
+
* @param {{memoryDir: string}} opts — 记忆目录(文案里要写给人/模型看的那条路径)
|
|
65
|
+
* @returns {{installed: boolean}} `installed:false` 表示宿主缺事件面,功能整体不生效
|
|
66
|
+
*/
|
|
67
|
+
export function mountPreCompact(ctx, { memoryDir }) {
|
|
68
|
+
const seen = new Set()
|
|
69
|
+
const logOnce = (key, msg) => {
|
|
70
|
+
if (seen.has(key)) return
|
|
71
|
+
seen.add(key)
|
|
72
|
+
warnLog(ctx, msg)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 开关与提前量:每步现读,改完立刻生效(见 `experimental.js` 的运行期覆盖)。 */
|
|
76
|
+
const readEnabled = () => Number(liveExperimental('preCompact')) > 0
|
|
77
|
+
const readLeadPct = () => {
|
|
78
|
+
const spec = EXPERIMENTAL_SPECS.preCompactLead
|
|
79
|
+
const v = Math.round(Number(liveExperimental('preCompactLead')))
|
|
80
|
+
// 边界只在 `EXPERIMENTAL_SPECS` 定义一处;这里只判「在不在里面」,不另编默认值。
|
|
81
|
+
return Number.isFinite(v) && v >= spec.lo && v <= spec.hi ? v : spec.dflt
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 压缩**之前**的一次取样。返回 null 表示「本步不关心」。
|
|
86
|
+
*
|
|
87
|
+
* 顺序是按代价排的:开关 → 会话类型 → 窗口 → 便宜门槛 → measure → 精确线。
|
|
88
|
+
* 绝大多数步数在前四步就返回了,`measure()`(O(surface))只在压力过半时才跑。
|
|
89
|
+
*/
|
|
90
|
+
function sampleBefore(agent) {
|
|
91
|
+
const session = agent?.session
|
|
92
|
+
if (!session) return null
|
|
93
|
+
if (!readEnabled()) return null
|
|
94
|
+
// 子代理不提醒:它的写入会污染主记忆,而且它通常活不过这一轮。
|
|
95
|
+
if (session.header?.origin === 'subagent') return null
|
|
96
|
+
const get = typeof ctx.get === 'function' ? (name) => ctx.get(name) : () => undefined
|
|
97
|
+
const meter = get('tokenMeter')
|
|
98
|
+
if (!meter || typeof meter.measure !== 'function' || typeof meter.contextPressure !== 'function') return null
|
|
99
|
+
// `contextPressure` 是投影直读(便宜),`measure` 要重算整个 surface(O(surface))。
|
|
100
|
+
// 所以先用前者的 `pressureTokens` 过便宜门槛 —— 顺序反了的话门槛就白设了
|
|
101
|
+
// (那正是这条测试第一次跑出来的失败:measure 被调了一次)。
|
|
102
|
+
const { contextWindow, pressureTokens } = meter.contextPressure(session) ?? {}
|
|
103
|
+
if (!(typeof contextWindow === 'number' && contextWindow > 0)) return null
|
|
104
|
+
if (!worthMeasuring({ totalTokens: pressureTokens, contextWindow })) return null
|
|
105
|
+
// 过了门槛才精确测一次。`pressureTokens` 只算 prompt 侧,可能低估 —— 所以用它
|
|
106
|
+
// 只是省开销,真正的判定一律用这里的 `totalTokens`(与引擎同一个函数)。
|
|
107
|
+
const totalTokens = meter.measure(session)?.totalTokens
|
|
108
|
+
// 输出预留是触发线公式的一项。拿不到就**不猜** —— 猜错方向是「提醒晚于压缩」,
|
|
109
|
+
// 而晚了就等于没提醒。首轮会话还拿不到 header 时压力也远未过半,实际不损失。
|
|
110
|
+
const reservedTokens = session.requestHeader?.()?.config?.maxTokens
|
|
111
|
+
if (!(typeof reservedTokens === 'number' && reservedTokens >= 0)) return null
|
|
112
|
+
const compactConfig = get('compaction')?.config ?? {}
|
|
113
|
+
const threshold = resolveThreshold({
|
|
114
|
+
contextWindow,
|
|
115
|
+
thresholdRatio: compactConfig.thresholdRatio,
|
|
116
|
+
headroomTokens: compactConfig.headroomTokens,
|
|
117
|
+
reservedTokens,
|
|
118
|
+
})
|
|
119
|
+
if (threshold === null) return null
|
|
120
|
+
const lines = resolveLines({
|
|
121
|
+
contextWindow,
|
|
122
|
+
thresholdTokens: threshold.thresholdTokens,
|
|
123
|
+
leadPct: readLeadPct(),
|
|
124
|
+
})
|
|
125
|
+
if (lines === null) return null
|
|
126
|
+
return {
|
|
127
|
+
session,
|
|
128
|
+
totalTokens,
|
|
129
|
+
contextWindow,
|
|
130
|
+
enginePct: threshold.enginePct,
|
|
131
|
+
lines,
|
|
132
|
+
// surface 代次:`next()` 之后拿它对比,就知道这一步有没有真的压缩过。
|
|
133
|
+
generation: session.surface?.replaceGeneration,
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** 造一条 notice 级的用户消息(与 `dsh-time-context` / `dsh-repeat-tool-reminder` 同形)。 */
|
|
138
|
+
function notice(text) {
|
|
139
|
+
return {
|
|
140
|
+
id: randomUUID(),
|
|
141
|
+
role: 'user',
|
|
142
|
+
content: [{ type: 'text', text }],
|
|
143
|
+
source: { ...SOURCE },
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** 该发哪条文案(不注入就返回 null)。 */
|
|
148
|
+
function textFor(before, compacted) {
|
|
149
|
+
const { session } = before
|
|
150
|
+
if (compacted) {
|
|
151
|
+
// 本步就压了:细节已经没了,换成「要补记就现在,记不清就别编」。
|
|
152
|
+
if (isArmed(session, 'after')) return null
|
|
153
|
+
armTier(session, 'after')
|
|
154
|
+
return renderAfterCompaction({ memoryDir })
|
|
155
|
+
}
|
|
156
|
+
const tier = decideTier({ totalTokens: before.totalTokens, lines: before.lines, armed: stateOf(session).armed })
|
|
157
|
+
if (tier === null) return null
|
|
158
|
+
armTier(session, tier)
|
|
159
|
+
return renderNudge({
|
|
160
|
+
tier,
|
|
161
|
+
memoryDir,
|
|
162
|
+
totalTokens: before.totalTokens,
|
|
163
|
+
windowTokens: before.contextWindow,
|
|
164
|
+
enginePct: before.enginePct,
|
|
165
|
+
})
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const onPreStep = async (payload, next) => {
|
|
169
|
+
let before = null
|
|
170
|
+
try {
|
|
171
|
+
before = sampleBefore(payload?.agent)
|
|
172
|
+
} catch (err) {
|
|
173
|
+
logOnce('sample', `压缩前提醒:取样失败,本步跳过(${err?.message ?? err})`)
|
|
174
|
+
before = null
|
|
175
|
+
}
|
|
176
|
+
// 不关心就走人:不 await、不再算任何东西。
|
|
177
|
+
if (before === null) return next()
|
|
178
|
+
|
|
179
|
+
const decision = await next()
|
|
180
|
+
try {
|
|
181
|
+
if (decision?.kind === 'reject') return decision
|
|
182
|
+
if (payload?.signal?.aborted) return decision
|
|
183
|
+
// 异步边界之后 fiber 可能已经被销毁(`dsh-time-context` 同款守卫)。
|
|
184
|
+
if (typeof ctx.fiber?.assertActive === 'function') ctx.fiber.assertActive()
|
|
185
|
+
const compacted = before.session.surface?.replaceGeneration !== before.generation
|
|
186
|
+
const text = textFor(before, compacted)
|
|
187
|
+
if (text === null) return decision
|
|
188
|
+
const messages = Array.isArray(decision?.messages) ? decision.messages : []
|
|
189
|
+
return { ...decision, messages: [...messages, notice(text)] }
|
|
190
|
+
} catch (err) {
|
|
191
|
+
logOnce('emit', `压缩前提醒:注入失败,本步照常继续(${err?.message ?? err})`)
|
|
192
|
+
return decision
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const onSessionEvent = (session, event) => {
|
|
197
|
+
try {
|
|
198
|
+
if (event?.type !== 'compaction/start') return
|
|
199
|
+
// 压缩把压力砍回去了:账也清掉,下一次逼近是新的危险。
|
|
200
|
+
resetSession(session)
|
|
201
|
+
} catch { /* 清账失败不该有任何存在感 */ }
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
let installed = false
|
|
205
|
+
try {
|
|
206
|
+
ctx.on('agent/pre-step', onPreStep, { prepend: true })
|
|
207
|
+
ctx.on('session/event', onSessionEvent)
|
|
208
|
+
installed = true
|
|
209
|
+
} catch (err) {
|
|
210
|
+
// 老宿主没有这两条事件面:功能整体不生效,但记忆注入照常。
|
|
211
|
+
warnLog(ctx, `压缩前提醒挂载失败(记忆注入不受影响):${err?.message ?? err}`)
|
|
212
|
+
}
|
|
213
|
+
return { installed }
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** 测试用:暴露消息来源标识,免得测试里另写一份字面量。 */
|
|
217
|
+
export const __testables = { SOURCE }
|
package/lib/client.js
CHANGED
|
@@ -4891,6 +4891,24 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
|
|
|
4891
4891
|
"todo.lab.onNotice": "已开启:右侧栏「+」里能看到待办清单",
|
|
4892
4892
|
"todo.lab.offNotice": "已关闭:卡片已移除,已打开的页签会显示为关闭态",
|
|
4893
4893
|
"todo.lab.rejected": "宿主拒绝了这次设置",
|
|
4894
|
+
|
|
4895
|
+
// ── 2.17.0:压缩前记忆提醒(实验性)────────────────────────
|
|
4896
|
+
"pre.compact.title": "压缩前记忆提醒(实验性)",
|
|
4897
|
+
"pre.compact.switch": "启用压缩前记忆提醒",
|
|
4898
|
+
"pre.compact.switch.title": "上下文逼近自动压缩触发线时,往会话里放一条提醒",
|
|
4899
|
+
"pre.compact.what1": "上下文快满时,宿主会自动把早先的对话压成摘要 —— 被压掉的具体细节,之后就没人看得见了。这个开关让 sage-mem 在压缩发生之前放一条提醒,让模型先把该跨会话留下的东西写下来。",
|
|
4900
|
+
"pre.compact.what2": "它只提醒、不代写:写什么、写不写由模型自己判断;没有值得留的东西时,那条提醒会明说可以忽略。",
|
|
4901
|
+
"pre.compact.what3": "触发线是算出来的,不是估的 —— 与压缩引擎(以及 dsh-context 面板上那个百分比)同一条公式。改完立刻生效,不用重启;关着的时候它连上下文都不测。",
|
|
4902
|
+
"pre.compact.lead": "提前量",
|
|
4903
|
+
"pre.compact.unit": "个百分点",
|
|
4904
|
+
"pre.compact.hint.lead": "在宿主预估的触发线之前多少个点提醒。dsh-context 面板显示「69.3% 触发」时,提前量 8 就是在 61.3% 提醒。范围 3–20。",
|
|
4905
|
+
"pre.compact.status.on": "已开启 · 提前 {value} 点",
|
|
4906
|
+
"pre.compact.status.off": "关闭(默认)",
|
|
4907
|
+
"pre.compact.notice.on": "已开启:下一次逼近压缩触发线时会提醒",
|
|
4908
|
+
"pre.compact.notice.off": "已关闭",
|
|
4909
|
+
"pre.compact.notice.lead": "提前量已保存为 {value} 个百分点",
|
|
4910
|
+
"pre.compact.err.range": "提前量要是 3–20 的整数",
|
|
4911
|
+
"pre.compact.err.noSettings": "宿主没有提供设置接口",
|
|
4894
4912
|
};
|
|
4895
4913
|
|
|
4896
4914
|
const EN = {
|
|
@@ -5537,6 +5555,24 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
|
|
|
5537
5555
|
"todo.lab.onNotice": "On: the to-do board is in the right sidebar's + menu",
|
|
5538
5556
|
"todo.lab.offNotice": "Off: the card is gone; an open tab now shows the closed state",
|
|
5539
5557
|
"todo.lab.rejected": "The host rejected the setting",
|
|
5558
|
+
|
|
5559
|
+
// ── 2.17.0:pre-compaction memory reminder ──────────────────
|
|
5560
|
+
"pre.compact.title": "Memory reminder before compaction (experimental)",
|
|
5561
|
+
"pre.compact.switch": "Enable the pre-compaction reminder",
|
|
5562
|
+
"pre.compact.switch.title": "Drops a reminder into the conversation as the context approaches the auto-compaction trigger",
|
|
5563
|
+
"pre.compact.what1": "When the context fills up, the host condenses earlier turns into a summary — and the details it drops are gone for good. This switch makes sage-mem drop a reminder before that happens, so the model can write down what deserves to survive across sessions.",
|
|
5564
|
+
"pre.compact.what2": "It only reminds; it never writes for you. What to keep (and whether to keep anything) stays the model's call, and the reminder says plainly that it can be ignored.",
|
|
5565
|
+
"pre.compact.what3": "The trigger is computed, not guessed: it uses the same formula as the compaction engine (and the percentage dsh-context shows in its panel). Takes effect immediately, no restart; when off it does not even measure the context.",
|
|
5566
|
+
"pre.compact.lead": "Lead time",
|
|
5567
|
+
"pre.compact.unit": "percentage points",
|
|
5568
|
+
"pre.compact.hint.lead": "How many points before the host's estimated trigger to remind. When dsh-context says \"fires at 69.3%\", a lead of 8 reminds at 61.3%. Range 3–20.",
|
|
5569
|
+
"pre.compact.status.on": "On · {value} points early",
|
|
5570
|
+
"pre.compact.status.off": "Off (default)",
|
|
5571
|
+
"pre.compact.notice.on": "On: it will remind the next time the context approaches the trigger",
|
|
5572
|
+
"pre.compact.notice.off": "Off",
|
|
5573
|
+
"pre.compact.notice.lead": "Lead time saved as {value} percentage points",
|
|
5574
|
+
"pre.compact.err.range": "Lead time must be an integer between 3 and 20",
|
|
5575
|
+
"pre.compact.err.noSettings": "This host exposes no settings API",
|
|
5540
5576
|
};
|
|
5541
5577
|
|
|
5542
5578
|
/**
|
|
@@ -7135,6 +7171,9 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
|
|
|
7135
7171
|
h("div", { key: "c" }, t("lab.declare.default")),
|
|
7136
7172
|
]),
|
|
7137
7173
|
|
|
7174
|
+
// ── 2.17.0 新增:压缩前记忆提醒(默认关;host 侧 live,改完立刻生效)──
|
|
7175
|
+
h(PreCompactLabCard, { key: "precompact", ctx: props.ctx }),
|
|
7176
|
+
|
|
7138
7177
|
// ── 2.11.0 新增:待办清单看板(界面入口类开关,改完立刻生效)──
|
|
7139
7178
|
h(TodoBoardLabCard, { key: "todos", ctx: props.ctx }),
|
|
7140
7179
|
|
|
@@ -7143,6 +7182,132 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
|
|
|
7143
7182
|
notice ? h("div", { className: "smem-ok", key: "ok" }, "✓ " + notice) : null,
|
|
7144
7183
|
]);
|
|
7145
7184
|
}
|
|
7185
|
+
|
|
7186
|
+
/**
|
|
7187
|
+
* 实验性页里的「压缩前记忆提醒」卡(2.17.0)。
|
|
7188
|
+
*
|
|
7189
|
+
* 与 `TodoBoardLabCard` 同构:读 → 开关 → 说明 → 数值 → 错误与回执。
|
|
7190
|
+
* 为什么单开一张卡而不是塞进 MMR 那张:它**不改选材**,改的是「会话里会不会
|
|
7191
|
+
* 冒出一条提醒」。出事的样子也不同 —— MMR 出事是「该来的记忆没来」,这条出事是
|
|
7192
|
+
* 「该提醒的时候没提醒」。用户在面板上得能分别关掉。
|
|
7193
|
+
*
|
|
7194
|
+
* ⚠️ 这里的 3 / 20 / 8 是**客户端的一份副本**(宿主侧 `EXPERIMENTAL_SPECS`
|
|
7195
|
+
* 才是判据)。为什么只能复制:client bundle 不能 import `memory/experimental.js`
|
|
7196
|
+
* —— 那条模块链会拉到 `node:os` 与 `process.env`,在浏览器里直接炸。所以边界写在
|
|
7197
|
+
* 这里是既定取舍(MMR 卡的 0–100 同样如此);改动时两边一起改,宿主那边会拒越界值。
|
|
7198
|
+
*/
|
|
7199
|
+
function PreCompactLabCard(props) {
|
|
7200
|
+
const remote = stableRemote(props.ctx, "remote.memory");
|
|
7201
|
+
const sSet = react.useState(null); const memSet = sSet[0], setMemSet = sSet[1];
|
|
7202
|
+
const sOn = react.useState(false); const on = sOn[0], setOn = sOn[1];
|
|
7203
|
+
const sLead = react.useState("8"); const lead = sLead[0], setLead = sLead[1];
|
|
7204
|
+
const sBusy = react.useState(false); const busy = sBusy[0], setBusy = sBusy[1];
|
|
7205
|
+
const sErr = react.useState(null); const err = sErr[0], setErr = sErr[1];
|
|
7206
|
+
const sNotice = react.useState(""); const notice = sNotice[0], setNotice = sNotice[1];
|
|
7207
|
+
|
|
7208
|
+
/**
|
|
7209
|
+
* 读整数:非数字给默认值。
|
|
7210
|
+
* 与上面 `pct` 的区别是有意的 —— 那个把非法当 0(= 关闭),而提前量的 0 不是
|
|
7211
|
+
* 合法值,静默变成 0 会让用户以为自己关掉了开关。
|
|
7212
|
+
*/
|
|
7213
|
+
const readInt = function (v, dflt) {
|
|
7214
|
+
const n = Number(v);
|
|
7215
|
+
return Number.isFinite(n) ? Math.round(n) : dflt;
|
|
7216
|
+
};
|
|
7217
|
+
|
|
7218
|
+
// 初次挂载:以宿主设置里的值为准(live 开关的 pending 与 active 是一致的)。
|
|
7219
|
+
react.useEffect(function () {
|
|
7220
|
+
if (!remote || typeof remote.getSettings !== "function") {
|
|
7221
|
+
setErr(t("pre.compact.err.noSettings"));
|
|
7222
|
+
return;
|
|
7223
|
+
}
|
|
7224
|
+
Promise.resolve(remote.getSettings()).then(function (res) {
|
|
7225
|
+
const d = unwrap(res) || {};
|
|
7226
|
+
setMemSet(d);
|
|
7227
|
+
const lab = d.pendingExperimental || d.experimental || {};
|
|
7228
|
+
setOn(readInt(lab.preCompact, 0) > 0);
|
|
7229
|
+
setLead(String(readInt(lab.preCompactLead, 8)));
|
|
7230
|
+
}, function (e) { setErr(String((e && e.message) || e)); });
|
|
7231
|
+
}, []);
|
|
7232
|
+
|
|
7233
|
+
/** 写一项:`setSettings` 自带 `{ok, settings, restartRequired}`,不要过 unwrap。 */
|
|
7234
|
+
function save(patch, okMsg) {
|
|
7235
|
+
if (!remote || typeof remote.setSettings !== "function") {
|
|
7236
|
+
setErr(t("pre.compact.err.noSettings"));
|
|
7237
|
+
return;
|
|
7238
|
+
}
|
|
7239
|
+
setBusy(true); setErr(null); setNotice("");
|
|
7240
|
+
Promise.resolve(remote.setSettings({ experimental: patch })).then(function (out) {
|
|
7241
|
+
setBusy(false);
|
|
7242
|
+
if (out && out.ok === false) { setErr(out.error || t("lab.err.rejected")); return; }
|
|
7243
|
+
if (out && out.settings) setMemSet(out.settings);
|
|
7244
|
+
setNotice(okMsg);
|
|
7245
|
+
}, function (e) {
|
|
7246
|
+
setBusy(false);
|
|
7247
|
+
setErr(String((e && e.message) || e));
|
|
7248
|
+
});
|
|
7249
|
+
}
|
|
7250
|
+
|
|
7251
|
+
function toggle() {
|
|
7252
|
+
const next = on ? 0 : 1;
|
|
7253
|
+
setOn(next > 0);
|
|
7254
|
+
save({ preCompact: next }, t(next > 0 ? "pre.compact.notice.on" : "pre.compact.notice.off"));
|
|
7255
|
+
}
|
|
7256
|
+
|
|
7257
|
+
/** 保存提前量:本地先拦明显笔误(宿主也会拒,但白跑一趟没必要)。 */
|
|
7258
|
+
function saveLead() {
|
|
7259
|
+
const raw = String(lead == null ? "" : lead).trim();
|
|
7260
|
+
const n = Number(raw);
|
|
7261
|
+
if (raw === "" || !Number.isInteger(n) || n < 3 || n > 20) { setErr(t("pre.compact.err.range")); return; }
|
|
7262
|
+
save({ preCompactLead: n }, t("pre.compact.notice.lead", { value: n }));
|
|
7263
|
+
}
|
|
7264
|
+
|
|
7265
|
+
const statusText = busy
|
|
7266
|
+
? t("lab.action.saving")
|
|
7267
|
+
: (on ? t("pre.compact.status.on", { value: readInt(lead, 8) }) : t("pre.compact.status.off"));
|
|
7268
|
+
|
|
7269
|
+
return h("div", { className: "smem-module-card" }, [
|
|
7270
|
+
h("div", { className: "smem-modcard-head", key: "head" }, [
|
|
7271
|
+
h(Switch, {
|
|
7272
|
+
key: "sw",
|
|
7273
|
+
on: on,
|
|
7274
|
+
label: t("pre.compact.switch"),
|
|
7275
|
+
title: t("pre.compact.switch.title"),
|
|
7276
|
+
disabled: busy || !memSet,
|
|
7277
|
+
onClick: toggle,
|
|
7278
|
+
}),
|
|
7279
|
+
h("span", { className: "smem-modcard-title", key: "t" }, t("pre.compact.title")),
|
|
7280
|
+
h("span", { className: "smem-modcard-status", key: "s" }, statusText),
|
|
7281
|
+
]),
|
|
7282
|
+
|
|
7283
|
+
h("div", { className: "smem-autodream-sec", key: "what" }, [
|
|
7284
|
+
h("div", { className: "smem-autodream-note", key: "p1" }, t("pre.compact.what1")),
|
|
7285
|
+
h("div", { className: "smem-autodream-note", key: "p2" }, t("pre.compact.what2")),
|
|
7286
|
+
h("div", { className: "smem-autodream-note", key: "p3" }, t("pre.compact.what3")),
|
|
7287
|
+
]),
|
|
7288
|
+
|
|
7289
|
+
h("div", { className: "smem-autodream-sec", key: "lead" }, [
|
|
7290
|
+
h("div", { className: "smem-autodream-row", key: "r" }, [
|
|
7291
|
+
h("span", { className: "smem-autodream-key", key: "k" }, t("pre.compact.lead")),
|
|
7292
|
+
h("input", {
|
|
7293
|
+
className: "smem-input smem-num", key: "i", type: "number", min: 3, max: 20, step: 1,
|
|
7294
|
+
value: lead,
|
|
7295
|
+
disabled: busy || !memSet,
|
|
7296
|
+
onChange: function (e) { setLead(e.target.value); },
|
|
7297
|
+
}),
|
|
7298
|
+
h("span", { className: "smem-muted", key: "u" }, t("pre.compact.unit")),
|
|
7299
|
+
h("button", {
|
|
7300
|
+
type: "button", className: "smem-btn smem-btn-primary", key: "save",
|
|
7301
|
+
disabled: busy || !memSet, onClick: saveLead,
|
|
7302
|
+
}, busy ? t("lab.action.saving") : t("lab.action.save")),
|
|
7303
|
+
]),
|
|
7304
|
+
h("div", { className: "smem-autodream-note", key: "hint" }, t("pre.compact.hint.lead")),
|
|
7305
|
+
]),
|
|
7306
|
+
|
|
7307
|
+
err ? h("div", { className: "smem-err", key: "err" }, "⚠ " + err) : null,
|
|
7308
|
+
notice ? h("div", { className: "smem-ok", key: "ok" }, "✓ " + notice) : null,
|
|
7309
|
+
]);
|
|
7310
|
+
}
|
|
7146
7311
|
/**
|
|
7147
7312
|
* 「不参与整理的文件」勾选面板(2.10.1 体积治理 · 契约 §6)。
|
|
7148
7313
|
*
|