dsh-aiyayi 1.5.21 → 1.5.22

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 CHANGED
@@ -2,12 +2,31 @@
2
2
 
3
3
  > **维护约定**:新版本发布时在顶部加条目。本文件由 README 正文拆出(2026-11-09 重构):版本条目与踩坑记录原文照录,数字、时间、日期一律不改(量化保真是本插件的规矩)。版本事实以 npm registry 为准。
4
4
  >
5
- > **npm 发布一览(2026-11-11 核对 registry,`npm view dsh-aiyayi versions --json`)**:latest = **1.5.20**(2026-11-11 发布)。已发布:1.0.0、…、1.5.7、**1.5.14**、**1.5.15**、**1.5.16**、**1.5.17**、**1.5.20**;跳号 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 权限集中化)。
5
+ > **npm 发布一览(2026-11-11 核对 registry,`npm view dsh-aiyayi versions --json`)**:latest = **1.5.21**(2026-11-11 发布)。已发布: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.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——主修 `lib/feishu.js` `extractText(message).trim()`、兜底 `lib/feishu-logic.js` `stripAttachmentMarkers(text).trim()`)。
6
6
  >
7
7
  > **环境标识约定(2026-11-10 新增)**:写版本条目/坑条目时,**顺手记录当时的 智能体工具-智能体模式-模型供应商-模型**(如 **DSH-创造模式-loomy讯飞-GLM5.3FLASH**),写在条目内(紧跟 git 记录行、或坑条目首行),方便回溯该条目是在哪套智能体/模型环境下产出与验证的。
8
8
 
9
9
  ---
10
10
 
11
+ ## 1.5.22(2026-11-11 多应用多长连接:双机器人各自收发,根因消灭 230002 错绑发送)
12
+
13
+ - 环境:DSH-执行智能体(DeepSeek Harness 子会话,模型名未确证)
14
+ - git:本次 commit(2026-11-11,阿依娅伊)1.5.22:多应用多长连接改造(背景:2026-11-11 诊断实锤——单飞书应用时代,运行版 config 换成新应用后,旧应用的 p2p 单聊收不到事件、新应用回发必报 230002「Bot/User can NOT be out of the chat」,因为 p2p chat 归属是 app 维度的)。
15
+ - **config 多应用格式**(`lib/feishu-logic.js`):
16
+ - 新格式 `{"apps":[{"appId","appSecret","domain"?},...]}`,每个应用一条独立长连接;旧顶层 `{appId,appSecret}` 单应用格式**继续兼容**(`normalizeApps` 自动包一层,`apps` 数组优先)。
17
+ - `mergeConfig` 仍是浅合并不变;appId 去重首个赢;per-app `domain` 可覆盖全局 `domain`(缺省回落 `null`,`feishu.js` 里 `appDomain = app.domain || merged.domain` 补全局域)。
18
+ - **自动迁移** `migrateConfigFile(root)`:读到旧格式→先备份 `config.json.bak-<yyyymmdd-HHmmss>`→原地改写为 apps 数组(其余顶层键保留、顶层不再留凭证副本);幂等(已是新格式返回 `already-multi`,文件缺失 `missing`,坏 JSON `parse:*` 不动文件)。apply() 每次启动自动调用。
19
+ - **每应用独立基础设施**(`lib/feishu.js`):逐 app 建 `createTokenManager` + `createLarkChannel({transport:'websocket'})` + `connect()`;WS 断连重连是 SDK `WSClient` 自带(autoReconnect:true, reconnectInterval=120s),各 channel 互不干扰。入站 `messageId` 去重(`SEEN_MESSAGE_LIMIT=2000` 环形缓存)防同群多 bot 重复投递。
20
+ - **归属机制(本次根因修复的核心)**:
21
+ - 落盘 `chat-owners.json`:{chatId→appId}。入站事件(消息/进单聊卡片事件)到达即记录 `recordChatOwner(chatId, 该channel的appId)`——事件从哪条 WS 来,归属就是谁,权威自愈。
22
+ - 发送前归属解析 `resolveChannelForChat(chatId)`:缓存命中直接用;未命中逐 app 探测 `GET /open-apis/im/v1/messages?container_id_type=chat&container_id=…&page_size=1`(code=0→成员,230002→非成员;判据为 2026-11-11 双 app 实锤,`GET /im/v1/chats/{id}` 两类 app 都返回 code=0 不能当判据)→命中写入缓存。
23
+ - 发送一律走 `sendViaOwner(chatId, payload)`:先归属解析,再从**该 app 自己的 channel** 发;发送报 230002→清缓存重探重试一次(会话回复/卡片兜底文本路径)。确定性归属,不盲试。
24
+ - 卡片就地刷新(`patchQuestionCard`)优先用 `record.appId` 对应的 channel——卡片是谁发的就必须用谁的凭证 patch。
25
+ - **工具升级**:`feishu_status` 增报 `apps:[{appId,connected,chatsOwned,error?}]`(逐应用长连接状态)、`chatOwners`、`boundChatAppId`、`singleApp`,旧字段全保留;`feishu_bind` 绑定前先探测归属:全部 app 非成员→`ok:false` 确定拒绝(绑了也收不到事件),探测基建故障→`ok:true + warning` 保持可用性,成功→回 `appId`。
26
+ - **既有机制理顺(改动最小化)**:`绑定会话` 指令、pending-bind 30 分钟时效、`bot_p2p_chat_entered_v1` 自动绑定逻辑不变,只是每条 WS 各自处理自己的事件并先记归属;问答卡片/文字兜底/附件下载的 domain 按 app 取。
27
+ - 测试:新增 `test/feishu-multiapp.test.mjs`(normalizeApps 双形态/去重/domain 覆盖、migrateConfigFile 备份+幂等+BOM、chat-owners 读写+损坏容错、isOutOfChatError 各层挖码);`node --test "test/*.test.mjs"` 18 文件 15 过 3 挂——挂的 `alarm-inject` / `home-relocate` / `tools-surface` 与 1.5.21 干净基线一致(磁盘类型探测断言,环境相关,非本次引入)。
28
+ - 部署顺序注意:**先装 1.5.22 再迁移运行版 config.json**(1.5.21 读不懂 apps 格式);迁移脚本自带备份。
29
+
11
30
  ## 1.5.21(2026-11-11 修复:飞书回复正文首尾空白行)
12
31
 
13
32
  - 环境:DSH-执行智能体(DeepSeek Harness 子会话,模型名未确证)
@@ -5,7 +5,14 @@
5
5
  * 任何 @deepseek-ai 或 @larksuiteoapi 包。飞书 SDK / dsh-llm 的连接与建会话
6
6
  * 都在 feishu.js(宿主插件壳)里做,这里只放可单测的纯函数。
7
7
  */
8
- import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
8
+ import {
9
+ copyFileSync,
10
+ existsSync,
11
+ mkdirSync,
12
+ readFileSync,
13
+ statSync,
14
+ writeFileSync,
15
+ } from 'node:fs'
9
16
  import { basename, extname, join } from 'node:path'
10
17
 
11
18
  /** 配置文件名(含 appId/appSecret,不入 git)。 */
@@ -64,6 +71,157 @@ export function mergeConfig(patchConfig = {}, fileConfig = null) {
64
71
  return merged
65
72
  }
66
73
 
