dsh-layers-hippocampus 1.9.4 → 1.9.8
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 +90 -0
- package/README.md +2 -2
- package/index.js +218 -67
- package/package.json +1 -1
- package/src/config.js +19 -1
- package/src/context/smartPrune.js +5 -5
- package/src/handoff/coordinator.js +417 -0
- package/src/memory.js +51 -0
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,96 @@ All notable changes to `dsh-layers-hippocampus` are documented here.
|
|
|
4
4
|
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
5
5
|
and the project adheres to [Semantic Versioning](https://semver.org/).
|
|
6
6
|
|
|
7
|
+
## [1.9.8] — 2026-12-01
|
|
8
|
+
|
|
9
|
+
**交接六路径收拢为一个协调器:一次事件只蒸馏一次。**
|
|
10
|
+
|
|
11
|
+
改造前:`recordToolCall`、`_maybeAutoHandoff`、once-fold、硬停、fail-fast、`/memory handoff`
|
|
12
|
+
六条路径各自直接调用 `checkHandoff()`,只有 `_maybeAutoHandoff` 带并发保护。同一 tick 内两次
|
|
13
|
+
触发 = 两次 `_distillHandoffTail`、两次 `clearHandoff()` + 原子写、最多两次阻塞蒸馏 ——
|
|
14
|
+
2026-12-01 那次「没崩溃却不回话」在结构上由它解释。
|
|
15
|
+
|
|
16
|
+
- **Added — `src/handoff/coordinator.js`**:`request()`(可 await)与 `offer()`(工具边界,
|
|
17
|
+
busy 即丢)。准入顺序 R1 单飞 → R2 时间防抖(默认 `0`,关闭)→ R3 阈值 → R4 再交接增量 →
|
|
18
|
+
R5 压力带去重。默认 `maxPending: 0`(纯合并,不再排第二次蒸馏);`maxPending: 1` 可选一深
|
|
19
|
+
队列,latest-wins。
|
|
20
|
+
- **Added — 按路径预算**:请求路径 `1500ms`、fail-fast `800ms`、命令 `10000ms`。超时后调用方
|
|
21
|
+
拿到 `budget-exceeded` 并放行请求,蒸馏继续在后台跑完,marker 留给下一轮。这是「不回话」
|
|
22
|
+
的直接解药:**provider 调用不再等一次蒸馏**。
|
|
23
|
+
- **Changed — `force` 语义收窄**:`'none' | 'early' | 'manual'`。`'early'` 只绕过阈值,
|
|
24
|
+
**不再**绕过再交接增量(活的 marker 不会被强制调用重新蒸馏);只有人类敲的
|
|
25
|
+
`/memory handoff` 用 `'manual'`。布尔 `force: true` 仍被接受,但降级为 `'early'`。
|
|
26
|
+
- **Changed — 引擎侧 `_maybeAutoHandoff` 委托**:宿主装配了协调器就交给它;`_handoffInFlight`
|
|
27
|
+
只留给没有宿主的独立嵌入者(引擎测试夹具)。
|
|
28
|
+
- **Tests — `test/v198.coordinator.test.js`(15 例)**:六触发一蒸馏、`offer()` 丢弃、
|
|
29
|
+
预算早退且后台继续、阈值/增量/`manual` 三档语义、legacy 布尔降级、时间防抖、
|
|
30
|
+
压力带去重、失败即值不抛、watchdog 释放锁、脏 policy 回退默认、`maxPending` 队列。
|
|
31
|
+
- **Tests — `test/v198.source.scan.test.js`(5 例)**:裸 `checkHandoff` 只允许引擎兜底与
|
|
32
|
+
`index.js` 装配各 1 处;协调器不得 import 引擎或 Node 内置模块;`index.js` 不得出现布尔
|
|
33
|
+
force;`_handoffInFlight` 只能留在引擎;每个调用点必须带 `source` 标签。
|
|
34
|
+
|
|
35
|
+
## [1.9.7] — 2026-12-01
|
|
36
|
+
|
|
37
|
+
**85% 以上「每个请求都强制交接一次」——这看起来不像交接,像 agent 不回话了。**
|
|
38
|
+
|
|
39
|
+
- **Fixed — 强制交接没有防抖(`index.js`)**。`force: true`(1.9.4 引入)故意绕过再交接增量门,
|
|
40
|
+
而触发条件 `!foldGate.allowed` 在 85% 以上**对每个请求都为真**。两者相乘的结果是:
|
|
41
|
+
越过 85% 之后,**每一轮**都要同步做一次交接蒸馏(最多 `HANDOFF_TIMEOUT_MS` = 5 秒的阻塞 LLM 调用)。
|
|
42
|
+
用户看到的现象不是「发生了一次交接」,而是「它不回了」。
|
|
43
|
+
现在强制分支复用未强制分支同一条纪律:**再交接需要压力再涨 5 个百分点**
|
|
44
|
+
(`FORCED_HANDOFF_DELTA = 0.05`,记在 `runtime.lastForcedRatio`)。
|
|
45
|
+
- **Tests — 3 个新用例(`test/v197.forced.debounce.test.js`)**:
|
|
46
|
+
86% 连续两次请求只蒸馏一次;压力再涨 3 个百分点仍不重复、涨 6 个百分点才再交接;
|
|
47
|
+
50% 时强制分支完全不走、也不消耗增量预算。
|
|
48
|
+
|
|
49
|
+
> **证据边界**:这条修复来自读代码确认的真实缺陷(每请求一次阻塞蒸馏),
|
|
50
|
+
> 但**不能证明**它就是 2026-12-01「进程没崩却不回话」的原因——
|
|
51
|
+
> 那次没有崩溃转储,也没有 agent-loop 级别的日志。当时代谢占用在 65% 附近,
|
|
52
|
+
> 尚未越过 85% 的触发线。把它当「已确证缺陷的修复」,不当「事故定论」。
|
|
53
|
+
## [1.9.6] — 2026-12-01
|
|
54
|
+
|
|
55
|
+
**折叠指针被当成了「人说的话」,这才是「反复缩小」与「交接摘要只剩三行通知」的共同根因。**
|
|
56
|
+
|
|
57
|
+
现场证据(`state/handoff.json`,2026-12-01 12:48):`tailTurns` 三条全是
|
|
58
|
+
`[System: 此段包含1 轮…已折叠。原文 ID: raw:turn_14_user]`,没有一句真实对话。
|
|
59
|
+
|
|
60
|
+
- **Fixed — 指针挤占保护窗口(`src/context/smartPrune.js`)**。折叠产物是以 `user/message` 类型
|
|
61
|
+
写回表面的,而 `planSmartPrune` 用「从后往前数 N 个 user/message」定位保护窗口——
|
|
62
|
+
于是「最近 3 轮」变成了**三个指针**,真正的最近消息落到保护窗口**之前**,下一轮就被折掉,
|
|
63
|
+
折完又多一个指针……**自我强化**。这正是「反复缩小」停不下来的机制。
|
|
64
|
+
新增 `isFoldPointer()`:数保护窗口与挑选候选时都跳过指针。
|
|
65
|
+
- **Fixed — 交接摘要被指针污染(`src/memory.js`)**。`_recordRecentTurn` 无条件记录 surface 文本,
|
|
66
|
+
折叠后记下的就是通知本身。现在以 `FOLD_MARKER` 开头的文本不入 tail,
|
|
67
|
+
所以交接标记带的是「最后真正说了什么」,而不是三条「此段已折叠」。
|
|
68
|
+
- **Tests — 6 个新用例(`test/v196.pointer.tail.test.js`)**:尾部三个指针不再遮住真实最近三轮、
|
|
69
|
+
指针自身不会被再折、`_recordRecentTurn` 拒绝指针、空白仍被丢弃、
|
|
70
|
+
**同样的表面两次规划结果一致**(不漂移=不失控)、只有指针在尾部时最新的真实轮次也不会被折。
|
|
71
|
+
|
|
72
|
+
> 说明:2026-12-01 那次 DSH 进程退出的**直接原因没有证据**——系统里没有崩溃转储,
|
|
73
|
+
> Windows 应用日志只有 SideBySide 配置警告,Electron 侧也没有 error 记录。
|
|
74
|
+
> 上面修的是在事故现场**确证存在**的两个 bug(指针挤占保护窗口是自我强化的折叠循环),
|
|
75
|
+
> 不宣称它们就是进程退出的原因。
|
|
76
|
+
## [1.9.5] — 2026-11-30
|
|
77
|
+
|
|
78
|
+
**恢复「到点真的缩小上下文」,但只允许缩一次。**
|
|
79
|
+
用户的原话是:以前是**直接缩小上下文**的,甚至反复缩小。查证结果:v1.6.4 及更早每轮都委托宿主
|
|
80
|
+
`toolResultPruner`,被 v1.6.5(`66a3b93`)关掉,代码里至今留着当时的原话记录——
|
|
81
|
+
`"context drops from 10% to 7% over and over"`。而 1.9.4 又把折叠推迟到 85% 并禁止它,
|
|
82
|
+
于是 60%~85% 之间什么都不缩。这两个极端都不要。
|
|
83
|
+
|
|
84
|
+
- **Added — `context.smartPrune.onceFoldAt`(默认 `0.65`,`0` 关闭)**。一个会话**只折叠一次**:
|
|
85
|
+
占用到 65% 时执行一次 `smartPrune`,随后**立即强制交接**,把变小的那面交出去。
|
|
86
|
+
之后本会话不再折叠,所以「反复缩小」不会重演。
|
|
87
|
+
- **Added — 折叠后交接**。`checkHandoff({force:true})`,结果记在 `runtime.lastOnceFoldHandoff`
|
|
88
|
+
(`ratio` / `onceFoldAt` / `folded` / `handoffActive` / `degraded`)。
|
|
89
|
+
- **Fixed — 守卫用错了测量**。1.9.4 的折叠门在**探针刷新之前**取 `hostProbes`,进程首个请求比率是 0,
|
|
90
|
+
于是硬停与一次性折叠都可能根本不触发。现在门与一次性判定都基于**本请求刷新后的 `state`**。
|
|
91
|
+
- **Fixed — 被拒绝的折叠不得消耗一次性机会**。85% 硬停时折叠被拒,但一次性额度若在那一刻被「消费」,
|
|
92
|
+
会话就永久失去它唯一一次变小的机会。现在额度只在 `foldGate.allowed` 为真时才会花掉。
|
|
93
|
+
- **Tests — 7 个新用例(`test/v195.oncefold.test.js`)**:`onceFoldAt` 默认值与 fail-fast;
|
|
94
|
+
66% 折叠一次并立刻交接;同一会话第二次/第三次请求**不再改写表面**;
|
|
95
|
+
50% 以下既不折叠也不交接;`onceFoldAt:0` 恢复 1.9.4 行为;
|
|
96
|
+
86% 硬停时折叠被拒;**硬停不消耗一次性额度**(这条是回归测试,实现里真的漏过一次)。
|
|
7
97
|
## [1.9.4] — 2026-11-30
|
|
8
98
|
|
|
9
99
|
**修「卸载外部压缩插件后 Handoff 再也不触发」,并实装短块聚合与极简状态。**
|
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
| | |
|
|
9
9
|
| --- | --- |
|
|
10
|
-
| 版本 | **1.9.
|
|
10
|
+
| 版本 | **1.9.7** |
|
|
11
11
|
| 包名 | `dsh-layers-hippocampus` |
|
|
12
12
|
| 仓库 | <https://github.com/382quaii/dsh-Layers-Hippocampus> |
|
|
13
13
|
| 许可证 | MIT |
|
|
@@ -296,7 +296,7 @@ clear_dropbox('D:/mem/sessions/abc');
|
|
|
296
296
|
pnpm add dsh-layers-hippocampus
|
|
297
297
|
|
|
298
298
|
# 或从 GitHub 指定 tag
|
|
299
|
-
pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.9.
|
|
299
|
+
pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.9.7"
|
|
300
300
|
```
|
|
301
301
|
|
|
302
302
|
### 2. 挂到 profile
|
package/index.js
CHANGED
|
@@ -46,6 +46,9 @@ 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
48
|
import { FOLD_HARD_STOP_RATIO, foldBlocked } from './src/context/windowGuard.js';
|
|
49
|
+
import { createHandoffCoordinator, FORCE, HANDOFF_STATUS } from './src/handoff/coordinator.js';
|
|
50
|
+
// v1.9.7: how much pressure must grow before the stop line hands off AGAIN.
|
|
51
|
+
const FORCED_HANDOFF_DELTA = 0.05;
|
|
49
52
|
|
|
50
53
|
// v1.7.4: how long a host-measured pressure reading may be reused while deciding
|
|
51
54
|
// whether a handoff marker still tells the truth. Requests are seconds apart, so five
|
|
@@ -80,7 +83,7 @@ export { resolveConfig, DEFAULT_CONFIG };
|
|
|
80
83
|
* of letting a raw 404 reach the user.
|
|
81
84
|
*/
|
|
82
85
|
export const CAPABILITIES = Object.freeze({
|
|
83
|
-
version: '1.9.
|
|
86
|
+
version: '1.9.8',
|
|
84
87
|
spaces: true,
|
|
85
88
|
memories: true,
|
|
86
89
|
transferConsent: true,
|
|
@@ -440,6 +443,46 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
440
443
|
};
|
|
441
444
|
runtimeRef = runtime;
|
|
442
445
|
|
|
446
|
+
/**
|
|
447
|
+
* v1.9.8 — the ONE handoff entry point (see src/handoff/coordinator.js).
|
|
448
|
+
*
|
|
449
|
+
* Six paths used to call `memory.checkHandoff()` directly and only one of them had a
|
|
450
|
+
* guard, so two distillations could run for one event. Every path below now goes
|
|
451
|
+
* through `runtime.handoff`; the engine keeps only the execution.
|
|
452
|
+
*
|
|
453
|
+
* `probe`/`run` read `runtime.memory` at CALL time, so the bootstrap retry that
|
|
454
|
+
* rebuilds the facade does not need a new coordinator.
|
|
455
|
+
*/
|
|
456
|
+
runtime.handoff = createHandoffCoordinator({
|
|
457
|
+
clock: { now: () => (Number.isFinite(runtime.memory?.clock?.now?.()) ? runtime.memory.clock.now() : Date.now()) },
|
|
458
|
+
logger: ctx?.logger ?? null,
|
|
459
|
+
// Live policy: a config patch must take effect without a restart. Unknown or
|
|
460
|
+
// non-numeric keys are filtered by the coordinator, so an absent section is fine.
|
|
461
|
+
policy: () => runtime.config?.handoff ?? {},
|
|
462
|
+
probe: () => {
|
|
463
|
+
const mem = runtime.memory;
|
|
464
|
+
if (!mem) return null;
|
|
465
|
+
const usage = mem.sessionUsage();
|
|
466
|
+
const native = mem.context.nativeState({ sessionTokens: usage.tokens });
|
|
467
|
+
return {
|
|
468
|
+
sessionId: usage.sessionId ?? null,
|
|
469
|
+
projectedRatio: native.projectedRatio,
|
|
470
|
+
rolloverDue: native.rolloverDue === true,
|
|
471
|
+
hardExceeded: native.hardExceeded === true,
|
|
472
|
+
marker: mem.handoffState(),
|
|
473
|
+
};
|
|
474
|
+
},
|
|
475
|
+
// The ONLY bare checkHandoff call outside the engine. `'early'`/`'manual'` were
|
|
476
|
+
// already validated against the re-handoff delta by the coordinator, so the engine
|
|
477
|
+
// boolean (which bypasses every gate) is only set for those two verbs.
|
|
478
|
+
run: ({ force }) =>
|
|
479
|
+
runtime.memory.checkHandoff({
|
|
480
|
+
now: runtime.memory.clock.now(),
|
|
481
|
+
force: force === FORCE.EARLY || force === FORCE.MANUAL,
|
|
482
|
+
}),
|
|
483
|
+
});
|
|
484
|
+
memory.setHandoffCoordinator?.(runtime.handoff);
|
|
485
|
+
|
|
443
486
|
/** Rebind the rings to the current dataDir / persistence flag (cosmetic state). */
|
|
444
487
|
runtime.resetActivityStores = () => {
|
|
445
488
|
activityStores.clear();
|
|
@@ -557,15 +600,13 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
557
600
|
// v1.5.0: every tool boundary is a natural pseudo-turn. Evaluate the rollover
|
|
558
601
|
// costlessly; only a due handoff performs I/O, and it must never surface as a
|
|
559
602
|
// tool failure (fire-and-forget).
|
|
603
|
+
//
|
|
604
|
+
// v1.9.8: the evaluation itself moved into the coordinator. `offer()` reads the
|
|
605
|
+
// live probe, applies every gate, and DROPS when a run is already in flight — so
|
|
606
|
+
// ten tool calls in one turn cost ten cheap decisions, not ten distillations.
|
|
560
607
|
if (runtime.phase === 'ready') {
|
|
561
608
|
try {
|
|
562
|
-
|
|
563
|
-
const native = memory.context.nativeState({ sessionTokens: usage.tokens });
|
|
564
|
-
if (native.rolloverDue || native.forceEvictionDue) {
|
|
565
|
-
memory
|
|
566
|
-
.checkHandoff()
|
|
567
|
-
.catch((error) => ctx?.logger?.warn?.(`hippocampus: handoff failed: ${asMemoryError(error).code}`));
|
|
568
|
-
}
|
|
609
|
+
runtime.handoff.offer({ source: 'tool-boundary' });
|
|
569
610
|
} catch {
|
|
570
611
|
/* accounting failure must never break a tool result */
|
|
571
612
|
}
|
|
@@ -1258,44 +1299,6 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1258
1299
|
// Our pointerization keeps head/tail plus a `deep_raw` recoverable pointer and
|
|
1259
1300
|
// only fires on a genuinely oversized single result, so a healthy conversation
|
|
1260
1301
|
// is never rewritten.
|
|
1261
|
-
// ---- 0. the folding stop line (v1.9.4) --------------------------------
|
|
1262
|
-
// Folding is fake relief: it shrinks the PROMPT without reducing what was said,
|
|
1263
|
-
// so a conversation that folds on every request can reset pressure just before
|
|
1264
|
-
// the handoff trigger and never hand over. At the hard stop folding is refused
|
|
1265
|
-
// outright and the handoff is forced — enforced BEFORE any folder runs, because
|
|
1266
|
-
// those folders are what would otherwise keep the ratio down.
|
|
1267
|
-
const prePressure = memory.context.nativeState({
|
|
1268
|
-
usedTokens: hostProbes.usedTokens ?? undefined,
|
|
1269
|
-
reservedTokens: hostProbes.reservedTokens ?? undefined,
|
|
1270
|
-
});
|
|
1271
|
-
const foldGate = foldBlocked({ projectedRatio: prePressure.projectedRatio });
|
|
1272
|
-
runtime.lastFoldGate = { ...foldGate, ratio: prePressure.projectedRatio, at: memory.clock.now() };
|
|
1273
|
-
if (!foldGate.allowed) {
|
|
1274
|
-
runtime.logger?.warn?.(
|
|
1275
|
-
`hippocampus: [Handoff Guard] 投影占用 ${(prePressure.projectedRatio * 100).toFixed(1)}% >= ` +
|
|
1276
|
-
`折叠硬阈值 ${(FOLD_HARD_STOP_RATIO * 100).toFixed(0)}%:本次请求禁止折叠,强制触发交接。`,
|
|
1277
|
-
);
|
|
1278
|
-
}
|
|
1279
|
-
|
|
1280
|
-
const liveConfig = runtime.config?.context?.liveCompact ?? {};
|
|
1281
|
-
if (liveConfig.enabled !== false && session && foldGate.allowed) {
|
|
1282
|
-
try {
|
|
1283
|
-
runtime.lastLiveCompact = {
|
|
1284
|
-
source: 'hippocampus',
|
|
1285
|
-
at: memory.clock.now(),
|
|
1286
|
-
...liveCompactSession(session, {
|
|
1287
|
-
thresholdChars: liveConfig.thresholdChars ?? LIVE_COMPACT_DEFAULTS.thresholdChars,
|
|
1288
|
-
headChars: liveConfig.headChars ?? LIVE_COMPACT_DEFAULTS.headChars,
|
|
1289
|
-
tailChars: liveConfig.tailChars ?? LIVE_COMPACT_DEFAULTS.tailChars,
|
|
1290
|
-
maxNodesPerRequest: liveConfig.maxNodesPerRequest ?? LIVE_COMPACT_DEFAULTS.maxNodesPerRequest,
|
|
1291
|
-
logger: runtime.logger,
|
|
1292
|
-
}),
|
|
1293
|
-
};
|
|
1294
|
-
} catch (error) {
|
|
1295
|
-
runtime.logger?.warn?.(`hippocampus: live compact failed: ${asMemoryError(error).code}`);
|
|
1296
|
-
}
|
|
1297
|
-
}
|
|
1298
|
-
|
|
1299
1302
|
// ---- 2. refresh the probes --------------------------------------------
|
|
1300
1303
|
const provider = requestConfig?.provider ?? null;
|
|
1301
1304
|
const model = requestConfig?.model ?? null;
|
|
@@ -1358,8 +1361,66 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1358
1361
|
usedTokens: hostProbes.usedTokens ?? undefined,
|
|
1359
1362
|
reservedTokens: hostProbes.reservedTokens ?? undefined,
|
|
1360
1363
|
});
|
|
1364
|
+
// ---- gate: decided from the REFRESHED measurement (v1.9.5) ------------
|
|
1365
|
+
// The gate used to be computed from `hostProbes` BEFORE this request refreshed
|
|
1366
|
+
// them, so on the first request of a process the ratio was 0 and neither the
|
|
1367
|
+
// hard stop nor the one-shot could ever fire. Every ratio below now comes from
|
|
1368
|
+
// `state`, which is a measurement of THIS request.
|
|
1369
|
+
// Folding is fake relief: it shrinks the PROMPT without reducing what was said,
|
|
1370
|
+
// so a conversation that folds on every request can reset pressure just before
|
|
1371
|
+
// the handoff trigger and never hand over. At the hard stop folding is refused
|
|
1372
|
+
// outright and the handoff is forced — enforced BEFORE any folder runs, because
|
|
1373
|
+
// those folders are what would otherwise keep the ratio down.
|
|
1374
|
+
const gateRatio = Number.isFinite(state.projectedRatio) ? state.projectedRatio : 0;
|
|
1375
|
+
// ---- 0.1 the ONE-SHOT fold (v1.9.5) ------------------------------------
|
|
1376
|
+
// Folding exists so a conversation can actually get smaller — but folding on
|
|
1377
|
+
// every request is the "context drops from 10% to 7% over and over" bug that
|
|
1378
|
+
// v1.6.5 removed. The compromise: a session folds EXACTLY ONCE, at
|
|
1379
|
+
// `context.smartPrune.onceFoldAt`, and is handed off immediately afterwards.
|
|
1380
|
+
// After that this session never folds again, so the surface stops churning and
|
|
1381
|
+
// the handoff — not the folder — is what carries the conversation forward.
|
|
1382
|
+
const onceFoldAt = Number(runtime.config?.context?.smartPrune?.onceFoldAt ?? 0);
|
|
1383
|
+
const sessionKey = session?.id ?? memory.sessionUsage()?.sessionId ?? null;
|
|
1384
|
+
if (!runtime.onceFoldedSessions) runtime.onceFoldedSessions = new Set();
|
|
1385
|
+
const onceFoldDue =
|
|
1386
|
+
onceFoldAt > 0 &&
|
|
1387
|
+
Number.isFinite(gateRatio) &&
|
|
1388
|
+
gateRatio >= onceFoldAt &&
|
|
1389
|
+
sessionKey !== null &&
|
|
1390
|
+
!runtime.onceFoldedSessions.has(sessionKey);
|
|
1391
|
+
// The one-shot allowance is consumed below; the folder itself still respects the
|
|
1392
|
+
// hard stop, so ">= 85%" can never fold even when the one-shot is available.
|
|
1393
|
+
const foldGate = foldBlocked({ projectedRatio: gateRatio });
|
|
1394
|
+
runtime.lastFoldGate = { ...foldGate, ratio: gateRatio, at: memory.clock.now() };
|
|
1395
|
+
if (!foldGate.allowed) {
|
|
1396
|
+
runtime.logger?.warn?.(
|
|
1397
|
+
`hippocampus: [Handoff Guard] 投影占用 ${(gateRatio * 100).toFixed(1)}% >= ` +
|
|
1398
|
+
`折叠硬阈值 ${(FOLD_HARD_STOP_RATIO * 100).toFixed(0)}%:本次请求禁止折叠,强制触发交接。`,
|
|
1399
|
+
);
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
const liveConfig = runtime.config?.context?.liveCompact ?? {};
|
|
1403
|
+
if (liveConfig.enabled !== false && session && foldGate.allowed) {
|
|
1404
|
+
try {
|
|
1405
|
+
runtime.lastLiveCompact = {
|
|
1406
|
+
source: 'hippocampus',
|
|
1407
|
+
at: memory.clock.now(),
|
|
1408
|
+
...liveCompactSession(session, {
|
|
1409
|
+
thresholdChars: liveConfig.thresholdChars ?? LIVE_COMPACT_DEFAULTS.thresholdChars,
|
|
1410
|
+
headChars: liveConfig.headChars ?? LIVE_COMPACT_DEFAULTS.headChars,
|
|
1411
|
+
tailChars: liveConfig.tailChars ?? LIVE_COMPACT_DEFAULTS.tailChars,
|
|
1412
|
+
maxNodesPerRequest: liveConfig.maxNodesPerRequest ?? LIVE_COMPACT_DEFAULTS.maxNodesPerRequest,
|
|
1413
|
+
logger: runtime.logger,
|
|
1414
|
+
}),
|
|
1415
|
+
};
|
|
1416
|
+
} catch (error) {
|
|
1417
|
+
runtime.logger?.warn?.(`hippocampus: live compact failed: ${asMemoryError(error).code}`);
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1361
1421
|
const pruneThreshold = Number.isFinite(pruneConfig.threshold) ? pruneConfig.threshold : 0.85;
|
|
1362
|
-
|
|
1422
|
+
const pruneAllowed = foldGate.allowed && (state.projectedRatio >= pruneThreshold || onceFoldDue);
|
|
1423
|
+
if (pruneConfig.enabled !== false && session && pruneAllowed) {
|
|
1363
1424
|
try {
|
|
1364
1425
|
runtime.lastSmartPrune = {
|
|
1365
1426
|
source: 'hippocampus',
|
|
@@ -1427,29 +1488,82 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1427
1488
|
/* advisory only: never block a request on marker upkeep */
|
|
1428
1489
|
}
|
|
1429
1490
|
|
|
1491
|
+
// ---- 2.6 one-shot fold -> immediate handoff (v1.9.5) ------------------
|
|
1492
|
+
// The fold above made the conversation smaller ONCE; now hand it over, so the
|
|
1493
|
+
// smaller surface is what gets summarised and the next session starts clean.
|
|
1494
|
+
// The allowance may only be SPENT where folding was actually permitted. At the
|
|
1495
|
+
// hard stop the fold was refused, so consuming it here would silently steal the
|
|
1496
|
+
// session's single chance to shrink (caught by v195's "cannot be consumed" test).
|
|
1497
|
+
if (onceFoldDue && foldGate.allowed) {
|
|
1498
|
+
if (sessionKey !== null) runtime.onceFoldedSessions.add(sessionKey);
|
|
1499
|
+
// v1.9.8: through the coordinator, with the REQUEST-path budget. If distillation
|
|
1500
|
+
// outlives it, this request goes out anyway and the marker lands for the next
|
|
1501
|
+
// turn — blocking the provider call is what used to read as "no reply".
|
|
1502
|
+
const outcome = await runtime.handoff.request({
|
|
1503
|
+
source: 'once-fold',
|
|
1504
|
+
force: FORCE.EARLY,
|
|
1505
|
+
budgetMs: runtime.handoff.policy().requestBudgetMs,
|
|
1506
|
+
context: {
|
|
1507
|
+
sessionId: sessionKey,
|
|
1508
|
+
projectedRatio: gateRatio,
|
|
1509
|
+
rolloverDue: true,
|
|
1510
|
+
marker: memory.handoffState(),
|
|
1511
|
+
},
|
|
1512
|
+
});
|
|
1513
|
+
const handed = outcome.result ?? null;
|
|
1514
|
+
const record = {
|
|
1515
|
+
at: memory.clock.now(),
|
|
1516
|
+
ratio: gateRatio,
|
|
1517
|
+
onceFoldAt,
|
|
1518
|
+
folded: runtime.lastSmartPrune?.folded ?? 0,
|
|
1519
|
+
handoffActive: handed?.handoff?.active === true,
|
|
1520
|
+
degraded: handed?.handoff?.degraded === true,
|
|
1521
|
+
status: outcome.status,
|
|
1522
|
+
};
|
|
1523
|
+
if (outcome.error) record.error = outcome.error.code;
|
|
1524
|
+
runtime.lastOnceFoldHandoff = record;
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1430
1527
|
// ---- 2.7 forced handoff at the folding hard stop (v1.9.4) -------------
|
|
1431
1528
|
// Reaching the stop line means folding is no longer allowed AND the conversation
|
|
1432
1529
|
// is at 85% of its window: hand off NOW instead of waiting for the 60% trigger,
|
|
1433
1530
|
// which folding may have made unreachable. `force` bypasses the threshold gates;
|
|
1434
1531
|
// a failure here is reported, never thrown (a handoff must not fail a request).
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1532
|
+
//
|
|
1533
|
+
// v1.9.7: AND IT MUST NOT REPEAT ON EVERY REQUEST. `force` bypasses the
|
|
1534
|
+
// re-handoff delta, so `!foldGate.allowed` (true for EVERY request at >=85%)
|
|
1535
|
+
// meant a fresh distillation -- up to HANDOFF_TIMEOUT_MS of blocking LLM work --
|
|
1536
|
+
// on every single turn. From the outside that reads as "the agent stopped
|
|
1537
|
+
// answering", not as a handoff. Reuse the same 5-point delta the unforced path
|
|
1538
|
+
// uses: hand off once, then again only after pressure really grows.
|
|
1539
|
+
const lastForcedRatio = Number.isFinite(runtime.lastForcedRatio) ? runtime.lastForcedRatio : 0;
|
|
1540
|
+
const forceDue = gateRatio >= lastForcedRatio + FORCED_HANDOFF_DELTA;
|
|
1541
|
+
if (!foldGate.allowed && forceDue) {
|
|
1542
|
+
runtime.lastForcedRatio = gateRatio;
|
|
1543
|
+
// v1.9.8: `'early'` bypasses the THRESHOLD only. The coordinator still applies
|
|
1544
|
+
// the re-handoff delta, so a forced call cannot re-distil a live marker.
|
|
1545
|
+
const outcome = await runtime.handoff.request({
|
|
1546
|
+
source: 'hard-stop',
|
|
1547
|
+
force: FORCE.EARLY,
|
|
1548
|
+
budgetMs: runtime.handoff.policy().requestBudgetMs,
|
|
1549
|
+
context: {
|
|
1550
|
+
sessionId: sessionKey,
|
|
1551
|
+
projectedRatio: gateRatio,
|
|
1552
|
+
rolloverDue: true,
|
|
1553
|
+
marker: memory.handoffState(),
|
|
1554
|
+
},
|
|
1555
|
+
});
|
|
1556
|
+
const forced = outcome.result ?? null;
|
|
1557
|
+
const record = {
|
|
1558
|
+
at: memory.clock.now(),
|
|
1559
|
+
ratio: gateRatio,
|
|
1560
|
+
active: forced?.handoff?.active === true,
|
|
1561
|
+
degraded: forced?.handoff?.degraded === true,
|
|
1562
|
+
reason: forced?.forced === true ? 'hard-stop' : 'already-handled',
|
|
1563
|
+
status: outcome.status,
|
|
1564
|
+
};
|
|
1565
|
+
if (outcome.error) record.error = outcome.error.code;
|
|
1566
|
+
runtime.lastForcedHandoff = record;
|
|
1453
1567
|
}
|
|
1454
1568
|
|
|
1455
1569
|
// ---- 3. fail fast on a request that CANNOT fit -------------------------
|
|
@@ -1458,7 +1572,22 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1458
1572
|
// distilled tail for the next one instead of repeating the same failure.
|
|
1459
1573
|
let handoff = null;
|
|
1460
1574
|
try {
|
|
1461
|
-
|
|
1575
|
+
// v1.9.8: the fail-fast path has its OWN budget — the request is already known
|
|
1576
|
+
// not to fit, so waiting the full request budget would only delay the error by
|
|
1577
|
+
// another 700ms. The run itself keeps going in the background.
|
|
1578
|
+
const outcome = await runtime.handoff.request({
|
|
1579
|
+
source: 'fail-fast',
|
|
1580
|
+
force: FORCE.NONE,
|
|
1581
|
+
budgetMs: runtime.handoff.policy().failFastBudgetMs,
|
|
1582
|
+
context: {
|
|
1583
|
+
sessionId: sessionKey,
|
|
1584
|
+
projectedRatio: gateRatio,
|
|
1585
|
+
rolloverDue: true,
|
|
1586
|
+
hardExceeded: true,
|
|
1587
|
+
marker: memory.handoffState(),
|
|
1588
|
+
},
|
|
1589
|
+
});
|
|
1590
|
+
handoff = outcome.result ?? null;
|
|
1462
1591
|
} catch {
|
|
1463
1592
|
/* the fail-fast below is the contract; a failed handoff only degrades recovery */
|
|
1464
1593
|
}
|
|
@@ -2295,6 +2424,9 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
2295
2424
|
}
|
|
2296
2425
|
memory = new Memory({ dataDir: next.dataDir, policy: nextOptions.policy, config: nextOptions.config, clock, activity: activityFor(null), ...multiSpaceExtras() });
|
|
2297
2426
|
runtime.memory = memory;
|
|
2427
|
+
// v1.9.8: a rebuilt facade must keep the same gate, or `_maybeAutoHandoff` would
|
|
2428
|
+
// silently fall back to its own lock after a bootstrap retry / migration reload.
|
|
2429
|
+
memory.setHandoffCoordinator?.(runtime.handoff);
|
|
2298
2430
|
runtime.config = next;
|
|
2299
2431
|
runtime.rawConfig = merged;
|
|
2300
2432
|
// The rings are bound to physical dirs; after the swap they must follow the new
|
|
@@ -2367,6 +2499,9 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
2367
2499
|
}
|
|
2368
2500
|
memory = new Memory({ dataDir: config.dataDir, policy: options.policy, config: options.config, clock, activity: runtime.activity, ...multiSpaceExtras() });
|
|
2369
2501
|
runtime.memory = memory;
|
|
2502
|
+
// v1.9.8: a rebuilt facade must keep the same gate, or `_maybeAutoHandoff` would
|
|
2503
|
+
// silently fall back to its own lock after a bootstrap retry / migration reload.
|
|
2504
|
+
memory.setHandoffCoordinator?.(runtime.handoff);
|
|
2370
2505
|
memory.setHandoffPresetProvider?.(() => runtime.agentPreset);
|
|
2371
2506
|
emit({ type: 'retry', phase: runtime.phase });
|
|
2372
2507
|
queueMicrotask(() => {
|
|
@@ -3859,7 +3994,23 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
3859
3994
|
let result = null;
|
|
3860
3995
|
let error = null;
|
|
3861
3996
|
try {
|
|
3862
|
-
|
|
3997
|
+
// v1.9.8: `'manual'` is the ONLY verb that skips the re-handoff delta, and a
|
|
3998
|
+
// human typed it. Single-flight still applies — a command must never start a
|
|
3999
|
+
// second distillation next to a running one.
|
|
4000
|
+
const outcome = await runtime.handoff.request({
|
|
4001
|
+
source: 'command',
|
|
4002
|
+
force: FORCE.MANUAL,
|
|
4003
|
+
budgetMs: runtime.handoff.policy().commandBudgetMs,
|
|
4004
|
+
});
|
|
4005
|
+
result = outcome.result ?? null;
|
|
4006
|
+
if (!result) {
|
|
4007
|
+
return ok(
|
|
4008
|
+
`[Handoff 强制检测]\n结果: ${outcome.status}` +
|
|
4009
|
+
(outcome.status === HANDOFF_STATUS.BUDGET_EXCEEDED
|
|
4010
|
+
? '(等待超时,蒸馏仍在后台进行;先用 /memory status 看 lastResult)'
|
|
4011
|
+
: '(本次未执行蒸馏)'),
|
|
4012
|
+
);
|
|
4013
|
+
}
|
|
3863
4014
|
} catch (caught) {
|
|
3864
4015
|
error = caught;
|
|
3865
4016
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-layers-hippocampus",
|
|
3
|
-
"version": "1.9.
|
|
3
|
+
"version": "1.9.8",
|
|
4
4
|
"private": false,
|
|
5
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
6
|
"type": "module",
|
package/src/config.js
CHANGED
|
@@ -294,7 +294,17 @@ export const DEFAULT_CONFIG = Object.freeze({
|
|
|
294
294
|
// replacement for "hope the host compacts": at `threshold` of the REAL window the
|
|
295
295
|
// oldest verbose turns are rewritten into `[System: …已折叠。原文 ID: ev_x]` pointers.
|
|
296
296
|
// The log itself is untouched — only the surface the model reads.
|
|
297
|
-
|
|
297
|
+
// v1.9.5: ONE fold, then hand over. `onceFoldAt` is the point where a session
|
|
298
|
+
// folds ONCE (to actually get smaller) and is then handed off; 0 disables it.
|
|
299
|
+
// The hard stop (0.85) stays the ceiling where folding is refused outright.
|
|
300
|
+
smartPrune: {
|
|
301
|
+
enabled: true,
|
|
302
|
+
threshold: 0.85,
|
|
303
|
+
keepRecentTurns: 3,
|
|
304
|
+
minChars: 1200,
|
|
305
|
+
maxNodes: 8,
|
|
306
|
+
onceFoldAt: 0.65,
|
|
307
|
+
},
|
|
298
308
|
// Security (v1.5.1): moving memories across spaces is NEVER an autonomous
|
|
299
309
|
// decision. While true, the engine refuses a model-initiated transfer unless
|
|
300
310
|
// the tool call carries `user_approved: true`; the UI route is the human
|
|
@@ -1020,6 +1030,13 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
|
|
|
1020
1030
|
'context.smartPrune.maxNodes',
|
|
1021
1031
|
{ min: 1, max: 64 },
|
|
1022
1032
|
);
|
|
1033
|
+
// v1.9.5: the one-shot fold point. 0 means "never fold early" (the old 1.9.4
|
|
1034
|
+
// behaviour); anything in (0, 1] is a ratio.
|
|
1035
|
+
const smartPruneOnceFoldAt = requireNumberInRange(
|
|
1036
|
+
smartPruneIn.onceFoldAt === undefined ? defaults.context.smartPrune.onceFoldAt : smartPruneIn.onceFoldAt,
|
|
1037
|
+
'context.smartPrune.onceFoldAt',
|
|
1038
|
+
{ min: 0, max: 1 },
|
|
1039
|
+
);
|
|
1023
1040
|
const liveCompactIn = contextIn.liveCompact ?? {};
|
|
1024
1041
|
const liveCompactEnabled = requireBoolean(
|
|
1025
1042
|
liveCompactIn.enabled === undefined ? defaults.context.liveCompact.enabled : liveCompactIn.enabled,
|
|
@@ -1712,6 +1729,7 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
|
|
|
1712
1729
|
smartPrune: {
|
|
1713
1730
|
enabled: smartPruneEnabled,
|
|
1714
1731
|
threshold: smartPruneThreshold,
|
|
1732
|
+
onceFoldAt: smartPruneOnceFoldAt,
|
|
1715
1733
|
keepRecentTurns: smartPruneKeepRecentTurns,
|
|
1716
1734
|
minChars: smartPruneMinChars,
|
|
1717
1735
|
maxNodes: smartPruneMaxNodes,
|
|
@@ -85,7 +85,7 @@ function textOfBlocks(content) {
|
|
|
85
85
|
return total;
|
|
86
86
|
}
|
|
87
87
|
|
|
88
|
-
function messageOf(session, seq) {
|
|
88
|
+
/** * v1.9.6: is this message already a FOLD POINTER rather than something a person said? * * This matters more than it looks. A pointer is written back as `user/message`, so * every later pass counted it as a user turn: the three most recent "user turns" * became three POINTERS, `protectedFrom` slid past the real messages, and the next * fold ate them -- which produced another pointer, and so on. That self-reinforcing * loop is what made folding look like it never stopped, and it is why the handoff * marker's `tailTurns` ended up carrying nothing but "此段已折叠" notices. */function isFoldPointer(message) { const content = message?.content; if (!Array.isArray(content)) return false; return content.some( (block) => block && typeof block.text === 'string' && block.text.startsWith(FOLD_MARKER), );}function messageOf(session, seq) {
|
|
89
89
|
try {
|
|
90
90
|
const event = typeof session?.eventAt === 'function' ? session.eventAt(seq) : null;
|
|
91
91
|
if (!event) return null;
|
|
@@ -120,7 +120,9 @@ export function planSmartPrune(session, options = {}) {
|
|
|
120
120
|
for (let index = nodes.length - 1; index >= 0; index -= 1) {
|
|
121
121
|
const node = messageOf(session, nodes[index]);
|
|
122
122
|
if (!node) continue;
|
|
123
|
-
|
|
123
|
+
// A fold pointer is not a turn a person took: counting it here slides the
|
|
124
|
+
// protected window past the real messages and folds them next time.
|
|
125
|
+
if (node.event?.type === 'user/message' && !isFoldPointer(node.message)) {
|
|
124
126
|
seen += 1;
|
|
125
127
|
if (seen >= keepRecentTurns) {
|
|
126
128
|
protectedFrom = index;
|
|
@@ -167,9 +169,7 @@ export function planSmartPrune(session, options = {}) {
|
|
|
167
169
|
continue;
|
|
168
170
|
}
|
|
169
171
|
const chars = textOfBlocks(message.content);
|
|
170
|
-
const alreadyMicro = message
|
|
171
|
-
(block) => block && typeof block.text === 'string' && block.text.startsWith(FOLD_MARKER),
|
|
172
|
-
);
|
|
172
|
+
const alreadyMicro = isFoldPointer(message);
|
|
173
173
|
if (alreadyMicro) {
|
|
174
174
|
closeRun();
|
|
175
175
|
continue;
|
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* v1.9.8 — the ONE handoff entry point.
|
|
3
|
+
*
|
|
4
|
+
* Before this module, six independent paths called `memory.checkHandoff()` and only
|
|
5
|
+
* `_maybeAutoHandoff()` carried a concurrency guard. `recordToolCall()`, the one-shot
|
|
6
|
+
* fold, the folding hard stop, the fail-fast path and `/memory handoff` could all fire
|
|
7
|
+
* in the same tick: two `_distillHandoffTail()` runs, two `clearHandoff()` +
|
|
8
|
+
* `writeJsonAtomic()` pairs, and up to two blocking LLM distillations for one event.
|
|
9
|
+
* The 2026-12-01 incident ("no crash, no reply") is structurally explained by that.
|
|
10
|
+
*
|
|
11
|
+
* The coordinator owns the DECISION and the QUEUE; the engine keeps the EXECUTION
|
|
12
|
+
* (`checkHandoff`). Consequences, all deliberate:
|
|
13
|
+
*
|
|
14
|
+
* - **Single flight.** At most one distillation runs at a time. A second awaited
|
|
15
|
+
* request becomes at most ONE pending entry (latest wins); a fire-and-forget offer
|
|
16
|
+
* is simply dropped while a run is in flight.
|
|
17
|
+
* - **Budgets are per path.** The provider call must not wait for a distillation:
|
|
18
|
+
* the request path reads the result within `requestBudgetMs` and returns, while the
|
|
19
|
+
* run itself finishes in the background and publishes the marker for the NEXT turn.
|
|
20
|
+
* - **`force` is narrowed.** `'early'` bypasses ONLY the threshold gate. The
|
|
21
|
+
* re-handoff delta still applies, so a forced call can no longer re-distill a
|
|
22
|
+
* marker that is already active. `'manual'` (a human typing `/memory handoff`) is
|
|
23
|
+
* the only verb that skips the delta, and it is named so it cannot be reached by
|
|
24
|
+
* accident. The old boolean `true` is accepted but demoted to `'early'`.
|
|
25
|
+
* - **Never throws into the caller.** A handoff is best-effort; a failure is a value.
|
|
26
|
+
*
|
|
27
|
+
* This module is deliberately dependency-free (no cordis, no store access): the host
|
|
28
|
+
* injects `probe()` and `run()`, and tests inject fakes.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
/** The three force verbs. There is no fourth way to start a distillation. */
|
|
32
|
+
export const FORCE = Object.freeze({
|
|
33
|
+
/** Respect every gate (threshold + re-handoff delta). Default for automatic paths. */
|
|
34
|
+
NONE: 'none',
|
|
35
|
+
/** Bypass the THRESHOLD only; the re-handoff delta still applies. */
|
|
36
|
+
EARLY: 'early',
|
|
37
|
+
/** A human asked (`/memory handoff`): skip the delta too. Still respects single-flight. */
|
|
38
|
+
MANUAL: 'manual',
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
/** Every terminal outcome carries one of these. A caller must not have to infer. */
|
|
42
|
+
export const HANDOFF_STATUS = Object.freeze({
|
|
43
|
+
DONE: 'done',
|
|
44
|
+
DEGRADED: 'degraded',
|
|
45
|
+
ERROR: 'error',
|
|
46
|
+
COALESCED: 'coalesced',
|
|
47
|
+
SUPERSEDED: 'superseded',
|
|
48
|
+
THROTTLED: 'throttled',
|
|
49
|
+
DEDUPED: 'deduped',
|
|
50
|
+
BELOW_GATE: 'below-gate',
|
|
51
|
+
ALREADY_ACTIVE: 'already-active',
|
|
52
|
+
BUDGET_EXCEEDED: 'budget-exceeded',
|
|
53
|
+
WATCHDOG: 'watchdog',
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
export const DEFAULT_HANDOFF_POLICY = Object.freeze({
|
|
57
|
+
/**
|
|
58
|
+
* Wall-clock spacing between two STARTED handoffs. Default 0 (off) on purpose:
|
|
59
|
+
* the real anti-repeat rule is the 5-point re-handoff delta, and a wall-clock gate
|
|
60
|
+
* would reject a genuine growth that happens two seconds later (v197 asserts that
|
|
61
|
+
* growth re-handoffs). Set it only if a profile wants a hard floor.
|
|
62
|
+
*/
|
|
63
|
+
minIntervalMs: 0,
|
|
64
|
+
/** The provider call waits this long for a handoff before it goes out anyway. */
|
|
65
|
+
requestBudgetMs: 1500,
|
|
66
|
+
/** Fail-fast has less time: the request is already known not to fit. */
|
|
67
|
+
failFastBudgetMs: 800,
|
|
68
|
+
/** A human command may wait longer; it is interactive, not per-turn. */
|
|
69
|
+
commandBudgetMs: 10_000,
|
|
70
|
+
/**
|
|
71
|
+
* Absolute ceiling for one run. `checkHandoff` has its own HANDOFF_TIMEOUT_MS (5s),
|
|
72
|
+
* so this only fires when the injected runner ignores its own contract. It exists so
|
|
73
|
+
* a hung run can never leave the single-flight lock held forever.
|
|
74
|
+
*/
|
|
75
|
+
maxRunMs: 15_000,
|
|
76
|
+
/** Re-handoff needs real growth past the marker's own ratio (same as windowGuard). */
|
|
77
|
+
rehandoffDelta: 0.05,
|
|
78
|
+
/** Above this the re-handoff is unconditional (do not argue with a full window). */
|
|
79
|
+
nearLimitRatio: 0.95,
|
|
80
|
+
/**
|
|
81
|
+
* How many AWAITED requests may wait for the run in flight. Default 0 = pure
|
|
82
|
+
* coalescing: the run that is already going writes the marker for the next turn, so
|
|
83
|
+
* a second distillation started the moment it finishes is exactly the duplicate work
|
|
84
|
+
* this release exists to remove. Raise it only for a profile that must eventually
|
|
85
|
+
* succeed at a specific trigger.
|
|
86
|
+
*/
|
|
87
|
+
maxPending: 0,
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
const BUDGET = Symbol('handoff-budget');
|
|
91
|
+
|
|
92
|
+
function normalizePolicy(policy) {
|
|
93
|
+
const raw = (typeof policy === 'function' ? policy() : policy) ?? {};
|
|
94
|
+
const merged = { ...DEFAULT_HANDOFF_POLICY };
|
|
95
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
96
|
+
if (Number.isFinite(value)) merged[key] = value;
|
|
97
|
+
}
|
|
98
|
+
return merged;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function normalizeForce(force) {
|
|
102
|
+
if (force === FORCE.EARLY || force === FORCE.MANUAL) return force;
|
|
103
|
+
// v1.9.4 callers passed `true` meaning "skip every gate". Demote it: the boolean is
|
|
104
|
+
// exactly the ambiguity this release removes, and no automatic path may keep it.
|
|
105
|
+
if (force === true) return FORCE.EARLY;
|
|
106
|
+
return FORCE.NONE;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* @param {object} deps
|
|
111
|
+
* @param {{ now(): number }} deps.clock
|
|
112
|
+
* @param {object|null} [deps.logger]
|
|
113
|
+
* @param {() => object} [deps.policy] live policy (config-backed); may change
|
|
114
|
+
* @param {() => object|null} [deps.probe] current pressure/marker snapshot
|
|
115
|
+
* @param {(input: { force: string, reason: string, runId: number, context: object|null }) => Promise<object>} deps.run
|
|
116
|
+
*/
|
|
117
|
+
export function createHandoffCoordinator({ clock, logger = null, policy = () => ({}), probe = null, run } = {}) {
|
|
118
|
+
if (typeof run !== 'function') throw new TypeError('createHandoffCoordinator requires a run() executor');
|
|
119
|
+
|
|
120
|
+
const now = () => {
|
|
121
|
+
try {
|
|
122
|
+
const value = typeof clock?.now === 'function' ? clock.now() : null;
|
|
123
|
+
if (Number.isFinite(value)) return value;
|
|
124
|
+
} catch {
|
|
125
|
+
/* a broken clock must not fail a handoff decision */
|
|
126
|
+
}
|
|
127
|
+
return Date.now();
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
/** `{ runId, source, startedAt, promise }` while a distillation is running. */
|
|
131
|
+
let inFlight = null;
|
|
132
|
+
/** At most one queued request: `{ request, context, decision, deferred }`. */
|
|
133
|
+
let pending = null;
|
|
134
|
+
let lastStartedAt = null;
|
|
135
|
+
/** Last settled outcome, for `/memory status` and tests. */
|
|
136
|
+
let lastResult = null;
|
|
137
|
+
let runCounter = 0;
|
|
138
|
+
/** sessionId -> pressure bucket of the last STARTED run (R5). */
|
|
139
|
+
const lastBucketBySession = new Map();
|
|
140
|
+
|
|
141
|
+
const warn = (message) => {
|
|
142
|
+
try {
|
|
143
|
+
logger?.warn?.(`hippocampus: handoff ${message}`);
|
|
144
|
+
} catch {
|
|
145
|
+
/* logging must never break the queue */
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
function snapshotContext(context) {
|
|
150
|
+
if (context && typeof context === 'object') return context;
|
|
151
|
+
try {
|
|
152
|
+
return probe?.() ?? null;
|
|
153
|
+
} catch {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* The rules, in order. Deliberately synchronous: two triggers arriving in the same
|
|
160
|
+
* tick must both observe the same pre-run state, so nothing here awaits.
|
|
161
|
+
*/
|
|
162
|
+
/** The pressure band a context belongs to (used by R5 and by coalesced outcomes). */
|
|
163
|
+
function bandOf(context) {
|
|
164
|
+
const ratio = Number.isFinite(context?.projectedRatio) ? context.projectedRatio : null;
|
|
165
|
+
return { bucket: ratio === null ? null : Math.round(ratio * 100), sessionId: context?.sessionId ?? null };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function evaluate(request, context, activePolicy) {
|
|
169
|
+
const sessionId = context?.sessionId ?? null;
|
|
170
|
+
const ratio = Number.isFinite(context?.projectedRatio) ? context.projectedRatio : null;
|
|
171
|
+
const marker = context?.marker ?? null;
|
|
172
|
+
const sameSession = !marker?.sessionId || !sessionId || marker.sessionId === sessionId;
|
|
173
|
+
const bucket = ratio === null ? null : Math.round(ratio * 100);
|
|
174
|
+
const base = { bucket, sessionId, ratio, marker, sameSession };
|
|
175
|
+
|
|
176
|
+
// R2 — wall-clock spacing (off by default; never applies to a human command).
|
|
177
|
+
if (activePolicy.minIntervalMs > 0 && request.force !== FORCE.MANUAL && lastStartedAt !== null) {
|
|
178
|
+
const elapsed = now() - lastStartedAt;
|
|
179
|
+
if (elapsed < activePolicy.minIntervalMs) {
|
|
180
|
+
return { ...base, status: HANDOFF_STATUS.THROTTLED, retryInMs: activePolicy.minIntervalMs - elapsed };
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// R3 — the threshold. `'early'` bypasses THIS and nothing else.
|
|
185
|
+
if (request.force === FORCE.NONE && context && context.rolloverDue !== true && context.hardExceeded !== true) {
|
|
186
|
+
return { ...base, status: HANDOFF_STATUS.BELOW_GATE };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// R4 — re-handoff inside the same session needs real growth past the marker.
|
|
190
|
+
// Applies to 'early' as well: forcing must not re-distil a live marker.
|
|
191
|
+
if (marker?.active === true && sameSession && request.force !== FORCE.MANUAL) {
|
|
192
|
+
const markerRatio = Number.isFinite(marker.ratio) ? marker.ratio : null;
|
|
193
|
+
if (markerRatio !== null && ratio !== null) {
|
|
194
|
+
const growth = ratio - markerRatio;
|
|
195
|
+
if (growth < activePolicy.rehandoffDelta && ratio < activePolicy.nearLimitRatio) {
|
|
196
|
+
return { ...base, status: HANDOFF_STATUS.ALREADY_ACTIVE, growth };
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// R5 — same pressure band, same session: the summary for this band already exists.
|
|
202
|
+
if (request.force !== FORCE.MANUAL && sessionId && bucket !== null && lastBucketBySession.get(sessionId) === bucket) {
|
|
203
|
+
return { ...base, status: HANDOFF_STATUS.DEDUPED };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return { ...base, status: null };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function buildOutcome({ status, runId = null, source = null, decision = null, result = null, error = null, waitedMs = 0, retryInMs = null, coalesced = false }) {
|
|
210
|
+
const handoff = result?.handoff ?? null;
|
|
211
|
+
const resolved = status === HANDOFF_STATUS.DONE && handoff?.degraded === true ? HANDOFF_STATUS.DEGRADED : status;
|
|
212
|
+
return {
|
|
213
|
+
status: resolved,
|
|
214
|
+
source,
|
|
215
|
+
runId,
|
|
216
|
+
bucket: decision?.bucket ?? null,
|
|
217
|
+
retryInMs,
|
|
218
|
+
coalesced,
|
|
219
|
+
waitedMs,
|
|
220
|
+
forced: result?.forced === true,
|
|
221
|
+
handoff,
|
|
222
|
+
diagnostic: result?.diagnostic ?? null,
|
|
223
|
+
result,
|
|
224
|
+
error: error ? { code: error?.code ?? 'MEM_E_HANDOFF_FAILED', message: error?.message ?? String(error) } : null,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Resolve the queued request (if any) now that the lock is free. */
|
|
229
|
+
function pumpPending() {
|
|
230
|
+
if (!pending || inFlight) return;
|
|
231
|
+
const next = pending;
|
|
232
|
+
pending = null;
|
|
233
|
+
startRun(next.request, next.context, next.decision).then(next.resolve, next.reject);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function releaseRun(runId) {
|
|
237
|
+
if (inFlight?.runId === runId) inFlight = null;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Start ONE run. The returned promise settles at `budgetMs` at the latest, but the
|
|
242
|
+
* underlying distillation is NOT cancelled: the marker it writes is what the next
|
|
243
|
+
* turn reads, so letting it finish is the point.
|
|
244
|
+
*/
|
|
245
|
+
function startRun(request, context, decision) {
|
|
246
|
+
const activePolicy = normalizePolicy(policy);
|
|
247
|
+
const startedAt = now();
|
|
248
|
+
runCounter += 1;
|
|
249
|
+
const runId = runCounter;
|
|
250
|
+
const sessionId = decision?.sessionId ?? null;
|
|
251
|
+
if (sessionId && decision?.bucket !== null && decision?.bucket !== undefined) {
|
|
252
|
+
lastBucketBySession.set(sessionId, decision.bucket);
|
|
253
|
+
}
|
|
254
|
+
lastStartedAt = startedAt;
|
|
255
|
+
|
|
256
|
+
const execute = Promise.resolve().then(() =>
|
|
257
|
+
run({ force: request.force, reason: request.source, runId, context }),
|
|
258
|
+
);
|
|
259
|
+
inFlight = { runId, source: request.source, startedAt, promise: execute };
|
|
260
|
+
|
|
261
|
+
// Absolute ceiling: a runner that ignores its own timeout must not wedge the queue.
|
|
262
|
+
let watchdog = null;
|
|
263
|
+
if (activePolicy.maxRunMs > 0) {
|
|
264
|
+
watchdog = setTimeout(() => {
|
|
265
|
+
if (inFlight?.runId !== runId) return;
|
|
266
|
+
warn(`watchdog: ${request.source} did not settle within ${activePolicy.maxRunMs}ms`);
|
|
267
|
+
releaseRun(runId);
|
|
268
|
+
const outcome = buildOutcome({ status: HANDOFF_STATUS.WATCHDOG, runId, source: request.source, decision, waitedMs: now() - startedAt });
|
|
269
|
+
lastResult = outcome;
|
|
270
|
+
pumpPending();
|
|
271
|
+
}, activePolicy.maxRunMs);
|
|
272
|
+
watchdog.unref?.();
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const settled = execute.then(
|
|
276
|
+
(result) => {
|
|
277
|
+
if (watchdog) clearTimeout(watchdog);
|
|
278
|
+
releaseRun(runId);
|
|
279
|
+
const outcome = buildOutcome({
|
|
280
|
+
status: HANDOFF_STATUS.DONE,
|
|
281
|
+
runId,
|
|
282
|
+
source: request.source,
|
|
283
|
+
decision,
|
|
284
|
+
result,
|
|
285
|
+
waitedMs: now() - startedAt,
|
|
286
|
+
});
|
|
287
|
+
lastResult = outcome;
|
|
288
|
+
pumpPending();
|
|
289
|
+
return outcome;
|
|
290
|
+
},
|
|
291
|
+
(error) => {
|
|
292
|
+
if (watchdog) clearTimeout(watchdog);
|
|
293
|
+
releaseRun(runId);
|
|
294
|
+
const outcome = buildOutcome({
|
|
295
|
+
status: HANDOFF_STATUS.ERROR,
|
|
296
|
+
runId,
|
|
297
|
+
source: request.source,
|
|
298
|
+
decision,
|
|
299
|
+
error,
|
|
300
|
+
waitedMs: now() - startedAt,
|
|
301
|
+
});
|
|
302
|
+
lastResult = outcome;
|
|
303
|
+
warn(`failed (${request.source}): ${outcome.error.code}`);
|
|
304
|
+
pumpPending();
|
|
305
|
+
return outcome;
|
|
306
|
+
},
|
|
307
|
+
);
|
|
308
|
+
// The budget race below may abandon `settled`; it must never look unhandled.
|
|
309
|
+
settled.catch(() => {});
|
|
310
|
+
|
|
311
|
+
const budgetMs = Number.isFinite(request.budgetMs) ? request.budgetMs : activePolicy.requestBudgetMs;
|
|
312
|
+
if (!(budgetMs > 0)) return settled;
|
|
313
|
+
|
|
314
|
+
const budget = new Promise((resolve) => {
|
|
315
|
+
const timer = setTimeout(() => resolve(BUDGET), budgetMs);
|
|
316
|
+
timer.unref?.();
|
|
317
|
+
});
|
|
318
|
+
return Promise.race([settled, budget.then((marker) => marker)]).then((value) => {
|
|
319
|
+
if (value === BUDGET) {
|
|
320
|
+
// The run keeps going; the caller gets the truth about WHY it has no answer.
|
|
321
|
+
return buildOutcome({
|
|
322
|
+
status: HANDOFF_STATUS.BUDGET_EXCEEDED,
|
|
323
|
+
runId,
|
|
324
|
+
source: request.source,
|
|
325
|
+
decision,
|
|
326
|
+
waitedMs: budgetMs,
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
return value;
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* Awaited entry point. Never rejects: every refusal and every failure is a status.
|
|
335
|
+
*
|
|
336
|
+
* @param {{ source?: string, force?: string|boolean, budgetMs?: number, context?: object|null, awaitable?: boolean }} options
|
|
337
|
+
*/
|
|
338
|
+
async function request(options = {}) {
|
|
339
|
+
const request_ = {
|
|
340
|
+
source: String(options.source ?? 'unknown'),
|
|
341
|
+
force: normalizeForce(options.force),
|
|
342
|
+
budgetMs: options.budgetMs,
|
|
343
|
+
};
|
|
344
|
+
const context = snapshotContext(options.context);
|
|
345
|
+
const activePolicy = normalizePolicy(policy);
|
|
346
|
+
|
|
347
|
+
// R1 FIRST. While a run is in flight, the only correct answer is "coalesce": the
|
|
348
|
+
// gates below describe a NEW run, and one is already happening. (Checking the gates
|
|
349
|
+
// first used to answer `deduped` for a trigger that was actually concurrent.)
|
|
350
|
+
if (inFlight) {
|
|
351
|
+
if (activePolicy.maxPending > 0) {
|
|
352
|
+
if (pending) {
|
|
353
|
+
// Latest wins: the queued request is superseded, not stacked behind.
|
|
354
|
+
const previous = pending;
|
|
355
|
+
pending = null;
|
|
356
|
+
previous.resolve(
|
|
357
|
+
buildOutcome({ status: HANDOFF_STATUS.SUPERSEDED, source: previous.request.source, decision: previous.decision }),
|
|
358
|
+
);
|
|
359
|
+
}
|
|
360
|
+
return new Promise((resolve, reject) => {
|
|
361
|
+
pending = { request: request_, context, decision: bandOf(context), resolve, reject };
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
const coalesced = buildOutcome({
|
|
365
|
+
status: HANDOFF_STATUS.COALESCED,
|
|
366
|
+
source: request_.source,
|
|
367
|
+
decision: bandOf(context),
|
|
368
|
+
coalesced: true,
|
|
369
|
+
});
|
|
370
|
+
lastResult = coalesced;
|
|
371
|
+
return coalesced;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const decision = evaluate(request_, context, activePolicy);
|
|
375
|
+
if (decision.status !== null) {
|
|
376
|
+
const outcome = buildOutcome({ status: decision.status, source: request_.source, decision, retryInMs: decision.retryInMs ?? null });
|
|
377
|
+
lastResult = outcome;
|
|
378
|
+
return outcome;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
return startRun(request_, context, decision);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* Fire-and-forget entry point for a tool boundary: it must cost nothing and it must
|
|
386
|
+
* not queue. If a run is in flight this is dropped — the run that is already going
|
|
387
|
+
* will produce the marker anyway.
|
|
388
|
+
*/
|
|
389
|
+
function offer(options = {}) {
|
|
390
|
+
const request_ = { source: String(options.source ?? 'tool-boundary'), force: normalizeForce(options.force), budgetMs: 0 };
|
|
391
|
+
const context = snapshotContext(options.context);
|
|
392
|
+
const activePolicy = normalizePolicy(policy);
|
|
393
|
+
if (inFlight) {
|
|
394
|
+
return { status: HANDOFF_STATUS.COALESCED, source: request_.source, coalesced: true, bucket: bandOf(context).bucket };
|
|
395
|
+
}
|
|
396
|
+
const decision = evaluate(request_, context, activePolicy);
|
|
397
|
+
if (decision.status !== null) {
|
|
398
|
+
return { status: decision.status, source: request_.source, bucket: decision.bucket ?? null };
|
|
399
|
+
}
|
|
400
|
+
startRun(request_, context, decision).catch(() => {});
|
|
401
|
+
return { status: HANDOFF_STATUS.DONE, source: request_.source, bucket: decision.bucket ?? null, started: true };
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function state() {
|
|
405
|
+
return {
|
|
406
|
+
inFlight: inFlight ? { runId: inFlight.runId, source: inFlight.source, startedAt: inFlight.startedAt } : null,
|
|
407
|
+
pending: pending ? { source: pending.request.source } : null,
|
|
408
|
+
lastStartedAt,
|
|
409
|
+
lastResult,
|
|
410
|
+
buckets: Object.fromEntries(lastBucketBySession),
|
|
411
|
+
runs: runCounter,
|
|
412
|
+
policy: normalizePolicy(policy),
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
return { request, offer, state, policy: () => normalizePolicy(policy) };
|
|
417
|
+
}
|
package/src/memory.js
CHANGED
|
@@ -54,6 +54,7 @@ import { SemanticStore } from './semantic/semanticStore.js';
|
|
|
54
54
|
import { TempSemanticStore } from './semantic/tempSemantic.js';
|
|
55
55
|
import { ContextEngine } from './context/contextEngine.js';
|
|
56
56
|
import { HANDOFF_CLEAR_RATIO, relievedDecision, rehandoffDecision } from './context/windowGuard.js';
|
|
57
|
+
import { FOLD_MARKER } from './context/smartPrune.js';
|
|
57
58
|
import { DEFAULT_SPACE_ID, SpaceRouter, normaliseSpaceId, validateNewSpaceId } from './spaces/singleSpace.js';
|
|
58
59
|
import { nextRun, parseCron } from './cron.js';
|
|
59
60
|
|
|
@@ -546,6 +547,14 @@ export class Memory {
|
|
|
546
547
|
/** Tags whose oversized hint has already been shown: the next recall is "insist". */
|
|
547
548
|
this._oversizedHintTags = new Set();
|
|
548
549
|
this._handoffInFlight = false;
|
|
550
|
+
/**
|
|
551
|
+
* v1.9.8: the host-owned single-flight gate (src/handoff/coordinator.js).
|
|
552
|
+
*
|
|
553
|
+
* Null in the engine-only fixture (tests that construct `Memory` directly keep the
|
|
554
|
+
* old standalone behaviour). The plugin wires it in `setHandoffCoordinator()`, and
|
|
555
|
+
* `_maybeAutoHandoff()` then routes through it instead of racing its own flag.
|
|
556
|
+
*/
|
|
557
|
+
this._handoffCoordinator = null;
|
|
549
558
|
this.maintenance.onPublished = () => {
|
|
550
559
|
this._semanticCache = null;
|
|
551
560
|
};
|
|
@@ -1948,6 +1957,11 @@ export class Memory {
|
|
|
1948
1957
|
_recordRecentTurn(role, text) {
|
|
1949
1958
|
const clean = String(text ?? '').replace(/\s+/g, ' ').trim();
|
|
1950
1959
|
if (clean.length === 0) return;
|
|
1960
|
+
// v1.9.6: a fold pointer is OUR bookkeeping, not something a person said. Recording
|
|
1961
|
+
// it made the handoff marker's `tailTurns` carry lines like "此段包含 1 轮…已折叠"
|
|
1962
|
+
// instead of the last things actually said, so the next conversation started with
|
|
1963
|
+
// three notices and no context. Caught in the field on 2026-12-01.
|
|
1964
|
+
if (clean.startsWith(FOLD_MARKER)) return;
|
|
1951
1965
|
this._recentTurns.push({
|
|
1952
1966
|
role: role === 'assistant' ? 'assistant' : 'user',
|
|
1953
1967
|
text: clean.slice(0, RECENT_TURN_MAX_CHARS),
|
|
@@ -2406,16 +2420,53 @@ export class Memory {
|
|
|
2406
2420
|
}
|
|
2407
2421
|
}
|
|
2408
2422
|
|
|
2423
|
+
/**
|
|
2424
|
+
* v1.9.8: wire the host-owned single-flight gate. See `src/handoff/coordinator.js`.
|
|
2425
|
+
* Nullable on purpose — an embedder that uses `Memory` on its own keeps the
|
|
2426
|
+
* standalone path below.
|
|
2427
|
+
*/
|
|
2428
|
+
setHandoffCoordinator(coordinator) {
|
|
2429
|
+
this._handoffCoordinator = coordinator ?? null;
|
|
2430
|
+
return this;
|
|
2431
|
+
}
|
|
2432
|
+
|
|
2409
2433
|
/**
|
|
2410
2434
|
* Fire-and-forget handoff trigger used by the session/event listener and by tool
|
|
2411
2435
|
* calls. It never throws into the host's event bus and has an OUTER watchdog as
|
|
2412
2436
|
* well as checkHandoff's internal one: even if checkHandoff itself hangs, the
|
|
2413
2437
|
* in-flight flag is released so the next session/turn can proceed.
|
|
2438
|
+
*
|
|
2439
|
+
* v1.9.8: when the host wired a coordinator, this DELEGATES instead of running its
|
|
2440
|
+
* own distillation. `_handoffInFlight` survives only for the standalone path, which
|
|
2441
|
+
* is why the source scan allows it exactly here.
|
|
2414
2442
|
*/
|
|
2415
2443
|
_maybeAutoHandoff() {
|
|
2416
2444
|
if (this._closed || this._handoffInFlight) return;
|
|
2417
2445
|
const state = this.context.nativeState({ sessionTokens: this.sessionUsage().tokens });
|
|
2418
2446
|
if (!state.rolloverDue && !state.forceEvictionDue) return;
|
|
2447
|
+
if (this._handoffCoordinator) {
|
|
2448
|
+
try {
|
|
2449
|
+
const usage = this.sessionUsage();
|
|
2450
|
+
this._handoffCoordinator
|
|
2451
|
+
.request({
|
|
2452
|
+
source: 'auto',
|
|
2453
|
+
force: 'none',
|
|
2454
|
+
context: {
|
|
2455
|
+
sessionId: usage.sessionId ?? null,
|
|
2456
|
+
projectedRatio: state.projectedRatio,
|
|
2457
|
+
rolloverDue: true,
|
|
2458
|
+
hardExceeded: state.hardExceeded === true,
|
|
2459
|
+
marker: this.handoffState(),
|
|
2460
|
+
},
|
|
2461
|
+
})
|
|
2462
|
+
.catch(() => {
|
|
2463
|
+
/* a failed handoff must never break session capture */
|
|
2464
|
+
});
|
|
2465
|
+
} catch {
|
|
2466
|
+
/* the coordinator is best-effort */
|
|
2467
|
+
}
|
|
2468
|
+
return;
|
|
2469
|
+
}
|
|
2419
2470
|
this._handoffInFlight = true;
|
|
2420
2471
|
const watchdog = new Promise((resolve) => {
|
|
2421
2472
|
const timer = setTimeout(
|