@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,387 @@
1
+ type LocaleKey = "zh_cn" | "en_us";
2
+
3
+ type PostTextElement = {
4
+ tag: "text";
5
+ text: string;
6
+ style?: string[];
7
+ };
8
+
9
+ type PostLinkElement = {
10
+ tag: "a";
11
+ text: string;
12
+ href: string;
13
+ };
14
+
15
+ type PostElement = PostTextElement | PostLinkElement;
16
+
17
+ export type FeishuMessageMode = "text" | "post" | "interactive";
18
+ export type MarkdownCardPart = {
19
+ card: object;
20
+ markdown: string;
21
+ };
22
+
23
+ const POST_LENGTH_THRESHOLD = 250;
24
+ const INTERACTIVE_LENGTH_THRESHOLD = 1200;
25
+ const MAX_POST_CHARS = 3500;
26
+ const MAX_CARD_BYTES = 29 * 1024;
27
+
28
+ export function shouldUseRichText(text: string) {
29
+ return chooseMessageMode(text) === "post";
30
+ }
31
+
32
+ export function chooseMessageMode(text: string): FeishuMessageMode {
33
+ const trimmed = text.trim();
34
+ if (!trimmed) return "text";
35
+ const metrics = analyzeText(trimmed);
36
+ if (
37
+ trimmed.length >= INTERACTIVE_LENGTH_THRESHOLD ||
38
+ metrics.hasTable ||
39
+ metrics.codeBlockCount > 0 ||
40
+ metrics.headingCount >= 3 ||
41
+ metrics.listItemCount >= 8 ||
42
+ metrics.linkCount >= 5
43
+ ) {
44
+ return "interactive";
45
+ }
46
+ if (metrics.lineCount >= 2 && (metrics.looksLikeMarkdown || trimmed.length >= POST_LENGTH_THRESHOLD)) return "post";
47
+ return "text";
48
+ }
49
+
50
+ export function buildMarkdownCard(text: string, language: "zh" | "en" = "zh") {
51
+ const trimmed = text.trim() || "(empty response)";
52
+ const { title, body } = extractMarkdownTitle(trimmed, language);
53
+ return createMarkdownCard(title, body || trimmed);
54
+ }
55
+
56
+ export function buildMarkdownCards(text: string, language: "zh" | "en" = "zh") {
57
+ return buildMarkdownCardParts(text, language).map((part) => part.card);
58
+ }
59
+
60
+ export function buildMarkdownCardParts(text: string, language: "zh" | "en" = "zh", copySourceId?: (index: number) => string): MarkdownCardPart[] {
61
+ const trimmed = text.trim() || "(empty response)";
62
+ const { title, body } = extractMarkdownTitle(trimmed, language);
63
+ const withCopyButton = Boolean(copySourceId);
64
+ const fullCard = createMarkdownCard(title, body || trimmed, withCopyButton ? "__copy_source_id__" : undefined);
65
+ if (byteSize(fullCard) < MAX_CARD_BYTES) {
66
+ const markdown = body || trimmed;
67
+ return [{ card: createMarkdownCard(title, markdown, copySourceId?.(0)), markdown }];
68
+ }
69
+
70
+ const parts = splitMarkdownToFit(body || trimmed, title, withCopyButton);
71
+ if (parts.length === 1) return [{ card: createMarkdownCard(title, parts[0], copySourceId?.(0)), markdown: parts[0] }];
72
+ return parts.map((part, index) => ({
73
+ card: createMarkdownCard(`${title} (${index + 1}/${parts.length})`, part, copySourceId?.(index)),
74
+ markdown: part,
75
+ }));
76
+ }
77
+
78
+ function createMarkdownCard(title: string, content: string, copySourceId?: string) {
79
+ return {
80
+ schema: "2.0",
81
+ header: {
82
+ title: {
83
+ tag: "plain_text",
84
+ content: title,
85
+ },
86
+ template: "blue",
87
+ },
88
+ body: {
89
+ elements: [
90
+ {
91
+ tag: "markdown",
92
+ content,
93
+ },
94
+ ...(copySourceId ? [{
95
+ tag: "button",
96
+ text: {
97
+ tag: "plain_text",
98
+ content: "返回MD原文",
99
+ },
100
+ type: "default",
101
+ width: "default",
102
+ behaviors: [
103
+ {
104
+ type: "callback",
105
+ value: {
106
+ action: "pi_feishu_copy_markdown",
107
+ copySourceId,
108
+ },
109
+ },
110
+ ],
111
+ }] : []),
112
+ ],
113
+ },
114
+ };
115
+ }
116
+
117
+ function analyzeText(text: string) {
118
+ const lines = text.split(/\r?\n/);
119
+ const lineCount = lines.filter((line) => line.trim()).length;
120
+ const tableLineCount = lines.filter((line) => /^\s*\|.+\|\s*$/.test(line)).length;
121
+ const hasTableSeparator = lines.some((line) => /^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(line));
122
+ return {
123
+ lineCount,
124
+ looksLikeMarkdown: looksLikeMarkdown(text),
125
+ hasTable: tableLineCount >= 2 && hasTableSeparator,
126
+ codeBlockCount: (text.match(/```/g) || []).length >= 2 ? Math.floor((text.match(/```/g) || []).length / 2) : 0,
127
+ headingCount: lines.filter((line) => /^#{1,6}\s+\S/.test(line.trim())).length,
128
+ listItemCount: lines.filter((line) => /^\s*([-*+]|\d+\.)\s+\S/.test(line)).length,
129
+ linkCount: (text.match(/\[[^\]\n]+\]\(https?:\/\/[^)\s]+\)/g) || []).length,
130
+ };
131
+ }
132
+
133
+ export function buildPostMessages(text: string, language: "zh" | "en" = "zh") {
134
+ return splitText(text.trim() || "(empty response)", MAX_POST_CHARS).map((chunk, index, chunks) => {
135
+ const parsed = markdownToPost(chunk, language);
136
+ const title = chunks.length > 1 ? `${parsed.title} (${index + 1}/${chunks.length})` : parsed.title;
137
+ const locale = language === "en" ? "en_us" : "zh_cn";
138
+ const post = {
139
+ title,
140
+ content: parsed.content.length ? parsed.content : [[{ tag: "text", text: chunk }]],
141
+ };
142
+ return {
143
+ [locale]: post,
144
+ [fallbackLocale(locale)]: post,
145
+ };
146
+ });
147
+ }
148
+
149
+ function looksLikeMarkdown(text: string) {
150
+ return [
151
+ /^#{1,6}\s+\S/m,
152
+ /^\s*[-*+]\s+\S/m,
153
+ /^\s*\d+\.\s+\S/m,
154
+ /^>\s+\S/m,
155
+ /```[\s\S]*?```/,
156
+ /\*\*[^*\n][\s\S]*?\*\*/,
157
+ /`[^`\n]+`/,
158
+ /\[[^\]\n]+\]\(https?:\/\/[^)\s]+\)/,
159
+ /^\s*\|.+\|\s*$/m,
160
+ ].some((pattern) => pattern.test(text));
161
+ }
162
+
163
+ function markdownToPost(text: string, language: "zh" | "en") {
164
+ const lines = text.replace(/\r\n/g, "\n").split("\n");
165
+ const titleIndex = lines.findIndex((line) => line.trim());
166
+ const firstLine = titleIndex >= 0 ? lines[titleIndex].trim() : "";
167
+ const heading = firstLine.match(/^#{1,6}\s+(.+)$/);
168
+ const title = cleanInlineMarkdown(heading?.[1] || firstLine || (language === "en" ? "Pi reply" : "Pi 回复")).slice(0, 120);
169
+ const content: PostElement[][] = [];
170
+ let inCodeBlock = false;
171
+
172
+ for (let i = 0; i < lines.length; i++) {
173
+ const raw = lines[i];
174
+ const trimmed = raw.trim();
175
+ if (!trimmed) continue;
176
+ if (i === titleIndex) continue;
177
+ if (/^```/.test(trimmed)) {
178
+ inCodeBlock = !inCodeBlock;
179
+ continue;
180
+ }
181
+
182
+ if (inCodeBlock) {
183
+ content.push([{ tag: "text", text: raw }]);
184
+ continue;
185
+ }
186
+
187
+ const headingMatch = trimmed.match(/^#{1,6}\s+(.+)$/);
188
+ if (headingMatch) {
189
+ content.push([{ tag: "text", text: cleanInlineMarkdown(headingMatch[1]), style: ["bold"] }]);
190
+ continue;
191
+ }
192
+
193
+ const quoteMatch = trimmed.match(/^>\s+(.+)$/);
194
+ if (quoteMatch) {
195
+ content.push([{ tag: "text", text: `> ${cleanInlineMarkdown(quoteMatch[1])}` }]);
196
+ continue;
197
+ }
198
+
199
+ const listMatch = trimmed.match(/^([-*+]|\d+\.)\s+(.+)$/);
200
+ if (listMatch) {
201
+ content.push([{ tag: "text", text: `${listMatch[1].match(/\d+\./) ? listMatch[1] : "•"} ${cleanInlineMarkdown(listMatch[2])}` }]);
202
+ continue;
203
+ }
204
+
205
+ if (/^\s*\|.+\|\s*$/.test(raw)) {
206
+ content.push([{ tag: "text", text: formatTableLine(raw) }]);
207
+ continue;
208
+ }
209
+
210
+ content.push(parseInlineElements(trimmed));
211
+ }
212
+
213
+ return { title, content };
214
+ }
215
+
216
+ function extractMarkdownTitle(text: string, language: "zh" | "en") {
217
+ const lines = text.replace(/\r\n/g, "\n").split("\n");
218
+ const titleIndex = lines.findIndex((line) => line.trim());
219
+ if (titleIndex < 0) return { title: language === "en" ? "Pi reply" : "Pi 回复", body: text };
220
+ const firstLine = lines[titleIndex].trim();
221
+ const heading = firstLine.match(/^#{1,6}\s+(.+)$/);
222
+ const title = cleanInlineMarkdown(heading?.[1] || firstLine || (language === "en" ? "Pi reply" : "Pi 回复")).slice(0, 120);
223
+ const body = lines
224
+ .filter((_, index) => index !== titleIndex)
225
+ .join("\n")
226
+ .trim();
227
+ return { title, body };
228
+ }
229
+
230
+ function splitMarkdownToFit(markdown: string, title: string, withCopyButton = false) {
231
+ const queue = splitMarkdownBlocks(markdown);
232
+ const parts: string[] = [];
233
+ let current = "";
234
+
235
+ for (const block of queue) {
236
+ if (!block.trim()) continue;
237
+ const candidate = current ? `${current}\n\n${block}` : block;
238
+ if (fitsMarkdownCard(title, candidate, withCopyButton)) {
239
+ current = candidate;
240
+ continue;
241
+ }
242
+ if (current) {
243
+ parts.push(current);
244
+ current = "";
245
+ }
246
+ if (fitsMarkdownCard(title, block, withCopyButton)) {
247
+ current = block;
248
+ continue;
249
+ }
250
+ parts.push(...splitOversizedBlock(block, title, withCopyButton));
251
+ }
252
+
253
+ if (current) parts.push(current);
254
+ return parts.length ? parts : [markdown];
255
+ }
256
+
257
+ function splitMarkdownBlocks(markdown: string) {
258
+ return splitByHeading(markdown, /^##\s+/m)
259
+ .flatMap((block) => splitByHeading(block, /^###\s+/m))
260
+ .flatMap((block) => block.split(/\n{2,}/))
261
+ .map((block) => block.trim())
262
+ .filter(Boolean);
263
+ }
264
+
265
+ function splitByHeading(markdown: string, pattern: RegExp) {
266
+ const lines = markdown.split("\n");
267
+ const blocks: string[] = [];
268
+ let current: string[] = [];
269
+
270
+ for (const line of lines) {
271
+ if (pattern.test(line) && current.length) {
272
+ blocks.push(current.join("\n").trim());
273
+ current = [];
274
+ }
275
+ current.push(line);
276
+ }
277
+ if (current.length) blocks.push(current.join("\n").trim());
278
+ return blocks.filter(Boolean);
279
+ }
280
+
281
+ function splitOversizedBlock(block: string, title: string, withCopyButton = false) {
282
+ const parts: string[] = [];
283
+ let current = "";
284
+ for (const line of block.split("\n")) {
285
+ const candidate = current ? `${current}\n${line}` : line;
286
+ if (fitsMarkdownCard(title, candidate, withCopyButton)) {
287
+ current = candidate;
288
+ continue;
289
+ }
290
+ if (current) {
291
+ parts.push(current);
292
+ current = "";
293
+ }
294
+ if (fitsMarkdownCard(title, line, withCopyButton)) {
295
+ current = line;
296
+ continue;
297
+ }
298
+ parts.push(...splitLongText(line, title, withCopyButton));
299
+ }
300
+ if (current) parts.push(current);
301
+ return parts;
302
+ }
303
+
304
+ function splitLongText(text: string, title: string, withCopyButton = false) {
305
+ const parts: string[] = [];
306
+ let rest = text;
307
+ while (rest) {
308
+ let low = 1;
309
+ let high = rest.length;
310
+ let best = 1;
311
+ while (low <= high) {
312
+ const mid = Math.floor((low + high) / 2);
313
+ if (fitsMarkdownCard(title, rest.slice(0, mid), withCopyButton)) {
314
+ best = mid;
315
+ low = mid + 1;
316
+ } else {
317
+ high = mid - 1;
318
+ }
319
+ }
320
+ parts.push(rest.slice(0, best));
321
+ rest = rest.slice(best);
322
+ }
323
+ return parts;
324
+ }
325
+
326
+ function fitsMarkdownCard(title: string, content: string, withCopyButton = false) {
327
+ return byteSize(createMarkdownCard(title, content, withCopyButton ? "__copy_source_id__" : undefined)) < MAX_CARD_BYTES;
328
+ }
329
+
330
+ function byteSize(value: unknown) {
331
+ return Buffer.byteLength(JSON.stringify(value), "utf8");
332
+ }
333
+
334
+ function parseInlineElements(text: string): PostElement[] {
335
+ const out: PostElement[] = [];
336
+ const linkPattern = /\[([^\]\n]+)\]\((https?:\/\/[^)\s]+)\)/g;
337
+ let lastIndex = 0;
338
+ for (const match of text.matchAll(linkPattern)) {
339
+ const index = match.index ?? 0;
340
+ if (index > lastIndex) {
341
+ out.push({ tag: "text", text: cleanInlineMarkdown(text.slice(lastIndex, index)) });
342
+ }
343
+ out.push({ tag: "a", text: cleanInlineMarkdown(match[1]), href: match[2] });
344
+ lastIndex = index + match[0].length;
345
+ }
346
+ if (lastIndex < text.length) {
347
+ out.push({ tag: "text", text: cleanInlineMarkdown(text.slice(lastIndex)) });
348
+ }
349
+ return out.length ? out : [{ tag: "text", text }];
350
+ }
351
+
352
+ function cleanInlineMarkdown(text: string) {
353
+ return text
354
+ .replace(/\*\*([^*]+)\*\*/g, "$1")
355
+ .replace(/__([^_]+)__/g, "$1")
356
+ .replace(/`([^`]+)`/g, "$1")
357
+ .replace(/~~([^~]+)~~/g, "$1")
358
+ .trim();
359
+ }
360
+
361
+ function formatTableLine(line: string) {
362
+ const cells = line
363
+ .trim()
364
+ .replace(/^\|/, "")
365
+ .replace(/\|$/, "")
366
+ .split("|")
367
+ .map((cell) => cell.trim());
368
+ if (cells.every((cell) => /^:?-{3,}:?$/.test(cell))) return "----------------";
369
+ return cells.join(" | ");
370
+ }
371
+
372
+ function splitText(text: string, max: number) {
373
+ const out: string[] = [];
374
+ let rest = text;
375
+ while (rest.length > max) {
376
+ let cut = rest.lastIndexOf("\n", max);
377
+ if (cut < max * 0.5) cut = max;
378
+ out.push(rest.slice(0, cut));
379
+ rest = rest.slice(cut).trimStart();
380
+ }
381
+ out.push(rest);
382
+ return out;
383
+ }
384
+
385
+ function fallbackLocale(locale: LocaleKey): LocaleKey {
386
+ return locale === "zh_cn" ? "en_us" : "zh_cn";
387
+ }
@@ -0,0 +1,286 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { parseGroupKeywords } from "./group-trigger.ts";
4
+ import { resolveRootDir } from "./instance.ts";
5
+
6
+ /** 运行时可改配置白名单(不含密钥/连接通道) */
7
+ export const RUNTIME_CONFIG_KEYS = [
8
+ "groupPolicy",
9
+ "groupKeywords",
10
+ "groupAlsoOnReply",
11
+ "ignoreBotMessages",
12
+ "reactEmoji",
13
+ "language",
14
+ "streamingReply",
15
+ "streamPrintFrequencyMs",
16
+ "streamPrintStep",
17
+ "streamPushIntervalMs",
18
+ "messageDelivery",
19
+ "progressMode",
20
+ "progressMaxLines",
21
+ "progressTimeoutSeconds",
22
+ ] as const;
23
+
24
+ export type RuntimeConfigKey = (typeof RUNTIME_CONFIG_KEYS)[number];
25
+
26
+ /** 最小配置形状,避免 runtime-config → types 的 type-only import 触发 strip-types 问题 */
27
+ export type RuntimeConfigView = {
28
+ groupPolicy?: "open" | "mention";
29
+ groupKeywords?: string[];
30
+ groupAlsoOnReply?: boolean;
31
+ ignoreBotMessages?: boolean;
32
+ reactEmoji?: string;
33
+ language?: "zh" | "en";
34
+ streamingReply?: boolean;
35
+ streamPrintFrequencyMs?: number;
36
+ streamPrintStep?: number;
37
+ streamPushIntervalMs?: number;
38
+ /**
39
+ * 正在生成回复时又收到新消息的处理方式:
40
+ * - queue(默认):排队,等上一条跑完再处理(当前行为)
41
+ * - interrupt:立即打断当前生成,用新消息开新一轮
42
+ */
43
+ messageDelivery?: "queue" | "interrupt";
44
+ /**
45
+ * 工具执行过程展示档位(默认 off):
46
+ * - off:不展示,等价于改造前
47
+ * - steps:累积清单(工具名 + 命令 + 耗时 + 成败)
48
+ * - action:只显示当前这一个工具
49
+ * - timeout:平时不显示,单个工具超阈值才提示
50
+ */
51
+ progressMode?: "off" | "steps" | "action" | "timeout";
52
+ /** 清单最多保留多少行,超出折叠(默认 50) */
53
+ progressMaxLines?: number;
54
+ /** 超过该秒数才显示耗时(默认 30) */
55
+ progressTimeoutSeconds?: number;
56
+ [key: string]: unknown;
57
+ };
58
+
59
+ export type RuntimeOverrides = Partial<Pick<RuntimeConfigView, RuntimeConfigKey>>;
60
+
61
+ // 实例目录由 instance.ts 统一解析,不要在这里再硬编码 ~/.pi/agent/feishu
62
+ const FEISHU_ROOT = resolveRootDir();
63
+ export const RUNTIME_OVERRIDES_PATH = join(FEISHU_ROOT, "runtime-overrides.json");
64
+
65
+ /** 当前 runtime 的 overrides 落盘路径;默认 Pi,由 setRuntimeOverridesPath 切换 */
66
+ let currentOverridesPath = RUNTIME_OVERRIDES_PATH;
67
+
68
+ export function setRuntimeOverridesPath(path: string) {
69
+ currentOverridesPath = path;
70
+ }
71
+
72
+ export function runtimeOverridesPath(): string {
73
+ return currentOverridesPath;
74
+ }
75
+
76
+ export function isRuntimeConfigKey(key: string): key is RuntimeConfigKey {
77
+ return (RUNTIME_CONFIG_KEYS as readonly string[]).includes(key);
78
+ }
79
+
80
+ export type ParseResult =
81
+ | { ok: true; value: unknown }
82
+ | { ok: false; error: string };
83
+
84
+ export function parseRuntimeConfigValue(key: string, raw: string): ParseResult {
85
+ if (!isRuntimeConfigKey(key)) {
86
+ return { ok: false, error: `不允许修改配置项: ${key}` };
87
+ }
88
+ const text = raw.trim();
89
+ switch (key) {
90
+ case "groupKeywords":
91
+ return { ok: true, value: parseGroupKeywords(text) };
92
+ case "groupPolicy": {
93
+ if (text !== "open" && text !== "mention") {
94
+ return { ok: false, error: "groupPolicy 仅支持 open | mention" };
95
+ }
96
+ return { ok: true, value: text as "open" | "mention" };
97
+ }
98
+ case "language": {
99
+ if (text !== "zh" && text !== "en") {
100
+ return { ok: false, error: "language 仅支持 zh | en" };
101
+ }
102
+ return { ok: true, value: text };
103
+ }
104
+ case "messageDelivery": {
105
+ if (text !== "queue" && text !== "interrupt") {
106
+ return { ok: false, error: "messageDelivery 仅支持 queue | interrupt" };
107
+ }
108
+ return { ok: true, value: text as "queue" | "interrupt" };
109
+ }
110
+ case "progressMode": {
111
+ const allowed = ["off", "steps", "action", "timeout"] as const;
112
+ if (!(allowed as readonly string[]).includes(text)) {
113
+ return { ok: false, error: "progressMode 仅支持 off | steps | action | timeout" };
114
+ }
115
+ return { ok: true, value: text as (typeof allowed)[number] };
116
+ }
117
+ case "groupAlsoOnReply":
118
+ case "ignoreBotMessages":
119
+ case "streamingReply": {
120
+ const b = parseBoolStrict(text);
121
+ if (b === undefined) return { ok: false, error: `${key} 请使用 true/false/1/0` };
122
+ return { ok: true, value: b };
123
+ }
124
+ case "reactEmoji": {
125
+ if (!text) return { ok: false, error: "reactEmoji 不能为空" };
126
+ return { ok: true, value: text };
127
+ }
128
+ case "streamPrintFrequencyMs":
129
+ case "streamPrintStep":
130
+ case "streamPushIntervalMs": {
131
+ const n = Number.parseInt(text, 10);
132
+ if (!Number.isFinite(n) || n <= 0) {
133
+ return { ok: false, error: `${key} 必须是正整数` };
134
+ }
135
+ return { ok: true, value: n };
136
+ }
137
+ case "progressMaxLines": {
138
+ const n = Number.parseInt(text, 10);
139
+ if (!Number.isFinite(n) || n < 3 || n > 100) {
140
+ return { ok: false, error: "progressMaxLines 必须是 3-100 的整数" };
141
+ }
142
+ return { ok: true, value: n };
143
+ }
144
+ case "progressTimeoutSeconds": {
145
+ const n = Number.parseInt(text, 10);
146
+ if (!Number.isFinite(n) || n <= 0) {
147
+ return { ok: false, error: "progressTimeoutSeconds 必须是正整数" };
148
+ }
149
+ return { ok: true, value: n };
150
+ }
151
+ default:
152
+ return { ok: false, error: `不允许修改配置项: ${key}` };
153
+ }
154
+ }
155
+
156
+ function parseBoolStrict(value: string): boolean | undefined {
157
+ const v = value.trim().toLowerCase();
158
+ if (["1", "true", "yes", "on"].includes(v)) return true;
159
+ if (["0", "false", "no", "off"].includes(v)) return false;
160
+ return undefined;
161
+ }
162
+
163
+ function readOverridesFile(path: string): Record<string, unknown> {
164
+ if (!existsSync(path)) return {};
165
+ try {
166
+ return JSON.parse(readFileSync(path, "utf8")) as Record<string, unknown>;
167
+ } catch {
168
+ return {};
169
+ }
170
+ }
171
+
172
+ function writeOverridesFile(path: string, value: unknown) {
173
+ mkdirSync(dirname(path), { recursive: true });
174
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`, "utf8");
175
+ try {
176
+ chmodSync(path, 0o600);
177
+ } catch {
178
+ // ignore chmod failures on non-posix volumes
179
+ }
180
+ }
181
+
182
+ /** 将 overrides 合并进 base;忽略非白名单字段 */
183
+ export function applyRuntimeOverrides<T extends RuntimeConfigView>(
184
+ base: T,
185
+ overrides: RuntimeOverrides | Record<string, unknown>,
186
+ ): T {
187
+ const next = { ...base };
188
+ for (const key of RUNTIME_CONFIG_KEYS) {
189
+ if (!Object.prototype.hasOwnProperty.call(overrides, key)) continue;
190
+ const value = (overrides as any)[key];
191
+ if (value === undefined) continue;
192
+ if (key === "groupKeywords") {
193
+ (next as any).groupKeywords = parseGroupKeywords(value);
194
+ } else {
195
+ (next as any)[key] = value;
196
+ }
197
+ }
198
+ return next;
199
+ }
200
+
201
+ export function getRuntimeOverrides(path: string = runtimeOverridesPath()): RuntimeOverrides {
202
+ const raw = readOverridesFile(path);
203
+ const out: RuntimeOverrides = {};
204
+ for (const key of RUNTIME_CONFIG_KEYS) {
205
+ if (!Object.prototype.hasOwnProperty.call(raw, key)) continue;
206
+ const value = raw[key];
207
+ if (value === undefined) continue;
208
+ if (key === "groupKeywords") {
209
+ out.groupKeywords = parseGroupKeywords(value);
210
+ } else {
211
+ (out as any)[key] = value;
212
+ }
213
+ }
214
+ return out;
215
+ }
216
+
217
+ export type SetRuntimeResult =
218
+ | { ok: true; key: RuntimeConfigKey; value: unknown; overrides: RuntimeOverrides }
219
+ | { ok: false; error: string };
220
+
221
+ export function setRuntimeConfig(
222
+ key: string,
223
+ rawValue: string,
224
+ options?: { path?: string },
225
+ ): SetRuntimeResult {
226
+ const parsed = parseRuntimeConfigValue(key, rawValue);
227
+ if (parsed.ok === false) return { ok: false, error: parsed.error };
228
+ const path = options?.path ?? runtimeOverridesPath();
229
+ const current = getRuntimeOverrides(path);
230
+ const next: RuntimeOverrides = {
231
+ ...current,
232
+ [key as RuntimeConfigKey]: parsed.value as any,
233
+ };
234
+ writeOverridesFile(path, next);
235
+ return { ok: true, key: key as RuntimeConfigKey, value: parsed.value, overrides: next };
236
+ }
237
+
238
+ export function clearRuntimeOverrides(
239
+ keyOrAll: RuntimeConfigKey | "all" | string,
240
+ path: string = runtimeOverridesPath(),
241
+ ): { ok: true; overrides: RuntimeOverrides } | { ok: false; error: string } {
242
+ if (keyOrAll === "all") {
243
+ writeOverridesFile(path, {});
244
+ return { ok: true, overrides: {} };
245
+ }
246
+ if (!isRuntimeConfigKey(keyOrAll)) {
247
+ return { ok: false, error: `不允许清除配置项: ${keyOrAll}` };
248
+ }
249
+ const current = { ...getRuntimeOverrides(path) };
250
+ delete (current as any)[keyOrAll];
251
+ writeOverridesFile(path, current);
252
+ return { ok: true, overrides: current };
253
+ }
254
+
255
+ export function formatRuntimeConfig(cfg: RuntimeConfigView, overrides?: RuntimeOverrides): string {
256
+ const ov = overrides ?? {};
257
+ const mark = (key: RuntimeConfigKey) =>
258
+ Object.prototype.hasOwnProperty.call(ov, key) ? " (override)" : "";
259
+
260
+ const kw = (cfg.groupKeywords || []).join(", ") || "(空)";
261
+ return [
262
+ "⚙️ 飞书运行时配置(白名单)",
263
+ "",
264
+ `groupPolicy: ${cfg.groupPolicy}${mark("groupPolicy")}`,
265
+ `groupKeywords: ${kw}${mark("groupKeywords")}`,
266
+ `groupAlsoOnReply: ${Boolean(cfg.groupAlsoOnReply)}${mark("groupAlsoOnReply")}`,
267
+ `ignoreBotMessages: ${cfg.ignoreBotMessages !== false}${mark("ignoreBotMessages")}`,
268
+ `reactEmoji: ${cfg.reactEmoji || ""}${mark("reactEmoji")}`,
269
+ `language: ${cfg.language || "zh"}${mark("language")}`,
270
+ `streamingReply: ${cfg.streamingReply !== false}${mark("streamingReply")}`,
271
+ `streamPrintFrequencyMs: ${cfg.streamPrintFrequencyMs ?? ""}${mark("streamPrintFrequencyMs")}`,
272
+ `streamPrintStep: ${cfg.streamPrintStep ?? ""}${mark("streamPrintStep")}`,
273
+ `streamPushIntervalMs: ${cfg.streamPushIntervalMs ?? ""}${mark("streamPushIntervalMs")}`,
274
+ `messageDelivery: ${cfg.messageDelivery ?? "queue"}${mark("messageDelivery")}`,
275
+ `progressMode: ${cfg.progressMode ?? "off"}${mark("progressMode")}`,
276
+ `progressMaxLines: ${cfg.progressMaxLines ?? 50}${mark("progressMaxLines")}`,
277
+ `progressTimeoutSeconds: ${cfg.progressTimeoutSeconds ?? 30}${mark("progressTimeoutSeconds")}`,
278
+ "",
279
+ "修改: /config <key> <value>",
280
+ "也可直接发 /delivery 弹卡片切换 messageDelivery",
281
+ "progressMode 也可用 Pi 侧 /feishu progress <值> 修改",
282
+ "清除: /config clear <key|all>",
283
+ `可改项: ${RUNTIME_CONFIG_KEYS.join(", ")}`,
284
+ ].join("\n");
285
+ }
286
+