dsh-layers-hippocampus 1.7.2 → 1.7.3
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/CHANGELOG.md +2049 -1976
- package/README.md +395 -395
- package/docs/ARCHITECTURE.zh.md +2 -2
- package/index.js +114 -5
- package/package.json +75 -75
- package/src/config.js +48 -0
- package/src/context/smartPrune.js +188 -0
- package/src/context/windowGuard.js +30 -0
- package/src/errors.js +4 -0
- package/src/memory.js +119 -5
- package/src/policy.js +14 -0
- package/src/rawStore.js +161 -23
- package/src/sensitive.js +130 -0
- package/src/tombstones.js +157 -0
- package/src/webRoutes.js +7 -0
package/docs/ARCHITECTURE.zh.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @local/dsh-memory — 分层长期记忆 Host 插件
|
|
2
2
|
|
|
3
|
-
> 版本:**1.7.
|
|
3
|
+
> 版本:**1.7.3** | 全量用例:**571/571** | 运行时依赖:**零**
|
|
4
4
|
|
|
5
5
|
给 DSH 智能体一份"活得比会话久"的记忆:**追加式原始日志是唯一真相源**,标签索引、日记、活跃集合全部是可丢弃、可重建的读模型,语义摘要独立于原始日志生死。
|
|
6
6
|
|
|
@@ -681,7 +681,7 @@ window.__ModuleLoader__.load({
|
|
|
681
681
|
|
|
682
682
|
运行器带**看门狗**:默认 **60s**(`MEM_TEST_TIMEOUT_MS` 可调)仍未退出,就打印**卡住时正在导入/执行的文件、最后完成的测试名与完成数、活动资源、尚未触发的定时器**,然后 `process.exit(1)`。它不会用 `process.exit(0)` 掩盖超时——挂起即失败。`MEM_TEST_TRACE=1` 可看文件级进度,`MEM_TEST_ONLY=<子串>` 只跑一组。
|
|
683
683
|
|
|
684
|
-
|
|
684
|
+
571 个用例(88 个文件)覆盖:
|
|
685
685
|
|
|
686
686
|
- 索引与标签:重建 digest 一致、行号漂移防护(eventId 不变、行号变)、同义合并、活跃集 cap 挤出、规则变更不改清单、空活跃集降级、top-k 有界有序去重。
|
|
687
687
|
- 衰减与删除:30 天半衰期、reinforce 移动锚点(不存字段)、仅文本粗筛、标签过滤、维护代切换且旧代可读、boot 检查、压缩不丢记录、并发维护串行化、四阶段删除、archive 可回滚 vs purge 不可、strict 巩固暂停与恢复、任务重放幂等、错误 id 零变更。
|
package/index.js
CHANGED
|
@@ -45,6 +45,14 @@ import { isLowValley, nextLowValleyStart, windowInfo } from './src/priceWindow.j
|
|
|
45
45
|
import { DreamTimer } from './src/dreamTimer.js';
|
|
46
46
|
import { probeCompression, resolveEngine } from './src/compression.js';
|
|
47
47
|
import { LIVE_COMPACT_DEFAULTS, liveCompactSession } from './src/context/liveCompact.js';
|
|
48
|
+
|
|
49
|
+
// v1.7.4: how long a host-measured pressure reading may be reused while deciding
|
|
50
|
+
// whether a handoff marker still tells the truth. Requests are seconds apart, so five
|
|
51
|
+
// minutes is generous — and a stale reading is never used to CLEAR something.
|
|
52
|
+
const HANDOFF_PRESSURE_FRESH_MS = 5 * 60 * 1000;
|
|
53
|
+
// v1.7.3 (module 1): physical context pruning. No host compaction, no model call —
|
|
54
|
+
// the turn is REPLACED with a pointer that keeps the event id.
|
|
55
|
+
import { smartPruneSession, FOLD_MIN_CHARS, FOLD_MAX_NODES } from './src/context/smartPrune.js';
|
|
48
56
|
import { snippet } from './src/util.js';
|
|
49
57
|
import { dimensionOf, groupByDimension, stripPhysiology, containsPhysiology } from './src/semantic/dimensions.js';
|
|
50
58
|
import { isSecretRecord } from './src/privacy.js';
|
|
@@ -68,7 +76,7 @@ export { resolveConfig, DEFAULT_CONFIG };
|
|
|
68
76
|
* of letting a raw 404 reach the user.
|
|
69
77
|
*/
|
|
70
78
|
export const CAPABILITIES = Object.freeze({
|
|
71
|
-
version: '1.7.
|
|
79
|
+
version: '1.7.3',
|
|
72
80
|
spaces: true,
|
|
73
81
|
memories: true,
|
|
74
82
|
transferConsent: true,
|
|
@@ -952,8 +960,23 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
952
960
|
// current preset is readable here even when no change event ever fired.
|
|
953
961
|
runtime.syncAgentPreset();
|
|
954
962
|
if (runtime.phase === 'ready') {
|
|
955
|
-
const handoff = memory.handoffState();
|
|
956
963
|
const usage = memory.sessionUsage();
|
|
964
|
+
// v1.7.4: the marker must expire with the pressure that wrote it. This used to be
|
|
965
|
+
// checked only on the fail-fast path, so "[交接标记] 上下文已接近原生窗口上限" was
|
|
966
|
+
// injected on every turn even at 10% usage, and the model handed off early.
|
|
967
|
+
let handoff = memory.handoffState();
|
|
968
|
+
try {
|
|
969
|
+
// Only a FRESH host measurement may expire the marker (see guardRequest); the
|
|
970
|
+
// local usage counter is empty in the real host, so it must not be trusted here.
|
|
971
|
+
const pressure = runtime.lastPressure;
|
|
972
|
+
const fresh =
|
|
973
|
+
pressure && Number.isFinite(pressure.ratio) && memory.clock.now() - pressure.at <= HANDOFF_PRESSURE_FRESH_MS;
|
|
974
|
+
if (handoff.active && fresh) {
|
|
975
|
+
handoff = memory.maintainHandoffMarker({ ratio: pressure.ratio, usage })?.marker ?? handoff;
|
|
976
|
+
}
|
|
977
|
+
} catch {
|
|
978
|
+
/* prompt assembly must never fail because of marker upkeep */
|
|
979
|
+
}
|
|
957
980
|
const sessionId = usage?.sessionId ?? 'anonymous';
|
|
958
981
|
// SessionStart OR rollover resets the dedup pool: the new session may receive
|
|
959
982
|
// the same handoff summary / tags that the old one already saw.
|
|
@@ -1168,11 +1191,81 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1168
1191
|
}
|
|
1169
1192
|
hostProbes.updatedAt = memory.clock.now();
|
|
1170
1193
|
|
|
1171
|
-
// ----
|
|
1172
|
-
|
|
1194
|
+
// ---- 2.5 physical pruning (v1.7.3, module 1) --------------------------
|
|
1195
|
+
// At the configured share of the REAL window we fold the oldest verbose turns
|
|
1196
|
+
// into pointers BEFORE measuring again. This is what makes the plugin usable
|
|
1197
|
+
// without the host's compaction engine: the surface shrinks, the log does not.
|
|
1198
|
+
const pruneConfig = runtime.config?.context?.smartPrune ?? {};
|
|
1199
|
+
let state = memory.context.nativeState({
|
|
1173
1200
|
usedTokens: hostProbes.usedTokens ?? undefined,
|
|
1174
1201
|
reservedTokens: hostProbes.reservedTokens ?? undefined,
|
|
1175
1202
|
});
|
|
1203
|
+
const pruneThreshold = Number.isFinite(pruneConfig.threshold) ? pruneConfig.threshold : 0.85;
|
|
1204
|
+
if (pruneConfig.enabled !== false && session && state.projectedRatio >= pruneThreshold) {
|
|
1205
|
+
try {
|
|
1206
|
+
runtime.lastSmartPrune = {
|
|
1207
|
+
source: 'hippocampus',
|
|
1208
|
+
at: memory.clock.now(),
|
|
1209
|
+
threshold: pruneThreshold,
|
|
1210
|
+
ratioBefore: state.projectedRatio,
|
|
1211
|
+
...smartPruneSession(session, {
|
|
1212
|
+
keepRecentTurns: pruneConfig.keepRecentTurns ?? 3,
|
|
1213
|
+
minChars: pruneConfig.minChars ?? FOLD_MIN_CHARS,
|
|
1214
|
+
maxNodes: pruneConfig.maxNodes ?? FOLD_MAX_NODES,
|
|
1215
|
+
logger: runtime.logger,
|
|
1216
|
+
// The pointer must name something a reader can actually resolve. The raw
|
|
1217
|
+
// store keys its turns deterministically (`turn_<seq>_<role>`), so the fold
|
|
1218
|
+
// points at the raw turn instead of an opaque number.
|
|
1219
|
+
describe: ({ seq, event }) => {
|
|
1220
|
+
let role = null;
|
|
1221
|
+
try {
|
|
1222
|
+
role = turnFromSessionEvent(event)?.role ?? null;
|
|
1223
|
+
} catch {
|
|
1224
|
+
role = null;
|
|
1225
|
+
}
|
|
1226
|
+
return {
|
|
1227
|
+
turnId: role ? `turn_${seq}_${role}` : `turn_${seq}`,
|
|
1228
|
+
tool: event?.type === 'tool/result' ? (event?.data?.name ?? null) : null,
|
|
1229
|
+
};
|
|
1230
|
+
},
|
|
1231
|
+
}),
|
|
1232
|
+
};
|
|
1233
|
+
if (runtime.lastSmartPrune.folded > 0) {
|
|
1234
|
+
// The surface changed, so the measurement must be taken again — and the
|
|
1235
|
+
// probe is refreshed too, because the host may not have re-measured yet.
|
|
1236
|
+
try {
|
|
1237
|
+
const after = typeof tokenMeter?.contextPressure === 'function' ? tokenMeter.contextPressure(session) : null;
|
|
1238
|
+
const values = [after?.pressureTokens, after?.projectedTokens].filter((value) => Number.isFinite(value));
|
|
1239
|
+
if (values.length > 0) hostProbes.usedTokens = Math.max(...values);
|
|
1240
|
+
} catch {
|
|
1241
|
+
/* a stale probe only costs one extra fold attempt */
|
|
1242
|
+
}
|
|
1243
|
+
state = memory.context.nativeState({
|
|
1244
|
+
usedTokens: hostProbes.usedTokens ?? undefined,
|
|
1245
|
+
reservedTokens: hostProbes.reservedTokens ?? undefined,
|
|
1246
|
+
});
|
|
1247
|
+
runtime.lastSmartPrune.ratioAfter = state.projectedRatio;
|
|
1248
|
+
}
|
|
1249
|
+
} catch (error) {
|
|
1250
|
+
runtime.logger?.warn?.(`hippocampus: smart prune failed: ${asMemoryError(error).code}`);
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
// v1.7.4: marker upkeep on EVERY request, not only on the fail-fast path below —
|
|
1255
|
+
// that asymmetry is exactly why a marker outlived the pressure that created it.
|
|
1256
|
+
// This is the ONE place that owns a host-true measurement, so it is also what the
|
|
1257
|
+
// next prompt assembly reuses (runtime.lastPressure).
|
|
1258
|
+
try {
|
|
1259
|
+
runtime.lastPressure = { ratio: state.projectedRatio, tokens: state.tokens, at: memory.clock.now() };
|
|
1260
|
+
runtime.lastHandoffMaintenance = memory.maintainHandoffMarker({
|
|
1261
|
+
ratio: state.projectedRatio,
|
|
1262
|
+
usage: { sessionId: session?.id ?? null, tokens: state.tokens },
|
|
1263
|
+
});
|
|
1264
|
+
} catch {
|
|
1265
|
+
/* advisory only: never block a request on marker upkeep */
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
// ---- 3. fail fast on a request that CANNOT fit -------------------------
|
|
1176
1269
|
if (!state.hardExceeded) return state;
|
|
1177
1270
|
// Try to hand off first: even though it cannot shrink THIS request, it leaves a
|
|
1178
1271
|
// distilled tail for the next one instead of repeating the same failure.
|
|
@@ -1197,6 +1290,7 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1197
1290
|
ratio: state.ratio,
|
|
1198
1291
|
handoff: handoff?.handoff?.summaryEventId ?? null,
|
|
1199
1292
|
liveCompact: runtime.lastLiveCompact ?? null,
|
|
1293
|
+
smartPrune: runtime.lastSmartPrune ?? null,
|
|
1200
1294
|
},
|
|
1201
1295
|
);
|
|
1202
1296
|
};
|
|
@@ -2097,6 +2191,9 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
2097
2191
|
// "a handoff summary exists and this conversation has not seen it yet"
|
|
2098
2192
|
// (inside noteColdStart). A delegated sub-agent also lands here — it merely
|
|
2099
2193
|
// arms its OWN entry, and the user's conversation arms its own on first turn.
|
|
2194
|
+
// v1.7.4: a new conversation starts with no pressure history; reusing the old
|
|
2195
|
+
// reading would let it clear a marker that belongs to a different conversation.
|
|
2196
|
+
runtime.lastPressure = null;
|
|
2100
2197
|
runtime.noteColdStart({ agentId: payload?.agent?.id ?? null, source: 'agent-created' });
|
|
2101
2198
|
// Track the mode this session actually runs in (a session may be created with
|
|
2102
2199
|
// a preset without emitting a change event).
|
|
@@ -2660,6 +2757,13 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
2660
2757
|
max_tokens: { type: 'number', description: 'deep_raw only: result token budget, default from raw.maxResultTokens' },
|
|
2661
2758
|
hash: { type: 'string', description: 'deep_raw only: restore one raw turn verbatim by sha256 (from [Slimmed] hash_…)' },
|
|
2662
2759
|
regex: { type: 'boolean', description: 'deep_raw only: treat text as a restricted regular expression' },
|
|
2760
|
+
allow_sensitive: {
|
|
2761
|
+
type: 'boolean',
|
|
2762
|
+
description:
|
|
2763
|
+
'Include records tagged sensitive:* (api_key / credential / pii). Omitted by default: they are ' +
|
|
2764
|
+
'PHYSICALLY excluded and only a count appears in notes (sensitive-withheld:N). ' +
|
|
2765
|
+
'Only pass this when the user has explicitly asked you to handle the secret.',
|
|
2766
|
+
},
|
|
2663
2767
|
include_secret: {
|
|
2664
2768
|
type: 'boolean',
|
|
2665
2769
|
description:
|
|
@@ -2673,7 +2777,10 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
2673
2777
|
if (args.mode === 'deep_raw') {
|
|
2674
2778
|
if (runtime.phase !== 'ready') return errorJson(runtime.notReady('deep_raw'));
|
|
2675
2779
|
if (typeof args.hash === 'string' && args.hash.trim()) {
|
|
2676
|
-
const restored = await runtime.memory.deepRaw({
|
|
2780
|
+
const restored = await runtime.memory.deepRaw({
|
|
2781
|
+
hash: args.hash.trim(),
|
|
2782
|
+
allowSensitive: args.allow_sensitive === true,
|
|
2783
|
+
});
|
|
2677
2784
|
return JSON.stringify({ ok: true, ...restored });
|
|
2678
2785
|
}
|
|
2679
2786
|
// A missing window is NOT pre-validated here: the engine decides. A
|
|
@@ -2687,6 +2794,7 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
2687
2794
|
limit,
|
|
2688
2795
|
regex: args.regex === true,
|
|
2689
2796
|
maxTokens: args.max_tokens,
|
|
2797
|
+
allowSensitive: args.allow_sensitive === true,
|
|
2690
2798
|
});
|
|
2691
2799
|
runtime.touch();
|
|
2692
2800
|
runtime.recordToolCall({ landed: (result.hits ?? []).length > 0 });
|
|
@@ -2698,6 +2806,7 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
2698
2806
|
topK: Math.min(args.top_k ?? config.retrieval.topK, config.maxRecallTopK),
|
|
2699
2807
|
targetSpaceId: args.target_space_id,
|
|
2700
2808
|
includeSecret: args.include_secret === true,
|
|
2809
|
+
allowSensitive: args.allow_sensitive === true,
|
|
2701
2810
|
});
|
|
2702
2811
|
runtime.recordToolCall({
|
|
2703
2812
|
landed: (result.hits ?? []).length > 0 || (result.ghostHints ?? []).length > 0,
|
package/package.json
CHANGED
|
@@ -1,75 +1,75 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "dsh-layers-hippocampus",
|
|
3
|
-
"version": "1.7.
|
|
4
|
-
"private": false,
|
|
5
|
-
"description": "Layered long-term memory for DeepSeek Harness: append-only event log, rebuildable tag index, day diaries, independent semantic layer, L2.5 trend quarantine, offline knowledge graph and a Web UI panel.",
|
|
6
|
-
"type": "module",
|
|
7
|
-
"main": "index.js",
|
|
8
|
-
"license": "MIT",
|
|
9
|
-
"author": "382quaii",
|
|
10
|
-
"repository": {
|
|
11
|
-
"type": "git",
|
|
12
|
-
"url": "git+https://github.com/382quaii/dsh-Layers-Hippocampus.git"
|
|
13
|
-
},
|
|
14
|
-
"homepage": "https://github.com/382quaii/dsh-Layers-Hippocampus#readme",
|
|
15
|
-
"bugs": {
|
|
16
|
-
"url": "https://github.com/382quaii/dsh-Layers-Hippocampus/issues"
|
|
17
|
-
},
|
|
18
|
-
"keywords": [
|
|
19
|
-
"deepseek",
|
|
20
|
-
"harness",
|
|
21
|
-
"dsh",
|
|
22
|
-
"dsh-plugin",
|
|
23
|
-
"memory",
|
|
24
|
-
"long-term-memory",
|
|
25
|
-
"knowledge-graph",
|
|
26
|
-
"ai-agent"
|
|
27
|
-
],
|
|
28
|
-
"engines": {
|
|
29
|
-
"node": ">=22"
|
|
30
|
-
},
|
|
31
|
-
"publishConfig": {
|
|
32
|
-
"registry": "https://registry.npmjs.org/",
|
|
33
|
-
"access": "public"
|
|
34
|
-
},
|
|
35
|
-
"exports": {
|
|
36
|
-
".": "./index.js",
|
|
37
|
-
"./package.json": "./package.json",
|
|
38
|
-
"./client": "./ui/client.js",
|
|
39
|
-
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
40
|
-
"./locale/*.json": "./locale/*.json",
|
|
41
|
-
"./icon": "./icon.svg",
|
|
42
|
-
"./src/*": "./src/*"
|
|
43
|
-
},
|
|
44
|
-
"files": [
|
|
45
|
-
"index.js",
|
|
46
|
-
"src/**/*.js",
|
|
47
|
-
"ui/**/*.js",
|
|
48
|
-
"cordis.patch.yml",
|
|
49
|
-
"locale/*.json",
|
|
50
|
-
"icon.svg",
|
|
51
|
-
"screenshots.json",
|
|
52
|
-
"assets/*.png",
|
|
53
|
-
"README.md",
|
|
54
|
-
"LICENSE",
|
|
55
|
-
"CHANGELOG.md",
|
|
56
|
-
"docs/ARCHITECTURE.zh.md",
|
|
57
|
-
"docs/PUBLISHING.md",
|
|
58
|
-
"market/**/*.yml",
|
|
59
|
-
"market/*.md"
|
|
60
|
-
],
|
|
61
|
-
"scripts": {
|
|
62
|
-
"test": "node test/run.mjs",
|
|
63
|
-
"bench": "node scripts/bench-protocol.mjs",
|
|
64
|
-
"repair-handoff": "node scripts/repair-handoff.mjs",
|
|
65
|
-
"check": "node --check index.js && node --check ui/client.js && node test/run.mjs"
|
|
66
|
-
},
|
|
67
|
-
"dsh": {
|
|
68
|
-
"bundle": {
|
|
69
|
-
"patch": "./cordis.patch.yml"
|
|
70
|
-
},
|
|
71
|
-
"client": {
|
|
72
|
-
"platform": "web"
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "dsh-layers-hippocampus",
|
|
3
|
+
"version": "1.7.3",
|
|
4
|
+
"private": false,
|
|
5
|
+
"description": "Layered long-term memory for DeepSeek Harness: append-only event log, rebuildable tag index, day diaries, independent semantic layer, L2.5 trend quarantine, offline knowledge graph and a Web UI panel.",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "index.js",
|
|
8
|
+
"license": "MIT",
|
|
9
|
+
"author": "382quaii",
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/382quaii/dsh-Layers-Hippocampus.git"
|
|
13
|
+
},
|
|
14
|
+
"homepage": "https://github.com/382quaii/dsh-Layers-Hippocampus#readme",
|
|
15
|
+
"bugs": {
|
|
16
|
+
"url": "https://github.com/382quaii/dsh-Layers-Hippocampus/issues"
|
|
17
|
+
},
|
|
18
|
+
"keywords": [
|
|
19
|
+
"deepseek",
|
|
20
|
+
"harness",
|
|
21
|
+
"dsh",
|
|
22
|
+
"dsh-plugin",
|
|
23
|
+
"memory",
|
|
24
|
+
"long-term-memory",
|
|
25
|
+
"knowledge-graph",
|
|
26
|
+
"ai-agent"
|
|
27
|
+
],
|
|
28
|
+
"engines": {
|
|
29
|
+
"node": ">=22"
|
|
30
|
+
},
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"registry": "https://registry.npmjs.org/",
|
|
33
|
+
"access": "public"
|
|
34
|
+
},
|
|
35
|
+
"exports": {
|
|
36
|
+
".": "./index.js",
|
|
37
|
+
"./package.json": "./package.json",
|
|
38
|
+
"./client": "./ui/client.js",
|
|
39
|
+
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
40
|
+
"./locale/*.json": "./locale/*.json",
|
|
41
|
+
"./icon": "./icon.svg",
|
|
42
|
+
"./src/*": "./src/*"
|
|
43
|
+
},
|
|
44
|
+
"files": [
|
|
45
|
+
"index.js",
|
|
46
|
+
"src/**/*.js",
|
|
47
|
+
"ui/**/*.js",
|
|
48
|
+
"cordis.patch.yml",
|
|
49
|
+
"locale/*.json",
|
|
50
|
+
"icon.svg",
|
|
51
|
+
"screenshots.json",
|
|
52
|
+
"assets/*.png",
|
|
53
|
+
"README.md",
|
|
54
|
+
"LICENSE",
|
|
55
|
+
"CHANGELOG.md",
|
|
56
|
+
"docs/ARCHITECTURE.zh.md",
|
|
57
|
+
"docs/PUBLISHING.md",
|
|
58
|
+
"market/**/*.yml",
|
|
59
|
+
"market/*.md"
|
|
60
|
+
],
|
|
61
|
+
"scripts": {
|
|
62
|
+
"test": "node test/run.mjs",
|
|
63
|
+
"bench": "node scripts/bench-protocol.mjs",
|
|
64
|
+
"repair-handoff": "node scripts/repair-handoff.mjs",
|
|
65
|
+
"check": "node --check index.js && node --check ui/client.js && node test/run.mjs"
|
|
66
|
+
},
|
|
67
|
+
"dsh": {
|
|
68
|
+
"bundle": {
|
|
69
|
+
"patch": "./cordis.patch.yml"
|
|
70
|
+
},
|
|
71
|
+
"client": {
|
|
72
|
+
"platform": "web"
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
package/src/config.js
CHANGED
|
@@ -244,6 +244,10 @@ export const DEFAULT_CONFIG = Object.freeze({
|
|
|
244
244
|
// permission rules here, only routing and context-window bookkeeping.
|
|
245
245
|
autoSpaceFollow: false,
|
|
246
246
|
autoRolloverEnabled: true,
|
|
247
|
+
// v1.7.4: a handoff marker is a claim about pressure. Below this ratio the claim is
|
|
248
|
+
// no longer true, so the marker is consumed and the [交接标记] block stops being
|
|
249
|
+
// injected (otherwise the model reads "context almost full" at 10% usage forever).
|
|
250
|
+
handoffClearRatio: 0.5,
|
|
247
251
|
autoRolloverThreshold: 0.85,
|
|
248
252
|
// v1.6.3: USER OVERRIDE ONLY. The model's real context window comes from the host
|
|
249
253
|
// adapter (`llm.resolveModelInfo().context.contextWindow`); this value is used only
|
|
@@ -262,6 +266,11 @@ export const DEFAULT_CONFIG = Object.freeze({
|
|
|
262
266
|
tailChars: 2_000,
|
|
263
267
|
maxNodesPerRequest: 4,
|
|
264
268
|
},
|
|
269
|
+
// v1.7.3 (module 1): physical pruning of the conversation surface. This is the
|
|
270
|
+
// replacement for "hope the host compacts": at `threshold` of the REAL window the
|
|
271
|
+
// oldest verbose turns are rewritten into `[System: …已折叠。原文 ID: ev_x]` pointers.
|
|
272
|
+
// The log itself is untouched — only the surface the model reads.
|
|
273
|
+
smartPrune: { enabled: true, threshold: 0.85, keepRecentTurns: 3, minChars: 1200, maxNodes: 8 },
|
|
265
274
|
// Security (v1.5.1): moving memories across spaces is NEVER an autonomous
|
|
266
275
|
// decision. While true, the engine refuses a model-initiated transfer unless
|
|
267
276
|
// the tool call carries `user_approved: true`; the UI route is the human
|
|
@@ -898,6 +907,11 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
|
|
|
898
907
|
contextIn.autoSpaceFollow === undefined ? defaults.context.autoSpaceFollow : contextIn.autoSpaceFollow,
|
|
899
908
|
'context.autoSpaceFollow',
|
|
900
909
|
);
|
|
910
|
+
const contextHandoffClearRatio = requireNumberInRange(
|
|
911
|
+
contextIn.handoffClearRatio === undefined ? defaults.context.handoffClearRatio : contextIn.handoffClearRatio,
|
|
912
|
+
'context.handoffClearRatio',
|
|
913
|
+
{ min: 0.1, max: 0.9 },
|
|
914
|
+
);
|
|
901
915
|
const contextAutoRolloverEnabled = requireBoolean(
|
|
902
916
|
contextIn.autoRolloverEnabled === undefined ? defaults.context.autoRolloverEnabled : contextIn.autoRolloverEnabled,
|
|
903
917
|
'context.autoRolloverEnabled',
|
|
@@ -917,6 +931,32 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
|
|
|
917
931
|
);
|
|
918
932
|
// v1.6.3 Live Compact tunables. `thresholdChars` is compared against the total
|
|
919
933
|
// characters of ONE tool result's text blocks.
|
|
934
|
+
// v1.7.3 physical pruning (module 1).
|
|
935
|
+
const smartPruneIn = contextIn.smartPrune ?? {};
|
|
936
|
+
const smartPruneEnabled = requireBoolean(
|
|
937
|
+
smartPruneIn.enabled === undefined ? defaults.context.smartPrune.enabled : smartPruneIn.enabled,
|
|
938
|
+
'context.smartPrune.enabled',
|
|
939
|
+
);
|
|
940
|
+
const smartPruneThreshold = requireNumberInRange(
|
|
941
|
+
smartPruneIn.threshold === undefined ? defaults.context.smartPrune.threshold : smartPruneIn.threshold,
|
|
942
|
+
'context.smartPrune.threshold',
|
|
943
|
+
{ min: 0.5, max: 0.99 },
|
|
944
|
+
);
|
|
945
|
+
const smartPruneKeepRecentTurns = requireInteger(
|
|
946
|
+
smartPruneIn.keepRecentTurns === undefined ? defaults.context.smartPrune.keepRecentTurns : smartPruneIn.keepRecentTurns,
|
|
947
|
+
'context.smartPrune.keepRecentTurns',
|
|
948
|
+
{ min: 0, max: 50 },
|
|
949
|
+
);
|
|
950
|
+
const smartPruneMinChars = requireInteger(
|
|
951
|
+
smartPruneIn.minChars === undefined ? defaults.context.smartPrune.minChars : smartPruneIn.minChars,
|
|
952
|
+
'context.smartPrune.minChars',
|
|
953
|
+
{ min: 200, max: 1_000_000 },
|
|
954
|
+
);
|
|
955
|
+
const smartPruneMaxNodes = requireInteger(
|
|
956
|
+
smartPruneIn.maxNodes === undefined ? defaults.context.smartPrune.maxNodes : smartPruneIn.maxNodes,
|
|
957
|
+
'context.smartPrune.maxNodes',
|
|
958
|
+
{ min: 1, max: 64 },
|
|
959
|
+
);
|
|
920
960
|
const liveCompactIn = contextIn.liveCompact ?? {};
|
|
921
961
|
const liveCompactEnabled = requireBoolean(
|
|
922
962
|
liveCompactIn.enabled === undefined ? defaults.context.liveCompact.enabled : liveCompactIn.enabled,
|
|
@@ -1522,6 +1562,7 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
|
|
|
1522
1562
|
// v1.5.0 routing knobs below; v1.5.3 removed minInjectConfidence entirely.
|
|
1523
1563
|
autoSpaceFollow: contextAutoSpaceFollow,
|
|
1524
1564
|
autoRolloverEnabled: contextAutoRolloverEnabled,
|
|
1565
|
+
handoffClearRatio: contextHandoffClearRatio,
|
|
1525
1566
|
autoRolloverThreshold: contextAutoRolloverThreshold,
|
|
1526
1567
|
nativeTokenLimit: contextNativeTokenLimit,
|
|
1527
1568
|
liveCompact: {
|
|
@@ -1531,6 +1572,13 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
|
|
|
1531
1572
|
tailChars: liveCompactTailChars,
|
|
1532
1573
|
maxNodesPerRequest: liveCompactMaxNodesPerRequest,
|
|
1533
1574
|
},
|
|
1575
|
+
smartPrune: {
|
|
1576
|
+
enabled: smartPruneEnabled,
|
|
1577
|
+
threshold: smartPruneThreshold,
|
|
1578
|
+
keepRecentTurns: smartPruneKeepRecentTurns,
|
|
1579
|
+
minChars: smartPruneMinChars,
|
|
1580
|
+
maxNodes: smartPruneMaxNodes,
|
|
1581
|
+
},
|
|
1534
1582
|
requireExplicitConsentForTransfer: contextRequireExplicitConsentForTransfer,
|
|
1535
1583
|
},
|
|
1536
1584
|
temp: { ttlDays: tempTtlDays, promotionWindowDays: tempPromotionWindowDays },
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* v1.7.3 (module 1): PHYSICAL context pruning with pointers.
|
|
3
|
+
*
|
|
4
|
+
* The host's `compaction-basic` summarises old history with a MODEL CALL: it costs
|
|
5
|
+
* tokens, it is slow, and its output is a lossy paraphrase that cannot be audited.
|
|
6
|
+
* This module folds instead of summarising:
|
|
7
|
+
*
|
|
8
|
+
* old turn (8 000 chars of tool output)
|
|
9
|
+
* → `[System: 此段包含 N 轮关于 [tag] 的细节,已折叠。原文 ID: ev_xxx。若需要,请使用 recall 工具检索。]`
|
|
10
|
+
*
|
|
11
|
+
* The original bytes are untouched in the raw log and still reachable through
|
|
12
|
+
* `deep_raw` / `recall`, so folding is REVERSIBLE in a way a summary is not. Nothing
|
|
13
|
+
* here sends a request to a provider: the only thing it spends is CPU.
|
|
14
|
+
*
|
|
15
|
+
* Invariants (a violation corrupts the conversation, so they are enforced here):
|
|
16
|
+
* - a node is replaced ON THE SURFACE ONLY: the log keeps the original event and a
|
|
17
|
+
* `compaction/prune` record explains what was shadowed and why;
|
|
18
|
+
* - `tool/call` nodes are never rewritten, so every surviving `tool/result` still
|
|
19
|
+
* has its call (and a folded result keeps its call id in the pointer context);
|
|
20
|
+
* - the most recent `keepRecentTurns` user turns are untouchable — the model must
|
|
21
|
+
* always see what was just asked;
|
|
22
|
+
* - the pointer is never empty: an empty replacement would look like the turn was
|
|
23
|
+
* deleted, which is exactly the failure mode this is meant to avoid.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
export const FOLD_MARKER = '[System: 此段包含';
|
|
27
|
+
/** Below this, folding a node saves nothing worth the risk. */
|
|
28
|
+
export const FOLD_MIN_CHARS = 1200;
|
|
29
|
+
/** Hard ceiling on how much one request may fold, so pruning cannot snowball. */
|
|
30
|
+
export const FOLD_MAX_NODES = 8;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The pointer text. Kept deliberately short (≈120 chars): the whole point is that it
|
|
34
|
+
* is much smaller than what it replaces.
|
|
35
|
+
*
|
|
36
|
+
* @param {{turns?: number, tags?: string[], eventId?: string|null, turnId?: string|null, tool?: string|null}} input
|
|
37
|
+
*/
|
|
38
|
+
export function foldPointer({ turns = 1, tags = [], eventId = null, turnId = null, tool = null } = {}) {
|
|
39
|
+
const label = (Array.isArray(tags) ? tags : []).filter((tag) => typeof tag === 'string' && tag.length > 0).slice(0, 2);
|
|
40
|
+
const topic = label.length > 0 ? label.map((tag) => `[${tag}]`).join('') : '[未标注]';
|
|
41
|
+
const turnWord = Number(turns) > 1 ? `${Number(turns)} 轮` : '1 轮';
|
|
42
|
+
const ref = eventId ? `ev_${String(eventId).replace(/^ev_/, '')}` : turnId ? `raw:${turnId}` : 'unknown';
|
|
43
|
+
const toolHint = tool ? `(${tool} 的工具输出)` : '';
|
|
44
|
+
return `${FOLD_MARKER}${turnWord}关于 ${topic} 的细节${toolHint},已折叠。原文 ID: ${ref}。若需要,请使用 recall 工具检索。]`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function textOfBlocks(content) {
|
|
48
|
+
const blocks = Array.isArray(content) ? content : [];
|
|
49
|
+
let total = 0;
|
|
50
|
+
for (const block of blocks) {
|
|
51
|
+
if (block && typeof block.text === 'string') total += block.text.length;
|
|
52
|
+
}
|
|
53
|
+
return total;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function messageOf(session, seq) {
|
|
57
|
+
try {
|
|
58
|
+
const event = typeof session?.eventAt === 'function' ? session.eventAt(seq) : null;
|
|
59
|
+
if (!event) return null;
|
|
60
|
+
const message = typeof session.deriveEventMessage === 'function' ? session.deriveEventMessage(event) : null;
|
|
61
|
+
return { event, message };
|
|
62
|
+
} catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Which surface nodes are eligible to be folded.
|
|
69
|
+
*
|
|
70
|
+
* Separated from the mutation so the decision is testable without a host session and
|
|
71
|
+
* so the caller can log what WOULD happen at a dry run.
|
|
72
|
+
*
|
|
73
|
+
* @param {object} session host Session (`surface.nodes`, `eventAt`, `deriveEventMessage`)
|
|
74
|
+
* @param {{keepRecentTurns?: number, minChars?: number, maxNodes?: number, describe?: Function}} options
|
|
75
|
+
* @returns {{candidates: object[], protectedFrom: number|null, scanned: number}}
|
|
76
|
+
*/
|
|
77
|
+
export function planSmartPrune(session, options = {}) {
|
|
78
|
+
const keepRecentTurns = Math.max(0, Number(options.keepRecentTurns ?? 3));
|
|
79
|
+
const minChars = Math.max(0, Number(options.minChars ?? FOLD_MIN_CHARS));
|
|
80
|
+
const maxNodes = Math.max(1, Number(options.maxNodes ?? FOLD_MAX_NODES));
|
|
81
|
+
const nodes = Array.isArray(session?.surface?.nodes) ? session.surface.nodes : [];
|
|
82
|
+
|
|
83
|
+
// The keep-window is measured in USER turns, not nodes: one turn may be a dozen
|
|
84
|
+
// tool results, and protecting only N nodes would fold the question itself.
|
|
85
|
+
let protectedFrom = null;
|
|
86
|
+
if (keepRecentTurns > 0) {
|
|
87
|
+
let seen = 0;
|
|
88
|
+
for (let index = nodes.length - 1; index >= 0; index -= 1) {
|
|
89
|
+
const node = messageOf(session, nodes[index]);
|
|
90
|
+
if (!node) continue;
|
|
91
|
+
if (node.event?.type === 'user/message') {
|
|
92
|
+
seen += 1;
|
|
93
|
+
if (seen >= keepRecentTurns) {
|
|
94
|
+
protectedFrom = index;
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const candidates = [];
|
|
102
|
+
let scanned = 0;
|
|
103
|
+
for (let index = 0; index < nodes.length; index += 1) {
|
|
104
|
+
if (protectedFrom !== null && index >= protectedFrom) break;
|
|
105
|
+
const seq = nodes[index];
|
|
106
|
+
const found = messageOf(session, seq);
|
|
107
|
+
if (!found) continue;
|
|
108
|
+
const { event, message } = found;
|
|
109
|
+
scanned += 1;
|
|
110
|
+
// A tool/call has no text and its pair must stay intact.
|
|
111
|
+
if (event?.type === 'tool/call') continue;
|
|
112
|
+
if (!message || !Array.isArray(message.content)) continue;
|
|
113
|
+
const chars = textOfBlocks(message.content);
|
|
114
|
+
if (chars < minChars) continue;
|
|
115
|
+
const already = message.content.some(
|
|
116
|
+
(block) => block && typeof block.text === 'string' && block.text.startsWith(FOLD_MARKER),
|
|
117
|
+
);
|
|
118
|
+
if (already) continue;
|
|
119
|
+
const described = typeof options.describe === 'function' ? options.describe({ seq, event, message, chars }) : null;
|
|
120
|
+
candidates.push({
|
|
121
|
+
seq,
|
|
122
|
+
type: event?.type ?? 'user/message',
|
|
123
|
+
chars,
|
|
124
|
+
eventId: described?.eventId ?? null,
|
|
125
|
+
turnId: described?.turnId ?? null,
|
|
126
|
+
tags: Array.isArray(described?.tags) ? described.tags : [],
|
|
127
|
+
tool: typeof described?.tool === 'string' ? described.tool : event?.data?.name ?? null,
|
|
128
|
+
message,
|
|
129
|
+
});
|
|
130
|
+
if (candidates.length >= maxNodes) break;
|
|
131
|
+
}
|
|
132
|
+
// Largest first: folding big nodes is where the tokens are, and folding many small
|
|
133
|
+
// ones costs more surface churn for the same saving.
|
|
134
|
+
candidates.sort((left, right) => right.chars - left.chars);
|
|
135
|
+
return { candidates, protectedFrom, scanned };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Apply the plan. One node at a time, each through the host's surface-replace
|
|
140
|
+
* protocol; a failure on one node never aborts the rest (pruning is best-effort,
|
|
141
|
+
* whereas a half-written surface would be corruption).
|
|
142
|
+
*
|
|
143
|
+
* @returns {{folded:number, charsBefore:number, charsAfter:number, pointers:object[], failed:string|null, scanned:number}}
|
|
144
|
+
*/
|
|
145
|
+
export function smartPruneSession(session, options = {}) {
|
|
146
|
+
const report = { folded: 0, charsBefore: 0, charsAfter: 0, pointers: [], failed: null, scanned: 0 };
|
|
147
|
+
if (!session || typeof session.append !== 'function') return report;
|
|
148
|
+
let plan;
|
|
149
|
+
try {
|
|
150
|
+
plan = planSmartPrune(session, options);
|
|
151
|
+
} catch (error) {
|
|
152
|
+
report.failed = error?.message ?? String(error);
|
|
153
|
+
return report;
|
|
154
|
+
}
|
|
155
|
+
report.scanned = plan.scanned;
|
|
156
|
+
const tagCount = Math.max(1, Number(options.turnsPerPointer ?? 1));
|
|
157
|
+
for (const candidate of plan.candidates) {
|
|
158
|
+
const pointer = foldPointer({
|
|
159
|
+
turns: tagCount,
|
|
160
|
+
tags: candidate.tags,
|
|
161
|
+
eventId: candidate.eventId,
|
|
162
|
+
turnId: candidate.turnId,
|
|
163
|
+
tool: candidate.tool,
|
|
164
|
+
});
|
|
165
|
+
const content = [{ type: 'text', text: pointer }];
|
|
166
|
+
try {
|
|
167
|
+
session.append('compaction/prune', {
|
|
168
|
+
shadowedRange: { start: candidate.seq, end: candidate.seq },
|
|
169
|
+
shadowedSeqs: [candidate.seq],
|
|
170
|
+
shadowedTokenCount: Math.ceil(candidate.chars / 4),
|
|
171
|
+
reason: 'hippocampus:smart-context-prune',
|
|
172
|
+
pointer,
|
|
173
|
+
});
|
|
174
|
+
session.append(
|
|
175
|
+
candidate.type,
|
|
176
|
+
{ ...(candidate.message?.data ?? null), ...(options.eventData?.(candidate) ?? {}), message: { ...candidate.message, content } },
|
|
177
|
+
{ surfaceOp: { op: 'replace', startSeq: candidate.seq, endSeq: candidate.seq }, sourceEventSeqs: [candidate.seq] },
|
|
178
|
+
);
|
|
179
|
+
report.folded += 1;
|
|
180
|
+
report.charsBefore += candidate.chars;
|
|
181
|
+
report.charsAfter += pointer.length;
|
|
182
|
+
report.pointers.push({ seq: candidate.seq, eventId: candidate.eventId, chars: candidate.chars, pointer });
|
|
183
|
+
} catch (error) {
|
|
184
|
+
report.failed = error?.message ?? String(error);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return report;
|
|
188
|
+
}
|