dsh-aiyayi 1.5.21 → 1.5.23
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 +29 -1
- package/lib/feishu-logic.js +159 -1
- package/lib/feishu.js +421 -122
- package/package.json +2 -1
- package/test/feishu-multiapp.test.mjs +154 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,12 +2,40 @@
|
|
|
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.
|
|
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.23(2026-11-11 修复:feishu_bind 对无效 chatId 的确定性拒绝——230001 与 230002 同判 not-member)
|
|
12
|
+
|
|
13
|
+
- 环境:DSH-执行智能体(DeepSeek Harness 子会话,模型名未确证)
|
|
14
|
+
- git:本次 commit(2026-11-11,阿依娅伊)1.5.23:1.5.22 装版静态断言发现的边界修正。
|
|
15
|
+
- 现象:用伪造 chatId(`oc_aaa…` 32 个 a)调 `feishu_bind`,归属探测返回的不是 230002(非成员)而是 **230001 invalid container_id**(chat 根本不存在)——探测代码把非 0/230002 的码一律当"探测故障"抛出,于是走了「探测基建故障→`ok:true + warning` 原样绑定」分支,把一个不存在的 chat 绑进了 mappings。
|
|
16
|
+
- 根因:230001 与 230002 同为飞书的**确定性答案**(前者=chatId 无效/不存在,后者=合法 chat 但非成员),两者都意味着"绑了也没用";只有网络/其他未知错误才是真正的探测故障,应保留 ok:true+warning 的可用性兜底。
|
|
17
|
+
- 修法(`lib/feishu.js` `resolveChannelForChat`):probe 抛错时经 `extractFeishuErrorCode` 挖出 feishuCode===230001 → 不计入探测故障(视同该 app 非成员证据);全部 app 均为 230002 非成员或 230001 抛错且无其他错误 → `{ok:'not-member'}` → `feishu_bind` 返回 `ok:false` 确定拒绝(拒绝文案同时说明两种情形)。
|
|
18
|
+
- 验证:装版后对伪造 chatId 实测返回 ok:false;对真实已绑定 chat 归属探测照常 ok:true+appId。
|
|
19
|
+
|
|
20
|
+
## 1.5.22(2026-11-11 多应用多长连接:双机器人各自收发,根因消灭 230002 错绑发送)
|
|
21
|
+
|
|
22
|
+
- 环境:DSH-执行智能体(DeepSeek Harness 子会话,模型名未确证)
|
|
23
|
+
- 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 维度的)。
|
|
24
|
+
- **config 多应用格式**(`lib/feishu-logic.js`):
|
|
25
|
+
- 新格式 `{"apps":[{"appId","appSecret","domain"?},...]}`,每个应用一条独立长连接;旧顶层 `{appId,appSecret}` 单应用格式**继续兼容**(`normalizeApps` 自动包一层,`apps` 数组优先)。
|
|
26
|
+
- `mergeConfig` 仍是浅合并不变;appId 去重首个赢;per-app `domain` 可覆盖全局 `domain`(缺省回落 `null`,`feishu.js` 里 `appDomain = app.domain || merged.domain` 补全局域)。
|
|
27
|
+
- **自动迁移** `migrateConfigFile(root)`:读到旧格式→先备份 `config.json.bak-<yyyymmdd-HHmmss>`→原地改写为 apps 数组(其余顶层键保留、顶层不再留凭证副本);幂等(已是新格式返回 `already-multi`,文件缺失 `missing`,坏 JSON `parse:*` 不动文件)。apply() 每次启动自动调用。
|
|
28
|
+
- **每应用独立基础设施**(`lib/feishu.js`):逐 app 建 `createTokenManager` + `createLarkChannel({transport:'websocket'})` + `connect()`;WS 断连重连是 SDK `WSClient` 自带(autoReconnect:true, reconnectInterval=120s),各 channel 互不干扰。入站 `messageId` 去重(`SEEN_MESSAGE_LIMIT=2000` 环形缓存)防同群多 bot 重复投递。
|
|
29
|
+
- **归属机制(本次根因修复的核心)**:
|
|
30
|
+
- 落盘 `chat-owners.json`:{chatId→appId}。入站事件(消息/进单聊卡片事件)到达即记录 `recordChatOwner(chatId, 该channel的appId)`——事件从哪条 WS 来,归属就是谁,权威自愈。
|
|
31
|
+
- 发送前归属解析 `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 不能当判据)→命中写入缓存。
|
|
32
|
+
- 发送一律走 `sendViaOwner(chatId, payload)`:先归属解析,再从**该 app 自己的 channel** 发;发送报 230002→清缓存重探重试一次(会话回复/卡片兜底文本路径)。确定性归属,不盲试。
|
|
33
|
+
- 卡片就地刷新(`patchQuestionCard`)优先用 `record.appId` 对应的 channel——卡片是谁发的就必须用谁的凭证 patch。
|
|
34
|
+
- **工具升级**:`feishu_status` 增报 `apps:[{appId,connected,chatsOwned,error?}]`(逐应用长连接状态)、`chatOwners`、`boundChatAppId`、`singleApp`,旧字段全保留;`feishu_bind` 绑定前先探测归属:全部 app 非成员→`ok:false` 确定拒绝(绑了也收不到事件),探测基建故障→`ok:true + warning` 保持可用性,成功→回 `appId`。
|
|
35
|
+
- **既有机制理顺(改动最小化)**:`绑定会话` 指令、pending-bind 30 分钟时效、`bot_p2p_chat_entered_v1` 自动绑定逻辑不变,只是每条 WS 各自处理自己的事件并先记归属;问答卡片/文字兜底/附件下载的 domain 按 app 取。
|
|
36
|
+
- 测试:新增 `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 干净基线一致(磁盘类型探测断言,环境相关,非本次引入)。
|
|
37
|
+
- 部署顺序注意:**先装 1.5.22 再迁移运行版 config.json**(1.5.21 读不懂 apps 格式);迁移脚本自带备份。
|
|
38
|
+
|
|
11
39
|
## 1.5.21(2026-11-11 修复:飞书回复正文首尾空白行)
|
|
12
40
|
|
|
13
41
|
- 环境:DSH-执行智能体(DeepSeek Harness 子会话,模型名未确证)
|
package/lib/feishu-logic.js
CHANGED
|
@@ -5,7 +5,14 @@
|
|
|
5
5
|
* 任何 @deepseek-ai 或 @larksuiteoapi 包。飞书 SDK / dsh-llm 的连接与建会话
|
|
6
6
|
* 都在 feishu.js(宿主插件壳)里做,这里只放可单测的纯函数。
|
|
7
7
|
*/
|
|
8
|
-
import {
|
|
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,268 @@ export function apply(ctx, config) {
|
|
|
159
180
|
)
|
|
160
181
|
|
|
161
182
|
// 没有凭证就不启动长连接(日志提示,不报错)。
|
|
162
|
-
if (
|
|
183
|
+
if (apps.length === 0) {
|
|
163
184
|
ctx.logger.warn(
|
|
164
|
-
`aiyayi-feishu:
|
|
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
|
-
//
|
|
172
|
-
//
|
|
173
|
-
|
|
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
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
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
|
+
* 1.5.23:230002(非成员,probe 返回 member:false)与 230001(invalid
|
|
238
|
+
* container_id,chat 不存在/伪造,probe 抛错)都是飞书的确定性答案,
|
|
239
|
+
* 同判 not-member——绑一个不存在的 chat 与绑非成员 chat 同样无意义。
|
|
240
|
+
*/
|
|
241
|
+
async function resolveChannelForChat(chatId) {
|
|
242
|
+
const owners = readChatOwners(root)
|
|
243
|
+
const recorded = owners[chatId]
|
|
244
|
+
if (recorded && channels.has(recorded)) {
|
|
245
|
+
return { ok: 'resolved', appId: recorded, channel: channels.get(recorded) }
|
|
180
246
|
}
|
|
247
|
+
const errors = []
|
|
248
|
+
let anyProbed = false
|
|
249
|
+
for (const app of apps) {
|
|
250
|
+
anyProbed = true
|
|
251
|
+
try {
|
|
252
|
+
const result = await probeChatMembership({
|
|
253
|
+
domain: app.domain || merged.domain,
|
|
254
|
+
appId: app.appId,
|
|
255
|
+
appSecret: app.appSecret,
|
|
256
|
+
chatId,
|
|
257
|
+
})
|
|
258
|
+
if (result.member) {
|
|
259
|
+
writeChatOwners(root, { ...readChatOwners(root), [chatId]: app.appId })
|
|
260
|
+
return { ok: 'resolved', appId: app.appId, channel: channels.get(app.appId) }
|
|
261
|
+
}
|
|
262
|
+
} catch (error) {
|
|
263
|
+
// 1.5.23:230001 invalid container_id(chat 不存在/伪造)是确定性"不可绑"
|
|
264
|
+
// 证据,与 230002 同判——不计入探测故障,直接视为该 app 非成员。
|
|
265
|
+
if (extractFeishuErrorCode(error) === 230001) continue
|
|
266
|
+
errors.push(`appId=${app.appId}: ${String(error)}`)
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
if (errors.length > 0) return { ok: 'probe-error', errors }
|
|
270
|
+
return anyProbed ? { ok: 'not-member' } : { ok: 'probe-error', errors: ['无可探测的应用'] }
|
|
181
271
|
}
|
|
182
272
|
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
273
|
+
function describeOwnership(resolved) {
|
|
274
|
+
if (resolved.ok === 'not-member') return '没有任何已配置飞书应用是该 chat 的成员'
|
|
275
|
+
if (resolved.ok === 'probe-error') return `归属探测失败(${resolved.errors.join(';')})`
|
|
276
|
+
return '未知归属状态'
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* 经归属解析发送简单 payload(纯文本/卡片——失败重试无重复副作用)。
|
|
281
|
+
* 发送报 230002 → 归属缓存失效自愈:清缓存重探,换正确 app 重试一次。
|
|
282
|
+
* (附件编排 sendReplyWithAttachments 不走这里:逐项内部消化失败,
|
|
283
|
+
* 230002 时无法确认已发出多少,盲试可能重发——归属解析已前置保证正确性。)
|
|
284
|
+
*/
|
|
285
|
+
async function sendViaOwner(chatId, payload, opts, label) {
|
|
286
|
+
let resolved = await resolveChannelForChat(chatId)
|
|
287
|
+
if (resolved.ok !== 'resolved') {
|
|
288
|
+
throw new Error(`${label} 无法发送 chat=${chatId}:${describeOwnership(resolved)}`)
|
|
289
|
+
}
|
|
200
290
|
try {
|
|
201
|
-
await
|
|
291
|
+
return await resolved.channel.sender.send(chatId, payload, opts)
|
|
202
292
|
} catch (error) {
|
|
203
|
-
|
|
293
|
+
if (!isOutOfChatError(error)) throw error
|
|
294
|
+
ctx.logger.warn(
|
|
295
|
+
`aiyayi-feishu: ${label} 报 230002(归属缓存失效),失效重探后重试 chat=${chatId}`,
|
|
296
|
+
)
|
|
297
|
+
const owners = readChatOwners(root)
|
|
298
|
+
delete owners[chatId]
|
|
299
|
+
writeChatOwners(root, owners)
|
|
300
|
+
resolved = await resolveChannelForChat(chatId)
|
|
301
|
+
if (resolved.ok !== 'resolved') throw error
|
|
302
|
+
return await resolved.channel.sender.send(chatId, payload, opts)
|
|
204
303
|
}
|
|
205
304
|
}
|
|
206
305
|
|
|
207
|
-
//
|
|
208
|
-
|
|
209
|
-
//
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
306
|
+
// appId → channel 直查(卡片就地刷新用:卡片是谁发的就必须用谁的凭证 patch)。
|
|
307
|
+
const channelForApp = (appId) => (appId && channels.get(appId)) || null
|
|
308
|
+
// 回填工具层句柄(feishu_status 报每条长连接状态;feishu_bind 发送前探测归属)。
|
|
309
|
+
sendInfra.connectStates = connectStates
|
|
310
|
+
sendInfra.resolveChannelForChat = resolveChannelForChat
|
|
311
|
+
|
|
312
|
+
for (const app of apps) {
|
|
313
|
+
// per-app domain 优先于全局域;tokenManager 每 app 独立(token 缓存互不串号)。
|
|
314
|
+
const appDomain = app.domain || merged.domain
|
|
315
|
+
const getTenantAccessToken = createTokenManager({
|
|
316
|
+
domain: appDomain,
|
|
317
|
+
appId: app.appId,
|
|
318
|
+
appSecret: app.appSecret,
|
|
319
|
+
})
|
|
320
|
+
let channelRef = null
|
|
321
|
+
const onMessage = async (mergedEvent) => {
|
|
216
322
|
try {
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
323
|
+
await onIncomingMessage(ctx, channelRef, mergedEvent, merged, root, getTenantAccessToken, {
|
|
324
|
+
app,
|
|
325
|
+
domain: appDomain,
|
|
326
|
+
markSeenOrDuplicate,
|
|
327
|
+
recordChatOwner,
|
|
328
|
+
channelForApp,
|
|
329
|
+
})
|
|
330
|
+
} catch (error) {
|
|
331
|
+
ctx.logger.warn(`aiyayi-feishu: 处理入站消息失败 appId=${app.appId}: ${String(error)}`)
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
const channel = createLarkChannel({
|
|
335
|
+
appId: app.appId,
|
|
336
|
+
appSecret: app.appSecret,
|
|
337
|
+
domain: appDomain,
|
|
338
|
+
transport: 'websocket',
|
|
339
|
+
handlers: { message: onMessage },
|
|
340
|
+
})
|
|
341
|
+
channelRef = channel
|
|
342
|
+
// 坑 #58:@larksuiteoapi/node-sdk 1.76.0 的 createLarkChannel/LarkChannel 构造函数
|
|
343
|
+
// 不读 opts.handlers(SDK lib/index.js:106879 只设 this.handlers={},107359 原样 new
|
|
344
|
+
// 后返回),传进去的 handlers 被整个丢弃——每条消息 ACK 后在 onMessage 处静默 no-op、
|
|
345
|
+
// 零日志(飞书后台事件日志却显示 SUCCESS)。handlers.message 在派发时才读取,
|
|
346
|
+
// 所以必须在返回的 channel 上显式补接线。
|
|
347
|
+
channel.handlers.message = onMessage
|
|
348
|
+
// 卡片按钮点击:SDK 的长连接默认已注册 `card.action.trigger`(SDK lib/index.js:107291),
|
|
349
|
+
// 但派发只在 `handlers.cardAction` 存在时才真正调业务(107297-107299),
|
|
350
|
+
// 且构造参数里的 handlers 会被丢弃(见上一条坑 #58 同源,106879)。所以显式挂。
|
|
351
|
+
channel.handlers.cardAction = async (event) => {
|
|
352
|
+
try {
|
|
353
|
+
await onCardAction(ctx, channel, event, root, channelForApp)
|
|
354
|
+
} catch (error) {
|
|
355
|
+
ctx.logger.warn(`aiyayi-feishu: 卡片点击处理失败 appId=${app.appId}: ${String(error)}`)
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// 改造 1(1.5.19):用户进入与 bot 的 P2P 单聊事件(im.chat.access_event.
|
|
360
|
+
// bot_p2p_chat_entered_v1,权限要求=无,事件体含 chat_id + operator_id open_id)。
|
|
361
|
+
// SDK 长连接默认只订阅 im.message.receive_v1 / card.action.trigger / reaction /
|
|
362
|
+
// bot.added / drive.notice,不在默认列表里——直接向 channel.dispatcher 补注册
|
|
363
|
+
// (SDK EventDispatcher.register 幂等;connect() 时 registerDispatcherHandlers
|
|
364
|
+
// 只注册固定类型,不会覆盖我们的 key)。
|
|
365
|
+
// 有待接入目标会话(pending-bind.json)→ 自动写 mappings[chat_id]=目标 sessionId
|
|
366
|
+
// 并清除待接入标记、回复确认;无待接入目标 → 仅记录归属不绑定。
|
|
367
|
+
// 1.5.22:每条长连接各自注册;事件从哪条 WS 来就用哪条回(该 app 必是 chat 成员)。
|
|
368
|
+
channel.dispatcher.register({
|
|
369
|
+
'im.chat.access_event.bot_p2p_chat_entered_v1': async (raw) => {
|
|
370
|
+
try {
|
|
371
|
+
const chatId = raw?.event?.chat_id
|
|
372
|
+
if (!chatId) return
|
|
373
|
+
recordChatOwner(chatId, app.appId)
|
|
374
|
+
const pending = readPendingBind(root)
|
|
375
|
+
if (!pending?.sessionId) {
|
|
376
|
+
ctx.logger.info(
|
|
377
|
+
`aiyayi-feishu: 用户进入单聊 chat=${chatId} appId=${app.appId}(无待接入目标,仅记录)`,
|
|
378
|
+
)
|
|
379
|
+
return
|
|
380
|
+
}
|
|
381
|
+
// 1.5.18-fix:待接入目标若指向子智能体,丢弃并清标记。
|
|
382
|
+
// 否则真人 chat 会被绑到一个跑完即休眠的 worker,之后每条飞书消息都投进死会话。
|
|
383
|
+
if (subagentSessions.has(pending.sessionId)) {
|
|
384
|
+
clearPendingBind(root)
|
|
385
|
+
ctx.logger.warn(
|
|
386
|
+
`aiyayi-feishu: 待接入目标 ${pending.sessionId} 是子智能体,已丢弃,不绑定 chat=${chatId}`,
|
|
387
|
+
)
|
|
388
|
+
return
|
|
389
|
+
}
|
|
390
|
+
// 时效:待接入目标超过 PENDING_BIND_TTL_MS 视为过期,清除后不自动绑定。
|
|
391
|
+
if (Date.now() - (pending.createdAt || 0) > PENDING_BIND_TTL_MS) {
|
|
392
|
+
clearPendingBind(root)
|
|
393
|
+
ctx.logger.info(
|
|
394
|
+
`aiyayi-feishu: 待接入目标已过期(会话 ${pending.sessionId}),清除,不自动绑定 chat=${chatId}`,
|
|
395
|
+
)
|
|
396
|
+
return
|
|
397
|
+
}
|
|
398
|
+
const refreshed = readMappings(root)
|
|
399
|
+
refreshed[chatId] = pending.sessionId
|
|
400
|
+
writeMappings(root, refreshed)
|
|
235
401
|
clearPendingBind(root)
|
|
236
402
|
ctx.logger.info(
|
|
237
|
-
`aiyayi-feishu:
|
|
403
|
+
`aiyayi-feishu: 用户进入单聊 chat=${chatId}(appId=${app.appId}),已自动接入会话 ${pending.sessionId}`,
|
|
238
404
|
)
|
|
239
|
-
|
|
405
|
+
await replyToChat(
|
|
406
|
+
channel,
|
|
407
|
+
chatId,
|
|
408
|
+
null,
|
|
409
|
+
`已自动接入 aiyayi 会话 ${pending.sessionId},现在可以直接在手机飞书上找我啦。`,
|
|
410
|
+
)
|
|
411
|
+
} catch (error) {
|
|
412
|
+
ctx.logger.warn(`aiyayi-feishu: bot_p2p_chat_entered_v1 处理失败: ${String(error)}`)
|
|
240
413
|
}
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
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
|
-
})
|
|
414
|
+
},
|
|
415
|
+
})
|
|
416
|
+
|
|
417
|
+
channels.set(app.appId, channel)
|
|
418
|
+
}
|
|
259
419
|
|
|
260
|
-
//
|
|
420
|
+
// 建立长连接:所有应用并发 connect,互不等待;任一条失败只记该 app 的状态,
|
|
421
|
+
// 不影响其他条(SDK 每 channel 独立自动重连循环,断连自愈)。
|
|
261
422
|
ctx.effect(
|
|
262
423
|
() => {
|
|
263
|
-
channel
|
|
264
|
-
|
|
265
|
-
|
|
424
|
+
for (const [appId, channel] of channels) {
|
|
425
|
+
const state = connectStates.get(appId)
|
|
426
|
+
channel
|
|
427
|
+
.connect()
|
|
428
|
+
.then(() => {
|
|
429
|
+
state.connected = true
|
|
430
|
+
state.error = null
|
|
431
|
+
state.connectedAt = Date.now()
|
|
432
|
+
ctx.logger.info(`aiyayi-feishu: 长连接已建立 appId=${appId}`)
|
|
433
|
+
})
|
|
434
|
+
.catch((error) => {
|
|
435
|
+
state.error = String(error)
|
|
436
|
+
ctx.logger.warn(`aiyayi-feishu: 飞书长连接失败 appId=${appId}: ${String(error)}`)
|
|
437
|
+
})
|
|
438
|
+
}
|
|
266
439
|
return () => {
|
|
267
440
|
// 防御:SDK disconnect() 在 WS 未初始化时返回 undefined(SDK 107014 行注释),
|
|
268
441
|
// 直接 .catch 会 TypeError。包一层 Promise.resolve。
|
|
269
|
-
|
|
442
|
+
for (const channel of channels.values()) {
|
|
443
|
+
Promise.resolve(channel.disconnect()).catch(() => {})
|
|
444
|
+
}
|
|
270
445
|
}
|
|
271
446
|
},
|
|
272
447
|
'aiyayi-feishu.connect()',
|
|
@@ -278,7 +453,7 @@ export function apply(ctx, config) {
|
|
|
278
453
|
// 监听者拿到 (request, next),返回答案即「认领」,调 next() 表示交给下游
|
|
279
454
|
// (桌面 GUI 的 answerer 在 dsh-client-ui-user-questions :asar .../lib/client.js:2277)。
|
|
280
455
|
// 所以这里必须排在 GUI 前面才能抢到——用 prepend。
|
|
281
|
-
registerQuestionAnswerer(ctx,
|
|
456
|
+
registerQuestionAnswerer(ctx, { sendViaOwner, resolveChannelForChat, channelForApp }, root)
|
|
282
457
|
|
|
283
458
|
// 回发:监听 host 级 session/event 总线,只处理属于已绑定会话的 assistant 消息。
|
|
284
459
|
// 同一轮 turn 里 assistant/message 是渐进追加的(每个 step 一条,settle 替换),
|
|
@@ -291,12 +466,43 @@ export function apply(ctx, config) {
|
|
|
291
466
|
// 每次发送前重读映射,避免 feishu_bind / 入站绑定新增后 relay 漏发。
|
|
292
467
|
const chatId = reverseLookup(readMappings(root), sessionId)
|
|
293
468
|
if (!chatId) return
|
|
469
|
+
// 1.5.22 根因修复:回发前先解析 chat→app 归属,用目标 chat 所属应用的凭证发——
|
|
470
|
+
// 非成员 app 发送必 230002(2026-11-11 实锤的根因类别)。
|
|
294
471
|
// 1.5.18/1.5.19:回发支持 [附件: <路径>] / [图片: <路径>] 标记——逐条按扩展名
|
|
295
472
|
// 分流(图片→msg_type=image,其他→file,失败降级),再发剥离标记后的正文
|
|
296
|
-
// (编排见 feishu-logic.sendReplyWithAttachments
|
|
297
|
-
//
|
|
298
|
-
|
|
299
|
-
|
|
473
|
+
// (编排见 feishu-logic.sendReplyWithAttachments)。附件编排不盲试重发
|
|
474
|
+
// (230002 时无法确认已发出多少),归属解析已前置保证正确性。
|
|
475
|
+
void (async () => {
|
|
476
|
+
const resolved = await resolveChannelForChat(chatId)
|
|
477
|
+
if (resolved.ok !== 'resolved') {
|
|
478
|
+
ctx.logger.warn(`aiyayi-feishu: 回发 ${chatId} 失败:${describeOwnership(resolved)}`)
|
|
479
|
+
return
|
|
480
|
+
}
|
|
481
|
+
try {
|
|
482
|
+
await sendReplyWithAttachments(resolved.channel, chatId, text, ctx.logger)
|
|
483
|
+
} catch (error) {
|
|
484
|
+
if (!isOutOfChatError(error)) {
|
|
485
|
+
ctx.logger.warn(`aiyayi-feishu: 回发 ${chatId} 失败: ${String(error)}`)
|
|
486
|
+
return
|
|
487
|
+
}
|
|
488
|
+
// 归属缓存失效自愈:清缓存重探换 app 重试一次。
|
|
489
|
+
ctx.logger.warn(`aiyayi-feishu: 回发 ${chatId} 报 230002,失效重探后重试`)
|
|
490
|
+
const owners = readChatOwners(root)
|
|
491
|
+
delete owners[chatId]
|
|
492
|
+
writeChatOwners(root, owners)
|
|
493
|
+
const retry = await resolveChannelForChat(chatId)
|
|
494
|
+
if (retry.ok !== 'resolved') {
|
|
495
|
+
ctx.logger.warn(`aiyayi-feishu: 回发重试放弃:${describeOwnership(retry)}`)
|
|
496
|
+
return
|
|
497
|
+
}
|
|
498
|
+
try {
|
|
499
|
+
await sendReplyWithAttachments(retry.channel, chatId, text, ctx.logger)
|
|
500
|
+
} catch (retryError) {
|
|
501
|
+
ctx.logger.warn(`aiyayi-feishu: 回发重试仍失败: ${String(retryError)}`)
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
})().catch((error) => {
|
|
505
|
+
ctx.logger.warn(`aiyayi-feishu: 回发编排异常: ${String(error)}`)
|
|
300
506
|
})
|
|
301
507
|
}
|
|
302
508
|
ctx.effect(
|
|
@@ -336,7 +542,7 @@ export function apply(ctx, config) {
|
|
|
336
542
|
)
|
|
337
543
|
|
|
338
544
|
ctx.logger.info(
|
|
339
|
-
`aiyayi-feishu: 已就绪,记忆根 ${root}
|
|
545
|
+
`aiyayi-feishu: 已就绪,记忆根 ${root}(${apps.length} 个应用长连接,已绑定 ${Object.keys(mappings).length} 个 chat)`,
|
|
340
546
|
)
|
|
341
547
|
}
|
|
342
548
|
|
|
@@ -376,12 +582,31 @@ function isSubagentSession(session) {
|
|
|
376
582
|
* 收一条入站消息:按自然语言指令决定绑定/新建/投递。
|
|
377
583
|
* 1.5.18:非 bind 分支先做附件收集下载(bind 只写映射不投递,无需下载),
|
|
378
584
|
* 保存/失败提示并进投递文本;下载失败不阻断消息投递。
|
|
585
|
+
* 1.5.22:route = { app, domain, markSeenOrDuplicate, recordChatOwner }——
|
|
586
|
+
* 事件从哪条长连接来就带哪个 app 的身份(该 app 必是此 chat 成员);
|
|
587
|
+
* 到达即记录归属 + messageId 去重(同群双 bot 场景同一条消息会推到多条 WS)。
|
|
379
588
|
*/
|
|
380
|
-
async function onIncomingMessage(
|
|
589
|
+
async function onIncomingMessage(
|
|
590
|
+
ctx,
|
|
591
|
+
channel,
|
|
592
|
+
mergedEvent,
|
|
593
|
+
merged,
|
|
594
|
+
root,
|
|
595
|
+
getTenantAccessToken,
|
|
596
|
+
route,
|
|
597
|
+
) {
|
|
381
598
|
const chatId = mergedEvent.chatId
|
|
382
599
|
const messageId = mergedEvent.messageId
|
|
383
600
|
const rawText = mergedEvent.content || ''
|
|
384
601
|
if (!chatId) return
|
|
602
|
+
const appId = route?.app?.appId ?? null
|
|
603
|
+
|
|
604
|
+
// 1.5.22:归属记录(权威自愈)+ 跨 WS 去重。去重必须先于归属记录之外的一切处理。
|
|
605
|
+
route?.recordChatOwner?.(chatId, appId)
|
|
606
|
+
if (route?.markSeenOrDuplicate?.(messageId)) {
|
|
607
|
+
ctx.logger.info(`aiyayi-feishu: 跳过重复消息 ${messageId}(其他应用长连接已处理)`)
|
|
608
|
+
return
|
|
609
|
+
}
|
|
385
610
|
|
|
386
611
|
// 坑 #66:机器人自己发出的消息也会以 im.message.receive_v1 推回来(同样进 handler),
|
|
387
612
|
// 若不跳过就会把「已新建并接入…」「正式回答」当成用户输入再喂给会话 → 自问自答死循环。
|
|
@@ -401,7 +626,7 @@ async function onIncomingMessage(ctx, channel, mergedEvent, merged, root, getTen
|
|
|
401
626
|
// 必须排在路由之前——否则用户回的「2」会被当普通消息投给会话,提问永远等不到答案。
|
|
402
627
|
// 解析不出答案(普通聊天正文)时返回 false,照常走路由,行为与 1.5.18 一致。
|
|
403
628
|
try {
|
|
404
|
-
const consumed = await tryAnswerByText(ctx, channel, root, chatId, messageId, rawText)
|
|
629
|
+
const consumed = await tryAnswerByText(ctx, channel, root, chatId, messageId, rawText, route?.channelForApp)
|
|
405
630
|
if (consumed) return
|
|
406
631
|
} catch (error) {
|
|
407
632
|
ctx.logger.warn(`aiyayi-feishu: 文字回答处理失败(继续按普通消息投递): ${String(error)}`)
|
|
@@ -420,7 +645,8 @@ async function onIncomingMessage(ctx, channel, mergedEvent, merged, root, getTen
|
|
|
420
645
|
logger: ctx.logger,
|
|
421
646
|
mergedEvent,
|
|
422
647
|
root,
|
|
423
|
-
domain
|
|
648
|
+
// 1.5.22:per-app 域优先(app.domain || 全局 merged.domain),token 也是该 app 的。
|
|
649
|
+
domain: route?.domain || merged.domain,
|
|
424
650
|
getTenantAccessToken,
|
|
425
651
|
})
|
|
426
652
|
} catch (error) {
|
|
@@ -625,11 +851,13 @@ function blockingTimeoutMs() {
|
|
|
625
851
|
|
|
626
852
|
/**
|
|
627
853
|
* 把本插件挂进 user-questions waterfall。
|
|
854
|
+
* 1.5.22:fns = { sendViaOwner, resolveChannelForChat, channelForApp }——
|
|
855
|
+
* 发卡片/文字前先解析 chat→app 归属,用目标 chat 所属应用的凭证发送。
|
|
628
856
|
* @param {object} ctx - Cordis 上下文(插件 fiber)。
|
|
629
|
-
* @param {object}
|
|
857
|
+
* @param {object} fns - apply() 里的发送/归属基础设施。
|
|
630
858
|
* @param {string} root - 记忆根。
|
|
631
859
|
*/
|
|
632
|
-
function registerQuestionAnswerer(ctx,
|
|
860
|
+
function registerQuestionAnswerer(ctx, fns, root) {
|
|
633
861
|
if (process.env[CARD_SWITCH_ENV] === '0') {
|
|
634
862
|
ctx.logger.info(`aiyayi-feishu: ${CARD_SWITCH_ENV}=0,卡片问答已关闭(走桌面 GUI 原生卡片)`)
|
|
635
863
|
return
|
|
@@ -646,7 +874,7 @@ function registerQuestionAnswerer(ctx, channel, root) {
|
|
|
646
874
|
'user-questions/request',
|
|
647
875
|
async (request, next) => {
|
|
648
876
|
try {
|
|
649
|
-
const claimed = await answerViaFeishu(ctx,
|
|
877
|
+
const claimed = await answerViaFeishu(ctx, fns, root, request)
|
|
650
878
|
if (claimed !== undefined) return claimed
|
|
651
879
|
} catch (error) {
|
|
652
880
|
// 认领失败必须回落 next(),否则提问会以插件异常的形式炸掉整轮对话。
|
|
@@ -664,15 +892,23 @@ function registerQuestionAnswerer(ctx, channel, root) {
|
|
|
664
892
|
|
|
665
893
|
/**
|
|
666
894
|
* 一次提问的飞书侧处理:发卡片(或文字兜底)→ 等用户点/回 → 返回答案。
|
|
895
|
+
* 1.5.22:发送前解析 chat→app 归属(fns.resolveChannelForChat);非成员 app 发送
|
|
896
|
+
* 必 230002(本次改造要消灭的根因类别),归属解析不出来就交回 GUI answerer。
|
|
667
897
|
* @returns {Promise<{answers:Array}|undefined>} undefined = 不认领,交回 next()。
|
|
668
898
|
*/
|
|
669
|
-
async function answerViaFeishu(ctx,
|
|
899
|
+
async function answerViaFeishu(ctx, fns, root, request) {
|
|
670
900
|
const agent = request?.agent
|
|
671
901
|
const sessionId = agent?.session?.id
|
|
672
902
|
if (!sessionId) return undefined
|
|
673
903
|
// 只接管「已绑定飞书 chat 的会话」:没绑定就让 GUI 原生卡片照常工作。
|
|
674
904
|
const chatId = reverseLookup(readMappings(root), sessionId)
|
|
675
905
|
if (!chatId) return undefined
|
|
906
|
+
// 1.5.22:先定归属。解析不出(非成员/探测失败)→ 不认领,GUI 兜底。
|
|
907
|
+
const resolved = await fns.resolveChannelForChat(chatId)
|
|
908
|
+
if (resolved.ok !== 'resolved') {
|
|
909
|
+
ctx.logger.warn(`aiyayi-feishu: 问答卡片放弃接管 ${chatId}:归属解析失败(${resolved.ok})`)
|
|
910
|
+
return undefined
|
|
911
|
+
}
|
|
676
912
|
const questions = Array.isArray(request.questions) ? request.questions : []
|
|
677
913
|
if (questions.length === 0) return undefined
|
|
678
914
|
|
|
@@ -680,6 +916,8 @@ async function answerViaFeishu(ctx, channel, root, request) {
|
|
|
680
916
|
qid: `q-${randomUUID()}`,
|
|
681
917
|
chatId,
|
|
682
918
|
sessionId,
|
|
919
|
+
// 1.5.22:记录归属 appId——卡片是谁发的就必须用谁的凭证就地刷新(updateCard)。
|
|
920
|
+
appId: resolved.appId,
|
|
683
921
|
callId: request.wait?.callId ?? null,
|
|
684
922
|
timed: request.wait?.timed === true,
|
|
685
923
|
createdAt: Date.now(),
|
|
@@ -712,7 +950,7 @@ async function answerViaFeishu(ctx, channel, root, request) {
|
|
|
712
950
|
// 1) 先试卡片;失败就退文字编号列表(权限/事件订阅没配好时卡片点不动)。
|
|
713
951
|
let cardSent = false
|
|
714
952
|
try {
|
|
715
|
-
const sent = await
|
|
953
|
+
const sent = await fns.sendViaOwner(chatId, { card: buildQuestionCard(record) }, {}, '问答卡片')
|
|
716
954
|
record.messageId = sent?.messageId ?? null
|
|
717
955
|
cardSent = true
|
|
718
956
|
ctx.logger.info(`aiyayi-feishu: 已发问答卡片 ${record.qid} → ${chatId} msg=${record.messageId}`)
|
|
@@ -723,7 +961,7 @@ async function answerViaFeishu(ctx, channel, root, request) {
|
|
|
723
961
|
}
|
|
724
962
|
if (!cardSent) {
|
|
725
963
|
try {
|
|
726
|
-
await
|
|
964
|
+
await fns.sendViaOwner(chatId, { text: buildQuestionText(record) }, {}, '问答文字兜底')
|
|
727
965
|
} catch (error) {
|
|
728
966
|
// 连文字都发不出去:不认领,交回 GUI。提问不能因为飞书侧故障而丢掉。
|
|
729
967
|
ctx.logger.warn(`aiyayi-feishu: 问答文字兜底也失败,交回下游: ${String(error)}`)
|
|
@@ -737,8 +975,10 @@ async function answerViaFeishu(ctx, channel, root, request) {
|
|
|
737
975
|
writePendingQuestions(root, persisted)
|
|
738
976
|
|
|
739
977
|
// 2) 等用户点/回(或宿主取消)。
|
|
740
|
-
const answer = await waitForQuestionAnswer(ctx, root,
|
|
978
|
+
const answer = await waitForQuestionAnswer(ctx, root, record, request.signal, {
|
|
741
979
|
timeoutMs: blockingTimeoutMs(),
|
|
980
|
+
sendViaOwner: fns.sendViaOwner,
|
|
981
|
+
channelForApp: fns.channelForApp,
|
|
742
982
|
})
|
|
743
983
|
if (answer === undefined) {
|
|
744
984
|
// 取消/超时后才轮到下游:此时宿主自己会按 ASK_ABORTED/ASK_TIMED_OUT 处理。
|
|
@@ -752,9 +992,11 @@ const questionWaiters = new Map() // qid → {resolve, cleanup}
|
|
|
752
992
|
|
|
753
993
|
/**
|
|
754
994
|
* 等一条提问被回答。
|
|
995
|
+
* 1.5.22:卡片就地刷新按 record.appId 取发卡片的那条 channel(卡片是谁发的
|
|
996
|
+
* 就必须用谁的凭证 patch);超时通知经 sendViaOwner 走归属解析发送。
|
|
755
997
|
* @returns {Promise<{answers:Array}|undefined>} undefined = 宿主取消/超时,交回下游。
|
|
756
998
|
*/
|
|
757
|
-
function waitForQuestionAnswer(ctx, root,
|
|
999
|
+
function waitForQuestionAnswer(ctx, root, record, signal, opts = {}) {
|
|
758
1000
|
return new Promise((resolve) => {
|
|
759
1001
|
let done = false
|
|
760
1002
|
let timer = null
|
|
@@ -781,6 +1023,7 @@ function waitForQuestionAnswer(ctx, root, channel, record, signal, opts = {}) {
|
|
|
781
1023
|
: '已结束(本轮已中断,本次提问不能补答;需要的话让助手重新提问)'
|
|
782
1024
|
writePendingQuestions(root, table)
|
|
783
1025
|
// 卡片就地改成结束态,避免用户对着还能点但没人收的卡片发呆。
|
|
1026
|
+
const channel = opts.channelForApp?.(record.appId) ?? null
|
|
784
1027
|
if (record.messageId && channel) {
|
|
785
1028
|
channel.updateCard(record.messageId, buildQuestionCard(table[record.qid])).catch(() => {})
|
|
786
1029
|
}
|
|
@@ -808,6 +1051,7 @@ function waitForQuestionAnswer(ctx, root, channel, record, signal, opts = {}) {
|
|
|
808
1051
|
table[record.qid].status = 'expired'
|
|
809
1052
|
table[record.qid].statusText = '已超时,本次按「跳过」继续;需要的话让助手重新提问'
|
|
810
1053
|
writePendingQuestions(root, table)
|
|
1054
|
+
const channel = opts.channelForApp?.(record.appId) ?? null
|
|
811
1055
|
if (record.messageId && channel) {
|
|
812
1056
|
channel.updateCard(record.messageId, buildQuestionCard(table[record.qid])).catch(() => {})
|
|
813
1057
|
}
|
|
@@ -815,12 +1059,14 @@ function waitForQuestionAnswer(ctx, root, channel, record, signal, opts = {}) {
|
|
|
815
1059
|
ctx.logger.warn(
|
|
816
1060
|
`aiyayi-feishu: 提问 ${record.qid} 本地超时(${opts.timeoutMs}ms),按全部跳过放行`,
|
|
817
1061
|
)
|
|
818
|
-
void
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
1062
|
+
void opts
|
|
1063
|
+
.sendViaOwner?.(
|
|
1064
|
+
record.chatId,
|
|
1065
|
+
{ text: `提问 ${record.qid} 等待超时(${Math.round(opts.timeoutMs / 1000)} 秒),本次按「跳过」继续。` },
|
|
1066
|
+
{},
|
|
1067
|
+
'提问超时通知',
|
|
1068
|
+
)
|
|
1069
|
+
.catch(() => {})
|
|
824
1070
|
finish({ answers: record.questions.map((q) => ({ id: String(q.id), selected: [] })) })
|
|
825
1071
|
}, opts.timeoutMs)
|
|
826
1072
|
}
|
|
@@ -845,8 +1091,10 @@ function liveQuestion(root, qid) {
|
|
|
845
1091
|
/**
|
|
846
1092
|
* 处理一次卡片点击(SDK 已 normalize,见 lib/index.js:106709-106732)。
|
|
847
1093
|
* 事件形状:{messageId, chatId, operator:{openId}, action:{value, tag, name, option}}。
|
|
1094
|
+
* 1.5.22:channelForApp —— patch 卡片优先用 record.appId 对应的 channel(发卡片的
|
|
1095
|
+
* app 才有 patch 权限),事件所在 channel 只作兜底。
|
|
848
1096
|
*/
|
|
849
|
-
async function onCardAction(ctx, channel, event, root) {
|
|
1097
|
+
async function onCardAction(ctx, channel, event, root, channelForApp) {
|
|
850
1098
|
const value = event?.action?.value
|
|
851
1099
|
if (!value || typeof value !== 'object') return
|
|
852
1100
|
const record = liveQuestion(root, value.q)
|
|
@@ -867,7 +1115,7 @@ async function onCardAction(ctx, channel, event, root) {
|
|
|
867
1115
|
record.status = 'answered'
|
|
868
1116
|
record.statusText = `已提交:\n${formatAnswerSummary(record)}`
|
|
869
1117
|
writePendingQuestions(root, table)
|
|
870
|
-
await patchQuestionCard(ctx, channel, record)
|
|
1118
|
+
await patchQuestionCard(ctx, channel, record, channelForApp)
|
|
871
1119
|
const waiter = questionWaiters.get(record.qid)
|
|
872
1120
|
if (waiter) {
|
|
873
1121
|
waiter.resolve(composeAnswerBatch(record))
|
|
@@ -880,19 +1128,23 @@ async function onCardAction(ctx, channel, event, root) {
|
|
|
880
1128
|
|
|
881
1129
|
if (applied.changed) {
|
|
882
1130
|
writePendingQuestions(root, table)
|
|
883
|
-
await patchQuestionCard(ctx, channel, record)
|
|
1131
|
+
await patchQuestionCard(ctx, channel, record, channelForApp)
|
|
884
1132
|
// 中途状态也要回 ACK:卡片回调 3 秒内必须响应(SDK README.zh.md:629),
|
|
885
1133
|
// patch 是异步的,这里不 await 具体结果,失败只记日志。
|
|
886
1134
|
}
|
|
887
1135
|
}
|
|
888
1136
|
|
|
889
1137
|
/**
|
|
890
|
-
* 就地刷新卡片。patch
|
|
1138
|
+
* 就地刷新卡片。1.5.22:优先用 record.appId 的 channel(谁发的卡片谁才有 patch
|
|
1139
|
+
* 权限),appId 查不到(app 已下线)再退事件所在 channel。
|
|
1140
|
+
* patch 失败(消息太老/无权限)只记日志:卡片状态落后不影响文字兜底。
|
|
891
1141
|
*/
|
|
892
|
-
async function patchQuestionCard(ctx, channel, record) {
|
|
1142
|
+
async function patchQuestionCard(ctx, channel, record, channelForApp) {
|
|
893
1143
|
if (!record.messageId) return
|
|
1144
|
+
const target = (channelForApp && channelForApp(record.appId)) || channel
|
|
1145
|
+
if (!target) return
|
|
894
1146
|
try {
|
|
895
|
-
await
|
|
1147
|
+
await target.updateCard(record.messageId, buildQuestionCard(record))
|
|
896
1148
|
} catch (error) {
|
|
897
1149
|
ctx.logger.warn(`aiyayi-feishu: 卡片刷新失败 ${record.qid}: ${String(error)}`)
|
|
898
1150
|
}
|
|
@@ -921,9 +1173,10 @@ async function deliverLateAnswer(ctx, record) {
|
|
|
921
1173
|
|
|
922
1174
|
/**
|
|
923
1175
|
* 文字回答:入站消息里最近一条仍可回答的提问,尝试把这条文本解析成答案。
|
|
1176
|
+
* 1.5.22:channelForApp —— patch 卡片按 record.appId 取发卡片的 channel。
|
|
924
1177
|
* @returns {Promise<boolean>} true = 已消费(不要再投给会话)。
|
|
925
1178
|
*/
|
|
926
|
-
async function tryAnswerByText(ctx, channel, root, chatId, messageId, rawText) {
|
|
1179
|
+
async function tryAnswerByText(ctx, channel, root, chatId, messageId, rawText, channelForApp) {
|
|
927
1180
|
const text = String(rawText || '').trim()
|
|
928
1181
|
if (!text) return false
|
|
929
1182
|
const table = prunePendingQuestions(readPendingQuestions(root))
|
|
@@ -941,7 +1194,7 @@ async function tryAnswerByText(ctx, channel, root, chatId, messageId, rawText) {
|
|
|
941
1194
|
: `已提交:\n${formatAnswerSummary(record)}`
|
|
942
1195
|
table[record.qid] = record
|
|
943
1196
|
writePendingQuestions(root, table)
|
|
944
|
-
await patchQuestionCard(ctx, channel, record)
|
|
1197
|
+
await patchQuestionCard(ctx, channel, record, channelForApp)
|
|
945
1198
|
const waiter = questionWaiters.get(record.qid)
|
|
946
1199
|
if (waiter) {
|
|
947
1200
|
waiter.resolve(parsed.kind === 'skip'
|
|
@@ -971,13 +1224,15 @@ export function feishuVersion() {
|
|
|
971
1224
|
|
|
972
1225
|
/**
|
|
973
1226
|
* 注册 aiyayi 可主动调用的两个飞书工具:
|
|
974
|
-
* feishu_status ——
|
|
975
|
-
* feishu_bind —— 把当前会话绑定到指定飞书 chat
|
|
1227
|
+
* feishu_status —— 查当前会话/其它会话的飞书绑定情况 + 所有应用长连接状态;
|
|
1228
|
+
* feishu_bind —— 把当前会话绑定到指定飞书 chat(1.5.22 起先确认归属)。
|
|
1229
|
+
* 1.5.22:apps 为归一化多应用列表;send 是 apply() 传来的基础设施
|
|
1230
|
+
* ({ connectStates, resolveChannelForChat }),无凭证时为 null。
|
|
976
1231
|
* 二者都读记忆根下 feishu/mappings.json,execute(args, exec) 里用
|
|
977
1232
|
* exec.agent.session.id 得知调用方会话。注册时登记进 own-tools 放行名单,
|
|
978
1233
|
* restrict.js 才会放行给 aiyayi。
|
|
979
1234
|
*/
|
|
980
|
-
function registerFeishuTools(ctx, root, merged) {
|
|
1235
|
+
function registerFeishuTools(ctx, root, merged, apps, send = null) {
|
|
981
1236
|
const tools = ctx.get('tools')
|
|
982
1237
|
if (!tools?.register) {
|
|
983
1238
|
ctx.logger.warn('aiyayi-feishu: tools 服务不可用,无法注册 feishu_status/feishu_bind。')
|
|
@@ -987,12 +1242,12 @@ function registerFeishuTools(ctx, root, merged) {
|
|
|
987
1242
|
registerOwnTool('feishu_status')
|
|
988
1243
|
registerOwnTool('feishu_bind')
|
|
989
1244
|
|
|
990
|
-
const configured =
|
|
1245
|
+
const configured = apps.length > 0
|
|
991
1246
|
|
|
992
1247
|
tools.register({
|
|
993
1248
|
name: 'feishu_status',
|
|
994
1249
|
description:
|
|
995
|
-
'查看当前会话以及其它 aiyayi 会话对接飞书(聊天机器人)的情况:本会话是否已绑定某个飞书 chat
|
|
1250
|
+
'查看当前会话以及其它 aiyayi 会话对接飞书(聊天机器人)的情况:本会话是否已绑定某个飞书 chat、有哪些其它会话已绑定、每个应用的飞书长连接是否在运行(1.5.22 起支持多应用,apps 里每个 appId 一条独立长连接)。新建会话首次对话自查用。注意:没绑定时不要向用户索要 chat_id——接入主要从飞书侧自动发起(用户在飞书里给机器人发条消息即自动新建会话并接入,或发 `绑定会话 <会话名>` 接入指定会话)。',
|
|
996
1251
|
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
|
997
1252
|
output: {
|
|
998
1253
|
schema: { type: 'object' },
|
|
@@ -1015,13 +1270,34 @@ function registerFeishuTools(ctx, root, merged) {
|
|
|
1015
1270
|
for (const [chatId, sid] of Object.entries(mappings)) {
|
|
1016
1271
|
if (sid !== sessionId) otherBound.push({ chatId, sessionId: sid })
|
|
1017
1272
|
}
|
|
1273
|
+
// 1.5.22:逐应用长连接状态 + chat→app 归属表(不含任何 secret)。
|
|
1274
|
+
const chatOwners = readChatOwners(root)
|
|
1275
|
+
const appsView = apps.map((app) => {
|
|
1276
|
+
const state = send?.connectStates?.get(app.appId) ?? null
|
|
1277
|
+
const chatsOwned = Object.entries(chatOwners)
|
|
1278
|
+
.filter(([, ownerAppId]) => ownerAppId === app.appId)
|
|
1279
|
+
.map(([chatId]) => chatId)
|
|
1280
|
+
const view = {
|
|
1281
|
+
appId: app.appId,
|
|
1282
|
+
connected: state ? state.connected === true : false,
|
|
1283
|
+
chatsOwned,
|
|
1284
|
+
}
|
|
1285
|
+
if (state?.error) view.error = state.error
|
|
1286
|
+
return view
|
|
1287
|
+
})
|
|
1288
|
+
const boundChatAppId = boundChat ? (chatOwners[boundChat] ?? null) : null
|
|
1018
1289
|
return {
|
|
1019
1290
|
configured,
|
|
1020
|
-
|
|
1291
|
+
// 语义不变:任一应用长连接在线即 true;具体每条看 apps[].connected。
|
|
1292
|
+
connected: appsView.some((a) => a.connected),
|
|
1021
1293
|
sessionId,
|
|
1022
1294
|
boundChat,
|
|
1295
|
+
boundChatAppId,
|
|
1023
1296
|
otherBound,
|
|
1024
1297
|
totalBound: Object.keys(mappings).length,
|
|
1298
|
+
apps: appsView,
|
|
1299
|
+
chatOwners,
|
|
1300
|
+
singleApp: apps.length === 1,
|
|
1025
1301
|
}
|
|
1026
1302
|
},
|
|
1027
1303
|
})
|
|
@@ -1029,7 +1305,7 @@ function registerFeishuTools(ctx, root, merged) {
|
|
|
1029
1305
|
tools.register({
|
|
1030
1306
|
name: 'feishu_bind',
|
|
1031
1307
|
description:
|
|
1032
|
-
'把当前 aiyayi 会话绑定到指定飞书 chat,使该飞书对话的消息都路由到这个会话、回复也发回那个 chat。传 chatId(飞书会话的 oc_ 开头的 chat_id
|
|
1308
|
+
'把当前 aiyayi 会话绑定到指定飞书 chat,使该飞书对话的消息都路由到这个会话、回复也发回那个 chat。传 chatId(飞书会话的 oc_ 开头的 chat_id)。1.5.22 多应用:绑定前会先探测哪个应用是该 chat 成员并回传 appId;没有任何已配置应用是该 chat 成员时绑定会失败(那种 chat 收不到事件也发不出消息)。通常只在用户明确给了某个 chat_id、或飞书侧已接入你想反向指定时才用;大多数接入从飞书侧自动发起,用户无需提供 chat_id。',
|
|
1033
1309
|
parameters: {
|
|
1034
1310
|
type: 'object',
|
|
1035
1311
|
properties: {
|
|
@@ -1053,10 +1329,33 @@ function registerFeishuTools(ctx, root, merged) {
|
|
|
1053
1329
|
if (!chatId) {
|
|
1054
1330
|
return { ok: false, error: '缺少 chatId 参数。' }
|
|
1055
1331
|
}
|
|
1332
|
+
// 1.5.22 归属确认:绑定一个「没有任何本机应用是其成员」的 chat 毫无意义
|
|
1333
|
+
// (收不到事件、发不出消息,必 230002)。确定性探测,不盲绑。
|
|
1334
|
+
// 探测基建故障(网络等)时不否决绑定,回 ok:true + warning(保持旧版可用性)。
|
|
1335
|
+
let ownerAppId = null
|
|
1336
|
+
let warning = null
|
|
1337
|
+
if (send?.resolveChannelForChat) {
|
|
1338
|
+
const resolved = await send.resolveChannelForChat(chatId)
|
|
1339
|
+
if (resolved.ok === 'resolved') {
|
|
1340
|
+
ownerAppId = resolved.appId
|
|
1341
|
+
} else if (resolved.ok === 'not-member') {
|
|
1342
|
+
return {
|
|
1343
|
+
ok: false,
|
|
1344
|
+
chatId,
|
|
1345
|
+
error:
|
|
1346
|
+
'没有任何已配置的飞书应用是该 chat 的成员(成员探测 230002 全否),或该 chatId 无效/不存在(230001 invalid container_id)——绑定不会生效。请确认 chatId 属于本机配置的机器人。',
|
|
1347
|
+
}
|
|
1348
|
+
} else {
|
|
1349
|
+
warning = `归属探测失败(${(resolved.errors || []).join(';')}),已按原样绑定,发送时会再自动探测`
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1056
1352
|
const mappings = readMappings(root)
|
|
1057
1353
|
mappings[chatId] = sessionId
|
|
1058
1354
|
writeMappings(root, mappings)
|
|
1059
|
-
|
|
1355
|
+
const result = { ok: true, chatId, sessionId, bound: true }
|
|
1356
|
+
if (ownerAppId) result.appId = ownerAppId
|
|
1357
|
+
if (warning) result.warning = warning
|
|
1358
|
+
return result
|
|
1060
1359
|
},
|
|
1061
1360
|
})
|
|
1062
1361
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-aiyayi",
|
|
3
|
-
"version": "1.5.
|
|
3
|
+
"version": "1.5.23",
|
|
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')
|