dsh-aiyayi 1.5.35 → 1.5.37
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 +58 -3
- package/README.md +3 -2
- package/cordis.patch.yml +23 -0
- package/lib/feishu-logic.js +186 -0
- package/lib/feishu.js +141 -10
- package/lib/own-tools.js +2 -0
- package/lib/precompact.js +554 -0
- package/package.json +3 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
> **维护约定**:新版本发布时在顶部加条目。本文件由 README 正文拆出(2026-11-09 重构):版本条目与踩坑记录原文照录,数字、时间、日期一律不改(量化保真是本插件的规矩)。版本事实以 npm registry 为准。
|
|
4
4
|
>
|
|
5
|
-
> **npm 发布一览(2026-11-12 核对 registry,`npm view dsh-aiyayi versions --json`)**:latest = **1.5.
|
|
5
|
+
> **npm 发布一览(2026-11-12 核对 registry,`npm view dsh-aiyayi versions --json`)**:latest = **1.5.37**(本次发版版;registry 实况 latest 目前为 **1.5.36**,已由并发会话发布,1.5.37 的 publish 由下一步单独执行,发布后以 registry 为准)。已发布:1.0.0、…、1.5.7、**1.5.14**、**1.5.15**、**1.5.16**、**1.5.17**、**1.5.20**、**1.5.21**、**1.5.22**、**1.5.23**、**1.5.24**、**1.5.25**、**1.5.26**、**1.5.27**、**1.5.28**、**1.5.29**、**1.5.30**、**1.5.31**、**1.5.32**、**1.5.33**、**1.5.34**、**1.5.35**、**1.5.36**;跳号 1.3.0、1.4.1、1.4.2、1.5.0、1.5.1、1.5.2、1.5.3、**1.5.8–1.5.13** 从未发布到 npm(本地开发线:1.5.8–1.5.11 飞书桥接、1.5.12 思考纪律约束、1.5.13 内置技能同步+feishu-setup 骨架);1.5.14 已发布(坑 #58–#67 修复);1.5.15 已发布(扫码接入改造);1.5.16 已发布(feishu-setup 技能脚本入包);1.5.17 已发布(坑 #68 重入保护修复);**1.5.18 / 1.5.19 也从未发布到 npm**(见下方 1.5.18 / 1.5.19 条目——它们的代码最终随 1.5.20 一起进 npm);**1.5.20 已发布**(飞书正文改走 interactive 卡片 + lark_md,含 1.5.19 附件收发与问答卡片、1.5.20 markdown 渲染,以及 create-bot v6 权限集中化);**1.5.21 已发布**(修飞书回复正文首尾空白行,坑 #72);**1.5.22 已发布**(多应用多长连接改造+chat 归属机制,见下方 1.5.22 条目);**1.5.23–1.5.25 已发布**(230001 边界/补 import/补 feishuCode 挖码三轮装版断言增量修复,见下方对应条目);**1.5.26 已发布**(回发多文本段覆盖丢段修复,坑 #73,见下方 1.5.26 条目);**1.5.27 已发布**(微信通道并入,默认关闭,见下方 1.5.27 条目);**1.5.28 已发布**(PowerShell 版本体检 + 微信通道收尾,见下方 1.5.28 条目);**1.5.29 已发布**(发布包排除 `test/` + 测试残留空目录清理,见下方 1.5.29 条目);**1.5.30 已发布**(create-bot 注释改用 `<记忆根>` 占位,见下方 1.5.30 条目);**1.5.31 已发布**(PowerShell 体检 `major:null` 根因修复:探测链补上 powershell.exe 一级,见下方 1.5.31 条目);**1.5.32 已发布**(行为变更:首次提示同时告知微信 ClawBot 能力 + 「对接默认落到发起对接的会话」固化为 persona 准则/文档;不含路由代码改动,见下方 1.5.32 条目);**1.5.33 已发布**(同一准则落成代码:未绑定 chat 三档复用,不再无条件新建会话,见下方 1.5.33 条目);**1.5.34 已发布**(纯测试修复:`presence-clock` 跨午夜偶发失败,`lib/` 零改动,见下方 1.5.34 条目);**1.5.35 已发布**(`feishu_status` 新增最近入站路由回看 `inboundRouting` 字段,见下方 1.5.35 条目);**1.5.36 已发布**(飞书连接状态失真修复,见下方 1.5.36 条目);**1.5.37 为本次发版版**(压缩前沉淀机制 precompact,见下方 1.5.37 条目;其 npm 发布状态以 registry 为准)。
|
|
6
6
|
>
|
|
7
7
|
> **环境标识约定(2026-11-10 新增)**:写版本条目/坑条目时,**顺手记录当时的 智能体工具-智能体模式-模型供应商-模型**(如 **DSH-创造模式-loomy讯飞-GLM5.3FLASH**),写在条目内(紧跟 git 记录行、或坑条目首行),方便回溯该条目是在哪套智能体/模型环境下产出与验证的。
|
|
8
8
|
|
|
@@ -10,15 +10,70 @@
|
|
|
10
10
|
|
|
11
11
|
---
|
|
12
12
|
|
|
13
|
-
## 1.5.
|
|
13
|
+
## 1.5.37(2026-11-12 新增:压缩前沉淀机制 precompact——先保知识,再清流水)
|
|
14
14
|
|
|
15
15
|
- 环境:DSH-执行智能体(DeepSeek Harness 子会话,模型名未确证)
|
|
16
|
+
- **改了什么(只动 `lib/` + `cordis.patch.yml` 挂载 + 新增测试,无对外行为变更)**:
|
|
17
|
+
- `lib/precompact.js`(新增,`aiyayi-precompact`):压缩前沉淀检查层。在 `dsh-compaction-basic` 真正动手压缩**之前**,把当前会话「值得沉淀但还没落盘」的内容(任务闭环 / 关键结论 / 可量化数据 / 新经验)先写成 经验文档(docs/)+ 记忆(memories/ 分类档案)+ 更新 memory.md 索引,让压缩只负责清流水,摘要变成「指向落盘位置的索引」而非裸内容。**不重写 DSH 压缩器核心**;一切动作包 try/catch,沉淀失败**绝不阻塞主流程**(出问题只 warn 跳过、压缩照常跑——与 feishu/weixin「加载失败只禁用不炸」同一思路)。
|
|
18
|
+
- 触发时机:**时机A(接近阈值)**——agent/pre-step 钩子里量一次 token,上下文估算量 ≥ `ratio × thresholdTokens`(默认 0.7,每会话最多一次)时对当前会话做一次沉淀检查,thresholdTokens 复刻 dsh-compaction-basic 公式;**时机B(收尾/显式)**——工具入口 `precompact_run`(`lib/own-tools.js` 白名单已加,本体收尾/update_state 前后随时可调)。
|
|
19
|
+
- 判断「值得沉淀」:落到阿依娅伊已有行为铁律的启发式(任务闭环 / 关键结论 / 可量化数据 / 新经验),keyword 与开关可配置。
|
|
20
|
+
- 沉淀动作三件套(路径可注入、不硬编码):① 写经验文档 `docsDir`(默认记忆根下 docs/)② 写记忆 `memories/<分类>/…`(默认 `事情/经验`)③ 更新 `memory.md` 的 `<!-- 索引 -->` 段(追加「分类: 标题 → 文档路径」)。
|
|
21
|
+
- `cordis.patch.yml` preset-aiyayi 挂载 `aiyayi-precompact`(config:ratio 0.7 / thresholdRatio 0.4 / headroomTokens 32768 / memoryPath 事情/经验 / updateIndex true;docsDir 不设 = 默认记忆根 docs/)。
|
|
22
|
+
- `package.json`:exports 与 files 白名单加 `./precompact` / `lib/precompact.js`。
|
|
23
|
+
- **为什么**:上下文逼近压缩阈值时,dsh-compaction-basic 直接压缩会把「值得沉淀的任务闭环/结论/新经验」从上下文里冲掉;先落盘再压缩,知识不随流水一起丢。
|
|
24
|
+
- **测试**:新增 `test/precompact.test.mjs`(临时沙盘造记忆根、指路文件隔离,绝不碰真实记忆目录)。覆盖:值得沉淀启发式(该留的留、该丢的丢)、沉淀动作三件套落盘、工具注册 schema 合规且名字进 own-tools 白名单、`runPrecompact` 主入口(显式 content 落盘 / 弱内容跳过 / 失败不抛 = 沉淀失败不阻塞)、触发A阈值公式复刻 dsh-compaction-basic。
|
|
25
|
+
- **发版前置核验(并发撞号教训,本次实做)**:发版前先 `npm view dsh-aiyayi dist-tags`(latest=1.5.36,已被并发会话占用)+ `git fetch`(三远端在 b1704c0);1.5.36 已占用,故本版升为 **1.5.37**。
|
|
26
|
+
- 打包与 npm publish **不在本次范围**:本版只做版本号对齐 + 推 git(gitcode / gitee / github 三远端),打包与 npm 发布留作下一步单独执行。
|
|
27
|
+
|
|
28
|
+
## 1.5.35(2026-11-12 新增:`feishu_status` 最近入站路由回看 `inboundRouting` 字段)——**已发布(npm 2026-11-12T02:27:31Z)**
|
|
29
|
+
|
|
30
|
+
- 环境:DSH-执行智能体(DeepSeek Harness 子会话,模型名未确证)
|
|
31
|
+
- git:`a6df9e7`(代码)+ `d023c1a`(DEPLOY 文档);npm publish 由并发会话于 2026-11-12T02:27:31Z 完成,registry `gitHead=d023c1a`、shasum `45fc11369c0a5aa5c4ca2aa5290d1560cc59069a`。
|
|
32
|
+
|
|
16
33
|
- **改了什么(只动 `lib/` 与新增测试,无对外行为变更)**:
|
|
17
34
|
- `lib/feishu-logic.js`:新增 `INBOUND_ROUTING_FILE='inbound-routing.json'`、`INBOUND_ROUTING_LIMIT=20`、`readInboundRouting(root)`、`appendInboundRouting(root,{at,chatId,appId,action,sessionId})`(空 chatId 忽略;环形缓冲 新→旧 超 20 丢最旧;写入 feishu 子目录)。
|
|
18
35
|
- `lib/feishu.js`:`onIncomingMessage()` 各路由分支(select/route/auto-new/bind/new/reuse/choose/new-fallback)调用 `recordRouting(action,sessionId)`;`feishu_status` 返回新增 `inboundRouting` 字段(读 `readInboundRouting(root)`)。
|
|
19
36
|
- **为什么**:`feishu_status` 此前只报当前绑定/应用状态,看不到最近入站消息被路由到哪个会话、怎么路由的,排查"消息去哪了"要翻日志;回看字段让最近的入站路由一目了然(新→旧,上限 20 条)。
|
|
20
37
|
- **测试**:新增 `test/feishu-inbound-routing.test.mjs`(本文件单跑全过);全量 159 项 3 挂 = 既有环境基线(`alarm-inject`/`home-relocate`/`tools-surface` 磁盘探测,非本次引入,与 1.5.21/1.5.22/1.5.27 条目同基线)。
|
|
21
|
-
-
|
|
38
|
+
- 发布:npm publish 由并发会话完成(2026-11-12T02:27:31Z),打包 47 files / packed 349.2 kB。
|
|
39
|
+
- **本版不含连接状态修复**:同一时间另一条工作线在做 `connected` 实时化(见 1.5.36)。两笔改动在 git 上合并后,1.5.35 的 npm 包**先于合并**被发布,故不含后者——这也是 1.5.36 单独发版的原因。
|
|
40
|
+
|
|
41
|
+
## 1.5.36(2026-11-12 修复:飞书连接状态失真——`connected` 在断开/重连期间从不回写)
|
|
42
|
+
|
|
43
|
+
- 环境:DSH-执行智能体(DeepSeek Harness 子会话,模型名未确证)
|
|
44
|
+
- **为什么单独发一版**:本修复原计划随 1.5.35 发布,但 1.5.35 已被一个并发会话抢先 `npm publish`(2026-11-12T02:27:31Z,内容只有 `inboundRouting`)。npm 不允许同版本重发,而线上包仍在报假 `connected: true`(用户被误导"飞书一切正常"),所以按"修复必须真到达用户"的原则升为 **1.5.36** 单独发布。代码层面两笔改动早已合并(git 上同一棵树),差异只在版本号与发布时机。
|
|
45
|
+
|
|
46
|
+
- 症状:`feishu_status` 的 `connected` 自首次建连成功后恒为 `true`,即使长连接早已断开、SDK 正在重连也照报在线。2026-11-11 日志里 `[ws] reconnect` 出现 **326 次**(平均 124.5 秒一次,与 SDK 的 120s + 0~30s 抖动重连定时器吻合),期间 `feishu_status` 一直报 `connected: true`,用户被误导成"飞书一切正常"。
|
|
47
|
+
- **根因(源码定位,不是推测)**:`lib/feishu.js` 旧 441-448 行只在 `channel.connect().then()` 里写 `state.connected = true`,**之后没有任何回写**。全仓 grep `onReconnecting|onReconnected|onError` → **0 处命中**。而 `feishu_status`(旧 1447/1453 行)读的就是这个粘性值:`connected: state ? state.connected === true : false`。SDK 的自动重连是在 WS 内部循环里完成的,插件从未被告知。
|
|
48
|
+
- **SDK 取证(@larksuiteoapi/node-sdk 1.76.0,`lib/index.js` 实读行号)**:
|
|
49
|
+
- `WSClient` 构造参数收 `onReady / onError / onReconnecting / onReconnected`(102422),存成实例字段(102446-102449)。
|
|
50
|
+
- `reConnect()`:打 `[ws] reconnect` 日志后 `if (this.hasEverConnected) safeInvoke('onReconnecting', ...)`(102759-102762);重连循环成功 → `safeInvoke('onReconnected', ...)`(102787-102792);重试耗尽/不可恢复错误 → `safeInvoke('onError', ...)`(102735-102741、102800-102815)。
|
|
51
|
+
- `createLarkChannel` 建 WSClient 时把 `onReconnecting/onReconnected` 转成 `handlers.reconnecting/reconnected`(106988-106989),即公开 API `channel.on('reconnecting'|'reconnected', fn)`(107021-107032)。
|
|
52
|
+
- **`onError` 没有转发**(106981-106986)——它只在首次握手前用于 reject `connect()`,之后重连耗尽的 `onError` 无处可去。所以错误改从 `channel.rawWsClient.onError`(实例字段,106961 建)上再包一层拿。
|
|
53
|
+
- 兜底:`channel.getConnectionStatus()`(107017-107020 → WSClient 102982)返回 `{state: 'connected'|'reconnecting'|'connecting'|'idle'|'failed', lastConnectTime, nextConnectTime, reconnectAttempts}`。
|
|
54
|
+
- 注意:SDK 的 `safeInvoke` 会吞回调异常(102543-102552),所以插件侧回调必须自己 try/catch + 日志,否则出错无声。
|
|
55
|
+
- 修法(分两层,纯逻辑与接线分离):
|
|
56
|
+
1. **新增纯状态机**(`lib/feishu-logic.js`,零外部依赖、可单测):`createConnectState()` / `noteConnectEstablished()` / `noteDisconnect()` / `noteConnectError()` / `reconnectsWithinWindow()` / `evaluateConnectHealth()` / `describeConnectState()` / `reconcileConnectState()`。状态字段:`connected / connectedAt / lastDisconnectAt / lastDisconnectReason / reconnectCount / reconnectTimestamps / error / lastError / lastErrorAt / everConnected`。
|
|
57
|
+
2. **接线**(`lib/feishu.js`):`wireConnectEvents()` 在 `connect()` 成功后挂 `channel.handlers.reconnecting`(断连 → `connected=false` + `lastDisconnectAt` + 原因 `ws-reconnecting`)、`channel.handlers.reconnected`(重连成功 → `connected=true`、更新 `connectedAt`、`reconnectCount++` + 窗口计数,并打一行"累计 N 次 / 5 分钟内 M 次"),并包 `channel.rawWsClient.onError`(错误 → `lastError` + 日志,同时仍调用 SDK 原 `onError` 不破坏其行为)。插件卸载时把状态落成 `connected=false / plugin-dispose`,热重启窗口里不再报假在线。
|
|
58
|
+
- `feishu_status` 返回扩展(**旧字段一个不少,只新增**):
|
|
59
|
+
- 顶层新增 `healthy`、`connectedAt`、`lastDisconnectAt`、`reconnectCount`、`lastError`、`reconnectsInLast5m`、`unhealthyApps`,以及不健康时的可读 `warning`("长连接不稳定,最近 5 分钟内重连 X 次——飞书消息可能延迟或漏收。");未配置凭证时 `warning` 给"长连接未启动"。
|
|
60
|
+
- `apps[]` 每条新增 `connectedAt / lastDisconnectAt / lastDisconnectReason / reconnectCount / reconnectsInLastWindow / lastError / lastErrorAt / healthy / healthHint`;旧 `appId / connected / chatsOwned / error` 原样保留。
|
|
61
|
+
- **`connected` 语义改为实时**(事件驱动 + 读时用 `getConnectionStatus()` 快照对账纠偏;对账只纠布尔字段,不动 `reconnectCount`,避免与事件重复计数)。全仓 grep `connected` 确认无其它模块依赖"粘性 true"这一行为——只有 `feishu.js` 自己写、自己读,另加文档与测试描述,故改语义不破坏调用方。
|
|
62
|
+
- 健康判据:`healthy = connected && 最近 5 分钟内重连次数 ≤ 3`。**阈值取"超过 3 次"**(正好 3 次仍健康)。窗口靠时间戳数组滚动裁剪,读时裁(不污染累计 `reconnectCount`)。
|
|
63
|
+
- persona 同步(`cordis.patch.yml` 的【飞书】段):写明 `connected` 是**实时状态**、`healthy` 是**综合健康度**、`warning` 是插件告警;明确要求 `connected:false` 就说"长连接现在是断的",`connected:true` 但 `healthy:false` 要补一句"在线但不太稳",**别只看 `connected:true` 就宣布一切正常**。
|
|
64
|
+
- 测试:新增 `test/feishu-status.test.mjs`(单文件 9 组断言段、A–I),覆盖任务要求的六项并加码:
|
|
65
|
+
- A 初始未连接(`connected=false`、`connectedAt=null`、`healthy=false`);B 建连成功 → `connected=true`;C 断连 → `connected=false` + `lastDisconnectAt`/原因有值;D 重连成功 → `connected=true` + `reconnectCount` 递增 + `connectedAt` 更新(并断言不停留在首次建连);E 5 分钟内重连超 3 次 → `healthy=false` + 提示文案,且阈值边界(正好 3 次)仍健康、窗口滑过后恢复健康、累计计数不因窗口滑动回退;F 错误 → `lastError` 有值(Error / 字符串 / LarkChannelError 形态均可),且"连上清 `error` 但保留 `lastError`";G 快照对账正反向纠偏 + 未知快照不猜;H 接线静态核对(**反向断言**:`.then(() => { state.connected = true` 的旧写法必须已消失)。
|
|
66
|
+
- **I 段走真实 `apply()` + 假 WS 事件序列**:`channel.handlers.reconnecting()` → `feishu_status` 必须立刻报 `connected:false`(即本 bug 的核心回归断言),`handlers.reconnected()` → 回 true 且计数递增,4 次抖动 → `healthy:false` + 顶层 `warning`、`unhealthyApps`,`rawWsClient.onError` → `lastError`,卸载 → 不再报在线;另断言 1.5.34 的 10 个旧字段一个不少。
|
|
67
|
+
- **测试隔离方式(重要,避免重踩坑 #76)**:本测试用 `node:module` 的 `registerHooks()` **进程内 loader 钩子**替换 `@larksuiteoapi/node-sdk` / `@deepseek-ai/dsh-llm`,**不落任何文件到 `node_modules`**。`test/feishu-accumulate.test.mjs` 用的是"落盘桩、已存在不覆盖",两文件并发跑会互抢同一批桩目录(本次开发中实锤触发过:accumulate 挂 `Cannot read properties of undefined (reading 'push')`)。进程内钩子从根上避开这一类并发污染。
|
|
68
|
+
- 全量单测 `node --test "test/*.test.mjs"`:**159 项全通过 / 0 失败**(1.5.34 基线 158,本版新增 `test/feishu-status.test.mjs` 一项)。连跑 3 遍均 159/0,且跑完 `node_modules` 目录不存在(无桩残留)。
|
|
69
|
+
- 另有独立取证脚本 `test/feishu-status-proof.mjs`(文件名不带 `.test.mjs`,**不进全量通配**):按 SDK 真实时序喂一串假 WS 事件(首次建连 → 抖动断连 → 重连成功 → 4 轮抖动风暴 → 重试耗尽 → 恢复),逐步打印 feishu_status 可见字段并断言。实跑输出 `exit 0`:`connected=true/healthy=true → false/false(断连)→ true/true 且 reconnectCount=1 → true/false 且 5min=5 → false/false + lastError → 窗口滑过后 healthy=true`,`PROVEN`。
|
|
70
|
+
- 取证脚本开发中自身纠正一次:最初「5 分钟窗口」把断连也推进了 120s,导致 4 轮抖动摊到 10 分钟外、`healthHint` 为 null——说明窗口裁剪逻辑正常工作,抖动必须真的密集才判不健康(把每轮压到 20s 内后如期触发)。
|
|
71
|
+
- 新文件均无 BOM。
|
|
72
|
+
- 未包含:SDK 事件里拿不到 close code / reason(`wsInstance.on('close', ...)` 在 SDK 内部只打 debug 日志、不回传参数,102873-102877),所以 `lastDisconnectReason` 记的是插件侧归因(`ws-reconnecting` / `sdk-state:<state>` / `plugin-dispose`),不是飞书的原始关闭码。
|
|
73
|
+
|
|
74
|
+
- **教训(并发发版会撞车,写在这供后来人省事)**:本版差点与另一条会话同时发同一个版本号——那边 10:21 推代码、10:27 直接 `npm publish 1.5.35`,而本会话 10:29 才 push,回查 registry 才发现版本号已被占。**以后发版前必须先查两处再动手:`npm view dsh-aiyayi dist-tags`(看 latest 有没有被抢)与 `git fetch <remote> && git log HEAD..<remote>/main`(看远端有没有新提交)**,不要闷头改完就直接 `git push` + `npm publish`。npm 的版本号是**全局不可逆**的,一旦被别人占了,只能改号重发,白折腾一轮。并发会话之间尤其要约定:改版本号属于"抢占式操作",先查后占。
|
|
75
|
+
- 版本号三处对齐:`package.json` version、本条目、profile `cordis.patch.yml` 里 `aiyayi-feishu` 的 `config.reloadTag` 均为 `1.5.36`(profile 已先备份为 `cordis.patch.yml.bak-1.5.36-20261112-104808`)。
|
|
76
|
+
- **与 1.5.35 的共存验证**(合并冲突解决后专门做的,不只看测试绿):用真实形状的 `inbound-routing.json`(3 条记录)跑 `feishu_status`,断言 ① 记录原样读出、顺序新→旧、`sessionId: null` 保留;② `healthy` 从 true→false→断连三次翻转时,`inboundRouting` **逐字节不变**(`JSON.stringify` 比对相同)。`healthy` 只读连接状态机、不读入站数据,两条数据通路互不干扰。23 项断言全过。
|
|
22
77
|
|
|
23
78
|
## 1.5.34(2026-11-12 修复:`presence-clock.test.mjs` 跨午夜偶发失败——**只改测试,无运行时行为变化**)
|
|
24
79
|
|
package/README.md
CHANGED
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
| 自我状态(体检单) | 同上 `aiyayi-presence`(v1.2.0 起) | `session/event` 总线折叠真实运行数据:模型与思考档、上下文用量(provider 实测 usage 优先,tokenMeter 估算兜底并标"估算")、缓存命中率、上轮输出 tok/s、本会话轮数、上轮异常。变化明显(≥2048 token / 模型切换 / 异常)才注入,不每轮白涨。用量过八成/九成(估算口径按中文偏差 ÷0.49 校准,见坑 #16)注入 `[上下文提醒]`:劝用户开新会话、并让用户走之前说一声好让她收尾(update_state/补记忆/把话说完);每档只提醒一次 |
|
|
21
21
|
| 主动开口 | `tool-schedule`(dsh 原生)+ persona 指引 | 到期提醒会把冷会话真唤醒、以 user 消息落进定闹钟的那个会话——她想主动说话就 `schedule_create` 定闹钟;DSH 没开着会存着、下次启动补投 |
|
|
22
22
|
| 新版本提醒 | 自写插件 `aiyayi-updates`(本包 `lib/updates.js`) | 每个会话第一个回合查一次 npm(registry.npmjs.org,失败落 npmmirror;成功结果缓存 6h、失败 30min 后重试):本地版本比 latest 旧时,往消息尾部追加 `[更新提示]` 快照,她会用自己的口吻顺口提一句。同一远端版本只提醒一次(updates.json 落盘去重,跨重启不重复念叨);检查失败/离线一律静默。**判据:`~\\.dsh\\aiyayi\\updates.json` 不存在 = 从没发现过新版(本地已是最新);她答不上"自己是什么版本"是设计边界(升级判断靠被动推送),已由 presence 的版本自述补上** |
|
|
23
|
-
| 飞书桥接 | 自写插件 `aiyayi-feishu`(本包 `lib/feishu.js`,1.5.8 起)+ 纯逻辑 `lib/feishu-logic.js` | 长连接 WebSocket 接入飞书机器人(SDK `@larksuiteoapi/node-sdk`,无需公网)。**2026-11-10 扫码改造**:新会话说「接入飞书」→ 引导出待接入目标 → 手机飞书扫码进 bot 单聊 → `bot_p2p_chat_entered_v1` 事件自动绑定(30 分钟时效);凭证 `feishu/config.json` 存记忆根(**不入 npm 包**)。**发附件需权限 `im:resource`**(后台真实标识「获取与上传图片或文件资源」,免审)——开发者后台搜 **`im:resource:upload` 为 0 条,后台不存在这个独立 scope**,真名就是 `im:resource`(详见坑 #70 / #71
|
|
23
|
+
| 飞书桥接 | 自写插件 `aiyayi-feishu`(本包 `lib/feishu.js`,1.5.8 起)+ 纯逻辑 `lib/feishu-logic.js` | 长连接 WebSocket 接入飞书机器人(SDK `@larksuiteoapi/node-sdk`,无需公网)。**2026-11-10 扫码改造**:新会话说「接入飞书」→ 引导出待接入目标 → 手机飞书扫码进 bot 单聊 → `bot_p2p_chat_entered_v1` 事件自动绑定(30 分钟时效);凭证 `feishu/config.json` 存记忆根(**不入 npm 包**)。**发附件需权限 `im:resource`**(后台真实标识「获取与上传图片或文件资源」,免审)——开发者后台搜 **`im:resource:upload` 为 0 条,后台不存在这个独立 scope**,真名就是 `im:resource`(详见坑 #70 / #71)。**1.5.36 起状态不再失真**:`feishu_status` 的 `connected` 是**实时值**(接 SDK 的 `onReconnecting`/`onReconnected`/`onError`,断连/重连期间立刻变 false,并用 `getConnectionStatus()` 快照兜底对账),另给 `healthy`(在线 且 5 分钟内重连未超过 3 次)与 `warning`;`apps[]` 逐条带 `connectedAt` / `lastDisconnectAt` / `reconnectCount` / `lastError`(1.5.35 的 `inboundRouting` 入站路由回看同时保留) |
|
|
24
24
|
| 微信桥接 | 自写插件 `aiyayi-weixin`(本包 `lib/weixin.js` + `lib/weixin/`,1.5.27 起) | 微信 **ClawBot 机器人**通道(腾讯官方 iLink 协议,长轮询,无需公网)。**默认关闭**:profile patch 里 `weixin.enabled` 必须显式 `true` 才加载,`weixin.accounts` 写 `[{accountId, credentialRef}]`,凭证先 `weixin_login` 扫码拿(二维码 121 秒寿命)。工具 `weixin_status` / `weixin_login` / `weixin_bind` / `weixin_unbind`。`allowlist` 留空 = **只放行已显式绑定的用户**(与官方相反,陌生消息丢弃)。**没有 weixin-setup 技能** |
|
|
25
25
|
| **对接落到哪个会话(默认规则,1.5.32 固化 + 1.5.33 三档落地)** | `lib/feishu.js` 的 `pending-bind` + `lib/feishu-logic.js` 的 `decideUnboundChatRouting()` + `lib/weixin/accounts.js` 的 pending-bind | **对机器人默认落到「发起对接的那个会话」,能复用就复用、不新建**:会话 A 里说「接入飞书/微信」→ 待接入目标记的就是 A → 扫码/绑定成功后该 chat 绑回 A,聊天接着聊。只有用户明确说「新建会话」才新建;chat 从没走过对接、也没有待接入目标时程序会新建一个会话接住(**兜底,非首选**)。**1.5.33 起**一个从没绑过的 chat 发来第一条消息时按三档自动处理:① 恰好 1 个活跃真人会话 → 直接接过去并告知;② 多个活跃 → 不绑不建,回编号列表(`1. 会话名(工作区:xxx)`)让用户选,**不替他挑"最近那个"**(会话各带上下文,投错比多问一句糟糕);③ 0 个 → 才新建并明说。开关 `feishu.reuseActiveSession` 默认 `true`,设 `false` 回退 1.5.32 旧行为(一律新建)。这条同时写进 persona【飞书】【微信】两段,属行为约定而非可选配置 |
|
|
26
26
|
| 其他 | time-context、compaction 组(提前压缩,见坑 #14/#16)、tool-ask-user | 她没有 bash/文件/技能/搜索/网络工具,想动手只能派活;纯查资料走 `retriever` 检索员,不惊动小伙伴 |
|
|
@@ -72,8 +72,9 @@ npm 包为平铺结构(仓库若保留 bundle/ 子目录,发布时把其内
|
|
|
72
72
|
- `lib/net.js` — aiyayi-net 联网工具(aiyayi_fetch + aiyayi_cdp,node 内建能力实现,零外置依赖,挂小伙伴与检索员 preset)
|
|
73
73
|
- `lib/doc.js` — aiyayi-doc 文档解析插件(1.4.0,挂检索员 preset;ZIP/XML 最小解析零依赖 + 动态加载 shipped libreoffice-kit 做 pdf 页图与旧版转换)
|
|
74
74
|
- `lib/own-tools.js` — 她的工具名单单一真源(注册处登记、放行处判定,防手写白名单漂移)
|
|
75
|
+
- `lib/precompact.js` — aiyayi-precompact 压缩前沉淀检查插件(1.5.37;在 dsh-compaction-basic 动手压缩前,把值得沉淀的任务闭环/结论/新经验先落盘为经验文档+记忆+索引,失败不阻塞主流程;`precompact_run` 显式工具入口 + 接近阈值自动触发)
|
|
75
76
|
- `lib/feishu.js` — aiyayi-feishu 飞书桥接宿主插件(1.5.8 起;跨会话服务,长连接收消息、按指令路由到 aiyayi 会话、回发;凭读取记忆根 `feishu/config.json`)
|
|
76
|
-
- `lib/feishu-logic.js` —
|
|
77
|
+
- `lib/feishu-logic.js` — 飞书纯逻辑(路由/映射/文本抽取/三档复用决策/**长连接状态机**,无外部依赖,可单测;test/feishu-route.test.mjs、test/feishu-reuse-session.test.mjs、test/feishu-status.test.mjs 覆盖)
|
|
77
78
|
- `skills/feishu-setup/` — 内置技能(1.5.13 起随包自动同步到 DSH 技能根):飞书机器人安装/验证/排障全流程(含 2026-11-10 扫码接入改造说明;脚本 `scripts/create-bot.js` v5 等由技能同步维护)
|
|
78
79
|
- `README.md` — 本文档
|
|
79
80
|
- `icon.svg` — 头像
|
package/cordis.patch.yml
CHANGED
|
@@ -118,6 +118,15 @@
|
|
|
118
118
|
你有个飞书机器人入口(aiyayi-feishu 插件,长连接已常驻)。
|
|
119
119
|
**新建会话第一次开口,先自查对接情况**:调 feishu_status,看
|
|
120
120
|
本会话是不是已绑定某个飞书对话、还有哪些别的会话已绑定、长连接是否在运行。
|
|
121
|
+
读这个返回值时,三个字段各管一摊,别混着说(1.5.35 起):
|
|
122
|
+
`connected` 是**实时状态**——长连接真在线才 true,断开/重连期间就是 false
|
|
123
|
+
(SDK 的连接事件实时回写,不再是「连上过一次就一直 true」的假象);
|
|
124
|
+
`healthy` 是**综合健康度**——在线的同时最近 5 分钟重连次数没超阈值才算 true;
|
|
125
|
+
`warning` 有值时就是插件给的告警(比如"长连接不稳定,最近 5 分钟内重连 X 次")。
|
|
126
|
+
所以:`connected:false` 就说"长连接现在是断的,飞书消息这会儿可能收不到";
|
|
127
|
+
`connected:true` 但 `healthy:false` 要照实补一句"在线但不太稳,最近在反复重连",
|
|
128
|
+
**别只看 connected:true 就宣布一切正常**。逐应用细节在 `apps[]` 里
|
|
129
|
+
(每个 appId 的 connected/connectedAt/lastDisconnectAt/reconnectCount/lastError)。
|
|
121
130
|
没绑定也别让用户提供 chat_id——接入主要从飞书侧发起、自动完成:
|
|
122
131
|
**告诉用户在飞书里给机器人随便发一条消息,bot 会自动新建会话并接上**;
|
|
123
132
|
要接入指定的已有会话,就发 `绑定会话 <会话名>`。chat_id 由 bot 自己从
|
|
@@ -191,6 +200,20 @@
|
|
|
191
200
|
name: 'dsh-aiyayi/presence'
|
|
192
201
|
- id: aiyayi-updates
|
|
193
202
|
name: 'dsh-aiyayi/updates'
|
|
203
|
+
# 压缩前沉淀(1.5.37):在 dsh-compaction-basic 动手压缩前,把值得沉淀的
|
|
204
|
+
# 知识先落盘(docs/ 经验文档 + 记忆 + 索引),让压缩只清流水。时机A=接近
|
|
205
|
+
# 阈值自动触发(pre-step 量 token,ratio×threshold);时机B=本体用
|
|
206
|
+
# precompact_run 显式调用(收尾/update_state 前后)。ratio 0.7 是设计文档
|
|
207
|
+
# 建议的提前量;thresholdRatio/headroomTokens 复刻本 preset 的 compaction。
|
|
208
|
+
- id: aiyayi-precompact
|
|
209
|
+
name: 'dsh-aiyayi/precompact'
|
|
210
|
+
config:
|
|
211
|
+
ratio: 0.7
|
|
212
|
+
thresholdRatio: 0.4
|
|
213
|
+
headroomTokens: 32768
|
|
214
|
+
memoryPath: 事情/经验
|
|
215
|
+
# docsDir 不设 → 默认落记忆根下 docs/(可改成工作区 docs 目录)。
|
|
216
|
+
updateIndex: true
|
|
194
217
|
- id: aiyayi-restrict
|
|
195
218
|
name: 'dsh-aiyayi/restrict'
|
|
196
219
|
- id: time-context
|
package/lib/feishu-logic.js
CHANGED
|
@@ -2082,6 +2082,192 @@ export function writePendingQuestions(root, table) {
|
|
|
2082
2082
|
writeFileSync(join(dir, PENDING_QUESTIONS_FILE), JSON.stringify(table, null, 2), 'utf8')
|
|
2083
2083
|
}
|
|
2084
2084
|
|
|
2085
|
+
// ═══ 1.5.35:长连接状态机(纯逻辑,无 SDK 依赖) ═══
|
|
2086
|
+
//
|
|
2087
|
+
// 缺陷背景(1.5.34 及以前):feishu.js 只在 `channel.connect().then()` 里把
|
|
2088
|
+
// `connected` 置 true,之后**从无回写**。SDK 的自动重连(120s + 0~30s 抖动)
|
|
2089
|
+
// 期间状态仍报 true,用户被误导。1.5.35 接入 SDK 的连接事件(WSClient 的
|
|
2090
|
+
// `onReconnecting` / `onReconnected` / `onError`,经 LarkChannel 转成
|
|
2091
|
+
// `channel.on('reconnecting'|'reconnected')` + `channel.rawWsClient.onError`),
|
|
2092
|
+
// 事件驱动地回写,并在读 status 时用 `getConnectionStatus()` 快照兜底对账。
|
|
2093
|
+
|
|
2094
|
+
/** 健康度统计窗口:最近 5 分钟。 */
|
|
2095
|
+
export const CONNECT_HEALTH_WINDOW_MS = 5 * 60 * 1000
|
|
2096
|
+
/** 窗口内允许的最大重连次数,超过即判不健康。 */
|
|
2097
|
+
export const CONNECT_HEALTH_MAX_RECONNECTS = 3
|
|
2098
|
+
|
|
2099
|
+
/**
|
|
2100
|
+
* 新建一条应用的连接状态。字段全部是「可由事件累积出来的事实」:
|
|
2101
|
+
* connected 当前真实是否在线(事件驱动 + 快照对账)
|
|
2102
|
+
* connectedAt 最近一次成功建连的时间戳(ms)
|
|
2103
|
+
* lastDisconnectAt 最近一次断连的时间戳(ms)
|
|
2104
|
+
* lastDisconnectReason 最近一次断连原因(SDK 事件不带 close code,见 feishu.js 注释)
|
|
2105
|
+
* reconnectCount 累计重连成功次数(首次建连不算)
|
|
2106
|
+
* reconnectTimestamps 重连成功的时间戳数组(滚动窗口用,读取时裁剪)
|
|
2107
|
+
* error 当前错误(成功建连即清空,兼容旧字段语义)
|
|
2108
|
+
* lastError/lastErrorAt 最近一次错误(成功不清空,供事后追查)
|
|
2109
|
+
*/
|
|
2110
|
+
export function createConnectState() {
|
|
2111
|
+
return {
|
|
2112
|
+
connected: false,
|
|
2113
|
+
connectedAt: null,
|
|
2114
|
+
lastDisconnectAt: null,
|
|
2115
|
+
lastDisconnectReason: null,
|
|
2116
|
+
reconnectCount: 0,
|
|
2117
|
+
reconnectTimestamps: [],
|
|
2118
|
+
error: null,
|
|
2119
|
+
lastError: null,
|
|
2120
|
+
lastErrorAt: null,
|
|
2121
|
+
everConnected: false,
|
|
2122
|
+
}
|
|
2123
|
+
}
|
|
2124
|
+
|
|
2125
|
+
/** 错误 → 一行文本(SDK 抛 Error / LarkChannelError / 字符串都能吃)。 */
|
|
2126
|
+
function connectErrorText(error) {
|
|
2127
|
+
if (error === null || error === undefined) return null
|
|
2128
|
+
if (typeof error === 'string') return error
|
|
2129
|
+
const message = error?.message !== undefined ? String(error.message) : String(error)
|
|
2130
|
+
return message || String(error)
|
|
2131
|
+
}
|
|
2132
|
+
|
|
2133
|
+
/**
|
|
2134
|
+
* 建连成功(首次 connect 成功 / 重连成功)。
|
|
2135
|
+
* `reconnected` 为 true 时计入 reconnectCount 与窗口。
|
|
2136
|
+
*/
|
|
2137
|
+
export function noteConnectEstablished(state, { now = Date.now(), reconnected = false, windowMs = CONNECT_HEALTH_WINDOW_MS } = {}) {
|
|
2138
|
+
if (!state) return null
|
|
2139
|
+
state.connected = true
|
|
2140
|
+
state.connectedAt = now
|
|
2141
|
+
state.error = null // 旧字段语义:连上就清「当前错误」
|
|
2142
|
+
if (reconnected) {
|
|
2143
|
+
state.reconnectCount = (state.reconnectCount || 0) + 1
|
|
2144
|
+
const stamps = Array.isArray(state.reconnectTimestamps) ? state.reconnectTimestamps : []
|
|
2145
|
+
stamps.push(now)
|
|
2146
|
+
state.reconnectTimestamps = pruneReconnectStamps(stamps, now, windowMs)
|
|
2147
|
+
}
|
|
2148
|
+
// 首次建连不计入 reconnectCount(reconnected=false 分支什么都不做)。
|
|
2149
|
+
state.everConnected = true
|
|
2150
|
+
return state
|
|
2151
|
+
}
|
|
2152
|
+
|
|
2153
|
+
/** 断连(SDK onReconnecting / 快照对账 / 插件卸载)。reason 可空。 */
|
|
2154
|
+
export function noteDisconnect(state, { now = Date.now(), reason = null } = {}) {
|
|
2155
|
+
if (!state) return null
|
|
2156
|
+
state.connected = false
|
|
2157
|
+
state.lastDisconnectAt = now
|
|
2158
|
+
if (reason) state.lastDisconnectReason = reason
|
|
2159
|
+
return state
|
|
2160
|
+
}
|
|
2161
|
+
|
|
2162
|
+
/** 出错(SDK onError:握手失败 / 重试耗尽 / 不可恢复配置错误)。 */
|
|
2163
|
+
export function noteConnectError(state, { now = Date.now(), error = null } = {}) {
|
|
2164
|
+
if (!state) return null
|
|
2165
|
+
const text = connectErrorText(error)
|
|
2166
|
+
state.connected = false
|
|
2167
|
+
state.error = text
|
|
2168
|
+
state.lastError = text
|
|
2169
|
+
state.lastErrorAt = now
|
|
2170
|
+
return state
|
|
2171
|
+
}
|
|
2172
|
+
|
|
2173
|
+
/** 裁掉窗口外的重连时间戳(就地返回新数组)。 */
|
|
2174
|
+
export function pruneReconnectStamps(stamps, now = Date.now(), windowMs = CONNECT_HEALTH_WINDOW_MS) {
|
|
2175
|
+
const list = Array.isArray(stamps) ? stamps : []
|
|
2176
|
+
const cutoff = now - windowMs
|
|
2177
|
+
return list.filter((t) => typeof t === 'number' && t > cutoff)
|
|
2178
|
+
}
|
|
2179
|
+
|
|
2180
|
+
/** 窗口内重连成功次数。 */
|
|
2181
|
+
export function reconnectsWithinWindow(state, { now = Date.now(), windowMs = CONNECT_HEALTH_WINDOW_MS } = {}) {
|
|
2182
|
+
if (!state) return 0
|
|
2183
|
+
return pruneReconnectStamps(state.reconnectTimestamps, now, windowMs).length
|
|
2184
|
+
}
|
|
2185
|
+
|
|
2186
|
+
/**
|
|
2187
|
+
* 综合健康度:在线 且 窗口内重连次数未超过阈值。
|
|
2188
|
+
* 返回 { healthy, reconnectsInWindow, windowMinutes, hint }。
|
|
2189
|
+
* hint 只在「在线但重连过频」或「重连过频」时给出可读提示。
|
|
2190
|
+
*/
|
|
2191
|
+
export function evaluateConnectHealth(
|
|
2192
|
+
state,
|
|
2193
|
+
{ now = Date.now(), windowMs = CONNECT_HEALTH_WINDOW_MS, maxReconnects = CONNECT_HEALTH_MAX_RECONNECTS } = {},
|
|
2194
|
+
) {
|
|
2195
|
+
const reconnectsInWindow = reconnectsWithinWindow(state, { now, windowMs })
|
|
2196
|
+
const connected = state?.connected === true
|
|
2197
|
+
const tooMany = reconnectsInWindow > maxReconnects
|
|
2198
|
+
const healthy = connected && !tooMany
|
|
2199
|
+
let hint = null
|
|
2200
|
+
if (tooMany) {
|
|
2201
|
+
const minutes = Math.max(1, Math.round(windowMs / 60000))
|
|
2202
|
+
hint = `长连接不稳定,最近 ${minutes} 分钟内重连 ${reconnectsInWindow} 次`
|
|
2203
|
+
}
|
|
2204
|
+
return { healthy, reconnectsInWindow, windowMinutes: Math.max(1, Math.round(windowMs / 60000)), hint }
|
|
2205
|
+
}
|
|
2206
|
+
|
|
2207
|
+
/** 时间戳 → ISO 字符串(空值原样返回 null)。 */
|
|
2208
|
+
function isoTime(value) {
|
|
2209
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return null
|
|
2210
|
+
return new Date(value).toISOString()
|
|
2211
|
+
}
|
|
2212
|
+
|
|
2213
|
+
/**
|
|
2214
|
+
* 状态机 → feishu_status 的 apps[] 视图(新增字段,不覆盖旧字段)。
|
|
2215
|
+
* 旧字段只有 appId/connected/chatsOwned/error,这里补齐 connectedAt /
|
|
2216
|
+
* lastDisconnectAt / reconnectCount / lastError / healthy 等。
|
|
2217
|
+
*/
|
|
2218
|
+
export function describeConnectState(
|
|
2219
|
+
state,
|
|
2220
|
+
{ now = Date.now(), windowMs = CONNECT_HEALTH_WINDOW_MS, maxReconnects = CONNECT_HEALTH_MAX_RECONNECTS } = {},
|
|
2221
|
+
) {
|
|
2222
|
+
const health = evaluateConnectHealth(state, { now, windowMs, maxReconnects })
|
|
2223
|
+
return {
|
|
2224
|
+
connected: state?.connected === true,
|
|
2225
|
+
connectedAt: isoTime(state?.connectedAt),
|
|
2226
|
+
lastDisconnectAt: isoTime(state?.lastDisconnectAt),
|
|
2227
|
+
lastDisconnectReason: state?.lastDisconnectReason ?? null,
|
|
2228
|
+
reconnectCount: typeof state?.reconnectCount === 'number' ? state.reconnectCount : 0,
|
|
2229
|
+
reconnectsInLastWindow: health.reconnectsInWindow,
|
|
2230
|
+
lastError: state?.lastError ?? null,
|
|
2231
|
+
lastErrorAt: isoTime(state?.lastErrorAt),
|
|
2232
|
+
healthy: health.healthy,
|
|
2233
|
+
healthHint: health.hint,
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
|
|
2237
|
+
/**
|
|
2238
|
+
* 用 SDK 的 `getConnectionStatus()` 快照对账(belt & braces):
|
|
2239
|
+
* 事件可能因插件热重启/极短断连而漏记,读 status 时用 SDK 的真实
|
|
2240
|
+
* state(connected / reconnecting / connecting / idle / failed)纠偏。
|
|
2241
|
+
* 只在布尔字段上纠偏,不动 reconnectCount(避免与事件重复计数)。
|
|
2242
|
+
*
|
|
2243
|
+
* 返回 'connected' | 'disconnected' | null(null = 无变化/无快照)。
|
|
2244
|
+
*/
|
|
2245
|
+
export function reconcileConnectState(state, sdkStatus, { now = Date.now() } = {}) {
|
|
2246
|
+
if (!state || !sdkStatus || typeof sdkStatus !== 'object') return null
|
|
2247
|
+
const sdkState = sdkStatus.state
|
|
2248
|
+
if (sdkState === 'connected') {
|
|
2249
|
+
if (state.connected === true) return null
|
|
2250
|
+
state.connected = true
|
|
2251
|
+
if (!state.connectedAt) state.connectedAt = typeof sdkStatus.lastConnectTime === 'number' ? sdkStatus.lastConnectTime : now
|
|
2252
|
+
state.error = null
|
|
2253
|
+
state.everConnected = true
|
|
2254
|
+
return 'connected'
|
|
2255
|
+
}
|
|
2256
|
+
if (sdkState === 'reconnecting' || sdkState === 'idle' || sdkState === 'failed' || sdkState === 'connecting') {
|
|
2257
|
+
if (state.connected !== true) {
|
|
2258
|
+
// 已经是断开态:只补 lastDisconnectAt(且只在「曾经连上过」时补,
|
|
2259
|
+
// 否则首次 connect() 之前就对账会凭空造出一条断开记录)。
|
|
2260
|
+
if (state.everConnected && !state.lastDisconnectAt) state.lastDisconnectAt = now
|
|
2261
|
+
return null
|
|
2262
|
+
}
|
|
2263
|
+
state.connected = false
|
|
2264
|
+
state.lastDisconnectAt = now
|
|
2265
|
+
state.lastDisconnectReason = state.lastDisconnectReason ?? `sdk-state:${sdkState}`
|
|
2266
|
+
return 'disconnected'
|
|
2267
|
+
}
|
|
2268
|
+
return null
|
|
2269
|
+
}
|
|
2270
|
+
|
|
2085
2271
|
/** 待答记录的有效期(毫秒):超时后仍保留一段时间供迟到回答,之后清理。 */
|
|
2086
2272
|
export const PENDING_QUESTION_TTL_MS = 24 * 60 * 60 * 1000
|
|
2087
2273
|
|
package/lib/feishu.js
CHANGED
|
@@ -77,6 +77,13 @@ import {
|
|
|
77
77
|
readPendingBind,
|
|
78
78
|
readPendingQuestions,
|
|
79
79
|
reverseLookup,
|
|
80
|
+
createConnectState,
|
|
81
|
+
describeConnectState,
|
|
82
|
+
evaluateConnectHealth,
|
|
83
|
+
noteConnectError,
|
|
84
|
+
noteConnectEstablished,
|
|
85
|
+
noteDisconnect,
|
|
86
|
+
reconcileConnectState,
|
|
80
87
|
routeMessage,
|
|
81
88
|
sendReplyWithAttachments,
|
|
82
89
|
writeChatOwners,
|
|
@@ -164,7 +171,7 @@ export function apply(ctx, config) {
|
|
|
164
171
|
const apps = normalizeApps(merged)
|
|
165
172
|
// 工具 execute 时才用得到的基础设施句柄(先注册后建连——无凭证也要能 status 自查,
|
|
166
173
|
// 所以用可变 holder 中转,连接层建好后回填)。
|
|
167
|
-
const sendInfra = { connectStates: null, resolveChannelForChat: null }
|
|
174
|
+
const sendInfra = { connectStates: null, channels: null, resolveChannelForChat: null }
|
|
168
175
|
|
|
169
176
|
// 先注册工具(即使没有凭证,aiyayi 也能用 feishu_status 自查绑定情况)。
|
|
170
177
|
registerFeishuTools(ctx, root, merged, apps, sendInfra)
|
|
@@ -214,9 +221,10 @@ export function apply(ctx, config) {
|
|
|
214
221
|
// 收发都报 230002「Bot/User can NOT be out of the chat」),所以一切主动推送
|
|
215
222
|
// 前必须先解析 chat→app 归属,用目标 chat 所属应用(= chat 成员)的凭证发送。
|
|
216
223
|
const channels = new Map() // appId → LarkChannel
|
|
217
|
-
|
|
224
|
+
// 1.5.35:连接状态由事件驱动回写(见 feishu-logic.js 的 createConnectState)。
|
|
225
|
+
const connectStates = new Map() // appId → createConnectState() 结构
|
|
218
226
|
for (const app of apps) {
|
|
219
|
-
connectStates.set(app.appId,
|
|
227
|
+
connectStates.set(app.appId, createConnectState())
|
|
220
228
|
}
|
|
221
229
|
|
|
222
230
|
// messageId 去重:同一 chat 若同时是多个 bot 的成员(群聊场景),同一条消息会
|
|
@@ -325,6 +333,8 @@ export function apply(ctx, config) {
|
|
|
325
333
|
const channelForApp = (appId) => (appId && channels.get(appId)) || null
|
|
326
334
|
// 回填工具层句柄(feishu_status 报每条长连接状态;feishu_bind 发送前探测归属)。
|
|
327
335
|
sendInfra.connectStates = connectStates
|
|
336
|
+
// 1.5.35:status 读时用 channel.getConnectionStatus() 对账(事件可能漏记)。
|
|
337
|
+
sendInfra.channels = channels
|
|
328
338
|
sendInfra.resolveChannelForChat = resolveChannelForChat
|
|
329
339
|
|
|
330
340
|
for (const app of apps) {
|
|
@@ -435,6 +445,75 @@ export function apply(ctx, config) {
|
|
|
435
445
|
channels.set(app.appId, channel)
|
|
436
446
|
}
|
|
437
447
|
|
|
448
|
+
/**
|
|
449
|
+
* 1.5.35:把 SDK 的连接事件接到状态机上(事件驱动回写,替换 1.5.34 的「只置一次
|
|
450
|
+
* true、从不回写」)。
|
|
451
|
+
*
|
|
452
|
+
* SDK 证据(@larksuiteoapi/node-sdk 1.76.0,lib/index.js):
|
|
453
|
+
* - `WSClient` 构造参数收 `onReady/onError/onReconnecting/onReconnected`
|
|
454
|
+
* (102422),存到实例字段(102446-102449)。
|
|
455
|
+
* - `reConnect()` 里:`this.logger.info('[ws]','reconnect')` 之后
|
|
456
|
+
* `if (this.hasEverConnected) safeInvoke('onReconnecting', ...)`(102759-102762);
|
|
457
|
+
* 重连循环成功时 `safeInvoke('onReconnected', ...)`(102787-102792);
|
|
458
|
+
* 重试耗尽 / 不可恢复错误时 `safeInvoke('onError', ...)`(102735-102741、102800-102815)。
|
|
459
|
+
* - `createLarkChannel` 建 WSClient 时把 `onReconnecting/onReconnected` 转成
|
|
460
|
+
* `handlers.reconnecting/reconnected`(106988-106989),即公开 API
|
|
461
|
+
* `channel.on('reconnecting'|'reconnected', fn)`(107021-107032)。
|
|
462
|
+
* - **`onError` 没有被转发**(106981-106986 只在首次握手前 reject connect(),
|
|
463
|
+
* 之后重试耗尽的 onError 无处可去)。所以错误改从
|
|
464
|
+
* `channel.rawWsClient.onError` 上**再包一层**拿(rawWsClient 在 106961 建、
|
|
465
|
+
* 公开字段),插件侧包装不改 SDK 行为。
|
|
466
|
+
* - 兜底:`channel.getConnectionStatus()`(107017-107020 → WSClient 102982)
|
|
467
|
+
* 给出 {state:'connected'|'reconnecting'|'connecting'|'idle'|'failed',
|
|
468
|
+
* lastConnectTime, nextConnectTime, reconnectAttempts},读 status 时对账。
|
|
469
|
+
* - 注意:SDK 的 `safeInvoke` 会吞掉回调异常(102543-102552),所以回调里
|
|
470
|
+
* 必须自己 try/catch + 日志,否则出错无声。
|
|
471
|
+
*/
|
|
472
|
+
function wireConnectEvents(appId, channel, state) {
|
|
473
|
+
// ① 重连开始(= 已经断开)。SDK 只在「曾经连上过」时才发这个事件。
|
|
474
|
+
channel.handlers.reconnecting = () => {
|
|
475
|
+
try {
|
|
476
|
+
noteDisconnect(state, { reason: 'ws-reconnecting' })
|
|
477
|
+
ctx.logger.warn(`aiyayi-feishu: 长连接断开、SDK 自动重连中 appId=${appId}`)
|
|
478
|
+
} catch (error) {
|
|
479
|
+
ctx.logger.warn(`aiyayi-feishu: reconnecting 事件处理失败: ${String(error)}`)
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
// ② 重连成功。
|
|
483
|
+
channel.handlers.reconnected = () => {
|
|
484
|
+
try {
|
|
485
|
+
noteConnectEstablished(state, { reconnected: true })
|
|
486
|
+
const health = evaluateConnectHealth(state)
|
|
487
|
+
ctx.logger.info(
|
|
488
|
+
`aiyayi-feishu: 长连接已重连 appId=${appId}(累计 ${state.reconnectCount} 次,5 分钟内 ${health.reconnectsInWindow} 次)`,
|
|
489
|
+
)
|
|
490
|
+
if (health.hint) ctx.logger.warn(`aiyayi-feishu: ${health.hint} appId=${appId}`)
|
|
491
|
+
} catch (error) {
|
|
492
|
+
ctx.logger.warn(`aiyayi-feishu: reconnected 事件处理失败: ${String(error)}`)
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
// ③ 错误:SDK 没把 WSClient.onError 转成 channel handler,这里直接包最底层
|
|
496
|
+
// 实例字段(connect() 之后才存在;它自己的 onError 由 SDK 在 106981 设置,
|
|
497
|
+
// 仅用于首次握手 reject,重连期的 onError 那时已 settled → 落空)。
|
|
498
|
+
const raw = channel.rawWsClient
|
|
499
|
+
if (raw && typeof raw === 'object') {
|
|
500
|
+
const sdkOnError = raw.onError
|
|
501
|
+
raw.onError = (error) => {
|
|
502
|
+
try {
|
|
503
|
+
noteConnectError(state, { error })
|
|
504
|
+
ctx.logger.warn(`aiyayi-feishu: 长连接错误 appId=${appId}: ${String(error?.message ?? error)}`)
|
|
505
|
+
} catch (inner) {
|
|
506
|
+
ctx.logger.warn(`aiyayi-feishu: onError 事件处理失败: ${String(inner)}`)
|
|
507
|
+
}
|
|
508
|
+
try {
|
|
509
|
+
if (typeof sdkOnError === 'function') sdkOnError(error)
|
|
510
|
+
} catch (inner) {
|
|
511
|
+
ctx.logger.warn(`aiyayi-feishu: SDK 原 onError 抛错: ${String(inner)}`)
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
438
517
|
// 建立长连接:所有应用并发 connect,互不等待;任一条失败只记该 app 的状态,
|
|
439
518
|
// 不影响其他条(SDK 每 channel 独立自动重连循环,断连自愈)。
|
|
440
519
|
ctx.effect(
|
|
@@ -444,17 +523,23 @@ export function apply(ctx, config) {
|
|
|
444
523
|
channel
|
|
445
524
|
.connect()
|
|
446
525
|
.then(() => {
|
|
447
|
-
state
|
|
448
|
-
state.error = null
|
|
449
|
-
state.connectedAt = Date.now()
|
|
526
|
+
noteConnectEstablished(state)
|
|
450
527
|
ctx.logger.info(`aiyayi-feishu: 长连接已建立 appId=${appId}`)
|
|
528
|
+
// 事件接线放在 connect() 成功之后:rawWsClient 此时才建好(106961),
|
|
529
|
+
// 而 handlers.reconnecting/reconnected 是幂等赋值,晚接也不会漏掉
|
|
530
|
+
// 之后的重连(首次握手前的 onReady 已由 connect() 的 resolve 覆盖)。
|
|
531
|
+
wireConnectEvents(appId, channel, state)
|
|
451
532
|
})
|
|
452
533
|
.catch((error) => {
|
|
453
|
-
state
|
|
534
|
+
noteConnectError(state, { error })
|
|
454
535
|
ctx.logger.warn(`aiyayi-feishu: 飞书长连接失败 appId=${appId}: ${String(error)}`)
|
|
455
536
|
})
|
|
456
537
|
}
|
|
457
538
|
return () => {
|
|
539
|
+
// 插件卸载:状态先落成断开(免得热重启窗口里 status 还报在线)。
|
|
540
|
+
for (const state of connectStates.values()) {
|
|
541
|
+
noteDisconnect(state, { reason: 'plugin-dispose' })
|
|
542
|
+
}
|
|
458
543
|
// 防御:SDK disconnect() 在 WS 未初始化时返回 undefined(SDK 107014 行注释),
|
|
459
544
|
// 直接 .catch 会 TypeError。包一层 Promise.resolve。
|
|
460
545
|
for (const channel of channels.values()) {
|
|
@@ -1438,7 +1523,7 @@ function registerFeishuTools(ctx, root, merged, apps, send = null) {
|
|
|
1438
1523
|
tools.register({
|
|
1439
1524
|
name: 'feishu_status',
|
|
1440
1525
|
description:
|
|
1441
|
-
'查看当前会话以及其它 aiyayi 会话对接飞书(聊天机器人)的情况:本会话是否已绑定某个飞书 chat、有哪些其它会话已绑定、每个应用的飞书长连接是否在运行(1.5.22 起支持多应用,apps 里每个 appId 一条独立长连接)。新建会话首次对话自查用。注意:没绑定时不要向用户索要 chat_id——接入主要从飞书侧自动发起(用户在飞书里给机器人发条消息即自动新建会话并接入,或发 `绑定会话 <会话名>` 接入指定会话)。',
|
|
1526
|
+
'查看当前会话以及其它 aiyayi 会话对接飞书(聊天机器人)的情况:本会话是否已绑定某个飞书 chat、有哪些其它会话已绑定、每个应用的飞书长连接是否在运行(1.5.22 起支持多应用,apps 里每个 appId 一条独立长连接)。新建会话首次对话自查用。注意:没绑定时不要向用户索要 chat_id——接入主要从飞书侧自动发起(用户在飞书里给机器人发条消息即自动新建会话并接入,或发 `绑定会话 <会话名>` 接入指定会话)。1.5.35 起:顶层与 apps[].connected 是**实时状态**(长连接断开/重连期间即为 false,由 SDK 的 onReconnecting/onReconnected/onError 事件回写);healthy 是**综合健康度**(在线 且 最近 5 分钟重连次数未超阈值),不健康时另给 warning 提示。报「长连接在跑」前先看 connected 与 healthy,别只看 configured。',
|
|
1442
1527
|
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
|
1443
1528
|
output: {
|
|
1444
1529
|
schema: { type: 'object' },
|
|
@@ -1462,27 +1547,62 @@ function registerFeishuTools(ctx, root, merged, apps, send = null) {
|
|
|
1462
1547
|
if (sid !== sessionId) otherBound.push({ chatId, sessionId: sid })
|
|
1463
1548
|
}
|
|
1464
1549
|
// 1.5.22:逐应用长连接状态 + chat→app 归属表(不含任何 secret)。
|
|
1550
|
+
// 1.5.35:connected 改为**事件驱动的实时值**(SDK onReconnecting/onReconnected
|
|
1551
|
+
// /onError 回写),并用 SDK 的 getConnectionStatus() 快照在读时对账,补齐
|
|
1552
|
+
// connectedAt / lastDisconnectAt / reconnectCount / lastError / healthy。
|
|
1465
1553
|
const chatOwners = readChatOwners(root)
|
|
1554
|
+
const now = Date.now()
|
|
1555
|
+
const appChannels = send?.channels ?? null
|
|
1466
1556
|
const appsView = apps.map((app) => {
|
|
1467
1557
|
const state = send?.connectStates?.get(app.appId) ?? null
|
|
1558
|
+
// 快照对账:事件可能因热重启/极短断连漏记,以 SDK 真实状态纠偏
|
|
1559
|
+
// (只纠布尔字段,不动 reconnectCount,避免与事件重复计数)。
|
|
1560
|
+
const channel = appChannels?.get?.(app.appId) ?? null
|
|
1561
|
+
if (state && channel && typeof channel.getConnectionStatus === 'function') {
|
|
1562
|
+
try {
|
|
1563
|
+
reconcileConnectState(state, channel.getConnectionStatus(), { now })
|
|
1564
|
+
} catch {
|
|
1565
|
+
// 快照拿不到就按现有状态报,不因为探测失败而误报断连。
|
|
1566
|
+
}
|
|
1567
|
+
}
|
|
1468
1568
|
const chatsOwned = Object.entries(chatOwners)
|
|
1469
1569
|
.filter(([, ownerAppId]) => ownerAppId === app.appId)
|
|
1470
1570
|
.map(([chatId]) => chatId)
|
|
1471
1571
|
const view = {
|
|
1472
1572
|
appId: app.appId,
|
|
1473
|
-
|
|
1573
|
+
...describeConnectState(state, { now }),
|
|
1474
1574
|
chatsOwned,
|
|
1475
1575
|
}
|
|
1576
|
+
// 兼容旧字段:error 仍是「当前错误」(成功建连后清空)。
|
|
1476
1577
|
if (state?.error) view.error = state.error
|
|
1477
1578
|
return view
|
|
1478
1579
|
})
|
|
1479
1580
|
const boundChatAppId = boundChat ? (chatOwners[boundChat] ?? null) : null
|
|
1480
1581
|
// 1.5.35:最近入站路由回看(新→旧)。字段:at(时间戳)/chatId/appId/action/sessionId。
|
|
1481
1582
|
const inboundRouting = readInboundRouting(root)
|
|
1482
|
-
|
|
1583
|
+
// 顶层 healthy:所有已配置应用都健康;任一应用不健康即整体不健康。
|
|
1584
|
+
// 未配置任何应用时 configured=false、apps=[],healthy 给 false(没接上谈不上健康)。
|
|
1585
|
+
const unhealthy = appsView.filter((a) => a.healthy !== true)
|
|
1586
|
+
const healthHints = appsView.map((a) => a.healthHint).filter(Boolean)
|
|
1587
|
+
const reconnectsRecent = appsView.reduce((sum, a) => sum + (a.reconnectsInLastWindow || 0), 0)
|
|
1588
|
+
const result = {
|
|
1483
1589
|
configured,
|
|
1484
1590
|
// 语义不变:任一应用长连接在线即 true;具体每条看 apps[].connected。
|
|
1485
1591
|
connected: appsView.some((a) => a.connected),
|
|
1592
|
+
// 1.5.35 新增:综合健康度(在线 且 5 分钟内重连次数未超阈值)。
|
|
1593
|
+
healthy: appsView.length > 0 && unhealthy.length === 0,
|
|
1594
|
+
connectedAt: appsView.length > 0 ? (appsView.find((a) => a.connectedAt)?.connectedAt ?? null) : null,
|
|
1595
|
+
lastDisconnectAt: appsView.reduce(
|
|
1596
|
+
(latest, a) => (a.lastDisconnectAt && (!latest || a.lastDisconnectAt > latest) ? a.lastDisconnectAt : latest),
|
|
1597
|
+
null,
|
|
1598
|
+
),
|
|
1599
|
+
reconnectCount: appsView.reduce((sum, a) => sum + (a.reconnectCount || 0), 0),
|
|
1600
|
+
lastError: appsView.reduce(
|
|
1601
|
+
(latest, a) => (a.lastErrorAt && (!latest?.at || a.lastErrorAt > latest.at) ? { at: a.lastErrorAt, error: a.lastError } : latest),
|
|
1602
|
+
null,
|
|
1603
|
+
)?.error ?? null,
|
|
1604
|
+
reconnectsInLast5m: reconnectsRecent,
|
|
1605
|
+
unhealthyApps: unhealthy.map((a) => a.appId),
|
|
1486
1606
|
sessionId,
|
|
1487
1607
|
boundChat,
|
|
1488
1608
|
boundChatAppId,
|
|
@@ -1493,6 +1613,17 @@ function registerFeishuTools(ctx, root, merged, apps, send = null) {
|
|
|
1493
1613
|
singleApp: apps.length === 1,
|
|
1494
1614
|
inboundRouting,
|
|
1495
1615
|
}
|
|
1616
|
+
// 1.5.35:重连频率告警——长连接不稳定时给一条可读提示(不藏在小字段里)。
|
|
1617
|
+
// healthHint 本身已是完整句子("长连接不稳定,最近 5 分钟内重连 X 次"),
|
|
1618
|
+
// 多应用时把各自的应用号并进去,最后补一句后果,避免同一句话重复两遍。
|
|
1619
|
+
if (healthHints.length > 0) {
|
|
1620
|
+
const scope = healthHints.length === 1 ? '' : `(${unhealthy.map((a) => `appId=${a.appId}`).join('、')})`
|
|
1621
|
+
result.warning = `${healthHints.join(';')}${scope}——飞书消息可能延迟或漏收。`
|
|
1622
|
+
}
|
|
1623
|
+
if (!configured) {
|
|
1624
|
+
result.warning = '未配置任何飞书应用凭证(feishu/config.json 的 apps 数组),长连接未启动。'
|
|
1625
|
+
}
|
|
1626
|
+
return result
|
|
1496
1627
|
},
|
|
1497
1628
|
})
|
|
1498
1629
|
|
package/lib/own-tools.js
CHANGED
|
@@ -0,0 +1,554 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* aiyayi-precompact — 压缩前沉淀检查层("先保知识,再清流水")。
|
|
3
|
+
*
|
|
4
|
+
* 设计目标(见 docs/设计方案-压缩前沉淀机制.md):
|
|
5
|
+
* 在 dsh-compaction-basic 真正动手压缩**之前**,检查当前会话有没有
|
|
6
|
+
* "值得沉淀但还没落盘"的内容(任务闭环 / 关键结论 / 可量化数据 / 新经验),
|
|
7
|
+
* 先写成 经验文档(docs/)+ 记忆(memories/ 分类档案)+ 更新索引,
|
|
8
|
+
* 让后面的压缩只负责清理流水。摘要变成"指向落盘位置的索引",而非裸内容。
|
|
9
|
+
*
|
|
10
|
+
* 本模块**不重写 dsh-compaction-basic**:只补"压缩前"一环,不碰 DSH 压缩器核心。
|
|
11
|
+
* 沉淀失败**绝不阻塞主流程**——与 feishu/weixin"加载失败只禁用不炸"同一思路:
|
|
12
|
+
* 一切动作包 try/catch,出问题只记 warn 并跳过,压缩照常跑。
|
|
13
|
+
*
|
|
14
|
+
* 触发时机:
|
|
15
|
+
* 时机 A(接近阈值):agent/pre-step 钩子里量一次 token,当上下文估算量到达
|
|
16
|
+
* `ratio × thresholdTokens`(默认 0.7)时,对当前会话做一次沉淀检查(每会话
|
|
17
|
+
* 一次)。thresholdTokens 复刻 dsh-compaction-basic 的公式:
|
|
18
|
+
* floor(min(contextWindow×thresholdRatio, (contextWindow−reservedCompletionTokens)−headroomTokens))
|
|
19
|
+
* 时机 B(会话收尾):显式工具入口 `precompact_run`,收尾流程 / 本体随时可调。
|
|
20
|
+
*
|
|
21
|
+
* 判断"值得沉淀":落到阿依娅伊已有行为铁律的启发式(任务闭环 / 关键结论 /
|
|
22
|
+
* 可量化数据 / 新经验),可配置 keyword 与开关。
|
|
23
|
+
*
|
|
24
|
+
* 沉淀动作(可注入路径,不硬编码):
|
|
25
|
+
* 1 写经验文档 → docsDir(默认 = 记忆根下 docs/,可配置)
|
|
26
|
+
* 2 写记忆 → memories/<分类>/…(默认 事情/经验,可配置)
|
|
27
|
+
* 3 更新索引 → 在 memory.md 的 <!-- 索引 --> 段追加一行"分类: 标题 → 文档路径"
|
|
28
|
+
*/
|
|
29
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
30
|
+
import { dirname, join, resolve } from 'node:path'
|
|
31
|
+
import { ensureRootDir, treeDir, coreFile } from './home.js'
|
|
32
|
+
import { registerOwnTool } from './own-tools.js'
|
|
33
|
+
|
|
34
|
+
/** Loader 身份。 */
|
|
35
|
+
export const name = 'aiyayi-precompact'
|
|
36
|
+
|
|
37
|
+
/** 需要的服务:注册工具要 tools;量测/取模型走 ctx.get 防御式拿,不放进 inject(缺了也不炸)。 */
|
|
38
|
+
export const inject = ['tools']
|
|
39
|
+
|
|
40
|
+
/** 记忆索引标记(与 lib/index.js 同口径)。 */
|
|
41
|
+
const INDEX_BEGIN = '<!-- 索引 -->'
|
|
42
|
+
const INDEX_END = '<!-- /索引 -->'
|
|
43
|
+
|
|
44
|
+
/** 默认配置。全部可被 cordis.patch.yml 的 config 覆盖。 */
|
|
45
|
+
const DEFAULT_CONFIG = {
|
|
46
|
+
// 时机A提前量:上下文估算量 ≥ ratio×thresholdTokens 时触发沉淀检查(设计文档 0.7×阈值)。
|
|
47
|
+
ratio: 0.7,
|
|
48
|
+
// 复刻 preset-aiyayi 里 compaction 的阈值参数(见 cordis.patch.yml L217-231)。
|
|
49
|
+
thresholdRatio: 0.4,
|
|
50
|
+
headroomTokens: 32768,
|
|
51
|
+
// 触发A每会话最多跑一次(防每步都做)。
|
|
52
|
+
maxPerSession: 1,
|
|
53
|
+
// 太小(估算 token 低于这个绝对下限)时直接跳过模型信息解析(省一次网络调用)。
|
|
54
|
+
minTokensBeforeCheck: 20000,
|
|
55
|
+
// 模型 contextWindow 信息的进程内缓存时长(resolveModelInfo 是网络调用,别每步都打)。
|
|
56
|
+
modelInfoTTL: 5 * 60 * 1000,
|
|
57
|
+
// 时机A自动抓取的"最近几条会话消息"作为候选材料。
|
|
58
|
+
scanTailMessages: 12,
|
|
59
|
+
// 沉淀动作路径:docsDir=null → 记忆根/docs(可注入);memoryPath 默认归档分类。
|
|
60
|
+
docsDir: null,
|
|
61
|
+
memoryPath: '事情/经验',
|
|
62
|
+
rememberKind: '事情',
|
|
63
|
+
updateIndex: true,
|
|
64
|
+
// 判断规则的开关与关键字(行为铁律的启发式落地)。
|
|
65
|
+
rules: {
|
|
66
|
+
minLength: 40,
|
|
67
|
+
taskClosure: ['闭环', '完成', '搞定', '已实现', '达成', '结论', '验收', '解决', '实现了', '完成了', '落地', '收尾'],
|
|
68
|
+
keyConclusion: ['结论', '决定', '判断', '取舍', '关键', '所以', '据此', '原因', '由此'],
|
|
69
|
+
quantifiable: /\d+(\.\d+)?\s*(%|%|GB|MB|KB|TB|token|条|个|项|位|版|v\d+|ms|秒|分钟|小时|天|版本)/i,
|
|
70
|
+
newExperience: ['踩坑', '踩过', '坑', '经验', '教训', '实测', '验证', '新方法', '注意', '记住', '备忘', '值得', '启发'],
|
|
71
|
+
},
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* 扁平化消息 content 块为文本(兼容 [{type:'text',text}] 数组)。
|
|
76
|
+
*/
|
|
77
|
+
function extractText(content) {
|
|
78
|
+
if (typeof content === 'string') return content
|
|
79
|
+
if (Array.isArray(content)) {
|
|
80
|
+
return content
|
|
81
|
+
.map((block) => (typeof block?.text === 'string' ? block.text : ''))
|
|
82
|
+
.join('\n')
|
|
83
|
+
}
|
|
84
|
+
return ''
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** 时间戳:`YYYY-MM-DD HH:MM`。 */
|
|
88
|
+
function stamp() {
|
|
89
|
+
const now = new Date()
|
|
90
|
+
const pad = (n) => String(n).padStart(2, '0')
|
|
91
|
+
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** 文件名时间戳:`YYYYMMDD-HHMM`。 */
|
|
95
|
+
function stampCompact() {
|
|
96
|
+
return stamp().replace(/[-: ]/g, '').slice(0, 12)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 从标题/内容里派生一个文件名安全的 slug(保留中文/字母数字,去掉非法字符)。 */
|
|
100
|
+
export function slugify(text) {
|
|
101
|
+
const s = String(text ?? '').trim()
|
|
102
|
+
const safe = s
|
|
103
|
+
.replace(/[<>:"/\\|?*\x00-\x1f]+/g, '')
|
|
104
|
+
.replace(/\s+/g, '-')
|
|
105
|
+
.replace(/-+/g, '-')
|
|
106
|
+
.replace(/^-+|-+$/g, '')
|
|
107
|
+
return safe || 'sediment'
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** 取文档标题:显式 title > 内容首行 > 内容前 N 字。 */
|
|
111
|
+
export function deriveTitle(content, explicit) {
|
|
112
|
+
if (typeof explicit === 'string' && explicit.trim()) return explicit.trim()
|
|
113
|
+
const text = String(content ?? '').trim()
|
|
114
|
+
const firstLine = text.split(/\r?\n/)[0]?.trim() ?? ''
|
|
115
|
+
if (firstLine) return firstLine.slice(0, 40)
|
|
116
|
+
return text.slice(0, 40) || '沉淀记录'
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** 分类路径 → 安全文件路径(深度≤3,禁路径穿越,与 lib/index.js 同口径)。 */
|
|
120
|
+
function normalizePath(input) {
|
|
121
|
+
const raw = String(input ?? '').trim()
|
|
122
|
+
if (raw.length === 0) throw new Error('记忆分类 path 不能为空')
|
|
123
|
+
const segments = raw.split(/[\\/]+/).filter((segment) => segment.length > 0)
|
|
124
|
+
if (segments.length === 0 || segments.length > 3) {
|
|
125
|
+
throw new Error(`分类深度最多 3 级,收到 "${raw}"`)
|
|
126
|
+
}
|
|
127
|
+
for (const segment of segments) {
|
|
128
|
+
if (segment === '.' || segment === '..' || /[<>:"|?*\x00-\x1f]/.test(segment)) {
|
|
129
|
+
throw new Error(`分类名不合法:"${segment}"`)
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return `${segments.join('/')}.md`
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/* ------------------------------------------------------------------ *
|
|
136
|
+
* 判断"哪些值得沉淀"(行为铁律的启发式,可配置)
|
|
137
|
+
* ------------------------------------------------------------------ */
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* 对一段内容做"是否值得沉淀"的启发式判断。
|
|
141
|
+
* @param {string} content 候选材料
|
|
142
|
+
* @param {object} cfg 合并后的配置
|
|
143
|
+
* @returns {{worth:boolean, score:number, reasons:string[]}}
|
|
144
|
+
*/
|
|
145
|
+
export function judgeSettle(content, cfg) {
|
|
146
|
+
const rules = cfg?.rules ?? DEFAULT_CONFIG.rules
|
|
147
|
+
const text = String(content ?? '').trim()
|
|
148
|
+
const reasons = []
|
|
149
|
+
let score = 0
|
|
150
|
+
if (text.length >= (rules.minLength ?? 40)) {
|
|
151
|
+
score += 1
|
|
152
|
+
reasons.push('有实质内容')
|
|
153
|
+
}
|
|
154
|
+
const hasAny = (words) => (words ?? []).some((w) => text.includes(w))
|
|
155
|
+
if (hasAny(rules.taskClosure)) {
|
|
156
|
+
score += 1
|
|
157
|
+
reasons.push('像有任务闭环')
|
|
158
|
+
}
|
|
159
|
+
if (hasAny(rules.keyConclusion)) {
|
|
160
|
+
score += 1
|
|
161
|
+
reasons.push('含关键结论/决定')
|
|
162
|
+
}
|
|
163
|
+
if (rules.quantifiable instanceof RegExp && rules.quantifiable.test(text)) {
|
|
164
|
+
score += 1
|
|
165
|
+
reasons.push('含可量化数据')
|
|
166
|
+
}
|
|
167
|
+
if (hasAny(rules.newExperience)) {
|
|
168
|
+
score += 1
|
|
169
|
+
reasons.push('含新经验/踩坑')
|
|
170
|
+
}
|
|
171
|
+
const worth = score >= 2
|
|
172
|
+
return { worth, score, reasons }
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/* ------------------------------------------------------------------ *
|
|
176
|
+
* 收集候选材料(时机A:从会话尾部抓最近几条消息)
|
|
177
|
+
* ------------------------------------------------------------------ */
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* 从 session 对象抓最近 count 条可派生文本消息,拼成候选材料。
|
|
181
|
+
* 只读、全程兜底(读不了就返回空串),绝不抛。
|
|
182
|
+
*/
|
|
183
|
+
export function collectRecentContent(session, count) {
|
|
184
|
+
try {
|
|
185
|
+
const nodes = session?.surface?.nodes ?? []
|
|
186
|
+
if (nodes.length === 0) return ''
|
|
187
|
+
const window = nodes.slice(-Math.max(1, count ?? DEFAULT_CONFIG.scanTailMessages))
|
|
188
|
+
const parts = []
|
|
189
|
+
for (const seq of window) {
|
|
190
|
+
try {
|
|
191
|
+
const event = session.eventAt?.(seq)
|
|
192
|
+
const msg = session.deriveEventMessage?.(event)
|
|
193
|
+
const text = extractText(msg?.content)
|
|
194
|
+
if (text && text.trim()) parts.push(text.trim())
|
|
195
|
+
} catch {
|
|
196
|
+
/* 单条读不了跳过 */
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
return parts.join('\n').trim()
|
|
200
|
+
} catch {
|
|
201
|
+
return ''
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/* ------------------------------------------------------------------ *
|
|
206
|
+
* 阈值 / 触发A
|
|
207
|
+
* ------------------------------------------------------------------ */
|
|
208
|
+
|
|
209
|
+
/** 路由目标(provider/model),读 session 请求头;无则返回 null。 */
|
|
210
|
+
function routedTarget(session) {
|
|
211
|
+
const config = session?.requestHeader?.()?.config
|
|
212
|
+
if (config && typeof config.provider === 'string' && config.provider.length > 0 &&
|
|
213
|
+
typeof config.model === 'string' && config.model.length > 0) {
|
|
214
|
+
return { provider: config.provider, model: config.model }
|
|
215
|
+
}
|
|
216
|
+
return null
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** 进程内 model-info 缓存:provider/model → {info, at}。 */
|
|
220
|
+
const modelInfoCache = new Map()
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* 拿模型 contextWindow(带 TTL 缓存,避免每步都打 resolveModelInfo 网络调用)。
|
|
224
|
+
* 失败返回 null(触发A退化为"跳过",不影响主流程)。
|
|
225
|
+
*/
|
|
226
|
+
async function getModelInfo(llm, target, cfg) {
|
|
227
|
+
const key = `${target.provider}\u0000${target.model}`
|
|
228
|
+
const hit = modelInfoCache.get(key)
|
|
229
|
+
if (hit && Date.now() - hit.at < (cfg.modelInfoTTL ?? DEFAULT_CONFIG.modelInfoTTL)) return hit.info
|
|
230
|
+
try {
|
|
231
|
+
const info = await llm.resolveModelInfo(target.provider, target.model)
|
|
232
|
+
if (info) modelInfoCache.set(key, { info, at: Date.now() })
|
|
233
|
+
return info ?? null
|
|
234
|
+
} catch {
|
|
235
|
+
return null
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* 复刻 dsh-compaction-basic 的阈值公式:
|
|
241
|
+
* thresholdTokens = floor(min(contextWindow×thresholdRatio,
|
|
242
|
+
* (contextWindow−reservedCompletionTokens)−headroomTokens))
|
|
243
|
+
* @returns {number} 阈值 token;算不出时返回 0。
|
|
244
|
+
*/
|
|
245
|
+
export function computeThresholdTokens(cfg, info, session) {
|
|
246
|
+
const contextWindow = info?.context?.contextWindow
|
|
247
|
+
if (!Number.isInteger(contextWindow) || contextWindow <= 0) return 0
|
|
248
|
+
const thresholdRatio = cfg.thresholdRatio ?? DEFAULT_CONFIG.thresholdRatio
|
|
249
|
+
const headroom = cfg.headroomTokens ?? DEFAULT_CONFIG.headroomTokens
|
|
250
|
+
const reserved = session?.requestHeader?.()?.config?.maxTokens ?? info?.defaultMaxTokens ?? 0
|
|
251
|
+
const messageBudget = contextWindow - reserved
|
|
252
|
+
const pressureBudget = messageBudget - headroom
|
|
253
|
+
if (pressureBudget <= 0) return 0
|
|
254
|
+
return Math.floor(Math.min(contextWindow * thresholdRatio, pressureBudget))
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/* ------------------------------------------------------------------ *
|
|
258
|
+
* 沉淀动作:写经验文档 + 写记忆 + 更新索引
|
|
259
|
+
* ------------------------------------------------------------------ */
|
|
260
|
+
|
|
261
|
+
/** 在 memory.md 的索引段追加一行(段不存在则新建段)。幂等。 */
|
|
262
|
+
function appendIndexLine(file, line) {
|
|
263
|
+
let raw = ''
|
|
264
|
+
try {
|
|
265
|
+
raw = readFileSync(file, 'utf8')
|
|
266
|
+
} catch {
|
|
267
|
+
raw = ''
|
|
268
|
+
}
|
|
269
|
+
const lines = raw.split(/\r?\n/)
|
|
270
|
+
const endIdx = lines.findIndex((l) => l.trim() === INDEX_END)
|
|
271
|
+
if (endIdx !== -1) {
|
|
272
|
+
lines.splice(endIdx, 0, line)
|
|
273
|
+
} else {
|
|
274
|
+
// 索引段不存在:段尾追一个完整块。
|
|
275
|
+
lines.push('', INDEX_BEGIN, line, INDEX_END, '')
|
|
276
|
+
}
|
|
277
|
+
writeFileSync(file, `${lines.join('\n').replace(/\n+$/, '')}\n`, 'utf8')
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* 执行沉淀:写 docs 文档 + 记忆条目 + 更新索引。
|
|
282
|
+
* 所有写操作都可能抛(由调用方 runPrecompact 兜住,保证不阻塞主流程)。
|
|
283
|
+
* @returns {{docPath:string, memoryFile:string, memoryLocation:string, indexUpdated:boolean, title:string}}
|
|
284
|
+
*/
|
|
285
|
+
export function settle(ctx, cfg, payload) {
|
|
286
|
+
const resolved = ensureRootDir()
|
|
287
|
+
const root = resolved.root
|
|
288
|
+
// docs 目录:可配置;默认 = 记忆根/docs。
|
|
289
|
+
const docsDir = cfg.docsDir ? resolve(cfg.docsDir) : join(root, 'docs')
|
|
290
|
+
mkdirSync(docsDir, { recursive: true })
|
|
291
|
+
|
|
292
|
+
const content = String(payload.content ?? '').trim()
|
|
293
|
+
if (!content) throw new Error('沉淀内容为空,跳过')
|
|
294
|
+
const title = deriveTitle(content, payload.title)
|
|
295
|
+
const slug = slugify(title)
|
|
296
|
+
const now = stamp()
|
|
297
|
+
const filename = `${stampCompact()}-${slug}.md`
|
|
298
|
+
const docPath = join(docsDir, filename)
|
|
299
|
+
|
|
300
|
+
const kind = payload.kind || cfg.rememberKind || '事情'
|
|
301
|
+
const trigger = payload.trigger || 'manual'
|
|
302
|
+
const reason = payload.reason || ''
|
|
303
|
+
|
|
304
|
+
// 1) 写经验文档。
|
|
305
|
+
const docBody = [
|
|
306
|
+
`# ${title}`,
|
|
307
|
+
'',
|
|
308
|
+
`- 时间:${now}`,
|
|
309
|
+
`- 触发:${trigger}`,
|
|
310
|
+
`- 类型:${kind}`,
|
|
311
|
+
reason ? `- 原因:${reason}` : '',
|
|
312
|
+
'',
|
|
313
|
+
'---',
|
|
314
|
+
'',
|
|
315
|
+
content,
|
|
316
|
+
'',
|
|
317
|
+
]
|
|
318
|
+
.filter((line) => line !== '')
|
|
319
|
+
.join('\n')
|
|
320
|
+
writeFileSync(docPath, `${docBody}\n`, 'utf8')
|
|
321
|
+
|
|
322
|
+
// 2) 写记忆(memories/<分类>/…,一条"结论 + 指向文档")。
|
|
323
|
+
const memoryPath = payload.memoryPath || cfg.memoryPath || DEFAULT_CONFIG.memoryPath
|
|
324
|
+
const memoryFile = join(treeDir(), normalizePath(memoryPath))
|
|
325
|
+
mkdirSync(dirname(memoryFile), { recursive: true })
|
|
326
|
+
const relDoc = `docs/${filename}`
|
|
327
|
+
appendFileSync(memoryFile, `- [${now}] ${content}(详见 ${relDoc})\n`, 'utf8')
|
|
328
|
+
|
|
329
|
+
// 3) 更新索引(memory.md 的索引段)。
|
|
330
|
+
let indexUpdated = false
|
|
331
|
+
if (cfg.updateIndex !== false) {
|
|
332
|
+
appendIndexLine(coreFile(), `${memoryPath}: ${title} → ${relDoc}`)
|
|
333
|
+
indexUpdated = true
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
ctx?.logger?.info?.(`aiyayi-precompact: 已沉淀「${title}」→ ${docPath};记忆 ${memoryPath};索引已更新`)
|
|
337
|
+
return { docPath, memoryFile, memoryLocation: memoryPath, indexUpdated, title, filename }
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/* ------------------------------------------------------------------ *
|
|
341
|
+
* 对外主入口:沉淀检查 + 执行(失败不抛,返回结果对象)
|
|
342
|
+
* ------------------------------------------------------------------ */
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* 压缩前沉淀检查主入口(时机A / 时机B / 显式都走这里)。
|
|
346
|
+
* @param {object} ctx cordis 上下文(可能没有 logger,防御)
|
|
347
|
+
* @param {object} cfg 合并后配置
|
|
348
|
+
* @param {{trigger?:string, reason?:string, content?:string, title?:string, kind?:string,
|
|
349
|
+
* session?:object, sessionId?:string, force?:boolean, docPath?:string,
|
|
350
|
+
* memoryPath?:string}} payload
|
|
351
|
+
* - content 缺失时,若给了 session 就抓尾部消息当候选材料(时机A自动触发用)。
|
|
352
|
+
* - force=true 跳过启发式判断,直接沉淀(显式调用且本体已确认时)。
|
|
353
|
+
* @returns {object} 永远正常返回:
|
|
354
|
+
* {settled:true, docPath, memoryLocation, indexUpdated, title, verdict, trigger}
|
|
355
|
+
* | {settled:false, skipped:true, verdict?, reason?}
|
|
356
|
+
* | {settled:false, skipped:true, error:string}
|
|
357
|
+
*/
|
|
358
|
+
export async function runPrecompact(ctx, cfg, payload) {
|
|
359
|
+
const merged = mergeConfig(cfg)
|
|
360
|
+
try {
|
|
361
|
+
let content = String(payload?.content ?? '').trim()
|
|
362
|
+
let session = payload?.session ?? null
|
|
363
|
+
|
|
364
|
+
// 内容没给:尝试从会话尾部抓候选材料(时机A)。
|
|
365
|
+
if (!content && session) {
|
|
366
|
+
content = collectRecentContent(session, merged.scanTailMessages)
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
const verdict = content
|
|
370
|
+
? judgeSettle(content, merged)
|
|
371
|
+
: { worth: false, score: 0, reasons: ['无候选材料'] }
|
|
372
|
+
|
|
373
|
+
if (payload?.force !== true && !verdict.worth) {
|
|
374
|
+
return { settled: false, skipped: true, verdict, trigger: payload?.trigger || 'manual' }
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
const result = settle(ctx, merged, {
|
|
378
|
+
trigger: payload?.trigger || 'manual',
|
|
379
|
+
reason: payload?.reason,
|
|
380
|
+
content,
|
|
381
|
+
title: payload?.title,
|
|
382
|
+
kind: payload?.kind,
|
|
383
|
+
memoryPath: payload?.memoryPath,
|
|
384
|
+
})
|
|
385
|
+
return { settled: true, ...result, verdict, trigger: payload?.trigger || 'manual' }
|
|
386
|
+
} catch (error) {
|
|
387
|
+
try {
|
|
388
|
+
ctx?.logger?.warn?.(`aiyayi-precompact: 沉淀失败(已跳过,不影响主流程): ${String(error?.message ?? error)}`)
|
|
389
|
+
} catch {
|
|
390
|
+
/* logger 都没有就算了 */
|
|
391
|
+
}
|
|
392
|
+
return { settled: false, skipped: true, error: String(error?.message ?? error), trigger: payload?.trigger || 'manual' }
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/* ------------------------------------------------------------------ *
|
|
397
|
+
* 触发A的 pre-step 处理
|
|
398
|
+
* ------------------------------------------------------------------ */
|
|
399
|
+
|
|
400
|
+
/** 本会话触发A是否已跑过(每会话最多一次)。 */
|
|
401
|
+
const settledThisSession = new WeakSet()
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* pre-step 触发器:量 token,接近阈值(ratio×threshold)时对当前会话做一次沉淀检查。
|
|
405
|
+
* 全程兜底:任何一步失败都只跳过,绝不阻塞或抛到钩子外。
|
|
406
|
+
*/
|
|
407
|
+
async function maybePrecompactOnStep(ctx, cfg, agent, _signal) {
|
|
408
|
+
if (!agent?.session) return
|
|
409
|
+
if (settledThisSession.has(agent.session)) return
|
|
410
|
+
// 服务缺了(tokenMeter/llm 不可用)就跳过自动触发,工具仍可用。
|
|
411
|
+
const meter = ctx.get?.('tokenMeter')
|
|
412
|
+
const llm = ctx.get?.('llm')
|
|
413
|
+
if (!meter || !llm) return
|
|
414
|
+
|
|
415
|
+
let measurement
|
|
416
|
+
try {
|
|
417
|
+
measurement = meter.measure(agent.session)
|
|
418
|
+
} catch {
|
|
419
|
+
return
|
|
420
|
+
}
|
|
421
|
+
const total = measurement?.totalTokens ?? 0
|
|
422
|
+
// 低于绝对下限时先不解析模型信息(省网络调用):这类会话必然远低于 0.7×52K。
|
|
423
|
+
if (total < (cfg.minTokensBeforeCheck ?? DEFAULT_CONFIG.minTokensBeforeCheck)) return
|
|
424
|
+
|
|
425
|
+
const target = routedTarget(agent.session)
|
|
426
|
+
if (!target) return
|
|
427
|
+
const info = await getModelInfo(llm, target, cfg)
|
|
428
|
+
if (!info) return
|
|
429
|
+
const threshold = computeThresholdTokens(cfg, info, agent.session)
|
|
430
|
+
if (threshold <= 0) return
|
|
431
|
+
|
|
432
|
+
if (total >= cfg.ratio * threshold) {
|
|
433
|
+
settledThisSession.add(agent.session)
|
|
434
|
+
try {
|
|
435
|
+
await runPrecompact(ctx, cfg, {
|
|
436
|
+
trigger: 'A',
|
|
437
|
+
reason: `上下文已接近压缩阈值(估算 ${total} / 阈值 ${threshold} token,提前量 ${cfg.ratio}),自动沉淀后再压缩`,
|
|
438
|
+
session: agent.session,
|
|
439
|
+
})
|
|
440
|
+
} catch {
|
|
441
|
+
/* runPrecompact 内部已兜,这里再兜一层 */
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/* ------------------------------------------------------------------ *
|
|
447
|
+
* 配置合并
|
|
448
|
+
* ------------------------------------------------------------------ */
|
|
449
|
+
|
|
450
|
+
export function mergeConfig(config) {
|
|
451
|
+
return { ...DEFAULT_CONFIG, ...(config ?? {}) }
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/* ------------------------------------------------------------------ *
|
|
455
|
+
* 工具注册
|
|
456
|
+
* ------------------------------------------------------------------ */
|
|
457
|
+
|
|
458
|
+
const TEXT_BLOCK = (text) => [{ type: 'text', text }]
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* 注册 precompact_run 工具 + 时机A的 pre-step 监听。
|
|
462
|
+
* @param {object} ctx - preset 作用域内的 agent 上下文。
|
|
463
|
+
* @param {object} [config] - cordis.patch.yml 里的 config。
|
|
464
|
+
*/
|
|
465
|
+
export function apply(ctx, config) {
|
|
466
|
+
const cfg = mergeConfig(config)
|
|
467
|
+
|
|
468
|
+
// 自己的工具进白名单(restrict 单一真源)。
|
|
469
|
+
registerOwnTool('precompact_run')
|
|
470
|
+
|
|
471
|
+
// 时机B / 显式:本体可随时调用的工具。
|
|
472
|
+
ctx.effect(
|
|
473
|
+
() =>
|
|
474
|
+
ctx.tools.register({
|
|
475
|
+
name: 'precompact_run',
|
|
476
|
+
description:
|
|
477
|
+
'压缩前沉淀检查:把当前值得沉淀但还没落盘的知识(任务闭环 / 关键结论 / 可量化数据 / 新经验)先写成 docs/ 经验文档 + 记忆 + 更新索引,让后续压缩安心清流水。收尾(update_state 前后)、或上下文快到压缩阈值时用它。content 写你要沉淀的那段知识;标题给 title;拿不准该不该沉淀时可不传 content(会自动抓最近对话判断),或先看它返回的 skipped/verdict。',
|
|
478
|
+
parameters: {
|
|
479
|
+
type: 'object',
|
|
480
|
+
additionalProperties: false,
|
|
481
|
+
properties: {
|
|
482
|
+
content: { type: 'string', description: '要沉淀的知识正文(结论/数据/经验)。留空则自动抓最近几条会话消息做判断。' },
|
|
483
|
+
title: { type: 'string', description: '经验文档标题,缺省取 content 首行。' },
|
|
484
|
+
kind: { type: 'string', enum: ['事情', '经验', '结论', '数据', '任务'], description: '沉淀类型,缺省"事情"。' },
|
|
485
|
+
reason: { type: 'string', description: '这次沉淀的原因(可选,写进文档)。' },
|
|
486
|
+
force: { type: 'boolean', description: 'true=跳过"值得沉淀"判断直接落盘(你已确认这段该留时用)。' },
|
|
487
|
+
memoryPath: { type: 'string', description: '记忆归档分类(1~3 级),缺省"事情/经验"。' },
|
|
488
|
+
},
|
|
489
|
+
},
|
|
490
|
+
output: {
|
|
491
|
+
schema: {
|
|
492
|
+
type: 'object',
|
|
493
|
+
additionalProperties: false,
|
|
494
|
+
properties: {
|
|
495
|
+
settled: { type: 'boolean' },
|
|
496
|
+
skipped: { type: 'boolean' },
|
|
497
|
+
docPath: { type: 'string' },
|
|
498
|
+
memoryLocation: { type: 'string' },
|
|
499
|
+
indexUpdated: { type: 'boolean' },
|
|
500
|
+
title: { type: 'string' },
|
|
501
|
+
reason: { type: 'string' },
|
|
502
|
+
error: { type: 'string' },
|
|
503
|
+
},
|
|
504
|
+
required: ['settled', 'skipped'],
|
|
505
|
+
},
|
|
506
|
+
render: (_args, value) => {
|
|
507
|
+
if (value.settled) {
|
|
508
|
+
return TEXT_BLOCK(
|
|
509
|
+
`已沉淀「${value.title ?? ''}」→ ${value.docPath ?? ''};记忆 ${value.memoryLocation ?? ''}${value.indexUpdated ? ';索引已更新' : ''}`,
|
|
510
|
+
)
|
|
511
|
+
}
|
|
512
|
+
if (value.error) return TEXT_BLOCK(`沉淀跳过(出错,不影响主流程):${value.error}`)
|
|
513
|
+
return TEXT_BLOCK('本次没有值得沉淀的内容,跳过(留给压缩清理流水)。')
|
|
514
|
+
},
|
|
515
|
+
},
|
|
516
|
+
async execute(args) {
|
|
517
|
+
return runPrecompact(ctx, cfg, {
|
|
518
|
+
trigger: args?.reason ? 'B' : 'manual',
|
|
519
|
+
content: args?.content,
|
|
520
|
+
title: args?.title,
|
|
521
|
+
kind: args?.kind,
|
|
522
|
+
reason: args?.reason,
|
|
523
|
+
force: args?.force === true,
|
|
524
|
+
memoryPath: args?.memoryPath,
|
|
525
|
+
})
|
|
526
|
+
},
|
|
527
|
+
}),
|
|
528
|
+
'aiyayi-precompact.precompact_run()',
|
|
529
|
+
)
|
|
530
|
+
|
|
531
|
+
// 时机A:接近阈值时自动触发一次。
|
|
532
|
+
ctx.effect(
|
|
533
|
+
() =>
|
|
534
|
+
ctx.on('agent/pre-step', async ({ agent, signal }, next) => {
|
|
535
|
+
try {
|
|
536
|
+
await maybePrecompactOnStep(ctx, cfg, agent, signal)
|
|
537
|
+
} catch (error) {
|
|
538
|
+
ctx.logger?.warn?.(`aiyayi-precompact: 时机A检查失败(已跳过): ${String(error?.message ?? error)}`)
|
|
539
|
+
}
|
|
540
|
+
return next()
|
|
541
|
+
}),
|
|
542
|
+
'aiyayi-precompact.pre-step()',
|
|
543
|
+
)
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/* 测试出口:只给单测用。 */
|
|
547
|
+
export const __testing = {
|
|
548
|
+
normalizePath,
|
|
549
|
+
appendIndexLine,
|
|
550
|
+
computeThresholdTokens,
|
|
551
|
+
resetTriggerA() {
|
|
552
|
+
// WeakSet 无法清空,测试直接新建模块实例即可。
|
|
553
|
+
},
|
|
554
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-aiyayi",
|
|
3
|
-
"version": "1.5.
|
|
3
|
+
"version": "1.5.37",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"author": "巴依浩爷 (bayihy)",
|
|
6
6
|
"keywords": [
|
|
@@ -27,6 +27,7 @@
|
|
|
27
27
|
"./feishu": "./lib/feishu.js",
|
|
28
28
|
"./feishu-logic": "./lib/feishu-logic.js",
|
|
29
29
|
"./weixin": "./lib/weixin.js",
|
|
30
|
+
"./precompact": "./lib/precompact.js",
|
|
30
31
|
"./icon": "./icon.svg"
|
|
31
32
|
},
|
|
32
33
|
"files": [
|
|
@@ -42,6 +43,7 @@
|
|
|
42
43
|
"lib/presence-worker.js",
|
|
43
44
|
"lib/feishu.js",
|
|
44
45
|
"lib/feishu-logic.js",
|
|
46
|
+
"lib/precompact.js",
|
|
45
47
|
"lib/weixin.js",
|
|
46
48
|
"lib/weixin/",
|
|
47
49
|
"skills",
|