@suwenguang/pi-feishu-bridge 0.0.0-stage → 0.6.2

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.
Files changed (52) hide show
  1. package/.pi/extensions/feishu/index.ts +11 -0
  2. package/.pi/feishu/debug.pi.log +81 -0
  3. package/.pi/feishu/state.pi.json +12 -0
  4. package/README.md +210 -2
  5. package/package.json +57 -4
  6. package/src/adapters/pi/PiConversationRuntime.ts +1559 -0
  7. package/src/adapters/pi/index.ts +1169 -0
  8. package/src/adapters/pi/setup.ts +108 -0
  9. package/src/feishu/app-register.ts +50 -0
  10. package/src/feishu/ask.ts +388 -0
  11. package/src/feishu/attachment-processor.ts +198 -0
  12. package/src/feishu/attachments.ts +192 -0
  13. package/src/feishu/bridge-runtime.ts +129 -0
  14. package/src/feishu/bridge-store.ts +92 -0
  15. package/src/feishu/card-action-webhook.ts +141 -0
  16. package/src/feishu/card-actions.ts +241 -0
  17. package/src/feishu/card-builder.ts +277 -0
  18. package/src/feishu/cardkit-stream.ts +483 -0
  19. package/src/feishu/cards.ts +413 -0
  20. package/src/feishu/config.ts +427 -0
  21. package/src/feishu/daemon-spec.ts +43 -0
  22. package/src/feishu/debug.ts +51 -0
  23. package/src/feishu/dedupe-store.ts +150 -0
  24. package/src/feishu/delivery.ts +185 -0
  25. package/src/feishu/gateway-lock.ts +256 -0
  26. package/src/feishu/group-trigger.ts +128 -0
  27. package/src/feishu/image-send.ts +256 -0
  28. package/src/feishu/instance.ts +170 -0
  29. package/src/feishu/instances.ts +148 -0
  30. package/src/feishu/interactive-card.ts +236 -0
  31. package/src/feishu/learn-approval.ts +321 -0
  32. package/src/feishu/live-cards.ts +128 -0
  33. package/src/feishu/message-handler.ts +512 -0
  34. package/src/feishu/messages.ts +356 -0
  35. package/src/feishu/oversize-progress-card.ts +101 -0
  36. package/src/feishu/progress-channel.ts +154 -0
  37. package/src/feishu/progress-note.ts +371 -0
  38. package/src/feishu/prompt-timeout.ts +81 -0
  39. package/src/feishu/reply-card-options.ts +73 -0
  40. package/src/feishu/reply-card.ts +498 -0
  41. package/src/feishu/restart.ts +286 -0
  42. package/src/feishu/retry.ts +102 -0
  43. package/src/feishu/rich-text.ts +387 -0
  44. package/src/feishu/runtime-config.ts +286 -0
  45. package/src/feishu/runtime.ts +110 -0
  46. package/src/feishu/slash-commands.ts +239 -0
  47. package/src/feishu/thinking.ts +24 -0
  48. package/src/feishu/transport.ts +792 -0
  49. package/src/feishu/types.ts +183 -0
  50. package/src/feishu/ui-notify.ts +44 -0
  51. package/src/feishu/user-name.ts +121 -0
  52. package/src/feishu/workspace.ts +42 -0