74
+ // ─── 1.5.22 多应用(multi-app)配置与 chat→app 归属 ─────────────────────────
75
+ // 背景:一台 DSH 可能同时接多个飞书自建应用(每个应用一条独立长连接)。
76
+ // 飞书 p2p chat 的成员归属是「应用」维度的:非成员应用对该 chat 的一切收发
77
+ // 都报 230002「Bot/User can NOT be out of the chat」。所以 config 支持多应用,
78
+ // 且发消息前必须确定目标 chat 属于哪个应用(chat-owners.json)。
79
+
80
+ /** chat → 应用归属表文件名(该 chat 的事件从哪条长连接来/用哪套凭证发)。 */
81
+ const CHAT_OWNERS_FILE = 'chat-owners.json'
82
+
83
+ /** 读 chat → appId 归属表;不存在或损坏返回空对象(归属只是加速缓存,可重建)。 */
84
+ export function readChatOwners(root) {
85
+ const file = join(feishuDir(root), CHAT_OWNERS_FILE)
86
+ if (!existsSync(file)) return {}
87
+ try {
88
+ const parsed = JSON.parse(stripBom(readFileSync(file, 'utf8')))
89
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}
90
+ } catch {
91
+ return {}
92
+ }
93
+ }
94
+
95
+ /** 写 chat → appId 归属表。 */
96
+ export function writeChatOwners(root, owners) {
97
+ const dir = ensureFeishuDir(root)
98
+ writeFileSync(join(dir, CHAT_OWNERS_FILE), JSON.stringify(owners, null, 2), 'utf8')
99
+ }
100
+
101
+ /**
102
+ * 归一化多应用配置。接受两种形态:
103
+ * 新(1.5.22+):{ apps: [{ appId, appSecret, domain? }, ...] }
104
+ * 旧(≤1.5.21):{ appId, appSecret, ... }(单应用,自动包一层)
105
+ * 规则:apps 数组优先于旧顶层字段;appId/appSecret 必须都非空才算有效应用;
106
+ * appId 去重(首个赢,重复项丢弃);per-app domain 缺省回落 null(调用方补全局域)。
107
+ * @returns {Array<{appId:string, appSecret:string, domain:(string|null)}>}
108
+ */
109
+ export function normalizeApps(config) {
110
+ const rawList = Array.isArray(config?.apps)
111
+ ? config.apps
112
+ : config?.appId && config?.appSecret
113
+ ? [{ appId: config.appId, appSecret: config.appSecret, domain: config.domain }]
114
+ : []
115
+ const seen = new Set()
116
+ const apps = []
117
+ for (const item of rawList) {
118
+ if (!item || typeof item !== 'object') continue
119
+ const appId = typeof item.appId === 'string' ? item.appId.trim() : ''
120
+ const appSecret = typeof item.appSecret === 'string' ? item.appSecret.trim() : ''
121
+ if (!appId || !appSecret || seen.has(appId)) continue
122
+ seen.add(appId)
123
+ apps.push({
124
+ appId,
125
+ appSecret,
126
+ domain: typeof item.domain === 'string' && item.domain ? item.domain : null,
127
+ })
128
+ }
129
+ return apps
130
+ }
131
+
132
+ /** 配置是否还是旧的单 app 顶层格式(appId/appSecret 在顶层且无 apps 数组)。 */
133
+ export function isLegacySingleAppConfig(config) {
134
+ return Boolean(
135
+ config &&
136
+ typeof config === 'object' &&
137
+ !Array.isArray(config.apps) &&
138
+ typeof config.appId === 'string' &&
139
+ typeof config.appSecret === 'string',
140
+ )
141
+ }
142
+
143
+ function configBackupStamp() {
144
+ const d = new Date()
145
+ const pad = (n) => String(n).padStart(2, '0')
146
+ return (
147
+ `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}` +
148
+ `-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`
149
+ )
150
+ }
151
+
152
+ /**
153
+ * 把旧单 app 配置文件原地迁移为 apps 数组格式(1.5.22 起在 apply() 自动调用)。
154
+ * 迁移前先备份 config.json → config.json.bak-<yyyymmdd-HHmmss>;
155
+ * appId/appSecret 移入 apps[0],其余顶层键原样保留,顶层不再留凭证副本。
156
+ * 已是新格式 / 文件不存在 / 解析失败时不动文件,返回 { migrated: false }。
157
+ */
158
+ export function migrateConfigFile(root) {
159
+ const file = join(feishuDir(root), CONFIG_FILE)
160
+ if (!existsSync(file)) return { migrated: false, reason: 'missing' }
161
+ let config
162
+ try {
163
+ config = JSON.parse(stripBom(readFileSync(file, 'utf8')))
164
+ } catch (error) {
165
+ return { migrated: false, reason: `parse: ${errorMessage(error)}` }
166
+ }
167
+ if (!isLegacySingleAppConfig(config)) return { migrated: false, reason: 'already-multi' }
168
+ const { appId, appSecret, ...rest } = config
169
+ const stamp = configBackupStamp()
170
+ const backup = `${file}.bak-${stamp}`
171
+ copyFileSync(file, backup)
172
+ writeFileSync(file, JSON.stringify({ ...rest, apps: [{ appId, appSecret }] }, null, 2), 'utf8')
173
+ return { migrated: true, backup, appId }
174
+ }
175
+
176
+ /**
177
+ * 成员探测(发送前确定 chat 归属用):对单个 app 调
178
+ * GET /open-apis/im/v1/messages?container_id_type=chat&container_id=…&page_size=1。
179
+ * 判据(2026-11-11 双 app 实锤):code=0 → 该 app 是 chat 成员(能收能发);
180
+ * code=230002 → 非成员(发了必 400);其余 code / 网络错 → 抛出(归属未知)。
181
+ * 注意 GET /im/v1/chats/{chat_id} 两类 app 都返回 code=0,不能当判据。
182
+ */
183
+ export async function probeChatMembership({ domain, appId, appSecret, chatId }) {
184
+ const getTenantAccessToken = createTokenManager({ domain, appId, appSecret })
185
+ const token = await getTenantAccessToken()
186
+ const url =
187
+ `${domain}/open-apis/im/v1/messages?container_id_type=chat` +
188
+ `&container_id=${encodeURIComponent(chatId)}&page_size=1`
189
+ const res = await fetch(url, {
190
+ headers: { authorization: `Bearer ${token}` },
191
+ signal: AbortSignal.timeout(15_000),
192
+ })
193
+ const data = await res.json().catch(() => ({}))
194
+ const code = data?.code
195
+ if (code === 0) return { member: true, code: 0 }
196
+ if (code === 230002) return { member: false, code: 230002 }
197
+ const error = new Error(
198
+ `成员探测失败: HTTP ${res.status} code=${code} msg=${data?.msg || ''} appId=${appId}`,
199
+ )
200
+ error.feishuCode = code
201
+ error.httpStatus = res.status
202
+ throw error
203
+ }
204
+
205
+ /** 从 SDK 抛出的错误里挖出飞书错误码(LarkChannelError 带 code + cause 链)。 */
206
+ export function extractFeishuErrorCode(error) {
207
+ const candidates = [
208
+ error?.cause?.response?.data?.code,
209
+ error?.cause?.data?.code,
210
+ typeof error?.cause?.code === 'number' ? error.cause.code : undefined,
211
+ error?.data?.code,
212
+ typeof error?.code === 'number' ? error.code : undefined,
213
+ ]
214
+ for (const code of candidates) {
215
+ if (typeof code === 'number') return code
216
+ }
217
+ return null
218
+ }
219
+
220
+ /** 是否「非 chat 成员」错误(230002)——发送侧归属失效的自愈信号。 */
221
+ export function isOutOfChatError(error) {
222
+ return extractFeishuErrorCode(error) === 230002
223
+ }
224
+
67
225
  /** 把一条消息的文本内容抽出来(content 是 {type:'text',text} 数组)。 */
