dsh-aiyayi 1.5.35 → 1.5.36
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 +42 -2
- package/README.md +2 -2
- package/cordis.patch.yml +9 -0
- package/lib/feishu-logic.js +186 -0
- package/lib/feishu.js +141 -10
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -10,15 +10,55 @@
|
|
|
10
10
|
|
|
11
11
|
---
|
|
12
12
|
|
|
13
|
-
## 1.5.35(2026-11-12 新增:`feishu_status` 最近入站路由回看 `inboundRouting`
|
|
13
|
+
## 1.5.35(2026-11-12 新增:`feishu_status` 最近入站路由回看 `inboundRouting` 字段)——**已发布(npm 2026-11-12T02:27:31Z)**
|
|
14
14
|
|
|
15
15
|
- 环境:DSH-执行智能体(DeepSeek Harness 子会话,模型名未确证)
|
|
16
|
+
- git:`a6df9e7`(代码)+ `d023c1a`(DEPLOY 文档);npm publish 由并发会话于 2026-11-12T02:27:31Z 完成,registry `gitHead=d023c1a`、shasum `45fc11369c0a5aa5c4ca2aa5290d1560cc59069a`。
|
|
17
|
+
|
|
16
18
|
- **改了什么(只动 `lib/` 与新增测试,无对外行为变更)**:
|
|
17
19
|
- `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
20
|
- `lib/feishu.js`:`onIncomingMessage()` 各路由分支(select/route/auto-new/bind/new/reuse/choose/new-fallback)调用 `recordRouting(action,sessionId)`;`feishu_status` 返回新增 `inboundRouting` 字段(读 `readInboundRouting(root)`)。
|
|
19
21
|
- **为什么**:`feishu_status` 此前只报当前绑定/应用状态,看不到最近入站消息被路由到哪个会话、怎么路由的,排查"消息去哪了"要翻日志;回看字段让最近的入站路由一目了然(新→旧,上限 20 条)。
|
|
20
22
|
- **测试**:新增 `test/feishu-inbound-routing.test.mjs`(本文件单跑全过);全量 159 项 3 挂 = 既有环境基线(`alarm-inject`/`home-relocate`/`tools-surface` 磁盘探测,非本次引入,与 1.5.21/1.5.22/1.5.27 条目同基线)。
|
|
21
|
-
-
|
|
23
|
+
- 发布:npm publish 由并发会话完成(2026-11-12T02:27:31Z),打包 47 files / packed 349.2 kB。
|
|
24
|
+
- **本版不含连接状态修复**:同一时间另一条工作线在做 `connected` 实时化(见 1.5.36)。两笔改动在 git 上合并后,1.5.35 的 npm 包**先于合并**被发布,故不含后者——这也是 1.5.36 单独发版的原因。
|
|
25
|
+
|
|
26
|
+
## 1.5.36(2026-11-12 修复:飞书连接状态失真——`connected` 在断开/重连期间从不回写)
|
|
27
|
+
|
|
28
|
+
- 环境:DSH-执行智能体(DeepSeek Harness 子会话,模型名未确证)
|
|
29
|
+
- **为什么单独发一版**:本修复原计划随 1.5.35 发布,但 1.5.35 已被一个并发会话抢先 `npm publish`(2026-11-12T02:27:31Z,内容只有 `inboundRouting`)。npm 不允许同版本重发,而线上包仍在报假 `connected: true`(用户被误导"飞书一切正常"),所以按"修复必须真到达用户"的原则升为 **1.5.36** 单独发布。代码层面两笔改动早已合并(git 上同一棵树),差异只在版本号与发布时机。
|
|
30
|
+
|
|
31
|
+
- 症状:`feishu_status` 的 `connected` 自首次建连成功后恒为 `true`,即使长连接早已断开、SDK 正在重连也照报在线。2026-11-11 日志里 `[ws] reconnect` 出现 **326 次**(平均 124.5 秒一次,与 SDK 的 120s + 0~30s 抖动重连定时器吻合),期间 `feishu_status` 一直报 `connected: true`,用户被误导成"飞书一切正常"。
|
|
32
|
+
- **根因(源码定位,不是推测)**:`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 内部循环里完成的,插件从未被告知。
|
|
33
|
+
- **SDK 取证(@larksuiteoapi/node-sdk 1.76.0,`lib/index.js` 实读行号)**:
|
|
34
|
+
- `WSClient` 构造参数收 `onReady / onError / onReconnecting / onReconnected`(102422),存成实例字段(102446-102449)。
|
|
35
|
+
- `reConnect()`:打 `[ws] reconnect` 日志后 `if (this.hasEverConnected) safeInvoke('onReconnecting', ...)`(102759-102762);重连循环成功 → `safeInvoke('onReconnected', ...)`(102787-102792);重试耗尽/不可恢复错误 → `safeInvoke('onError', ...)`(102735-102741、102800-102815)。
|
|
36
|
+
- `createLarkChannel` 建 WSClient 时把 `onReconnecting/onReconnected` 转成 `handlers.reconnecting/reconnected`(106988-106989),即公开 API `channel.on('reconnecting'|'reconnected', fn)`(107021-107032)。
|
|
37
|
+
- **`onError` 没有转发**(106981-106986)——它只在首次握手前用于 reject `connect()`,之后重连耗尽的 `onError` 无处可去。所以错误改从 `channel.rawWsClient.onError`(实例字段,106961 建)上再包一层拿。
|
|
38
|
+
- 兜底:`channel.getConnectionStatus()`(107017-107020 → WSClient 102982)返回 `{state: 'connected'|'reconnecting'|'connecting'|'idle'|'failed', lastConnectTime, nextConnectTime, reconnectAttempts}`。
|
|
39
|
+
- 注意:SDK 的 `safeInvoke` 会吞回调异常(102543-102552),所以插件侧回调必须自己 try/catch + 日志,否则出错无声。
|
|
40
|
+
- 修法(分两层,纯逻辑与接线分离):
|
|
41
|
+
1. **新增纯状态机**(`lib/feishu-logic.js`,零外部依赖、可单测):`createConnectState()` / `noteConnectEstablished()` / `noteDisconnect()` / `noteConnectError()` / `reconnectsWithinWindow()` / `evaluateConnectHealth()` / `describeConnectState()` / `reconcileConnectState()`。状态字段:`connected / connectedAt / lastDisconnectAt / lastDisconnectReason / reconnectCount / reconnectTimestamps / error / lastError / lastErrorAt / everConnected`。
|
|
42
|
+
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`,热重启窗口里不再报假在线。
|
|
43
|
+
- `feishu_status` 返回扩展(**旧字段一个不少,只新增**):
|
|
44
|
+
- 顶层新增 `healthy`、`connectedAt`、`lastDisconnectAt`、`reconnectCount`、`lastError`、`reconnectsInLast5m`、`unhealthyApps`,以及不健康时的可读 `warning`("长连接不稳定,最近 5 分钟内重连 X 次——飞书消息可能延迟或漏收。");未配置凭证时 `warning` 给"长连接未启动"。
|
|
45
|
+
- `apps[]` 每条新增 `connectedAt / lastDisconnectAt / lastDisconnectReason / reconnectCount / reconnectsInLastWindow / lastError / lastErrorAt / healthy / healthHint`;旧 `appId / connected / chatsOwned / error` 原样保留。
|
|
46
|
+
- **`connected` 语义改为实时**(事件驱动 + 读时用 `getConnectionStatus()` 快照对账纠偏;对账只纠布尔字段,不动 `reconnectCount`,避免与事件重复计数)。全仓 grep `connected` 确认无其它模块依赖"粘性 true"这一行为——只有 `feishu.js` 自己写、自己读,另加文档与测试描述,故改语义不破坏调用方。
|
|
47
|
+
- 健康判据:`healthy = connected && 最近 5 分钟内重连次数 ≤ 3`。**阈值取"超过 3 次"**(正好 3 次仍健康)。窗口靠时间戳数组滚动裁剪,读时裁(不污染累计 `reconnectCount`)。
|
|
48
|
+
- persona 同步(`cordis.patch.yml` 的【飞书】段):写明 `connected` 是**实时状态**、`healthy` 是**综合健康度**、`warning` 是插件告警;明确要求 `connected:false` 就说"长连接现在是断的",`connected:true` 但 `healthy:false` 要补一句"在线但不太稳",**别只看 `connected:true` 就宣布一切正常**。
|
|
49
|
+
- 测试:新增 `test/feishu-status.test.mjs`(单文件 9 组断言段、A–I),覆盖任务要求的六项并加码:
|
|
50
|
+
- 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` 的旧写法必须已消失)。
|
|
51
|
+
- **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 个旧字段一个不少。
|
|
52
|
+
- **测试隔离方式(重要,避免重踩坑 #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')`)。进程内钩子从根上避开这一类并发污染。
|
|
53
|
+
- 全量单测 `node --test "test/*.test.mjs"`:**159 项全通过 / 0 失败**(1.5.34 基线 158,本版新增 `test/feishu-status.test.mjs` 一项)。连跑 3 遍均 159/0,且跑完 `node_modules` 目录不存在(无桩残留)。
|
|
54
|
+
- 另有独立取证脚本 `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`。
|
|
55
|
+
- 取证脚本开发中自身纠正一次:最初「5 分钟窗口」把断连也推进了 120s,导致 4 轮抖动摊到 10 分钟外、`healthHint` 为 null——说明窗口裁剪逻辑正常工作,抖动必须真的密集才判不健康(把每轮压到 20s 内后如期触发)。
|
|
56
|
+
- 新文件均无 BOM。
|
|
57
|
+
- 未包含:SDK 事件里拿不到 close code / reason(`wsInstance.on('close', ...)` 在 SDK 内部只打 debug 日志、不回传参数,102873-102877),所以 `lastDisconnectReason` 记的是插件侧归因(`ws-reconnecting` / `sdk-state:<state>` / `plugin-dispose`),不是飞书的原始关闭码。
|
|
58
|
+
|
|
59
|
+
- **教训(并发发版会撞车,写在这供后来人省事)**:本版差点与另一条会话同时发同一个版本号——那边 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 的版本号是**全局不可逆**的,一旦被别人占了,只能改号重发,白折腾一轮。并发会话之间尤其要约定:改版本号属于"抢占式操作",先查后占。
|
|
60
|
+
- 版本号三处对齐:`package.json` version、本条目、profile `cordis.patch.yml` 里 `aiyayi-feishu` 的 `config.reloadTag` 均为 `1.5.36`(profile 已先备份为 `cordis.patch.yml.bak-1.5.36-20261112-104808`)。
|
|
61
|
+
- **与 1.5.35 的共存验证**(合并冲突解决后专门做的,不只看测试绿):用真实形状的 `inbound-routing.json`(3 条记录)跑 `feishu_status`,断言 ① 记录原样读出、顺序新→旧、`sessionId: null` 保留;② `healthy` 从 true→false→断连三次翻转时,`inboundRouting` **逐字节不变**(`JSON.stringify` 比对相同)。`healthy` 只读连接状态机、不读入站数据,两条数据通路互不干扰。23 项断言全过。
|
|
22
62
|
|
|
23
63
|
## 1.5.34(2026-11-12 修复:`presence-clock.test.mjs` 跨午夜偶发失败——**只改测试,无运行时行为变化**)
|
|
24
64
|
|
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` 检索员,不惊动小伙伴 |
|
|
@@ -73,7 +73,7 @@ npm 包为平铺结构(仓库若保留 bundle/ 子目录,发布时把其内
|
|
|
73
73
|
- `lib/doc.js` — aiyayi-doc 文档解析插件(1.4.0,挂检索员 preset;ZIP/XML 最小解析零依赖 + 动态加载 shipped libreoffice-kit 做 pdf 页图与旧版转换)
|
|
74
74
|
- `lib/own-tools.js` — 她的工具名单单一真源(注册处登记、放行处判定,防手写白名单漂移)
|
|
75
75
|
- `lib/feishu.js` — aiyayi-feishu 飞书桥接宿主插件(1.5.8 起;跨会话服务,长连接收消息、按指令路由到 aiyayi 会话、回发;凭读取记忆根 `feishu/config.json`)
|
|
76
|
-
- `lib/feishu-logic.js` —
|
|
76
|
+
- `lib/feishu-logic.js` — 飞书纯逻辑(路由/映射/文本抽取/三档复用决策/**长连接状态机**,无外部依赖,可单测;test/feishu-route.test.mjs、test/feishu-reuse-session.test.mjs、test/feishu-status.test.mjs 覆盖)
|
|
77
77
|
- `skills/feishu-setup/` — 内置技能(1.5.13 起随包自动同步到 DSH 技能根):飞书机器人安装/验证/排障全流程(含 2026-11-10 扫码接入改造说明;脚本 `scripts/create-bot.js` v5 等由技能同步维护)
|
|
78
78
|
- `README.md` — 本文档
|
|
79
79
|
- `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 自己从
|
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
|
|