sage-mem 2.16.0 → 2.17.0
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 +31 -1
- package/README.md +34 -2
- 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 +9 -5
- 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/typert.host.js +5 -3
- package/package.json +1 -1
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.0`** — 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.
|
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.0`** —— 顶部 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 把它搬进**右侧栏**:设置 → 记忆管理 → 实验性 → 打开「待办清单看板」,右侧栏「开始」页就会多一张卡片,点开是一个页签。
|
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
|
*
|
package/lib/index.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
9
|
import { AutodreamEngine, DEFAULT_CONFIG, auditMemoryDir } from './autodream.js'
|
|
10
|
-
import { EXPERIMENTAL_SPECS,
|
|
10
|
+
import { EXPERIMENTAL_SPECS, applyRuntimeExperimental, liveExperimental, STARTUP_EXPERIMENTAL_DIAGNOSTICS } from './memory/experimental.js'
|
|
11
11
|
import { LIMIT_SPECS, MAX_BASELINE, MAX_CHARS_PER_FILE, MAX_FILE_BYTES, MAX_RESULTS, MAX_SESSION_BYTES, MEMORY_DIR, RECALL_DISCIPLINE, RESERVED_FILES, SESSIONS_ROOT, STALE_DAYS, STARTUP_LIMIT_DIAGNOSTICS, STATE_ROOT, resolveLimits } from './memory/config.js'
|
|
12
12
|
import { INDEX_FILE_KEY, SESSION_LOG_KEY, isPlainMdName } from './shared/md-name.js'
|
|
13
13
|
import { parseAliases, parseBaseline, parseBaselinePriority, parseFrontmatter, parseTags } from './memory/frontmatter.js'
|
|
@@ -28,7 +28,7 @@ import { join } from 'node:path'
|
|
|
28
28
|
import { checkUpdate as checkUpdateImpl } from './update.js'
|
|
29
29
|
import { autodreamConfigSnapshot, clampInt, MAX_RAW_BYTES, parseExperimentalPatch, parseUiPatch, pendingExperimental, pendingUi, rawName, readReservedFile, readSettingsFileDetailed, RESERVED_FILE, SETTINGS_FILE } from './settings.js'
|
|
30
30
|
import { createRecallInjector, createSessionInjectState, readRecallDebug } from './recall/index.js'
|
|
31
|
-
import { mountAutodream, mountMemoryTools, mountObserve, mountWriteGate } from './assembly/index.js'
|
|
31
|
+
import { mountAutodream, mountMemoryTools, mountObserve, mountPreCompact, mountWriteGate } from './assembly/index.js'
|
|
32
32
|
|
|
33
33
|
/**
|
|
34
34
|
* 读方法的拒绝:**抛**一个带 `.code` 的 Error(写方法返回 `{ok:false, code}` 回执,见 prepareWrite)。
|
|
@@ -80,6 +80,9 @@ export class MemoryGateway extends TypertRemoteService {
|
|
|
80
80
|
// ⚠️ 写入门必须在 apply 里**同步**注册(见 lib/assembly/write-gate-mount.js 头注的「注册窗口」)。
|
|
81
81
|
mountWriteGate(ctx, MEMORY_DIR)
|
|
82
82
|
|
|
83
|
+
// 2.17.0:压缩前提醒(实验性,默认关;关着时每步只是一次开关读取)。
|
|
84
|
+
mountPreCompact(ctx, { memoryDir: MEMORY_DIR })
|
|
85
|
+
|
|
83
86
|
// 会话级注入状态:一处持有、一处提交(见 lib/recall/state.js 的头注)。
|
|
84
87
|
const injectState = createSessionInjectState()
|
|
85
88
|
|
|
@@ -427,9 +430,8 @@ export class MemoryGateway extends TypertRemoteService {
|
|
|
427
430
|
}
|
|
428
431
|
// Q04:pending 与**启动解析**共用 `resolveLimits` 这一份判据(持久设置 > 环境变量 > 默认)。
|
|
429
432
|
const pending = resolveLimits(fileRead.data?.limits)
|
|
430
|
-
// 2.
|
|
431
|
-
|
|
432
|
-
const experimental = { mmr: MMR_PERCENT, todoBoard: TODO_BOARD_ON }
|
|
433
|
+
// 2.17.0:从 `EXPERIMENTAL_SPECS` 派生(原先手写 mmr/todoBoard 两份,加开关就得来改第三次)。
|
|
434
|
+
const experimental = Object.fromEntries(Object.keys(EXPERIMENTAL_SPECS).map((k) => [k, liveExperimental(k)]))
|
|
433
435
|
const pendingLab = pendingExperimental(fileRead.data)
|
|
434
436
|
// 坏设置给明确诊断、不静默回默认:启动期那份 + 这次读文件的问题 + 逐项非法/越界说明,去重后一起给。
|
|
435
437
|
const limitDiagnostics = [...new Set([
|
|
@@ -538,6 +540,8 @@ export class MemoryGateway extends TypertRemoteService {
|
|
|
538
540
|
if (nextReserved !== null) {
|
|
539
541
|
await writeFileAtomic(RESERVED_FILE, `${JSON.stringify(nextReserved, null, 2)}\n`)
|
|
540
542
|
}
|
|
543
|
+
// 2.17.0:live 开关写盘后立刻生效;必须在下面 getSettings 之前(否则返回的已生效值是旧的)。
|
|
544
|
+
if (labPatch !== null) applyRuntimeExperimental(labPatch)
|
|
541
545
|
// 上限 / 保护名单在模块加载时就固化了,写盘即提示重启;ui 是**客户端行为**,改完立刻生效,
|
|
542
546
|
// 所以只有前两者会强制 true,纯 ui 补丁照实回传(通常就是 false)。
|
|
543
547
|
const settings = await this.getSettings()
|
|
@@ -28,6 +28,17 @@ export const EXPERIMENTAL_SPECS = {
|
|
|
28
28
|
// 不计入 `restartRequired`(组合根按这个标记跳过它,见 `lib/index.js` 的 restartRequired)。
|
|
29
29
|
// 之所以仍住在 EXPERIMENTAL_SPECS:同一套持久化、同一套环境变量优先级、同一处面板。
|
|
30
30
|
todoBoard: { env: 'SAGE_MEM_TODO_BOARD', dflt: 0, lo: 0, hi: 1, live: true },
|
|
31
|
+
// 2.17.0:**压缩前记忆提醒**(0 = 关闭 / 1 = 开启)。宿主自动压缩前若干步,往本轮注入一条
|
|
32
|
+
// 提醒,让模型先把该跨会话留的东西写下来。消费者是 host 半的 `agent/pre-step`(见
|
|
33
|
+
// `lib/assembly/precompact-mount.js`),但标 `live: true` —— 监听器每步现读生效值,
|
|
34
|
+
// 不需要重启。挂载是常驻的、极便宜的一层壳(开关关着时第一步就返回),
|
|
35
|
+
// 所以「先挂上、再开关」不会带来任何后台开销。
|
|
36
|
+
preCompact: { env: 'SAGE_MEM_PRECOMPACT', dflt: 0, lo: 0, hi: 1, live: true },
|
|
37
|
+
// 提前量:在「引擎预计触发点」之前多少个**百分点**提醒。默认 8(面板显示 69.3% 时
|
|
38
|
+
// 约在 61.3% 提醒)。为什么是百分点而不是「触发线的百分之几」:宿主面板与压缩引擎
|
|
39
|
+
// 用的是同一个窗口百分比(`precompact/policy.js` 复刻了那条公式),用百分点能让人
|
|
40
|
+
// 直接对着面板读数理解「还差 8 个点」。
|
|
41
|
+
preCompactLead: { env: 'SAGE_MEM_PRECOMPACT_LEAD', dflt: 8, lo: 3, hi: 20, live: true },
|
|
31
42
|
}
|
|
32
43
|
|
|
33
44
|
/**
|
|
@@ -78,3 +89,69 @@ export const TODO_BOARD_ON = STARTUP_EXPERIMENTAL.experimental.todoBoard
|
|
|
78
89
|
* 调用点(`lib/recall/select.js`)以它为默认值,因此「面板/环境变量改了 → 下一次注入生效」。
|
|
79
90
|
*/
|
|
80
91
|
export const MMR_LAMBDA = MMR_PERCENT / 100
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* 运行期覆盖层(2.17.0):面板改了 `live: true` 的开关后,host 侧**不必重启**
|
|
95
|
+
* 就能读到新值。
|
|
96
|
+
*
|
|
97
|
+
* 为什么需要这一层:`STARTUP_EXPERIMENTAL` 是模块加载时算出来的常量,改设置
|
|
98
|
+
* 只能等重启。而「压缩前提醒」的消费者是 `agent/pre-step` 监听器,它每一步都跑 ——
|
|
99
|
+
* 让它去读 `settings.json` 就是每步一次磁盘 IO。这里换成「写设置时顺手把新值
|
|
100
|
+
* 塞进内存」,零 IO、零延迟。
|
|
101
|
+
*
|
|
102
|
+
* ⚠️ **不是第二套解析**:进来的补丁已经过 `parseExperimentalPatch` 与
|
|
103
|
+
* `resolveExperimental` 的同一套 `parseLimitValue`,这里只做「收下」动作。
|
|
104
|
+
* 判据仍只有一处。
|
|
105
|
+
*/
|
|
106
|
+
let runtimeOverride = null
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* 收下面板刚保存的补丁。未知键与非法值直接丢弃(上游已经校验过一遍,这里只兜底)。
|
|
110
|
+
*
|
|
111
|
+
* @param {Record<string, number>|null|undefined} patch
|
|
112
|
+
*/
|
|
113
|
+
export function applyRuntimeExperimental(patch) {
|
|
114
|
+
if (!patch || typeof patch !== 'object' || Array.isArray(patch)) return
|
|
115
|
+
const next = { ...(runtimeOverride ?? {}) }
|
|
116
|
+
let changed = false
|
|
117
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
118
|
+
const spec = EXPERIMENTAL_SPECS[key]
|
|
119
|
+
if (!spec) continue
|
|
120
|
+
const parsed = parseLimitValue(value, spec)
|
|
121
|
+
if (parsed === undefined) continue
|
|
122
|
+
next[key] = parsed
|
|
123
|
+
changed = true
|
|
124
|
+
}
|
|
125
|
+
if (changed) runtimeOverride = next
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* 读一个实验性开关的**当前实际生效值**。
|
|
130
|
+
*
|
|
131
|
+
* 优先级:运行期覆盖(仅 `live: true`)> 启动快照 > 内置默认。
|
|
132
|
+
*
|
|
133
|
+
* ⚠️ **非 `live` 的开关不吃运行期覆盖**,这一点是刻意的,也是 `panel-api-test`
|
|
134
|
+
* 逼出来的:`mmr` 这类开关的生效点在模块加载时(注入链每步都读那份常量),
|
|
135
|
+
* 面板改完必须重启才真的变。如果这里也返回覆盖值,`getSettings()` 就会报
|
|
136
|
+
* 「已生效 35」,而「待生效 35 / 当前生效 0」那行说明还在同一屏上 —— 同一个界面
|
|
137
|
+
* 说两套话,比不说更糟。
|
|
138
|
+
*
|
|
139
|
+
* 所以本函数回答的是「**现在真的按哪个值在跑**」,不是「用户最近保存了什么」。
|
|
140
|
+
* 后者是 `pendingExperimental` 的事。
|
|
141
|
+
*
|
|
142
|
+
* @param {string} key — `EXPERIMENTAL_SPECS` 的键
|
|
143
|
+
* @returns {number|undefined}
|
|
144
|
+
*/
|
|
145
|
+
export function liveExperimental(key) {
|
|
146
|
+
const spec = EXPERIMENTAL_SPECS[key]
|
|
147
|
+
if (!spec) return undefined
|
|
148
|
+
const startup = STARTUP_EXPERIMENTAL.experimental[key] ?? spec.dflt
|
|
149
|
+
if (!spec.live) return startup
|
|
150
|
+
const live = runtimeOverride?.[key]
|
|
151
|
+
return live !== undefined ? live : startup
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** 测试用:把运行期覆盖清回「只有启动快照」的状态。 */
|
|
155
|
+
export function resetRuntimeExperimental() {
|
|
156
|
+
runtimeOverride = null
|
|
157
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 「压缩前提醒」的判据 —— **纯函数,零 I/O,零 import**。
|
|
3
|
+
*
|
|
4
|
+
* ## 为什么要把引擎的公式抄一份
|
|
5
|
+
*
|
|
6
|
+
* 宿主的自动压缩没有对外事件(压缩发生在 `agent/pre-step` 的 waterfall 里,
|
|
7
|
+
* 由 `dsh-compaction-basic` 就地判定)。想在压缩**之前**提醒,就只能自己算
|
|
8
|
+
* 「引擎会在哪一点动手」。
|
|
9
|
+
*
|
|
10
|
+
* 抄的不是它的实现,是它公开的判据(`dsh-compaction-basic/lib/index.js:124-132`):
|
|
11
|
+
*
|
|
12
|
+
* threshold = min( floor(W × thresholdRatio), W − reserved − headroom )
|
|
13
|
+
*
|
|
14
|
+
* 三个输入全部可读:`W` 来自 `ctx.tokenMeter.contextPressure()`,
|
|
15
|
+
* `thresholdRatio` / `headroom` 来自 `ctx.compaction.config`(本机没配过,走默认
|
|
16
|
+
* 0.8 / 65536),`reserved` 来自 `session.requestHeader().config.maxTokens`。
|
|
17
|
+
*
|
|
18
|
+
* **对过表的一次**:窗口 1048576、输出预留 256000、headroom 65536
|
|
19
|
+
* → 727040 tokens → 69.34%,与 dsh-context 面板显示的 69.3% 一致。
|
|
20
|
+
* 也就是说:用户看到面板说「69.3% 触发」,提醒就会在 61.3%(提前 8 个点)出现
|
|
21
|
+
* —— 两端同一个数,不是各算一套。
|
|
22
|
+
*
|
|
23
|
+
* ## 为什么 `pressureBudget <= 0` 时返回 null(不提醒)
|
|
24
|
+
*
|
|
25
|
+
* 那个分支里引擎**会抛错而不是压缩**(`TargetPressureConfigError`,见引擎
|
|
26
|
+
* `:129-131`)。没有压缩威胁却去打扰模型,是把提醒当噪声发。宁可沉默。
|
|
27
|
+
*
|
|
28
|
+
* ## 为什么两档而不是一档
|
|
29
|
+
*
|
|
30
|
+
* 一档要么太早(写完了后面还有很长,白打扰一次)、要么太晚(只剩一两步,
|
|
31
|
+
* 模型来不及写)。两档给模型一次「可以写」和一次「只写要紧的」,也让人
|
|
32
|
+
* 在会话里看得出趋势。
|
|
33
|
+
*
|
|
34
|
+
* ## 提前量为什么不在这里定边界
|
|
35
|
+
*
|
|
36
|
+
* `{dflt, lo, hi}` 的唯一定义处是 `memory/experimental.js` 的 `EXPERIMENTAL_SPECS`
|
|
37
|
+
* (它同时供解析、面板校验、环境变量兜底三处使用)。这里再存一份 `3/20/8`
|
|
38
|
+
* 就是第二份真相 —— 改一处漏一处。所以本模块对外部传入的 `leadPct` 只做
|
|
39
|
+
* **合法性判定**(非法就返回 null 让调用方跳过),不自己编一个默认值。
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
/** 引擎的压缩预留默认值(token)。源:`dsh-compaction-basic` 的 `headroomTokens ?? 65536`。 */
|
|
43
|
+
export const DEFAULT_HEADROOM_TOKENS = 65536
|
|
44
|
+
|
|
45
|
+
/** 引擎的触发比例默认值。源:同文件 `thresholdRatio ?? 0.8`。 */
|
|
46
|
+
export const DEFAULT_THRESHOLD_RATIO = 0.8
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* 便宜门槛:窗口用量不到这个比例时,pre-step 连 `measure()` 都不调。
|
|
50
|
+
*
|
|
51
|
+
* 为什么是 0.5 而不是贴着提前量(比如 0.55):`measure()` 是 O(surface) 的,
|
|
52
|
+
* 而 pre-step 每一步都跑。大多数步数离压缩很远,用一个明显偏低的常数挡住,
|
|
53
|
+
* 比「按档位动态算门槛」少一次计算,也少一处可能与档位算错的地方。
|
|
54
|
+
*/
|
|
55
|
+
export const NEAR_WINDOW_RATIO = 0.5
|
|
56
|
+
|
|
57
|
+
const isPos = (n) => typeof n === 'number' && Number.isFinite(n) && n > 0
|
|
58
|
+
const isNonNeg = (n) => typeof n === 'number' && Number.isFinite(n) && n >= 0
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 复刻引擎的触发线。
|
|
62
|
+
*
|
|
63
|
+
* @param {object} input
|
|
64
|
+
* @param {number} input.contextWindow — 该路由模型的窗口(`tokenMeter.contextPressure` 给的)
|
|
65
|
+
* @param {number} [input.thresholdRatio] — 引擎的触发比例,缺失/非法回落 0.8
|
|
66
|
+
* @param {number} [input.headroomTokens] — 引擎的压缩预留,缺失/非法回落 65536
|
|
67
|
+
* @param {number} [input.reservedTokens] — 模型最大输出预留,缺失按 0 算
|
|
68
|
+
* @returns {{thresholdTokens:number, enginePct:number}|null} 窗口未知或预算非正 → null(不提醒)
|
|
69
|
+
*/
|
|
70
|
+
export function resolveThreshold({ contextWindow, thresholdRatio, headroomTokens, reservedTokens }) {
|
|
71
|
+
if (!isPos(contextWindow)) return null
|
|
72
|
+
const ratio = isPos(thresholdRatio) && thresholdRatio <= 1 ? thresholdRatio : DEFAULT_THRESHOLD_RATIO
|
|
73
|
+
const headroom = isNonNeg(headroomTokens) ? headroomTokens : DEFAULT_HEADROOM_TOKENS
|
|
74
|
+
// 输出预留不许超过窗口本身 —— 引擎那边用 Math.min(t, e) 做同一件事(`dsh-context:305575`)。
|
|
75
|
+
const reserved = Math.min(isNonNeg(reservedTokens) ? reservedTokens : 0, contextWindow)
|
|
76
|
+
const byRatio = Math.floor(contextWindow * ratio)
|
|
77
|
+
const byBudget = contextWindow - reserved - headroom
|
|
78
|
+
// 预算非正 = 引擎这个目标根本压不了(它会抛配置错)。没有威胁就不打扰。
|
|
79
|
+
if (byBudget <= 0) return null
|
|
80
|
+
const thresholdTokens = Math.min(byRatio, byBudget)
|
|
81
|
+
if (thresholdTokens <= 0) return null
|
|
82
|
+
return { thresholdTokens, enginePct: pct(thresholdTokens, contextWindow) }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 把触发线换算成两条提醒线(绝对值,token)。
|
|
87
|
+
*
|
|
88
|
+
* @param {object} input
|
|
89
|
+
* @param {number} input.contextWindow
|
|
90
|
+
* @param {number} input.thresholdTokens — `resolveThreshold` 的 `thresholdTokens`
|
|
91
|
+
* @param {number} input.leadPct — 提前多少个百分点(调用方按 `EXPERIMENTAL_SPECS` 收敛过的值)
|
|
92
|
+
* @returns {{warnTokens:number, urgeTokens:number, warnPct:number, urgePct:number}|null}
|
|
93
|
+
* 窗口或提前量非法 → null
|
|
94
|
+
*/
|
|
95
|
+
export function resolveLines({ contextWindow, thresholdTokens, leadPct }) {
|
|
96
|
+
if (!isPos(contextWindow)) return null
|
|
97
|
+
if (!isNonNeg(thresholdTokens) || thresholdTokens <= 0) return null
|
|
98
|
+
if (!isPos(leadPct) || leadPct >= 100) return null
|
|
99
|
+
// 催促档只提前 lead/3(默认 8 → 2.67 个点),夹在预警档与触发线之间。
|
|
100
|
+
const warnTokens = Math.max(0, thresholdTokens - (contextWindow * leadPct) / 100)
|
|
101
|
+
const urgeTokens = Math.max(0, thresholdTokens - (contextWindow * (leadPct / 3)) / 100)
|
|
102
|
+
return {
|
|
103
|
+
warnTokens,
|
|
104
|
+
urgeTokens,
|
|
105
|
+
warnPct: pct(warnTokens, contextWindow),
|
|
106
|
+
urgePct: pct(urgeTokens, contextWindow),
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* 该发哪一档。**只判「还没发过」的档**,已发过的由 `armed` 挡住。
|
|
112
|
+
*
|
|
113
|
+
* 一次跨两档的情形(一步吃掉很多 token)只发 `urge` —— 更紧急的那条已经把
|
|
114
|
+
* 话说全了,再补一条 `warn` 是同一步里发两条噪音。
|
|
115
|
+
*
|
|
116
|
+
* 还有一条单调性在这里兜底:**`urge` 发过之后 `warn` 也不必再发**。`state.js`
|
|
117
|
+
* 的 `armTier('urge')` 会顺手把 `warn` 一起标上,两层都说同一件事是有意的 ——
|
|
118
|
+
* 判据自身正确,才不依赖调用方记得先 arm。
|
|
119
|
+
*
|
|
120
|
+
* @param {object} input
|
|
121
|
+
* @param {number} input.totalTokens — 当前压力(压缩**之前**取的)
|
|
122
|
+
* @param {{warnTokens:number, urgeTokens:number}} input.lines
|
|
123
|
+
* @param {Set<string>} input.armed — 本会话已发过的档
|
|
124
|
+
* @returns {'warn'|'urge'|null}
|
|
125
|
+
*/
|
|
126
|
+
export function decideTier({ totalTokens, lines, armed }) {
|
|
127
|
+
if (!isNonNeg(totalTokens) || !lines) return null
|
|
128
|
+
if (armed.has('urge')) return null
|
|
129
|
+
if (totalTokens >= lines.urgeTokens) return 'urge'
|
|
130
|
+
if (totalTokens >= lines.warnTokens && !armed.has('warn')) return 'warn'
|
|
131
|
+
return null
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* 便宜门槛:这一步值得往下算吗。
|
|
136
|
+
*
|
|
137
|
+
* 只跟窗口比,不与档位比 —— 它是在「还不知道触发线」的时候用的最早那层闸。
|
|
138
|
+
*/
|
|
139
|
+
export function worthMeasuring({ totalTokens, contextWindow }) {
|
|
140
|
+
if (!isPos(contextWindow) || !isNonNeg(totalTokens)) return false
|
|
141
|
+
return totalTokens >= contextWindow * NEAR_WINDOW_RATIO
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** 百分比,保留一位小数(与 dsh-context 面板的取整一致,好让人一眼对上)。 */
|
|
145
|
+
export function pct(tokens, window) {
|
|
146
|
+
if (!isPos(window)) return 0
|
|
147
|
+
return Math.min(100, Math.round((tokens / window) * 1000) / 10)
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* token 数的显示形式(`727040` → `727k`)。
|
|
152
|
+
*
|
|
153
|
+
* 为什么不用 1024 进制:面板与模型都习惯看「1.0M / 69.3%」这种十进制读数,
|
|
154
|
+
* 这里跟它保持一致,别让同屏出现两种口径。
|
|
155
|
+
*/
|
|
156
|
+
export function fmtTokens(n) {
|
|
157
|
+
const v = typeof n === 'number' && Number.isFinite(n) ? n : 0
|
|
158
|
+
if (v >= 1e6) return `${Math.round((v / 1e6) * 10) / 10}M`
|
|
159
|
+
if (v >= 1e4) return `${Math.round(v / 1e3)}k`
|
|
160
|
+
return String(Math.round(v))
|
|
161
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 提醒档位的**会话内记忆** —— 只在进程内存里,不落盘、不跨会话、不参与持久化。
|
|
3
|
+
*
|
|
4
|
+
* ## 为什么按 session 而不是按 agent
|
|
5
|
+
*
|
|
6
|
+
* 一个 agent 可以在会话之间切换(`agent.session` 会变),而「这次会话已经提醒到
|
|
7
|
+
* 哪一档」讲的是会话的事实。按 agent 记会在切换会话时把旧账带过去,于是新会话
|
|
8
|
+
* 永远收不到第一条提醒 —— 这种 bug 不报错,只是静默少了一条。
|
|
9
|
+
*
|
|
10
|
+
* ## 为什么用 WeakMap
|
|
11
|
+
*
|
|
12
|
+
* 会话对象被回收时账也该跟着走。用普通 Map 会攒住已经结束的会话,长跑进程里
|
|
13
|
+
* 一直涨 —— 而这个插件的寿命与宿主进程一样长。
|
|
14
|
+
*
|
|
15
|
+
* ## 为什么 `armTier('urge')` 连 `warn` 一起标
|
|
16
|
+
*
|
|
17
|
+
* 一步吃掉很多 token 时会从「没到预警线」直接跨到触发线附近。此时只发 `urge`
|
|
18
|
+
* (更紧急的那条已经把话说全),但若不把 `warn` 也标上,下一次判定会在同一条
|
|
19
|
+
* 会话里补发一条「预警」—— 两档的说辞几乎一样,两条连着发只是噪音。
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
const STATES = new WeakMap()
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 取(或建)一个会话的提醒账。
|
|
26
|
+
*
|
|
27
|
+
* @param {object} session
|
|
28
|
+
* @returns {{armed: Set<'warn'|'urge'>}}
|
|
29
|
+
*/
|
|
30
|
+
export function stateOf(session) {
|
|
31
|
+
let st = STATES.get(session)
|
|
32
|
+
if (st === undefined) {
|
|
33
|
+
st = { armed: new Set() }
|
|
34
|
+
STATES.set(session, st)
|
|
35
|
+
}
|
|
36
|
+
return st
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 这一档在本会话里发过没有。 */
|
|
40
|
+
export function isArmed(session, tier) {
|
|
41
|
+
return stateOf(session).armed.has(tier)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 记账:这一档已发。
|
|
46
|
+
*
|
|
47
|
+
* @param {object} session
|
|
48
|
+
* @param {'warn'|'urge'|'after'} tier
|
|
49
|
+
*/
|
|
50
|
+
export function armTier(session, tier) {
|
|
51
|
+
const { armed } = stateOf(session)
|
|
52
|
+
armed.add(tier)
|
|
53
|
+
// 跨档只发一条:发过 urge 就把 warn 一并标掉,免得下一步补一条重复话术。
|
|
54
|
+
if (tier === 'urge') armed.add('warn')
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 压缩发生后重新武装(两档都清空)。
|
|
59
|
+
*
|
|
60
|
+
* 为什么压缩就要复位:压缩把上下文砍回低压力,之前「已经提醒过」的账对应的
|
|
61
|
+
* 是**压缩前**的那一段历史。下一次逼近触发线时是新的危险,该说就得说。
|
|
62
|
+
*
|
|
63
|
+
* @param {object} session
|
|
64
|
+
*/
|
|
65
|
+
export function resetSession(session) {
|
|
66
|
+
const st = STATES.get(session)
|
|
67
|
+
if (st !== undefined) st.armed.clear()
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 测试用:把某个会话的账彻底丢掉(不影响别人)。 */
|
|
71
|
+
export function forgetSession(session) {
|
|
72
|
+
STATES.delete(session)
|
|
73
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 提醒文案的渲染 —— **纯函数,零 I/O**。
|
|
3
|
+
*
|
|
4
|
+
* 三条口径,都是踩过坑才定下来的:
|
|
5
|
+
*
|
|
6
|
+
* 1. **不带 `{{ }}`**。注入链早就在 `recall/injector.js` 上吃过这个亏:宿主的
|
|
7
|
+
* prompt 模板会把双花括号当变量解析,正文里出现一对就抛
|
|
8
|
+
* `malformed prompt variable reference`,模型还没开跑就挂了。提醒走的是另一条
|
|
9
|
+
* 路(user 消息,不过模板),但同一份纪律不因为路径不同就放松。
|
|
10
|
+
*
|
|
11
|
+
* 2. **明说「没有就忽略」**。提醒最坏的失败形态不是没提醒到,而是把模型从用户
|
|
12
|
+
* 手上的活里拽出来、逼它编几条记忆填数。所以每一档结尾都给一条退路。
|
|
13
|
+
*
|
|
14
|
+
* 3. **数字全用实际算出来的值**,与 dsh-context 面板同一个触发线(见 `policy.js`)。
|
|
15
|
+
* 写「快满了」这种定性描述,人和模型都没法判断还有多少步。
|
|
16
|
+
*
|
|
17
|
+
* 文案里出现的工具名只有 `search_memory` / `read_memory` —— 写入走宿主文件工具,
|
|
18
|
+
* 这个插件自己没有写记忆的工具(`lib/assembly/tools-mount.js` 只注册三个读/裁工具)。
|
|
19
|
+
*/
|
|
20
|
+
import { fmtTokens, pct } from './policy.js'
|
|
21
|
+
|
|
22
|
+
/** 提醒消息的来源标识。也是面板/会话里认这条消息的唯一标记。 */
|
|
23
|
+
export const NUDGE_SOURCE_KIND = 'sage-mem:precompact'
|
|
24
|
+
|
|
25
|
+
/** 一句话摘要(UI 折叠时显示)。 */
|
|
26
|
+
export const NUDGE_SUMMARY = '压缩前记忆提醒'
|
|
27
|
+
|
|
28
|
+
const HEAD = '【sage-mem】'
|
|
29
|
+
const MEMORY_TODO = [
|
|
30
|
+
'- 定下来的决定,以及为什么这么定',
|
|
31
|
+
'- 查清的事实、踩过的坑(症状 → 根因 → 修法)',
|
|
32
|
+
'- 下次要接着做的事',
|
|
33
|
+
].join('\n')
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 渲染一条提醒。
|
|
37
|
+
*
|
|
38
|
+
* @param {object} input
|
|
39
|
+
* @param {'warn'|'urge'} input.tier
|
|
40
|
+
* @param {string} input.memoryDir — 记忆目录(注入链同一份路径)
|
|
41
|
+
* @param {number} input.totalTokens — 压缩**之前**测到的压力
|
|
42
|
+
* @param {number} input.windowTokens
|
|
43
|
+
* @param {number} input.enginePct — 引擎预计触发点(百分比)
|
|
44
|
+
* @returns {string}
|
|
45
|
+
*/
|
|
46
|
+
export function renderNudge({ tier, memoryDir, totalTokens, windowTokens, enginePct }) {
|
|
47
|
+
const head = `${HEAD}上下文约 ${fmtTokens(totalTokens)} / ${fmtTokens(windowTokens)}(${pct(totalTokens, windowTokens)}%)。`
|
|
48
|
+
const engine = `这个会话的自动压缩预计在 ${enginePct}% 处触发。`
|
|
49
|
+
const where = `写进记忆目录 \`${memoryDir}\`:新建一条 \`project_*.md\`,或在已有文件里补一段;动了清单就同步更新 \`MEMORY.md\`。写之前先用 \`search_memory\` 搜一下、\`read_memory\` 看看,别写重复的。`
|
|
50
|
+
|
|
51
|
+
if (tier === 'urge') {
|
|
52
|
+
return [
|
|
53
|
+
`${head}${engine}也就是说随时会压 —— 被压掉的对话细节,之后你就看不见了。`,
|
|
54
|
+
'',
|
|
55
|
+
'只写真正要紧的(决定了什么、为什么、下一步做什么),别整段抄对话。' + where,
|
|
56
|
+
'',
|
|
57
|
+
'已经写完了、或者这个会话没什么值得留的,就忽略这条,继续手上的事。',
|
|
58
|
+
].join('\n')
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return [
|
|
62
|
+
`${head}${engine}再往后若干步,早先的对话细节就会被整段压掉,压掉之后就看不见了。`,
|
|
63
|
+
'',
|
|
64
|
+
'如果本会话里有值得跨会话留下的东西:',
|
|
65
|
+
MEMORY_TODO,
|
|
66
|
+
'',
|
|
67
|
+
'现在' + where,
|
|
68
|
+
'',
|
|
69
|
+
'没有要留的就忽略这条,继续手上的事 —— 同一档位每次压缩前只发一次。',
|
|
70
|
+
].join('\n')
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* 压缩**已经在本步发生**时用的文案。
|
|
75
|
+
*
|
|
76
|
+
* 为什么要单独一套:pre-step 里我们抢在引擎之前测压,但压力可能一步就从
|
|
77
|
+
* 预警线跳到触发线以上 —— 那一步引擎当场就压了,此时再喊「快压缩了」是假话。
|
|
78
|
+
* 这一档只说真话:已经压了、细节你看不到了、还记得就补记。
|
|
79
|
+
*
|
|
80
|
+
* 最后一句「别凭印象编」是有意的:被摘要替换之后模型并没有原文,
|
|
81
|
+
* 让它「回忆」只会得到一段听起来合理、实际编造的记忆 —— 那比不记更坏。
|
|
82
|
+
*
|
|
83
|
+
* @param {object} input
|
|
84
|
+
* @param {string} input.memoryDir
|
|
85
|
+
* @returns {string}
|
|
86
|
+
*/
|
|
87
|
+
export function renderAfterCompaction({ memoryDir }) {
|
|
88
|
+
return [
|
|
89
|
+
`${HEAD}刚才这一步上下文被压缩了:早先的一整段对话已被摘要替换,具体细节你看不到了。`,
|
|
90
|
+
'',
|
|
91
|
+
`如果你还记得本会话里值得跨会话保留的东西(决定 / 事实 / 坑 / 待办),现在补记到 \`${memoryDir}\`:新建一条 \`project_*.md\` 或补进已有文件,动了清单就同步 \`MEMORY.md\`。`,
|
|
92
|
+
'',
|
|
93
|
+
'记不清具体内容就忽略这条 —— 别凭印象编。',
|
|
94
|
+
].join('\n')
|
|
95
|
+
}
|
package/lib/typert.host.js
CHANGED
|
@@ -297,8 +297,10 @@ const settingsSchema = z.object({
|
|
|
297
297
|
'ui': settingsUiSchema,
|
|
298
298
|
'reserved': z.array(z.string()).readonly(),
|
|
299
299
|
'reservedExtra': z.array(z.string()).readonly(),
|
|
300
|
-
|
|
301
|
-
|
|
300
|
+
// 2.17.0:加 `preCompact` / `preCompactLead`。这四处必须同步 —— zod 的 object 默认
|
|
301
|
+
// **剥掉未声明的键**,漏一处就是「面板保存成功、读回却少了这一项」的静默丢字段。
|
|
302
|
+
'experimental': z.object({ 'mmr': z.number().readonly(), 'todoBoard': z.number().readonly(), 'preCompact': z.number().readonly(), 'preCompactLead': z.number().readonly() }).readonly(),
|
|
303
|
+
'pendingExperimental': z.object({ 'mmr': z.number().readonly(), 'todoBoard': z.number().readonly(), 'preCompact': z.number().readonly(), 'preCompactLead': z.number().readonly() }).readonly(),
|
|
302
304
|
// 2.15.6(M1):Q04 的诊断出口 —— 坏设置 / 逐项越界 / 启动期告警。不声明就等于把
|
|
303
305
|
// 「保存了但没生效」这句话在传输层抹掉,面板只能显示「保存成功」。
|
|
304
306
|
'limitDiagnostics': z.array(z.string()).readonly(),
|
|
@@ -316,7 +318,7 @@ const settingsPatchSchema = z.object({
|
|
|
316
318
|
'sidebarEntry': z.boolean().optional(),
|
|
317
319
|
}).readonly().optional(),
|
|
318
320
|
'reserved': z.array(z.string()).optional(),
|
|
319
|
-
'experimental': z.object({ 'mmr': z.number().optional(), 'todoBoard': z.number().optional() }).readonly().optional(),
|
|
321
|
+
'experimental': z.object({ 'mmr': z.number().optional(), 'todoBoard': z.number().optional(), 'preCompact': z.number().optional(), 'preCompactLead': z.number().optional() }).readonly().optional(),
|
|
320
322
|
}).readonly()
|
|
321
323
|
const settingsResultSchema = z.object({
|
|
322
324
|
'ok': z.boolean().readonly(),
|
package/package.json
CHANGED