68
226
  export function extractText(message) {
69
227
  if (!message || !Array.isArray(message.content)) return ''
package/lib/feishu.js CHANGED
@@ -44,12 +44,17 @@ import {
44
44
  ensureFeishuDir,
45
45
  extractText,
46
46
  formatAnswerSummary,
47
+ isOutOfChatError,
47
48
  markGuided,
48
49
  matchOnboardIntent,
49
50
  matchSkipIntent,
50
51
  mergeConfig,
52
+ migrateConfigFile,
53
+ normalizeApps,
51
54
  parseQuestionReply,
55
+ probeChatMembership,
52
56
  prunePendingQuestions,
57
+ readChatOwners,
53
58
  readConfigFile,
54
59
  readGuided,
55
60
  readMappings,
@@ -58,6 +63,7 @@ import {
58
63
  reverseLookup,
59
64
  routeMessage,
60
65
  sendReplyWithAttachments,
66
+ writeChatOwners,
61
67
  writeMappings,
62
68
  writePendingBind,
63
69
  writePendingQuestions,
@@ -125,10 +131,25 @@ async function safeDeliverToSession(ctx, root, sessionId, messageId, text) {
125
131
  export function apply(ctx, config) {
126
132
  const { root } = resolveRoot()
127
133
  ensureFeishuDir(root)
134
+ // 1.5.22:旧单 app 配置自动迁移为 apps 数组格式(先备份再原地改写;幂等,
135
+ // 已是新格式/文件缺失/解析失败都不动文件)。
136
+ const migration = migrateConfigFile(root)
137
+ if (migration.migrated) {
138
+ ctx.logger.info(
139
+ `aiyayi-feishu: 旧单 app 配置已迁移为 apps 数组格式(appId=${migration.appId},备份 ${migration.backup})`,
140
+ )
141
+ } else if (migration.reason && migration.reason !== 'already-multi' && migration.reason !== 'missing') {
142
+ ctx.logger.warn(`aiyayi-feishu: 配置迁移跳过(${migration.reason})`)
143
+ }
128
144
  const merged = mergeConfig(config, readConfigFile(root))
145
+ // 1.5.22 多应用:apps 数组优先,旧顶层 appId/appSecret 自动当单应用包一层。
146
+ const apps = normalizeApps(merged)
147
+ // 工具 execute 时才用得到的基础设施句柄(先注册后建连——无凭证也要能 status 自查,
148
+ // 所以用可变 holder 中转,连接层建好后回填)。
149
+ const sendInfra = { connectStates: null, resolveChannelForChat: null }
129
150
 
130
151
  // 先注册工具(即使没有凭证,aiyayi 也能用 feishu_status 自查绑定情况)。
131
- registerFeishuTools(ctx, root, merged)
152
+ registerFeishuTools(ctx, root, merged, apps, sendInfra)
132
153
 
133
154
  // 改造 2+3:会话侧接入引导(与长连接无关——无凭证也注册:用户仍可表达「要接入」,
134
155
  // pending 落盘,等凭证配好后由 bot_p2p_chat_entered_v1 完成绑定)。
@@ -159,114 +180,262 @@ export function apply(ctx, config) {
159
180
  )
160
181
 
161
182
  // 没有凭证就不启动长连接(日志提示,不报错)。
162
- if (!merged.appId || !merged.appSecret) {
183
+ if (apps.length === 0) {
163
184
  ctx.logger.warn(
164
- `aiyayi-feishu: 缺少 appId/appSecret,长连接未启动。请在记忆根 feishu/config.json 或 patch config 里配置。`,
185
+ `aiyayi-feishu: 缺少应用凭证(feishu/config.json 的 apps 数组,或旧版顶层 appId/appSecret),长连接未启动。`,
165
186
  )
166
187
  return
167
188
  }
168
189
 
169
- const mappings = readMappings(root) // 进程内缓存 + 落盘
190
+ const mappings = readMappings(root) // 进程内缓存 + 落盘(仅日志计数用)
191
+
192
+ // ═══ 1.5.22 多应用多长连接 ═══
193
+ // 每个应用一条独立 WS client(独立 tokenManager、独立自动重连——SDK WSClient
194
+ // 默认 autoReconnect:true、重连循环按实例隔离),任一条断连不影响其他条。
195
+ // 发送侧根因修复:飞书 p2p chat 归属是「应用」维度(非成员 app 对该 chat 一切
196
+ // 收发都报 230002「Bot/User can NOT be out of the chat」),所以一切主动推送
197
+ // 前必须先解析 chat→app 归属,用目标 chat 所属应用(= chat 成员)的凭证发送。
198
+ const channels = new Map() // appId → LarkChannel
199
+ const connectStates = new Map() // appId → {connected, error, connectedAt}
200
+ for (const app of apps) {
201
+ connectStates.set(app.appId, { connected: false, error: null, connectedAt: null })
202
+ }
170
203
 
171
- // 1.5.18 附件收发:tenant_access_token 管理器(收件下载/详情兜底共用,进程内缓存
172
- // 到过期前 60s;fetch 用 Node 内建,凭证不落日志)。
173
- const getTenantAccessToken = createTokenManager(merged)
204
+ // messageId 去重:同一 chat 若同时是多个 bot 的成员(群聊场景),同一条消息会
205
+ // 从多条 WS 各推一次;只处理先到的一条,避免重复投递/重复回复。
206
+ // 容量封顶防无界增长(Map 保持插入序,超限丢最旧)。
207
+ const SEEN_MESSAGE_LIMIT = 2000
208
+ const seenMessageIds = new Map() // messageId → 首见时间戳
209
+ function markSeenOrDuplicate(messageId) {
210
+ if (!messageId) return false
211
+ if (seenMessageIds.has(messageId)) return true
212
+ seenMessageIds.set(messageId, Date.now())
213
+ if (seenMessageIds.size > SEEN_MESSAGE_LIMIT) {
214
+ const oldest = seenMessageIds.keys().next().value
215
+ if (oldest !== undefined) seenMessageIds.delete(oldest)
216
+ }
217
+ return false
218
+ }
174
219
 
175
- const onMessage = async (mergedEvent) => {
176
- try {
177
- await onIncomingMessage(ctx, channel, mergedEvent, merged, root, getTenantAccessToken)
178
- } catch (error) {
179
- ctx.logger.warn(`aiyayi-feishu: 处理入站消息失败: ${String(error)}`)
220
+ // 入站事件到达即记录归属(权威自愈:事件从哪条 WS 来,该 chat 就属于哪个 app)。
221
+ function recordChatOwner(chatId, appId) {
222
+ const owners = readChatOwners(root)
223
+ if (owners[chatId] === appId) return
224
+ writeChatOwners(root, { ...owners, [chatId]: appId })
225
+ ctx.logger.info(`aiyayi-feishu: 归属记录 chat=${chatId} → appId=${appId}`)
226
+ }
227
+
228
+ /**
229
+ * chat → 应用归属解析(确定性机制,不靠盲试):
230
+ * 1) chat-owners.json 缓存命中且该 app 仍在本机配置里 → 直接用;
231
+ * 2) 缓存未命中/指向已下线 app → 逐 app 成员探测
232
+ * (GET /open-apis/im/v1/messages 列表接口:code=0=成员,230002=非成员,
233
+ * 2026-11-11 双 app 实锤判据;GET /im/v1/chats/{id} 两类 app 都 code=0,
234
+ * 不是判据),命中即写缓存并返回该 channel;
235
+ * 3) 全部探测成功但都不是成员 → { ok:'not-member' }(确定性否决);
236
+ * 有探测因网络/其他错误失败 → { ok:'probe-error' }(归属未知,不硬猜)。
237
+ */
238
+ async function resolveChannelForChat(chatId) {
239
+ const owners = readChatOwners(root)
240
+ const recorded = owners[chatId]
241
+ if (recorded && channels.has(recorded)) {
242
+ return { ok: 'resolved', appId: recorded, channel: channels.get(recorded) }
180
243
  }
244
+ const errors = []
245
+ let anyProbed = false
246
+ for (const app of apps) {
247
+ anyProbed = true
248
+ try {
249
+ const result = await probeChatMembership({
250
+ domain: app.domain || merged.domain,
251
+ appId: app.appId,
252
+ appSecret: app.appSecret,
253
+ chatId,
254
+ })
255
+ if (result.member) {
256
+ writeChatOwners(root, { ...readChatOwners(root), [chatId]: app.appId })
257
+ return { ok: 'resolved', appId: app.appId, channel: channels.get(app.appId) }
258
+ }
259
+ } catch (error) {
260
+ errors.push(`appId=${app.appId}: ${String(error)}`)
261
+ }
262
+ }
263
+ if (errors.length > 0) return { ok: 'probe-error', errors }
264
+ return anyProbed ? { ok: 'not-member' } : { ok: 'probe-error', errors: ['无可探测的应用'] }
181
265
  }
182
266
 
183
- const channel = createLarkChannel({
184
- appId: merged.appId,
185
- appSecret: merged.appSecret,
186
- domain: merged.domain,
187
- transport: 'websocket',
188
- handlers: { message: onMessage },
189
- })
190
- // 坑 #58:@larksuiteoapi/node-sdk 1.76.0 的 createLarkChannel/LarkChannel 构造函数
191
- // 不读 opts.handlers(SDK lib/index.js:106879 只设 this.handlers={},107359 原样 new
192
- // 后返回),传进去的 handlers 被整个丢弃——每条消息 ACK 后在 onMessage 处静默 no-op、
193
- // 零日志(飞书后台事件日志却显示 SUCCESS)。handlers.message 在派发时才读取,
194
- // 所以必须在返回的 channel 上显式补接线。
195
- channel.handlers.message = onMessage
196
- // 卡片按钮点击:SDK 的长连接默认已注册 `card.action.trigger`(SDK lib/index.js:107291),
197
- // 但派发只在 `handlers.cardAction` 存在时才真正调业务(107297-107299),
198
- // 且构造参数里的 handlers 会被丢弃(见上一条坑 #58 同源,106879)。所以显式挂。
199
- channel.handlers.cardAction = async (event) => {
267
+ function describeOwnership(resolved) {
268
+ if (resolved.ok === 'not-member') return '没有任何已配置飞书应用是该 chat 的成员'
269
+ if (resolved.ok === 'probe-error') return `归属探测失败(${resolved.errors.join(';')})`
270
+ return '未知归属状态'
271
+ }
272
+
273
+ /**
274
+ * 经归属解析发送简单 payload(纯文本/卡片——失败重试无重复副作用)。
275
+ * 发送报 230002 → 归属缓存失效自愈:清缓存重探,换正确 app 重试一次。
276
+ * (附件编排 sendReplyWithAttachments 不走这里:逐项内部消化失败,
277
+ * 230002 时无法确认已发出多少,盲试可能重发——归属解析已前置保证正确性。)
278
+ */
279
+ async function sendViaOwner(chatId, payload, opts, label) {
280
+ let resolved = await resolveChannelForChat(chatId)
281
+ if (resolved.ok !== 'resolved') {
282
+ throw new Error(`${label} 无法发送 chat=${chatId}:${describeOwnership(resolved)}`)
283
+ }
200
284
  try {
201
- await onCardAction(ctx, channel, event, root)
285
+ return await resolved.channel.sender.send(chatId, payload, opts)
202
286
  } catch (error) {
203
- ctx.logger.warn(`aiyayi-feishu: 卡片点击处理失败: ${String(error)}`)
287
+ if (!isOutOfChatError(error)) throw error
288
+ ctx.logger.warn(
289
+ `aiyayi-feishu: ${label} 报 230002(归属缓存失效),失效重探后重试 chat=${chatId}`,
290
+ )
291
+ const owners = readChatOwners(root)
292
+ delete owners[chatId]
293
+ writeChatOwners(root, owners)
294
+ resolved = await resolveChannelForChat(chatId)
295
+ if (resolved.ok !== 'resolved') throw error
296
+ return await resolved.channel.sender.send(chatId, payload, opts)
204
297
  }
205
298
  }
206
299
 
207
- // 改造 1:用户进入与 bot 的 P2P 单聊事件(im.chat.access_event.bot_p2p_chat_entered_v1,
208
- // 权限要求=无,事件体含 chat_id + operator_id open_id)。SDK 长连接默认只订阅
209
- // im.message.receive_v1 / card.action.trigger / reaction / bot.added / drive.notice,
210
- // 不在默认列表里——直接向 channel.dispatcher 补注册(SDK EventDispatcher.register
211
- // 幂等;connect() 时 registerDispatcherHandlers 只注册固定类型,不会覆盖我们的 key)。
212
- // 有待接入目标会话(pending-bind.json)→ 自动写 mappings[chat_id]=目标 sessionId
213
- // 并清除待接入标记、回复确认;无待接入目标 → 仅记录不绑定。
214
- channel.dispatcher.register({
215
- 'im.chat.access_event.bot_p2p_chat_entered_v1': async (raw) => {
300
+ // appId → channel 直查(卡片就地刷新用:卡片是谁发的就必须用谁的凭证 patch)。
301
+ const channelForApp = (appId) => (appId && channels.get(appId)) || null
302
+ // 回填工具层句柄(feishu_status 报每条长连接状态;feishu_bind 发送前探测归属)。
303
+ sendInfra.connectStates = connectStates
304
+ sendInfra.resolveChannelForChat = resolveChannelForChat
305
+
306
+ for (const app of apps) {
307
+ // per-app domain 优先于全局域;tokenManager 每 app 独立(token 缓存互不串号)。
308
+ const appDomain = app.domain || merged.domain
309
+ const getTenantAccessToken = createTokenManager({
310
+ domain: appDomain,
311
+ appId: app.appId,
312
+ appSecret: app.appSecret,
313
+ })
314
+ let channelRef = null
315
+ const onMessage = async (mergedEvent) => {
216
316
  try {
217
- const chatId = raw?.event?.chat_id
218
- if (!chatId) return
219
- const pending = readPendingBind(root)
220
- if (!pending?.sessionId) {
221
- ctx.logger.info(`aiyayi-feishu: 用户进入单聊 chat=${chatId}(无待接入目标,仅记录)`)
222
- return
223
- }
224
- // 1.5.18-fix:待接入目标若指向子智能体,丢弃并清标记。
225
- // 否则真人 chat 会被绑到一个跑完即休眠的 worker,之后每条飞书消息都投进死会话。
226
- if (subagentSessions.has(pending.sessionId)) {
227
- clearPendingBind(root)
228
- ctx.logger.warn(
229
- `aiyayi-feishu: 待接入目标 ${pending.sessionId} 是子智能体,已丢弃,不绑定 chat=${chatId}`,
230
- )
231
- return
232
- }
233
- // 时效:待接入目标超过 PENDING_BIND_TTL_MS 视为过期,清除后不自动绑定。
234
- if (Date.now() - (pending.createdAt || 0) > PENDING_BIND_TTL_MS) {
317
+ await onIncomingMessage(ctx, channelRef, mergedEvent, merged, root, getTenantAccessToken, {
318
+ app,
319
+ domain: appDomain,
320
+ markSeenOrDuplicate,
321
+ recordChatOwner,
322
+ channelForApp,
323
+ })
324
+ } catch (error) {
325
+ ctx.logger.warn(`aiyayi-feishu: 处理入站消息失败 appId=${app.appId}: ${String(error)}`)
326
+ }
327
+ }
328
+ const channel = createLarkChannel({
329
+ appId: app.appId,
330
+ appSecret: app.appSecret,
331
+ domain: appDomain,
332
+ transport: 'websocket',
333
+ handlers: { message: onMessage },
334
+ })
335
+ channelRef = channel
336
+ // 坑 #58:@larksuiteoapi/node-sdk 1.76.0 的 createLarkChannel/LarkChannel 构造函数
337
+ // 不读 opts.handlers(SDK lib/index.js:106879 只设 this.handlers={},107359 原样 new
338
+ // 后返回),传进去的 handlers 被整个丢弃——每条消息 ACK 后在 onMessage 处静默 no-op、
339
+ // 零日志(飞书后台事件日志却显示 SUCCESS)。handlers.message 在派发时才读取,
340
+ // 所以必须在返回的 channel 上显式补接线。
341
+ channel.handlers.message = onMessage
342
+ // 卡片按钮点击:SDK 的长连接默认已注册 `card.action.trigger`(SDK lib/index.js:107291),
343
+ // 但派发只在 `handlers.cardAction` 存在时才真正调业务(107297-107299),
344
+ // 且构造参数里的 handlers 会被丢弃(见上一条坑 #58 同源,106879)。所以显式挂。
345
+ channel.handlers.cardAction = async (event) => {
346
+ try {
347
+ await onCardAction(ctx, channel, event, root, channelForApp)
348
+ } catch (error) {
349
+ ctx.logger.warn(`aiyayi-feishu: 卡片点击处理失败 appId=${app.appId}: ${String(error)}`)
350
+ }
351
+ }
352
+
353
+ // 改造 1(1.5.19):用户进入与 bot 的 P2P 单聊事件(im.chat.access_event.
354
+ // bot_p2p_chat_entered_v1,权限要求=无,事件体含 chat_id + operator_id open_id)。
355
+ // SDK 长连接默认只订阅 im.message.receive_v1 / card.action.trigger / reaction /
356
+ // bot.added / drive.notice,不在默认列表里——直接向 channel.dispatcher 补注册
357
+ // (SDK EventDispatcher.register 幂等;connect() 时 registerDispatcherHandlers
358
+ // 只注册固定类型,不会覆盖我们的 key)。
359
+ // 有待接入目标会话(pending-bind.json)→ 自动写 mappings[chat_id]=目标 sessionId
360
+ // 并清除待接入标记、回复确认;无待接入目标 → 仅记录归属不绑定。
361
+ // 1.5.22:每条长连接各自注册;事件从哪条 WS 来就用哪条回(该 app 必是 chat 成员)。
362
+ channel.dispatcher.register({
363
+ 'im.chat.access_event.bot_p2p_chat_entered_v1': async (raw) => {
364
+ try {
365
+ const chatId = raw?.event?.chat_id
366
+ if (!chatId) return
367
+ recordChatOwner(chatId, app.appId)
368
+ const pending = readPendingBind(root)
369
+ if (!pending?.sessionId) {
370
+ ctx.logger.info(
371
+ `aiyayi-feishu: 用户进入单聊 chat=${chatId} appId=${app.appId}(无待接入目标,仅记录)`,
372
+ )
373
+ return
374
+ }
375
+ // 1.5.18-fix:待接入目标若指向子智能体,丢弃并清标记。
376
+ // 否则真人 chat 会被绑到一个跑完即休眠的 worker,之后每条飞书消息都投进死会话。
377
+ if (subagentSessions.has(pending.sessionId)) {
378
+ clearPendingBind(root)
379
+ ctx.logger.warn(
380
+ `aiyayi-feishu: 待接入目标 ${pending.sessionId} 是子智能体,已丢弃,不绑定 chat=${chatId}`,
381
+ )
382
+ return
383
+ }
384
+ // 时效:待接入目标超过 PENDING_BIND_TTL_MS 视为过期,清除后不自动绑定。
385
+ if (Date.now() - (pending.createdAt || 0) > PENDING_BIND_TTL_MS) {
386
+ clearPendingBind(root)
387
+ ctx.logger.info(
388
+ `aiyayi-feishu: 待接入目标已过期(会话 ${pending.sessionId}),清除,不自动绑定 chat=${chatId}`,
389
+ )
390
+ return
391
+ }
392
+ const refreshed = readMappings(root)
393
+ refreshed[chatId] = pending.sessionId
394
+ writeMappings(root, refreshed)
235
395
  clearPendingBind(root)
236
396
  ctx.logger.info(
237
- `aiyayi-feishu: 待接入目标已过期(会话 ${pending.sessionId}),清除,不自动绑定 chat=${chatId}`,
397
+ `aiyayi-feishu: 用户进入单聊 chat=${chatId}(appId=${app.appId}),已自动接入会话 ${pending.sessionId}`,
238
398
  )
239
- return
399
+ await replyToChat(
400
+ channel,
401
+ chatId,
402
+ null,
403
+ `已自动接入 aiyayi 会话 ${pending.sessionId},现在可以直接在手机飞书上找我啦。`,
404
+ )
405
+ } catch (error) {
406
+ ctx.logger.warn(`aiyayi-feishu: bot_p2p_chat_entered_v1 处理失败: ${String(error)}`)
240
407
  }
241
- const refreshed = readMappings(root)
242
- refreshed[chatId] = pending.sessionId
243
- writeMappings(root, refreshed)
244
- clearPendingBind(root)
245
- ctx.logger.info(
246
- `aiyayi-feishu: 用户进入单聊 chat=${chatId},已自动接入会话 ${pending.sessionId}`,
247
- )
248
- await replyToChat(
249
- channel,
250
- chatId,
251
- null,
252
- `已自动接入 aiyayi 会话 ${pending.sessionId},现在可以直接在手机飞书上找我啦。`,
253
- )
254
- } catch (error) {
255
- ctx.logger.warn(`aiyayi-feishu: bot_p2p_chat_entered_v1 处理失败: ${String(error)}`)
256
- }
257
- },
258
- })
408
+ },
409
+ })
410
+
411
+ channels.set(app.appId, channel)
412
+ }
259
413
 
260
- // 建立长连接(后台异步,握手成功后 channel.connect() 才 resolve)。
414
+ // 建立长连接:所有应用并发 connect,互不等待;任一条失败只记该 app 的状态,
415
+ // 不影响其他条(SDK 每 channel 独立自动重连循环,断连自愈)。
261
416
  ctx.effect(
262
417
  () => {
263
- channel.connect().catch((error) => {
264
- ctx.logger.warn(`aiyayi-feishu: 飞书长连接失败: ${String(error)}`)
265
- })
418
+ for (const [appId, channel] of channels) {
419
+ const state = connectStates.get(appId)
420
+ channel
421
+ .connect()
422
+ .then(() => {
423
+ state.connected = true
424
+ state.error = null
425
+ state.connectedAt = Date.now()
426
+ ctx.logger.info(`aiyayi-feishu: 长连接已建立 appId=${appId}`)
427
+ })
428
+ .catch((error) => {
429
+ state.error = String(error)
430
+ ctx.logger.warn(`aiyayi-feishu: 飞书长连接失败 appId=${appId}: ${String(error)}`)
431
+ })
432
+ }
266
433
  return () => {
267
434
  // 防御:SDK disconnect() 在 WS 未初始化时返回 undefined(SDK 107014 行注释),
268
435
  // 直接 .catch 会 TypeError。包一层 Promise.resolve。
269
- Promise.resolve(channel.disconnect()).catch(() => {})
436
+ for (const channel of channels.values()) {
437
+ Promise.resolve(channel.disconnect()).catch(() => {})
438
+ }
270
439
  }
271
440
  },
272
441
  'aiyayi-feishu.connect()',
@@ -278,7 +447,7 @@ export function apply(ctx, config) {
278
447
  // 监听者拿到 (request, next),返回答案即「认领」,调 next() 表示交给下游
279
448
  // (桌面 GUI 的 answerer 在 dsh-client-ui-user-questions :asar .../lib/client.js:2277)。
280
449
  // 所以这里必须排在 GUI 前面才能抢到——用 prepend。
281
- registerQuestionAnswerer(ctx, channel, root)
450
+ registerQuestionAnswerer(ctx, { sendViaOwner, resolveChannelForChat, channelForApp }, root)
282
451
 
283
452
  // 回发:监听 host 级 session/event 总线,只处理属于已绑定会话的 assistant 消息。
284
453
  // 同一轮 turn 里 assistant/message 是渐进追加的(每个 step 一条,settle 替换),
@@ -291,12 +460,43 @@ export function apply(ctx, config) {
291
460
  // 每次发送前重读映射,避免 feishu_bind / 入站绑定新增后 relay 漏发。
292
461
  const chatId = reverseLookup(readMappings(root), sessionId)
293
462
  if (!chatId) return
463
+ // 1.5.22 根因修复:回发前先解析 chat→app 归属,用目标 chat 所属应用的凭证发——
464
+ // 非成员 app 发送必 230002(2026-11-11 实锤的根因类别)。
294
465
  // 1.5.18/1.5.19:回发支持 [附件: <路径>] / [图片: <路径>] 标记——逐条按扩展名
295
466
  // 分流(图片→msg_type=image,其他→file,失败降级),再发剥离标记后的正文
296
- // (编排见 feishu-logic.sendReplyWithAttachments)。
297
- // 异步发送,失败只记日志(编排内逐项 info/warn,排障能直接确认回发闭环)。
298
- sendReplyWithAttachments(channel, chatId, text, ctx.logger).catch((error) => {
299
- ctx.logger.warn(`aiyayi-feishu: 回发 ${chatId} 失败: ${String(error)}`)
467
+ // (编排见 feishu-logic.sendReplyWithAttachments)。附件编排不盲试重发
468
+ // (230002 时无法确认已发出多少),归属解析已前置保证正确性。
469
+ void (async () => {
470
+ const resolved = await resolveChannelForChat(chatId)
471
+ if (resolved.ok !== 'resolved') {
472
+ ctx.logger.warn(`aiyayi-feishu: 回发 ${chatId} 失败:${describeOwnership(resolved)}`)
473
+ return
474
+ }
475
+ try {
476
+ await sendReplyWithAttachments(resolved.channel, chatId, text, ctx.logger)
477
+ } catch (error) {
478
+ if (!isOutOfChatError(error)) {
479
+ ctx.logger.warn(`aiyayi-feishu: 回发 ${chatId} 失败: ${String(error)}`)
480
+ return
481
+ }
482
+ // 归属缓存失效自愈:清缓存重探换 app 重试一次。
483
+ ctx.logger.warn(`aiyayi-feishu: 回发 ${chatId} 报 230002,失效重探后重试`)
484
+ const owners = readChatOwners(root)
485
+ delete owners[chatId]
486
+ writeChatOwners(root, owners)
487
+ const retry = await resolveChannelForChat(chatId)
488
+ if (retry.ok !== 'resolved') {
489
+ ctx.logger.warn(`aiyayi-feishu: 回发重试放弃:${describeOwnership(retry)}`)
490
+ return
491
+ }
492
+ try {
493
+ await sendReplyWithAttachments(retry.channel, chatId, text, ctx.logger)
494
+ } catch (retryError) {
495
+ ctx.logger.warn(`aiyayi-feishu: 回发重试仍失败: ${String(retryError)}`)
496
+ }
497
+ }
498
+ })().catch((error) => {
499
+ ctx.logger.warn(`aiyayi-feishu: 回发编排异常: ${String(error)}`)
300
500
  })
301
501
  }
302
502
  ctx.effect(
@@ -336,7 +536,7 @@ export function apply(ctx, config) {
336
536
  )
337
537
 
338
538
  ctx.logger.info(
339
- `aiyayi-feishu: 已就绪,记忆根 ${root}(已绑定 ${Object.keys(mappings).length} 个 chat)`,
539
+ `aiyayi-feishu: 已就绪,记忆根 ${root}(${apps.length} 个应用长连接,已绑定 ${Object.keys(mappings).length} 个 chat)`,
340
540
  )
341
541
  }
342
542
 
@@ -376,12 +576,31 @@ function isSubagentSession(session) {
376
576
  * 收一条入站消息:按自然语言指令决定绑定/新建/投递。
377
577
  * 1.5.18:非 bind 分支先做附件收集下载(bind 只写映射不投递,无需下载),
378
578
  * 保存/失败提示并进投递文本;下载失败不阻断消息投递。
579
+ * 1.5.22:route = { app, domain, markSeenOrDuplicate, recordChatOwner }——
580
+ * 事件从哪条长连接来就带哪个 app 的身份(该 app 必是此 chat 成员);
581
+ * 到达即记录归属 + messageId 去重(同群双 bot 场景同一条消息会推到多条 WS)。
379
582
  */
380
- async function onIncomingMessage(ctx, channel, mergedEvent, merged, root, getTenantAccessToken) {
583
+ async function onIncomingMessage(
584
+ ctx,
585
+ channel,
586
+ mergedEvent,
587
+ merged,
588
+ root,
589
+ getTenantAccessToken,
590
+ route,
591
+ ) {
381
592
  const chatId = mergedEvent.chatId
382
593
  const messageId = mergedEvent.messageId
383
594
  const rawText = mergedEvent.content || ''
384
595
  if (!chatId) return
596
+ const appId = route?.app?.appId ?? null
597
+
598
+ // 1.5.22:归属记录(权威自愈)+ 跨 WS 去重。去重必须先于归属记录之外的一切处理。
599
+ route?.recordChatOwner?.(chatId, appId)
600
+ if (route?.markSeenOrDuplicate?.(messageId)) {
601
+ ctx.logger.info(`aiyayi-feishu: 跳过重复消息 ${messageId}(其他应用长连接已处理)`)
602
+ return
603
+ }
385
604
 
386
605
  // 坑 #66:机器人自己发出的消息也会以 im.message.receive_v1 推回来(同样进 handler),
387
606
  // 若不跳过就会把「已新建并接入…」「正式回答」当成用户输入再喂给会话 → 自问自答死循环。
@@ -401,7 +620,7 @@ async function onIncomingMessage(ctx, channel, mergedEvent, merged, root, getTen
401
620
  // 必须排在路由之前——否则用户回的「2」会被当普通消息投给会话,提问永远等不到答案。
402
621
  // 解析不出答案(普通聊天正文)时返回 false,照常走路由,行为与 1.5.18 一致。
403
622
  try {
404
- const consumed = await tryAnswerByText(ctx, channel, root, chatId, messageId, rawText)
623
+ const consumed = await tryAnswerByText(ctx, channel, root, chatId, messageId, rawText, route?.channelForApp)
405
624
  if (consumed) return
406
625
  } catch (error) {
407
626
  ctx.logger.warn(`aiyayi-feishu: 文字回答处理失败(继续按普通消息投递): ${String(error)}`)
@@ -420,7 +639,8 @@ async function onIncomingMessage(ctx, channel, mergedEvent, merged, root, getTen
420
639
  logger: ctx.logger,
421
640
  mergedEvent,
422
641
  root,
423
- domain: merged.domain,
642
+ // 1.5.22:per-app 域优先(app.domain || 全局 merged.domain),token 也是该 app 的。
643
+ domain: route?.domain || merged.domain,
424
644
  getTenantAccessToken,
425
645
  })
426
646
  } catch (error) {
@@ -625,11 +845,13 @@ function blockingTimeoutMs() {
625
845
 
626
846
  /**
627
847
  * 把本插件挂进 user-questions waterfall。
848
+ * 1.5.22:fns = { sendViaOwner, resolveChannelForChat, channelForApp }——
849
+ * 发卡片/文字前先解析 chat→app 归属,用目标 chat 所属应用的凭证发送。
628
850
  * @param {object} ctx - Cordis 上下文(插件 fiber)。
629
- * @param {object} channel - SDK LarkChannel。
851
+ * @param {object} fns - apply() 里的发送/归属基础设施。
630
852
  * @param {string} root - 记忆根。
631
853
  */
632
- function registerQuestionAnswerer(ctx, channel, root) {
854
+ function registerQuestionAnswerer(ctx, fns, root) {
633
855
  if (process.env[CARD_SWITCH_ENV] === '0') {
634
856
  ctx.logger.info(`aiyayi-feishu: ${CARD_SWITCH_ENV}=0,卡片问答已关闭(走桌面 GUI 原生卡片)`)
635
857
  return
@@ -646,7 +868,7 @@ function registerQuestionAnswerer(ctx, channel, root) {
646
868
  'user-questions/request',
647
869
  async (request, next) => {
648
870
  try {
649
- const claimed = await answerViaFeishu(ctx, channel, root, request)
871
+ const claimed = await answerViaFeishu(ctx, fns, root, request)
650
872
  if (claimed !== undefined) return claimed
651
873
  } catch (error) {
652
874
  // 认领失败必须回落 next(),否则提问会以插件异常的形式炸掉整轮对话。
@@ -664,15 +886,23 @@ function registerQuestionAnswerer(ctx, channel, root) {
664
886
 
665
887
  /**
666
888
  * 一次提问的飞书侧处理:发卡片(或文字兜底)→ 等用户点/回 → 返回答案。
889
+ * 1.5.22:发送前解析 chat→app 归属(fns.resolveChannelForChat);非成员 app 发送
890
+ * 必 230002(本次改造要消灭的根因类别),归属解析不出来就交回 GUI answerer。
667
891
  * @returns {Promise<{answers:Array}|undefined>} undefined = 不认领,交回 next()。
668
892
  */
669
- async function answerViaFeishu(ctx, channel, root, request) {
893
+ async function answerViaFeishu(ctx, fns, root, request) {
670
894
  const agent = request?.agent
671
895
  const sessionId = agent?.session?.id
672
896
  if (!sessionId) return undefined
673
897
  // 只接管「已绑定飞书 chat 的会话」:没绑定就让 GUI 原生卡片照常工作。
674
898
  const chatId = reverseLookup(readMappings(root), sessionId)
675
899
  if (!chatId) return undefined
900
+ // 1.5.22:先定归属。解析不出(非成员/探测失败)→ 不认领,GUI 兜底。
901
+ const resolved = await fns.resolveChannelForChat(chatId)
902
+ if (resolved.ok !== 'resolved') {
903
+ ctx.logger.warn(`aiyayi-feishu: 问答卡片放弃接管 ${chatId}:归属解析失败(${resolved.ok})`)
904
+ return undefined
905
+ }
676
906
  const questions = Array.isArray(request.questions) ? request.questions : []
677
907
  if (questions.length === 0) return undefined
678
908
 
@@ -680,6 +910,8 @@ async function answerViaFeishu(ctx, channel, root, request) {
680
910
  qid: `q-${randomUUID()}`,
681
911
  chatId,
682
912
  sessionId,
913
+ // 1.5.22:记录归属 appId——卡片是谁发的就必须用谁的凭证就地刷新(updateCard)。
914
+ appId: resolved.appId,
683
915
  callId: request.wait?.callId ?? null,
684
916
  timed: request.wait?.timed === true,
685
917
  createdAt: Date.now(),
@@ -712,7 +944,7 @@ async function answerViaFeishu(ctx, channel, root, request) {
712
944
  // 1) 先试卡片;失败就退文字编号列表(权限/事件订阅没配好时卡片点不动)。
713
945
  let cardSent = false
714
946
  try {
715
- const sent = await channel.sender.send(chatId, { card: buildQuestionCard(record) })
947
+ const sent = await fns.sendViaOwner(chatId, { card: buildQuestionCard(record) }, {}, '问答卡片')
716
948
  record.messageId = sent?.messageId ?? null
717
949
  cardSent = true
718
950
  ctx.logger.info(`aiyayi-feishu: 已发问答卡片 ${record.qid} → ${chatId} msg=${record.messageId}`)
@@ -723,7 +955,7 @@ async function answerViaFeishu(ctx, channel, root, request) {
723
955
  }
724
956
  if (!cardSent) {
725
957
  try {
726
- await replyToChat(channel, chatId, null, buildQuestionText(record))
958
+ await fns.sendViaOwner(chatId, { text: buildQuestionText(record) }, {}, '问答文字兜底')
727
959
  } catch (error) {
728
960
  // 连文字都发不出去:不认领,交回 GUI。提问不能因为飞书侧故障而丢掉。
729
961
  ctx.logger.warn(`aiyayi-feishu: 问答文字兜底也失败,交回下游: ${String(error)}`)
@@ -737,8 +969,10 @@ async function answerViaFeishu(ctx, channel, root, request) {
737
969
  writePendingQuestions(root, persisted)
738
970
 
739
971
  // 2) 等用户点/回(或宿主取消)。
740
- const answer = await waitForQuestionAnswer(ctx, root, channel, record, request.signal, {
972
+ const answer = await waitForQuestionAnswer(ctx, root, record, request.signal, {
741
973
  timeoutMs: blockingTimeoutMs(),
974
+ sendViaOwner: fns.sendViaOwner,
975
+ channelForApp: fns.channelForApp,
742
976
  })
743
977
  if (answer === undefined) {
744
978
  // 取消/超时后才轮到下游:此时宿主自己会按 ASK_ABORTED/ASK_TIMED_OUT 处理。
@@ -752,9 +986,11 @@ const questionWaiters = new Map() // qid → {resolve, cleanup}
752
986
 
753
987
  /**
754
988
  * 等一条提问被回答。
989
+ * 1.5.22:卡片就地刷新按 record.appId 取发卡片的那条 channel(卡片是谁发的
990
+ * 就必须用谁的凭证 patch);超时通知经 sendViaOwner 走归属解析发送。
755
991
  * @returns {Promise<{answers:Array}|undefined>} undefined = 宿主取消/超时,交回下游。
756
992
  */
757
- function waitForQuestionAnswer(ctx, root, channel, record, signal, opts = {}) {
993
+ function waitForQuestionAnswer(ctx, root, record, signal, opts = {}) {
758
994
  return new Promise((resolve) => {
759
995
  let done = false
760
996
  let timer = null
@@ -781,6 +1017,7 @@ function waitForQuestionAnswer(ctx, root, channel, record, signal, opts = {}) {
781
1017
  : '已结束(本轮已中断,本次提问不能补答;需要的话让助手重新提问)'
782
1018
  writePendingQuestions(root, table)
783
1019
  // 卡片就地改成结束态,避免用户对着还能点但没人收的卡片发呆。
1020
+ const channel = opts.channelForApp?.(record.appId) ?? null
784
1021
  if (record.messageId && channel) {
785
1022
  channel.updateCard(record.messageId, buildQuestionCard(table[record.qid])).catch(() => {})
786
1023
  }
@@ -808,6 +1045,7 @@ function waitForQuestionAnswer(ctx, root, channel, record, signal, opts = {}) {
808
1045
  table[record.qid].status = 'expired'
809
1046
  table[record.qid].statusText = '已超时,本次按「跳过」继续;需要的话让助手重新提问'
810
1047
  writePendingQuestions(root, table)
1048
+ const channel = opts.channelForApp?.(record.appId) ?? null
811
1049
  if (record.messageId && channel) {
812
1050
  channel.updateCard(record.messageId, buildQuestionCard(table[record.qid])).catch(() => {})
813
1051
  }
@@ -815,12 +1053,14 @@ function waitForQuestionAnswer(ctx, root, channel, record, signal, opts = {}) {
815
1053
  ctx.logger.warn(
816
1054
  `aiyayi-feishu: 提问 ${record.qid} 本地超时(${opts.timeoutMs}ms),按全部跳过放行`,
817
1055
  )
818
- void replyToChat(
819
- channel,
820
- record.chatId,
821
- null,
822
- `提问 ${record.qid} 等待超时(${Math.round(opts.timeoutMs / 1000)} 秒),本次按「跳过」继续。`,
823
- ).catch(() => {})
1056
+ void opts
1057
+ .sendViaOwner?.(
1058
+ record.chatId,
1059
+ { text: `提问 ${record.qid} 等待超时(${Math.round(opts.timeoutMs / 1000)} 秒),本次按「跳过」继续。` },
1060
+ {},
1061
+ '提问超时通知',
1062
+ )
1063
+ .catch(() => {})
824
1064
  finish({ answers: record.questions.map((q) => ({ id: String(q.id), selected: [] })) })
825
1065
  }, opts.timeoutMs)
826
1066
  }
@@ -845,8 +1085,10 @@ function liveQuestion(root, qid) {
845
1085
  /**
846
1086
  * 处理一次卡片点击(SDK 已 normalize,见 lib/index.js:106709-106732)。
847
1087
  * 事件形状:{messageId, chatId, operator:{openId}, action:{value, tag, name, option}}。
1088
+ * 1.5.22:channelForApp —— patch 卡片优先用 record.appId 对应的 channel(发卡片的
1089
+ * app 才有 patch 权限),事件所在 channel 只作兜底。
848
1090
  */
849
- async function onCardAction(ctx, channel, event, root) {
1091
+ async function onCardAction(ctx, channel, event, root, channelForApp) {
850
1092
  const value = event?.action?.value
851
1093
  if (!value || typeof value !== 'object') return
852
1094
  const record = liveQuestion(root, value.q)
@@ -867,7 +1109,7 @@ async function onCardAction(ctx, channel, event, root) {
867
1109
  record.status = 'answered'
868
1110
  record.statusText = `已提交:\n${formatAnswerSummary(record)}`
869
1111
  writePendingQuestions(root, table)
870
- await patchQuestionCard(ctx, channel, record)
1112
+ await patchQuestionCard(ctx, channel, record, channelForApp)
871
1113
  const waiter = questionWaiters.get(record.qid)
872
1114
  if (waiter) {
873
1115
  waiter.resolve(composeAnswerBatch(record))
@@ -880,19 +1122,23 @@ async function onCardAction(ctx, channel, event, root) {
880
1122
 
881
1123
  if (applied.changed) {
882
1124
  writePendingQuestions(root, table)
883
- await patchQuestionCard(ctx, channel, record)
1125
+ await patchQuestionCard(ctx, channel, record, channelForApp)
884
1126
  // 中途状态也要回 ACK:卡片回调 3 秒内必须响应(SDK README.zh.md:629),
885
1127
  // patch 是异步的,这里不 await 具体结果,失败只记日志。
886
1128
  }
887
1129
  }
888
1130
 
889
1131
  /**
890
- * 就地刷新卡片。patch 失败(消息太老/无权限)只记日志:卡片状态落后不影响文字兜底。
1132
+ * 就地刷新卡片。1.5.22:优先用 record.appId 的 channel(谁发的卡片谁才有 patch
1133
+ * 权限),appId 查不到(app 已下线)再退事件所在 channel。
1134
+ * patch 失败(消息太老/无权限)只记日志:卡片状态落后不影响文字兜底。
891
1135
  */
892
- async function patchQuestionCard(ctx, channel, record) {
1136
+ async function patchQuestionCard(ctx, channel, record, channelForApp) {
893
1137
  if (!record.messageId) return
1138
+ const target = (channelForApp && channelForApp(record.appId)) || channel
1139
+ if (!target) return
894
1140
  try {
895
- await channel.updateCard(record.messageId, buildQuestionCard(record))
1141
+ await target.updateCard(record.messageId, buildQuestionCard(record))
896
1142
  } catch (error) {
897
1143
  ctx.logger.warn(`aiyayi-feishu: 卡片刷新失败 ${record.qid}: ${String(error)}`)
898
1144
  }
@@ -921,9 +1167,10 @@ async function deliverLateAnswer(ctx, record) {
921
1167
 
922
1168
  /**
923
1169
  * 文字回答:入站消息里最近一条仍可回答的提问,尝试把这条文本解析成答案。
1170
+ * 1.5.22:channelForApp —— patch 卡片按 record.appId 取发卡片的 channel。
924
1171
  * @returns {Promise<boolean>} true = 已消费(不要再投给会话)。
925
1172
  */
926
- async function tryAnswerByText(ctx, channel, root, chatId, messageId, rawText) {
1173
+ async function tryAnswerByText(ctx, channel, root, chatId, messageId, rawText, channelForApp) {
927
1174
  const text = String(rawText || '').trim()
928
1175
  if (!text) return false
929
1176
  const table = prunePendingQuestions(readPendingQuestions(root))
@@ -941,7 +1188,7 @@ async function tryAnswerByText(ctx, channel, root, chatId, messageId, rawText) {
941
1188
  : `已提交:\n${formatAnswerSummary(record)}`
942
1189
  table[record.qid] = record
943
1190
  writePendingQuestions(root, table)
944
- await patchQuestionCard(ctx, channel, record)
1191
+ await patchQuestionCard(ctx, channel, record, channelForApp)
945
1192
  const waiter = questionWaiters.get(record.qid)
946
1193
  if (waiter) {
947
1194
  waiter.resolve(parsed.kind === 'skip'
@@ -971,13 +1218,15 @@ export function feishuVersion() {
971
1218
 
972
1219
  /**
973
1220
  * 注册 aiyayi 可主动调用的两个飞书工具:
974
- * feishu_status —— 查当前会话/其它会话的飞书绑定情况;
975
- * feishu_bind —— 把当前会话绑定到指定飞书 chat。
1221
+ * feishu_status —— 查当前会话/其它会话的飞书绑定情况 + 所有应用长连接状态;
1222
+ * feishu_bind —— 把当前会话绑定到指定飞书 chat(1.5.22 起先确认归属)。
1223
+ * 1.5.22:apps 为归一化多应用列表;send 是 apply() 传来的基础设施
1224
+ * ({ connectStates, resolveChannelForChat }),无凭证时为 null。
976
1225
  * 二者都读记忆根下 feishu/mappings.json,execute(args, exec) 里用
977
1226
  * exec.agent.session.id 得知调用方会话。注册时登记进 own-tools 放行名单,
978
1227
  * restrict.js 才会放行给 aiyayi。
979
1228
  */
980
- function registerFeishuTools(ctx, root, merged) {
1229
+ function registerFeishuTools(ctx, root, merged, apps, send = null) {
981
1230
  const tools = ctx.get('tools')
982
1231
  if (!tools?.register) {
983
1232
  ctx.logger.warn('aiyayi-feishu: tools 服务不可用,无法注册 feishu_status/feishu_bind。')
@@ -987,12 +1236,12 @@ function registerFeishuTools(ctx, root, merged) {
987
1236
  registerOwnTool('feishu_status')
988
1237
  registerOwnTool('feishu_bind')
989
1238
 
990
- const configured = !!(merged.appId && merged.appSecret)
1239
+ const configured = apps.length > 0
991
1240
 
992
1241
  tools.register({
993
1242
  name: 'feishu_status',
994
1243
  description:
995
- '查看当前会话以及其它 aiyayi 会话对接飞书(聊天机器人)的情况:本会话是否已绑定某个飞书 chat、有哪些其它会话已绑定、飞书长连接是否在运行。新建会话首次对话自查用。注意:没绑定时不要向用户索要 chat_id——接入主要从飞书侧自动发起(用户在飞书里给机器人发条消息即自动新建会话并接入,或发 `绑定会话 <会话名>` 接入指定会话)。',
1244
+ '查看当前会话以及其它 aiyayi 会话对接飞书(聊天机器人)的情况:本会话是否已绑定某个飞书 chat、有哪些其它会话已绑定、每个应用的飞书长连接是否在运行(1.5.22 起支持多应用,apps 里每个 appId 一条独立长连接)。新建会话首次对话自查用。注意:没绑定时不要向用户索要 chat_id——接入主要从飞书侧自动发起(用户在飞书里给机器人发条消息即自动新建会话并接入,或发 `绑定会话 <会话名>` 接入指定会话)。',
996
1245
  parameters: { type: 'object', properties: {}, additionalProperties: false },
997
1246
  output: {
998
1247
  schema: { type: 'object' },
@@ -1015,13 +1264,34 @@ function registerFeishuTools(ctx, root, merged) {
1015
1264
  for (const [chatId, sid] of Object.entries(mappings)) {
1016
1265
  if (sid !== sessionId) otherBound.push({ chatId, sessionId: sid })
1017
1266
  }
1267
+ // 1.5.22:逐应用长连接状态 + chat→app 归属表(不含任何 secret)。
1268
+ const chatOwners = readChatOwners(root)
1269
+ const appsView = apps.map((app) => {
1270
+ const state = send?.connectStates?.get(app.appId) ?? null
1271
+ const chatsOwned = Object.entries(chatOwners)
1272
+ .filter(([, ownerAppId]) => ownerAppId === app.appId)
1273
+ .map(([chatId]) => chatId)
1274
+ const view = {
1275
+ appId: app.appId,
1276
+ connected: state ? state.connected === true : false,
1277
+ chatsOwned,
1278
+ }
1279
+ if (state?.error) view.error = state.error
1280
+ return view
1281
+ })
1282
+ const boundChatAppId = boundChat ? (chatOwners[boundChat] ?? null) : null
1018
1283
  return {
1019
1284
  configured,
1020
- connected: configured, // 长连接随 apply 建立;未配置则为 false。
1285
+ // 语义不变:任一应用长连接在线即 true;具体每条看 apps[].connected。
1286
+ connected: appsView.some((a) => a.connected),
1021
1287
  sessionId,
1022
1288
  boundChat,
1289
+ boundChatAppId,
1023
1290
  otherBound,
1024
1291
  totalBound: Object.keys(mappings).length,
1292
+ apps: appsView,
1293
+ chatOwners,
1294
+ singleApp: apps.length === 1,
1025
1295
  }
1026
1296
  },
1027
1297
  })
@@ -1029,7 +1299,7 @@ function registerFeishuTools(ctx, root, merged) {
1029
1299
  tools.register({
1030
1300
  name: 'feishu_bind',
1031
1301
  description:
1032
- '把当前 aiyayi 会话绑定到指定飞书 chat,使该飞书对话的消息都路由到这个会话、回复也发回那个 chat。传 chatId(飞书会话的 oc_ 开头的 chat_id)。通常只在用户明确给了某个 chat_id、或飞书侧已接入你想反向指定时才用;大多数接入从飞书侧自动发起,用户无需提供 chat_id。',
1302
+ '把当前 aiyayi 会话绑定到指定飞书 chat,使该飞书对话的消息都路由到这个会话、回复也发回那个 chat。传 chatId(飞书会话的 oc_ 开头的 chat_id)。1.5.22 多应用:绑定前会先探测哪个应用是该 chat 成员并回传 appId;没有任何已配置应用是该 chat 成员时绑定会失败(那种 chat 收不到事件也发不出消息)。通常只在用户明确给了某个 chat_id、或飞书侧已接入你想反向指定时才用;大多数接入从飞书侧自动发起,用户无需提供 chat_id。',
1033
1303
  parameters: {
1034
1304
  type: 'object',
1035
1305
  properties: {
@@ -1053,10 +1323,33 @@ function registerFeishuTools(ctx, root, merged) {
1053
1323
  if (!chatId) {
1054
1324
  return { ok: false, error: '缺少 chatId 参数。' }
1055
1325
  }
1326
+ // 1.5.22 归属确认:绑定一个「没有任何本机应用是其成员」的 chat 毫无意义
1327
+ // (收不到事件、发不出消息,必 230002)。确定性探测,不盲绑。
1328
+ // 探测基建故障(网络等)时不否决绑定,回 ok:true + warning(保持旧版可用性)。
1329
+ let ownerAppId = null
1330
+ let warning = null
1331
+ if (send?.resolveChannelForChat) {
1332
+ const resolved = await send.resolveChannelForChat(chatId)
1333
+ if (resolved.ok === 'resolved') {
1334
+ ownerAppId = resolved.appId
1335
+ } else if (resolved.ok === 'not-member') {
1336
+ return {
1337
+ ok: false,
1338
+ chatId,
1339
+ error:
1340
+ '没有任何已配置的飞书应用是该 chat 的成员(成员探测 230002 全否)——绑定不会生效。请确认 chatId 属于本机配置的机器人。',
1341
+ }
1342
+ } else {
1343
+ warning = `归属探测失败(${(resolved.errors || []).join(';')}),已按原样绑定,发送时会再自动探测`
1344
+ }
1345
+ }
1056
1346
  const mappings = readMappings(root)
1057
1347
  mappings[chatId] = sessionId
1058
1348
  writeMappings(root, mappings)
1059
- return { ok: true, chatId, sessionId, bound: true }
1349
+ const result = { ok: true, chatId, sessionId, bound: true }
1350
+ if (ownerAppId) result.appId = ownerAppId
1351
+ if (warning) result.warning = warning
1352
+ return result
1060
1353
  },
1061
1354
  })
1062
1355
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-aiyayi",
3
- "version": "1.5.21",
3
+ "version": "1.5.22",
4
4
  "license": "MIT",
5
5
  "author": "阿依娅伊 <aiyayi@local>",
6
6
  "keywords": [
@@ -40,6 +40,7 @@
40
40
  "lib/feishu.js",
41
41
  "lib/feishu-logic.js",
42
42
  "skills",
43
+ "!skills/feishu-setup/scripts/logs",
43
44
  "cordis.patch.yml",
44
45
  "icon.svg",
45
46
  "CHANGELOG.md",
@@ -0,0 +1,154 @@
1
+ import assert from 'node:assert/strict'
2
+ import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
3
+ import { tmpdir } from 'node:os'
4
+ import { join } from 'node:path'
5
+ import {
6
+ isOutOfChatError,
7
+ migrateConfigFile,
8
+ normalizeApps,
9
+ readChatOwners,
10
+ readConfigFile,
11
+ writeChatOwners,
12
+ writeConfigFile,
13
+ } from '../lib/feishu-logic.js'
14
+
15
+ // ── normalizeApps:旧单应用格式自动包一层 ──
16
+ assert.deepEqual(
17
+ normalizeApps({ appId: 'cli_legacy', appSecret: 'sec1', domain: 'https://open.feishu.cn' }),
18
+ [{ appId: 'cli_legacy', appSecret: 'sec1', domain: 'https://open.feishu.cn' }],
19
+ )
20
+ // 顶层无凭证 → 空数组。
21
+ assert.deepEqual(normalizeApps({ domain: 'x' }), [])
22
+ assert.deepEqual(normalizeApps({}), [])
23
+ assert.deepEqual(normalizeApps(null), [])
24
+
25
+ // ── normalizeApps:apps 数组优先于旧顶层字段 ──
26
+ assert.deepEqual(
27
+ normalizeApps({ appId: 'old', appSecret: 'old-sec', apps: [{ appId: 'cli_a', appSecret: 'sa' }] }),
28
+ [{ appId: 'cli_a', appSecret: 'sa', domain: null }],
29
+ )
30
+ // 多应用 + per-app domain 覆盖(normalizeApps 不掺全局域,per-app 缺省回落 null,
31
+ // 全局域由调用方 feishu.js 的 appDomain = app.domain || merged.domain 补)。
32
+ assert.deepEqual(
33
+ normalizeApps({
34
+ domain: 'https://open.feishu.cn',
35
+ apps: [
36
+ { appId: 'cli_a', appSecret: 'sa' },
37
+ { appId: 'cli_b', appSecret: 'sb', domain: 'https://open.larksuite.com' },
38
+ ],
39
+ }),
40
+ [
41
+ { appId: 'cli_a', appSecret: 'sa', domain: null },
42
+ { appId: 'cli_b', appSecret: 'sb', domain: 'https://open.larksuite.com' },
43
+ ],
44
+ )
45
+ // appId 去重:首个赢;缺 appId / 非 app 对象 / 非 array 的 apps 被忽略。
46
+ assert.deepEqual(
47
+ normalizeApps({ apps: [{ appId: ' dup ', appSecret: '1' }, { appId: 'dup', appSecret: '2' }] }),
48
+ [{ appId: 'dup', appSecret: '1', domain: null }],
49
+ )
50
+ assert.deepEqual(normalizeApps({ apps: ['nope', { appSecret: 'x' }, null] }), [])
51
+
52
+ // ── migrateConfigFile:旧格式 → 备份 + 原地迁移(其余顶层键保留)──
53
+ const root = mkdtempSync(join(tmpdir(), 'feishu-multiapp-test-'))
54
+ try {
55
+ writeConfigFile(root, { appId: 'cli_old', appSecret: 'sec-old', defaultPermissionPreset: 'workspace-write' })
56
+ const mig1 = migrateConfigFile(root)
57
+ assert.equal(mig1.migrated, true)
58
+ assert.equal(mig1.appId, 'cli_old')
59
+ assert.ok(mig1.backup, 'backup path should be reported')
60
+ const migratedFile = readConfigFile(root)
61
+ assert.deepEqual(migratedFile.apps, [{ appId: 'cli_old', appSecret: 'sec-old' }])
62
+ assert.equal(migratedFile.defaultPermissionPreset, 'workspace-write')
63
+ assert.equal(migratedFile.appId, undefined, 'legacy top-level appId should be dropped after migration')
64
+ // 备份文件存在且内容是旧格式(mig1.backup 是完整路径)。
65
+ const backupPath = mig1.backup
66
+ assert.ok(existsSync(backupPath), `backup missing: ${backupPath}`)
67
+ const backupRaw = readFileSync(backupPath, 'utf8').replace(/^\uFEFF/, '')
68
+ assert.ok(JSON.parse(backupRaw).appId === 'cli_old')
69
+
70
+ // 幂等:已是新格式 → already-multi。
71
+ const mig2 = migrateConfigFile(root)
72
+ assert.deepEqual(mig2, { migrated: false, reason: 'already-multi' })
73
+
74
+ // 文件不存在 → missing。
75
+ const mig3 = migrateConfigFile(join(root, 'not-a-root'))
76
+ assert.deepEqual(mig3, { migrated: false, reason: 'missing' })
77
+
78
+ // 坏 JSON → parse:*,且不迁移。
79
+ writeFileSync(join(root, 'feishu', 'config.json'), '{oops', 'utf8')
80
+ const mig4 = migrateConfigFile(root)
81
+ assert.equal(mig4.migrated, false)
82
+ assert.ok(mig4.reason.startsWith('parse'), `reason=${mig4.reason}`)
83
+
84
+ // BOM 容忍:带 BOM 的旧格式照样迁移。
85
+ writeFileSync(
86
+ join(root, 'feishu', 'config.json'),
87
+ '\uFEFF' + JSON.stringify({ appId: 'cli_bom', appSecret: 'sec-bom' }),
88
+ 'utf8',
89
+ )
90
+ const mig5 = migrateConfigFile(root)
91
+ assert.equal(mig5.migrated, true)
92
+ assert.equal(mig5.appId, 'cli_bom')
93
+ assert.deepEqual(readConfigFile(root).apps, [{ appId: 'cli_bom', appSecret: 'sec-bom' }])
94
+ } finally {
95
+ rmSync(root, { recursive: true, force: true })
96
+ }
97
+
98
+ // ── chat-owners.json:读写往返 + 损坏容错 ──
99
+ const root2 = mkdtempSync(join(tmpdir(), 'feishu-owners-test-'))
100
+ try {
101
+ assert.deepEqual(readChatOwners(root2), {}, 'missing file → empty owners')
102
+ writeChatOwners(root2, { 'oc_ed556d47': 'cli_aa7bd555a3ba5c09', 'oc_0348f9a2': 'cli_aa7864baf0bbdbf8' })
103
+ assert.deepEqual(readChatOwners(root2), {
104
+ 'oc_ed556d47': 'cli_aa7bd555a3ba5c09',
105
+ 'oc_0348f9a2': 'cli_aa7864baf0bbdbf8',
106
+ })
107
+ // 覆盖写(writeChatOwners 原样写盘,不做条目过滤;过滤是读侧/调用方职责)。
108
+ writeChatOwners(root2, { 'oc_x': 'cli_a', keep: 'junk', 'oc_y': 42 })
109
+ const owners = readChatOwners(root2)
110
+ assert.deepEqual(owners, { 'oc_x': 'cli_a', keep: 'junk', 'oc_y': 42 })
111
+ // 损坏 → 返回空表,不抛。
112
+ writeFileSync(join(root2, 'feishu', 'chat-owners.json'), 'not-json', 'utf8')
113
+ assert.deepEqual(readChatOwners(root2), {})
114
+ } finally {
115
+ rmSync(root2, { recursive: true, force: true })
116
+ }
117
+
118
+ // ── isOutOfChatError:230002 判定(cause.response.data.code 各层挖)──
119
+ assert.equal(
120
+ isOutOfChatError({ cause: { response: { data: { code: 230002, msg: 'Bot/User can NOT be out of the chat' } } } }),
121
+ true,
122
+ )
123
+ assert.equal(isOutOfChatError({ cause: { data: { code: 230002 } } }), true)
124
+ assert.equal(isOutOfChatError({ code: 230002 }), true)
125
+ assert.equal(isOutOfChatError(new Error('plain boom')), false)
126
+ assert.equal(isOutOfChatError({ cause: { response: { data: { code: 99991663 } } } }), false)
127
+ assert.equal(isOutOfChatError(null), false)
128
+ assert.equal(isOutOfChatError('230002-string'), false, 'bare string is not an error code object')
129
+
130
+ // ── 与旧测试共存检查:迁移后的 config 能被 normalizeApps 直接消化 ──
131
+ const root3 = mkdtempSync(join(tmpdir(), 'feishu-roundtrip-test-'))
132
+ try {
133
+ writeConfigFile(root3, {
134
+ apps: [
135
+ { appId: 'cli_aa7bd555a3ba5c09', appSecret: 's1' },
136
+ { appId: 'cli_aa7864baf0bbdbf8', appSecret: 's2' },
137
+ ],
138
+ })
139
+ const cfg = readConfigFile(root3)
140
+ const apps = normalizeApps(cfg)
141
+ assert.equal(apps.length, 2)
142
+ assert.equal(apps[0].appId, 'cli_aa7bd555a3ba5c09')
143
+ assert.equal(apps[1].appId, 'cli_aa7864baf0bbdbf8')
144
+ assert.equal(apps.every((a) => typeof a.domain === 'string' || a.domain === null), true)
145
+ // 迁移过的新格式文件再跑迁移 → already-multi(幂等闭环)。
146
+ assert.deepEqual(migrateConfigFile(root3), { migrated: false, reason: 'already-multi' })
147
+ // feishu 目录不应残留多余迁移文件(除 config.json 与备份外)。
148
+ const dirFiles = readdirSync(join(root3, 'feishu'))
149
+ assert.deepEqual(dirFiles, ['config.json'])
150
+ } finally {
151
+ rmSync(root3, { recursive: true, force: true })
152
+ }
153
+
154
+ console.log('feishu-multiapp.test.mjs: ALL PASS')