@@ -0,0 +1,185 @@
1
+ import { loadConfig } from "./config.ts";
2
+ import { debugLog } from "./debug.ts";
3
+ import type { FeishuRoute } from "./types.ts";
4
+ import type { FeishuTransport } from "./transport.ts";
5
+ import { buildMarkdownCards, buildPostMessages, chooseMessageMode } from "./rich-text.ts";
6
+
7
+ const TEXT_CHUNK_MAX_BYTES = 120 * 1024;
8
+
9
+ export class FeishuDelivery {
10
+ private sdkClient: any;
11
+ private readonly getTransport: () => FeishuTransport | undefined;
12
+
13
+ constructor(getTransport: () => FeishuTransport | undefined) {
14
+ this.getTransport = getTransport;
15
+ }
16
+
17
+ async send(route: FeishuRoute, text: string) {
18
+ const transport = this.getTransport();
19
+ if (transport?.isRunning()) {
20
+ if (route.threadMessageId) await transport.replyText(route.threadMessageId, text);
21
+ else await transport.sendText(route.chatId, text);
22
+ return;
23
+ }
24
+
25
+ await this.ensureClient();
26
+ if (route.threadMessageId) await this.replyText(route.threadMessageId, text);
27
+ else await this.sendText(route.chatId, text);
28
+ }
29
+
30
+ private async ensureClient() {
31
+ if (this.sdkClient) return;
32
+ const cfg = loadConfig();
33
+ if (!cfg) throw new Error("Missing Feishu config");
34
+ const lark = await import("@larksuiteoapi/node-sdk");
35
+ const domain = cfg.domain === "lark" ? lark.Domain.Lark : lark.Domain.Feishu;
36
+ this.sdkClient = new lark.Client({
37
+ appId: cfg.appId,
38
+ appSecret: cfg.appSecret,
39
+ appType: lark.AppType.SelfBuild,
40
+ domain,
41
+ loggerLevel: lark.LoggerLevel.error,
42
+ });
43
+ }
44
+
45
+ private async replyText(messageId: string, text: string) {
46
+ const mode = chooseMessageMode(text);
47
+ if (mode === "interactive") {
48
+ await this.replyMarkdownCard(messageId, text);
49
+ return;
50
+ }
51
+ if (mode === "post") {
52
+ await this.replyPost(messageId, text);
53
+ return;
54
+ }
55
+ debugLog("feishu.bridge.reply", { messageId, length: text.length });
56
+ for (const chunk of splitText(text, TEXT_CHUNK_MAX_BYTES)) {
57
+ await this.sdkClient.im.message.reply({
58
+ path: { message_id: messageId },
59
+ data: { msg_type: "text", content: JSON.stringify({ text: chunk }) },
60
+ });
61
+ }
62
+ }
63
+
64
+ private async sendText(chatId: string, text: string) {
65
+ const mode = chooseMessageMode(text);
66
+ if (mode === "interactive") {
67
+ await this.sendMarkdownCard(chatId, text);
68
+ return;
69
+ }
70
+ if (mode === "post") {
71
+ await this.sendPost(chatId, text);
72
+ return;
73
+ }
74
+ debugLog("feishu.bridge.send", { chatId, length: text.length });
75
+ for (const chunk of splitText(text, TEXT_CHUNK_MAX_BYTES)) {
76
+ await this.sdkClient.im.message.create({
77
+ params: { receive_id_type: "chat_id" },
78
+ data: {
79
+ receive_id: chatId,
80
+ msg_type: "text",
81
+ content: JSON.stringify({ text: chunk }),
82
+ },
83
+ });
84
+ }
85
+ }
86
+
87
+ private async replyMarkdownCard(messageId: string, text: string) {
88
+ const cfg = loadConfig();
89
+ debugLog("feishu.bridge.reply_markdown_card", { messageId, length: text.length });
90
+ for (const card of buildMarkdownCards(text, cfg?.language)) {
91
+ await this.sdkClient.im.message.reply({
92
+ path: { message_id: messageId },
93
+ data: { msg_type: "interactive", content: JSON.stringify(card) },
94
+ });
95
+ }
96
+ }
97
+
98
+ private async sendMarkdownCard(chatId: string, text: string) {
99
+ const cfg = loadConfig();
100
+ debugLog("feishu.bridge.send_markdown_card", { chatId, length: text.length });
101
+ for (const card of buildMarkdownCards(text, cfg?.language)) {
102
+ await this.sdkClient.im.message.create({
103
+ params: { receive_id_type: "chat_id" },
104
+ data: {
105
+ receive_id: chatId,
106
+ msg_type: "interactive",
107
+ content: JSON.stringify(card),
108
+ },
109
+ });
110
+ }
111
+ }
112
+
113
+ private async replyPost(messageId: string, text: string) {
114
+ const cfg = loadConfig();
115
+ debugLog("feishu.bridge.reply_post", { messageId, length: text.length });
116
+ for (const post of buildPostMessages(text, cfg?.language)) {
117
+ await this.sdkClient.im.message.reply({
118
+ path: { message_id: messageId },
119
+ data: { msg_type: "post", content: JSON.stringify(post) },
120
+ });
121
+ }
122
+ }
123
+
124
+ private async sendPost(chatId: string, text: string) {
125
+ const cfg = loadConfig();
126
+ debugLog("feishu.bridge.send_post", { chatId, length: text.length });
127
+ for (const post of buildPostMessages(text, cfg?.language)) {
128
+ await this.sdkClient.im.message.create({
129
+ params: { receive_id_type: "chat_id" },
130
+ data: {
131
+ receive_id: chatId,
132
+ msg_type: "post",
133
+ content: JSON.stringify(post),
134
+ },
135
+ });
136
+ }
137
+ }
138
+ }
139
+
140
+ function splitText(text: string, maxBytes: number) {
141
+ const out: string[] = [];
142
+ let rest = text.trim() || "(empty response)";
143
+ while (textPayloadSize(rest) > maxBytes) {
144
+ const cut = findCutIndexByBytes(rest, maxBytes);
145
+ out.push(rest.slice(0, cut));
146
+ rest = rest.slice(cut);
147
+ }
148
+ out.push(rest);
149
+ return out;
150
+ }
151
+
152
+ function findCutIndexByBytes(text: string, maxBytes: number) {
153
+ let low = 1;
154
+ let high = text.length;
155
+ let best = 1;
156
+ while (low <= high) {
157
+ const mid = Math.floor((low + high) / 2);
158
+ const safeMid = avoidHalfSurrogate(text, mid);
159
+ if (safeMid > 0 && textPayloadSize(text.slice(0, safeMid)) <= maxBytes) {
160
+ best = safeMid;
161
+ low = mid + 1;
162
+ } else {
163
+ high = mid - 1;
164
+ }
165
+ }
166
+
167
+ const newline = text.lastIndexOf("\n", best);
168
+ if (newline > 0 && newline >= Math.floor(best * 0.6)) return newline + 1;
169
+ return Math.max(1, best);
170
+ }
171
+
172
+ function avoidHalfSurrogate(text: string, index: number) {
173
+ if (index <= 0 || index >= text.length) return index;
174
+ const prev = text.charCodeAt(index - 1);
175
+ if (prev >= 0xd800 && prev <= 0xdbff) return index - 1;
176
+ return index;
177
+ }
178
+
179
+ function byteSize(text: string) {
180
+ return Buffer.byteLength(text, "utf8");
181
+ }
182
+
183
+ function textPayloadSize(text: string) {
184
+ return byteSize(JSON.stringify({ text }));
185
+ }
@@ -0,0 +1,256 @@
1
+ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { debugLog } from "./debug.ts";
5
+
6
+ /** 兼容旧版锁(未按 appId 区分时的固定 key)。 */
7
+ const LEGACY_LOCK_KEY = "pi-feishu-lark.feishu-gateway";
8
+ /** 网关锁 key 前缀:`<前缀><appId>`,一个机器人一把锁。 */
9
+ const GATEWAY_LOCK_PREFIX = "ax-feishu-bridge.gateway.";
10
+ const PI_AGENT_DIR = join(homedir(), ".pi", "agent");
11
+ const LOCK_STALE_MS = 30_000;
12
+ const LOCK_RETRY_MS = 25;
13
+ const LOCK_ATTEMPTS = 40;
14
+ const HEARTBEAT_MS = 5_000;
15
+
16
+ /**
17
+ * 锁按机器人凭证(appId)区分:不同机器人各拿各的钥匙,可并行;
18
+ * 同一机器人(误配)仍互斥,避免抢同一个飞书连接。
19
+ */
20
+ function lockKeyFor(appId: string | undefined) {
21
+ return appId ? `${GATEWAY_LOCK_PREFIX}${appId}` : LEGACY_LOCK_KEY;
22
+ }
23
+
24
+ /**
25
+ * 锁文件选址:一律在 Pi 的 agent 目录(`~/.pi/agent/locks.json`)。
26
+ * 锁按 appId 全局互斥是护栏:飞书长连接是集群模式、不广播,
27
+ * 同一台机器上多个工作区共用同一个机器人会互相抢连接,所以要放在机器级位置协商。
28
+ */
29
+ const LOCKS_PATH = join(PI_AGENT_DIR, "locks.json");
30
+
31
+ export type GatewayOwner = {
32
+ key: string;
33
+ pid: number;
34
+ token: string;
35
+ cwd: string;
36
+ startedAt: string;
37
+ heartbeatAt: string;
38
+ status: "starting" | "connected" | "disconnected";
39
+ };
40
+
41
+ type LocksFile = Record<string, unknown>;
42
+
43
+ export type GatewayLockResult =
44
+ | { status: "acquired"; handle: GatewayLockHandle }
45
+ | { status: "busy"; owner: GatewayOwner };
46
+
47
+ export class GatewayLockHandle {
48
+ private heartbeat: NodeJS.Timeout | undefined;
49
+ private onLost: (() => void | Promise<void>) | undefined;
50
+ readonly owner: GatewayOwner;
51
+
52
+ constructor(owner: GatewayOwner) {
53
+ this.owner = owner;
54
+ }
55
+
56
+ setOnLost(handler: () => void | Promise<void>) {
57
+ this.onLost = handler;
58
+ }
59
+
60
+ startHeartbeat() {
61
+ if (this.heartbeat) return;
62
+ this.heartbeat = setInterval(() => {
63
+ this.update("connected").catch((error) => {
64
+ debugLog("feishu.gateway.heartbeat_error", { error: error instanceof Error ? error.message : String(error) });
65
+ });
66
+ }, HEARTBEAT_MS);
67
+ this.heartbeat.unref?.();
68
+ }
69
+
70
+ async update(status: GatewayOwner["status"]) {
71
+ let lostOwnership = false;
72
+ await withLocksFileLock(() => {
73
+ const locks = readLocksFile();
74
+ const current = asGatewayOwner(locks[this.owner.key], this.owner.key);
75
+ if (!current || current.token !== this.owner.token || current.pid !== this.owner.pid) {
76
+ this.stopHeartbeat();
77
+ lostOwnership = true;
78
+ return;
79
+ }
80
+ const next: GatewayOwner = {
81
+ ...current,
82
+ heartbeatAt: new Date().toISOString(),
83
+ status,
84
+ };
85
+ locks[this.owner.key] = next;
86
+ writeLocksFile(locks);
87
+ });
88
+ if (lostOwnership) {
89
+ debugLog("feishu.gateway.lock_lost", { pid: this.owner.pid });
90
+ await this.onLost?.();
91
+ }
92
+ }
93
+
94
+ async release() {
95
+ this.stopHeartbeat();
96
+ await withLocksFileLock(() => {
97
+ const locks = readLocksFile();
98
+ const current = asGatewayOwner(locks[this.owner.key], this.owner.key);
99
+ if (current?.token === this.owner.token && current.pid === this.owner.pid) {
100
+ delete locks[this.owner.key];
101
+ writeLocksFile(locks);
102
+ debugLog("feishu.gateway.lock_released", { pid: this.owner.pid });
103
+ }
104
+ });
105
+ }
106
+
107
+ private stopHeartbeat() {
108
+ if (!this.heartbeat) return;
109
+ clearInterval(this.heartbeat);
110
+ this.heartbeat = undefined;
111
+ }
112
+ }
113
+
114
+ export async function acquireGatewayLock(cwd: string, force = false, appId?: string): Promise<GatewayLockResult> {
115
+ const key = lockKeyFor(appId);
116
+ return withLocksFileLock(() => {
117
+ const locks = readLocksFile();
118
+ const existing = asGatewayOwner(locks[key], key);
119
+ if (existing && !force && !isStale(existing)) {
120
+ debugLog("feishu.gateway.lock_busy", {
121
+ ownerPid: existing.pid,
122
+ heartbeatAt: existing.heartbeatAt,
123
+ currentPid: process.pid,
124
+ });
125
+ return { status: "busy", owner: existing };
126
+ }
127
+
128
+ const owner: GatewayOwner = {
129
+ key,
130
+ pid: process.pid,
131
+ token: randomToken(),
132
+ cwd,
133
+ startedAt: new Date().toISOString(),
134
+ heartbeatAt: new Date().toISOString(),
135
+ status: "starting",
136
+ };
137
+ locks[key] = owner;
138
+ writeLocksFile(locks);
139
+ debugLog("feishu.gateway.lock_acquired", {
140
+ pid: owner.pid,
141
+ cwd,
142
+ replacedPid: existing?.pid,
143
+ force,
144
+ });
145
+ return { status: "acquired", handle: new GatewayLockHandle(owner) };
146
+ });
147
+ }
148
+
149
+ export function readGatewayOwner(appId?: string): GatewayOwner | undefined {
150
+ const key = lockKeyFor(appId);
151
+ const owner = asGatewayOwner(readLocksFile()[key], key);
152
+ return owner && !isStale(owner) ? owner : undefined;
153
+ }
154
+
155
+ /**
156
+ * 列出本机**所有**实例(所有 appId,含 legacy key)当前活着的网关锁 owner pid。
157
+ *
158
+ * 用途:残留 daemon 回收只能按命令行里的 `feishu/index.ts` 广谱匹配 —— 各工作区共用同一份
159
+ * 插件源码,子串匹配分不出实例归属。多开(同机多工作区 + 各自的自建应用)时必须以锁为准:
160
+ * 凡被任何一把网关锁认领的 pid 都不回收,否则重启一个工作区会把另一个工作区一起 SIGTERM。
161
+ */
162
+ export function readAllGatewayOwnerPids(): number[] {
163
+ const locks = readLocksFile();
164
+ const pids = new Set<number>();
165
+ for (const [key, value] of Object.entries(locks)) {
166
+ if (key !== LEGACY_LOCK_KEY && !key.startsWith(GATEWAY_LOCK_PREFIX)) continue;
167
+ const owner = asGatewayOwner(value, key);
168
+ // 死 pid 留着没用,还可能已被系统回收给无关进程 —— 只认活着的
169
+ if (owner && isProcessAlive(owner.pid)) pids.add(owner.pid);
170
+ }
171
+ return [...pids];
172
+ }
173
+
174
+ export function gatewayLockPath() {
175
+ return LOCKS_PATH;
176
+ }
177
+
178
+ function asGatewayOwner(value: unknown, expectedKey: string): GatewayOwner | undefined {
179
+ if (!value || typeof value !== "object") return undefined;
180
+ const raw = value as Partial<GatewayOwner>;
181
+ if (raw.key !== expectedKey) return undefined;
182
+ if (typeof raw.pid !== "number" || typeof raw.token !== "string") return undefined;
183
+ if (typeof raw.cwd !== "string" || typeof raw.startedAt !== "string" || typeof raw.heartbeatAt !== "string") return undefined;
184
+ if (raw.status !== "starting" && raw.status !== "connected" && raw.status !== "disconnected") return undefined;
185
+ return raw as GatewayOwner;
186
+ }
187
+
188
+ function isStale(owner: GatewayOwner) {
189
+ if (!isProcessAlive(owner.pid)) return true;
190
+ const heartbeatAt = Date.parse(owner.heartbeatAt);
191
+ if (!Number.isFinite(heartbeatAt)) return true;
192
+ return Date.now() - heartbeatAt > LOCK_STALE_MS;
193
+ }
194
+
195
+ function isProcessAlive(pid: number) {
196
+ try {
197
+ process.kill(pid, 0);
198
+ return true;
199
+ } catch {
200
+ return false;
201
+ }
202
+ }
203
+
204
+ function randomToken() {
205
+ return `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
206
+ }
207
+
208
+ function readLocksFile(): LocksFile {
209
+ try {
210
+ if (!existsSync(LOCKS_PATH)) return {};
211
+ return JSON.parse(readFileSync(LOCKS_PATH, "utf8")) as LocksFile;
212
+ } catch {
213
+ return {};
214
+ }
215
+ }
216
+
217
+ function writeLocksFile(locks: LocksFile) {
218
+ mkdirSync(dirname(LOCKS_PATH), { recursive: true });
219
+ writeFileSync(LOCKS_PATH, `${JSON.stringify(locks, null, 2)}\n`, "utf8");
220
+ }
221
+
222
+ async function withLocksFileLock<T>(fn: () => T | Promise<T>): Promise<T> {
223
+ const lockPath = `${LOCKS_PATH}.lock`;
224
+ mkdirSync(dirname(LOCKS_PATH), { recursive: true });
225
+
226
+ for (let attempt = 0; attempt < LOCK_ATTEMPTS; attempt += 1) {
227
+ if (tryAcquireFileLock(lockPath)) {
228
+ try {
229
+ return await fn();
230
+ } finally {
231
+ try { rmSync(lockPath, { recursive: true, force: true }); } catch {}
232
+ }
233
+ }
234
+ await sleep(LOCK_RETRY_MS);
235
+ }
236
+
237
+ debugLog("feishu.gateway.file_lock_timeout", { lockPath });
238
+ return await fn();
239
+ }
240
+
241
+ function tryAcquireFileLock(lockPath: string) {
242
+ try {
243
+ mkdirSync(lockPath);
244
+ return true;
245
+ } catch {
246
+ try {
247
+ const age = Date.now() - statSync(lockPath).mtimeMs;
248
+ if (age > LOCK_STALE_MS) rmSync(lockPath, { recursive: true, force: true });
249
+ } catch {}
250
+ return false;
251
+ }
252
+ }
253
+
254
+ function sleep(ms: number) {
255
+ return new Promise((resolve) => setTimeout(resolve, ms));
256
+ }
@@ -0,0 +1,128 @@
1
+ import { extractTextFromInteractiveCard } from "./interactive-card.ts";
2
+
3
+ export type GroupTriggerDecision = {
4
+ accept: boolean;
5
+ reason:
6
+ | "p2p"
7
+ | "open"
8
+ | "mentioned"
9
+ | "keyword"
10
+ | "reply_to_bot"
11
+ | "not_mentioned"
12
+ | "mention_all_only"
13
+ | "no_keyword";
14
+ };
15
+
16
+ export type GroupTriggerInput = {
17
+ chatType: "p2p" | "group" | string;
18
+ groupPolicy: "open" | "mention";
19
+ mentioned: boolean;
20
+ text: string;
21
+ keywords: string[];
22
+ alsoOnReply: boolean;
23
+ replyToBot: boolean;
24
+ /** 消息里只有 @所有人(@_all)、并没有 @ 本机器人 */
25
+ mentionAllOnly?: boolean;
26
+ };
27
+
28
+ /** 解析关键词:逗号/分号分隔字符串,或字符串数组 */
29
+ export function parseGroupKeywords(value: unknown): string[] {
30
+ if (Array.isArray(value)) {
31
+ return value
32
+ .map((v) => (typeof v === "string" ? v.trim() : ""))
33
+ .filter(Boolean);
34
+ }
35
+ if (typeof value !== "string") return [];
36
+ return value
37
+ .split(/[,;]/)
38
+ .map((s) => s.trim())
39
+ .filter(Boolean);
40
+ }
41
+
42
+ /** 大小写不敏感子串匹配;先把空白压成单空格 */
43
+ export function textMatchesKeywords(text: string, keywords: string[]): boolean {
44
+ if (!keywords.length) return false;
45
+ const normalized = text.replace(/\s+/g, " ").trim().toLowerCase();
46
+ if (!normalized) return false;
47
+ return keywords.some((k) => {
48
+ const key = k.replace(/\s+/g, " ").trim().toLowerCase();
49
+ return key.length > 0 && normalized.includes(key);
50
+ });
51
+ }
52
+
53
+ /** 从飞书原始 content JSON 抽触发用纯文本(轻量,不依赖完整 parseMessageInput) */
54
+ export function extractPlainTextForTrigger(msgType: string, content: string): string {
55
+ // interactive 卡片:复用完整抽取,供 groupKeywords 子串匹配
56
+ if (msgType === "interactive") {
57
+ try {
58
+ return extractTextFromInteractiveCard(content, { maxChars: 4000 }).text.trim();
59
+ } catch {
60
+ return "";
61
+ }
62
+ }
63
+ try {
64
+ const json = JSON.parse(content || "{}");
65
+ if (msgType === "text") {
66
+ return String(json.text || "").trim();
67
+ }
68
+ if (msgType === "post") {
69
+ const parts: string[] = [];
70
+ for (const locale of Object.values(json) as Array<{ title?: string; content?: unknown[] }>) {
71
+ if (!locale || typeof locale !== "object") continue;
72
+ if (typeof locale.title === "string" && locale.title.trim()) parts.push(locale.title.trim());
73
+ for (const para of locale.content || []) {
74
+ if (!Array.isArray(para)) continue;
75
+ const line = para
76
+ .map((el: any) => {
77
+ if (el?.tag === "text" && typeof el.text === "string") return el.text;
78
+ if (el?.tag === "a" && typeof el.text === "string") return el.text;
79
+ return "";
80
+ })
81
+ .join("");
82
+ if (line.trim()) parts.push(line.trim());
83
+ }
84
+ }
85
+ return parts.join("\n").trim();
86
+ }
87
+ } catch {
88
+ // fall through
89
+ }
90
+ if (msgType === "text") return content || "";
91
+ return "";
92
+ }
93
+
94
+ /**
95
+ * 群聊触发决策(私聊始终 accept)。
96
+ * mention 基线 + 可选 keyword / alsoOnReply 叠加。
97
+ */
98
+ export function shouldAcceptGroupMessage(input: GroupTriggerInput): GroupTriggerDecision {
99
+ if (input.chatType === "p2p") {
100
+ return { accept: true, reason: "p2p" };
101
+ }
102
+
103
+ if (input.groupPolicy === "open") {
104
+ // @所有人 不等于 @ 机器人:这种消息不触发,避免刷卡片(2026-10-22 强森要求)
105
+ if (input.mentionAllOnly) {
106
+ return { accept: false, reason: "mention_all_only" };
107
+ }
108
+ return { accept: true, reason: "open" };
109
+ }
110
+
111
+ // mention 基线(及未来 keyword-only 仍走叠加语义)
112
+ if (input.mentioned) {
113
+ return { accept: true, reason: "mentioned" };
114
+ }
115
+ if (textMatchesKeywords(input.text, input.keywords)) {
116
+ return { accept: true, reason: "keyword" };
117
+ }
118
+ if (input.alsoOnReply && input.replyToBot) {
119
+ return { accept: true, reason: "reply_to_bot" };
120
+ }
121
+
122
+ // 有关键词配置但未命中时,日志可区分;最终统一为 not_mentioned 语义也可
123
+ if (input.keywords.length > 0 && !input.mentioned) {
124
+ return { accept: false, reason: "not_mentioned" };
125
+ }
126
+ return { accept: false, reason: "not_mentioned" };
127
+ }
128
+