Repository navigation
Expand file tree
/
Copy pathfeishu.mjs
More file actions
1789 lines (1762 loc) · 73.6 KB
/
Copy pathfeishu.mjs
File metadata and controls
1789 lines (1762 loc) · 73.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { artifactContentPath, imageMime, maxMediaBytes, maxUploadBytes, qrImages, qrImagePattern } from "../shared/media.mjs";
import { createHash, randomUUID } from "node:crypto";
const stableId = (value) => {
const hex = createHash("sha256").update(value).digest("hex");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
};
import { feishuContextReader } from "./feishu-context.mjs";
import { explainFailure, turnsAPI } from "./turns.mjs";
import { waitingHeadline } from "../shared/turn-status.mjs";
import { feishuSource } from "../shared/feishu-source.mjs";
import { feishuAppName } from "./feishu-registration.mjs";
import { AppError, text, uuid, transientError } from "./store.mjs";
const stamp = () => Date.now();
const sendExpired = (row) => row.first_attempt_at && stamp() - row.first_attempt_at >= 55 * 60000;
export const publicFeishu = ({ app_secret, ...record }) => ({
...record,
has_app_secret: !!app_secret,
});
export function feishuAPI(store, fetchImpl = fetch) {
return async (method, path, body) => {
const retryMatch = path.match(
/^\/app\/feishu\/deliveries\/outbound\/([a-f0-9-]{36})$/,
);
if (retryMatch && method === "PUT" && uuid.test(retryMatch[1])) {
const kind = "feishu_outbound",
row = store.get(kind, retryMatch[1]);
if (!row) throw new AppError(404, "投递记录不存在。");
if (row.state !== "failed")
throw new AppError(409, "此记录不需要手动重试。");
if (sendExpired(row))
throw new AppError(
409,
"飞书去重窗口已过。请人工检查原话题,不能安全自动重发。",
);
store.put(kind, {
...row,
state: "queued",
attempts: 0,
error: undefined,
next_at: 0,
});
return {};
}
if (path === "/app/feishu/bots" && method === "GET")
return store.list("feishu_bots").map((row) => ({
...publicFeishu(row),
health: store.get("feishu_health", row.id) || { state: "stopped" },
}));
if (path === "/app/feishu/deliveries" && method === "GET")
return [
...store
.list("feishu_inbound")
.map((row) => ({ ...row, direction: "inbound" })),
...store
.list("feishu_outbound")
.map((row) => ({ ...row, direction: "outbound" })),
]
.sort((a, b) => b.created_at - a.created_at)
.filter(
(row, index) =>
index < 100 ||
["queued", "submitting", "failed"].includes(row.state),
)
.map(({ text, payload, event, resources, media, uploaded_media, context, ...row }) => {
const sessionId = store.get("feishu_threads", row.thread_id)?.session_id;
return {
...row,
session_id:
sessionId && store.get("sessions", sessionId)?.core_session_id
? sessionId
: undefined,
};
});
const botMatch = path.match(/^\/app\/feishu\/bots\/([a-f0-9-]{36})$/);
if (!botMatch || !uuid.test(botMatch[1]))
throw new AppError(404, "Not found.");
const id = botMatch[1];
const old = store.get("feishu_bots", id) || {
id,
name: "",
revision: 0,
enabled: false,
app_id: "",
app_secret: "",
agent_id: "",
direct: false,
groups: false,
};
if (method === "GET") return publicFeishu(old);
// Deleting a bot stops it and drops what it had not delivered yet;
// conversations and delivered messages stay.
if (method === "DELETE") {
store.transaction(() => {
for (const kind of ["feishu_inbound", "feishu_outbound"])
for (const row of store.list(kind))
if (row.app_id === old.app_id && !["delivered", "rejected"].includes(row.state)) store.remove(kind, row.id);
store.remove("feishu_bots", id);
});
return {};
}
if (method !== "PUT") throw new AppError(405, "Method not allowed.");
if (old.revision !== body.revision)
throw new AppError(409, "配置已更新,请重新加载。");
if (body.brand !== undefined && !["feishu", "lark"].includes(body.brand))
throw new AppError(400, "机器人地区无效。");
const app_id = text(body.app_id, "App ID", 100).trim();
// A new app takes the name it has in Feishu; connecting keeps it current.
const name = app_id === old.app_id && old.name
? old.name
: (app_id && body.app_secret && (await feishuAppName(fetchImpl, { app_id, app_secret: body.app_secret.trim(), brand: body.brand ?? old.brand }))) || app_id || "Feishu";
if (
app_id &&
store
.list("feishu_bots")
.some((row) => row.id !== id && row.app_id === app_id)
)
throw new AppError(409, "这个 App ID 已由另一机器人连接。");
const secret = body.app_secret
? text(body.app_secret, "App Secret", 300, true).trim()
: old.app_secret;
if (app_id !== old.app_id && !body.app_secret)
throw new AppError(400, "更换 App ID 时请同时填写 App Secret。");
if (typeof body.enabled !== "boolean")
throw new AppError(400, "飞书配置无效。");
const agent_id = text(body.agent_id || "", "Agent", 36);
const agent = agent_id && store.get("agents", agent_id);
if (agent_id && !agent) throw new AppError(400, "Agent 不存在。");
if (
agent_id &&
store
.list("feishu_bots")
.some((row) => row.id !== id && row.agent_id === agent_id)
)
throw new AppError(409, "这个 Agent 已绑定另一个机器人。");
const direct = body.direct === true;
// Group membership is the group boundary: any group the bot joins can mention it.
const groups = body.groups === true;
if (
body.enabled &&
(!/^cli_[0-9a-fA-F]{16}$/.test(app_id) ||
!secret ||
!agent ||
(!direct && !groups))
)
throw new AppError(
400,
"启用前请配置 App ID、App Secret、Agent,并开启私聊或群聊。",
);
if (body.enabled && !store.get("runtimes", agent.runtime_id || ""))
throw new AppError(400, "Agent 未配置环境模板。");
const value = {
id,
name,
app_id,
app_secret: secret,
brand: body.brand || old.brand || "feishu",
enabled: body.enabled,
agent_id,
direct,
groups,
revision: old.revision + 1,
};
store.put("feishu_bots", value);
return publicFeishu(value);
};
}
// Feishu's rich-text box can bold or code-format a command; the command is
// what remains without that formatting.
export function asCommand(text) {
const plain = text.replace(/^[*_~`]+|[*_~`]+$/g, "").trim();
return /^\/(clear|stop|help)$/.test(plain) || /^\/answer\s/.test(plain) ? plain : text;
}
const cardTones = {
in_progress: ["处理中", "blue"],
requires_action: ["需要你补充信息", "orange"],
completed: ["已完成", "green"],
cancelled: ["已停止", "grey"],
failed: ["执行失败", "red"],
missing_scopes: ["需要开通权限", "orange"],
moved: ["已并入下方回复", "grey"],
};
const grey = (text) => `<font color='grey'>${text}</font>`;
// Budget serialized UTF-8 bytes, including JSON escaping, for Feishu cards.
function excerpt(value, limit) {
const text = typeof value === "string" ? value : JSON.stringify(value, null, 2) || "";
if (Buffer.byteLength(JSON.stringify(text)) <= limit) return text;
const prefix = [];
let size = 0;
for (const char of text) {
size += Buffer.byteLength(JSON.stringify(char)) - 2;
if (size > limit - 60) break;
prefix.push(char);
}
return prefix.join("") + "\n…(内容较长,已截取)";
}
// A `block` panel is a tinted, rounded area that holds folded history.
function panel({ title, content, elements, block = false }) {
return {
tag: "collapsible_panel",
expanded: false,
vertical_spacing: "4px",
padding: block ? "0px 12px 8px 12px" : "0px 0px 4px 0px",
...(block && { background_color: "grey-50", border: { color: "grey-50", corner_radius: "8px" } }),
header: {
title: { tag: "markdown", content: title },
width: "fill",
// The header ignores the panel padding, so a block indents its own title.
padding: block ? "8px 12px 8px 12px" : "2px 0px 2px 0px",
icon: { tag: "standard_icon", token: "down-small-ccm_outlined", size: "16px 16px" },
icon_position: "right",
icon_expanded_angle: -180,
},
elements: elements || [{ tag: "markdown", content }],
};
}
// Feishu rejects cards above about 30 KB of JSON.
const cardBudget = 28000;
const bytes = (value) => Buffer.byteLength(JSON.stringify(value));
// The colored header carries the status and, while running, what is
// happening now on the same line, so the body starts with the content.
function statusCard(status, body, elements = [], subtitle = "") {
const [title, template] = cardTones[status] || cardTones.failed;
// A card needs a body; with nothing else to show, what is happening is the body.
if (!body && !elements.length && subtitle) [body, subtitle] = [`**${subtitle}**`, ""];
const heading = subtitle ? `${title} · ${subtitle}` : title;
return JSON.stringify({
schema: "2.0",
config: { update_multi: true, summary: { content: heading } },
header: { title: { tag: "plain_text", content: heading }, template },
body: {
padding: "12px 16px 12px 16px",
vertical_spacing: "6px",
elements: [...(body ? [{ tag: "markdown", content: body }] : []), ...elements],
},
});
}
export function feishuCard(payload) {
const text = String(payload);
if (text.startsWith("{")) return JSON.parse(text);
const [title, ...rest] = text.split("\n");
const body = rest.join("\n").trim();
if (title === "执行失败" && body) return JSON.parse(statusCard("failed", body));
return {
schema: "2.0",
config: { update_multi: true },
body: { elements: [{ tag: "markdown", content: text }] },
};
}
export function progressCard(text, notice) {
return statusCard("in_progress", notice ? grey(notice) : "", [], text);
}
function questionText(action, includeOptions = true) {
let args = action.arguments;
try { if (typeof args === "string") args = JSON.parse(args); } catch { args = {}; }
return [
typeof args?.question === "string" ? args.question : "请补充信息",
includeOptions && Array.isArray(args?.options) ? args.options.filter((x) => typeof x === "string").map((x) => `- ${x}`).join("\n") : "",
].filter(Boolean).join("\n\n");
}
function step(item) {
if (item.type === "command_execution" || typeof item.command === "string") {
const command = String(item.command || "").replace(/\s+/g, " ").trim()
.replace(/^\/bin\/(?:ba|z)?sh -lc (['"])([\s\S]*)\1$/, "$2");
return ["运行", command];
}
if (item.type === "mcp_call") return ["调用工具", [item.server_label, item.name].filter(Boolean).join(" · ")];
if (item.type === "function_call") return ["调用工具", item.name || ""];
if (item.type === "web_search_call") return ["搜索网页", item.action?.query || item.action?.url || ""];
if (item.type === "file_change") return ["修改文件", ""];
return ["执行步骤", item.name || item.type || ""];
}
// Wide (CJK and full-width) characters take two columns in a card; general
// punctuation such as the ellipsis is narrow.
const wide = (char) => {
const code = char.codePointAt(0);
return code >= 0x1100 && !(code >= 0x2000 && code <= 0x206f);
};
const columns = (text) => [...text].reduce((sum, char) => sum + (wide(char) ? 2 : 1), 0);
const clip = (value, limit) => {
const text = String(value ?? "").replace(/\s+/g, " ").trim();
if (columns(text) <= limit) return text;
let kept = "";
for (const char of text) {
if (columns(kept + char) > limit - 1) break;
kept += char;
}
return `${kept}…`;
};
// Markdown and Feishu tags stay literal inside a one-line title.
const literal = (value) => value.replace(/[<>]/g, "").replaceAll("`", "'");
// Thinking and tool rows stay on one line: the detail gets what the label
// and state leave of the row.
const rowColumns = 52;
const oneLine = (label, detail, state = "") => {
const room = rowColumns - columns(label) - columns(state.replace(/<[^>]*>/g, "")) - 2;
return [grey(label), detail ? literal(clip(detail, Math.max(8, room))) : "", state].filter(Boolean).join(" ");
};
const toolState = (item) =>
item.status === "failed"
? "<font color='red'>失败</font>"
: item.status === "in_progress"
? grey("进行中")
: item.status === "incomplete"
? grey("未完成")
: typeof item.duration_ms === "number"
? grey(`${(item.duration_ms / 1000).toFixed(1)}s`)
: "";
// One tool call: the command is the title, its result folds below it.
function toolRow(item) {
const [label, detail] = step(item);
const title = oneLine(label, detail, toolState(item));
const fields = [
// A shortened title keeps the whole command one click away.
["命令", item.command && title.includes("…") ? detail : undefined],
["参数", item.command ? undefined : item.arguments ?? item.action],
["输出", item.output], ["错误", item.error], ["退出码", item.exit_code],
].filter(([, value]) => value !== undefined && value !== null && value !== "");
if (!fields.length) return { tag: "markdown", content: title };
// Plain text keeps tool output literal, including code fences and mention markup.
return panel({
title,
elements: [{ tag: "div", text: { tag: "plain_text", content: excerpt(fields.map(([name, value]) => `${name}\n${excerpt(value, 1200)}`).join("\n\n"), 1600) } }],
});
}
// Consecutive tool calls fold into one row; each call folds again inside it.
// With less room, calls keep only their titles, then the group is one line.
function toolsRow(items, level = 0) {
const failed = items.filter((item) => item.status === "failed").length;
const state = items.some((item) => item.status === "in_progress")
? grey("进行中")
: failed
? `<font color='red'>失败 ${failed} 次</font>`
: items.every((item) => typeof item.duration_ms === "number")
? grey(`${(items.reduce((sum, item) => sum + item.duration_ms, 0) / 1000).toFixed(1)}s`)
: "";
const [label, detail] = step(items[0]);
const title = items.length === 1
? oneLine(label, detail, state)
: [grey(items.every((item) => step(item)[0] === "运行") ? `运行 ${items.length} 条命令` : `调用 ${items.length} 次工具`), state].filter(Boolean).join(" ");
if (level >= 2 || (level === 1 && items.length === 1)) return { tag: "markdown", content: title };
const calls = level === 1
? items.map((item) => ({ tag: "markdown", content: oneLine(...step(item), toolState(item)) }))
: items.map(toolRow);
return panel({ title, elements: calls });
}
// One step at decreasing detail: everything; tool calls without their output;
// thinking and tool groups as one line; commentary shortened.
function timelineRow(entry, level = 0) {
if (entry.type === "say") return { tag: "markdown", content: excerpt(entry.text, level < 3 ? 4000 : 400) };
if (entry.type === "think") {
const title = oneLine("思考", entry.text.split("\n").find((line) => line.trim()) || "");
return level < 2 ? panel({ title, content: excerpt(entry.text, 1500) }) : { tag: "markdown", content: title };
}
return toolsRow(entry.items, level);
}
// Every step stays in the card. When it would pass Feishu's size limit, the
// oldest steps give up detail first.
function fitRows(entries, budget) {
const rows = entries.map((entry) => timelineRow(entry));
for (let level = 1; level <= 3 && bytes(rows) > budget; level++)
for (let i = 0; i < entries.length && bytes(rows) > budget; i++) {
rows[i] = timelineRow(entries[i], level);
}
// Hundreds of steps: the oldest become one summary line.
let merged = 0;
while (merged < entries.length - 1 && bytes(rows.slice(merged)) + 200 > budget) merged++;
if (!merged) return rows;
const counted = entries.slice(0, merged);
const commands = counted.flatMap((entry) => entry.items || []).length;
const thoughts = counted.filter((entry) => entry.type === "think").length;
const summary = [commands && `运行 ${commands} 条命令`, thoughts && `思考 ${thoughts} 次`].filter(Boolean).join("、");
return [{ tag: "markdown", content: grey(`第 1–${merged} 步${summary ? `:${summary}` : ""}`) }, ...rows.slice(merged)];
}
// A tool-result answer resumes the same Core Turn. Display only the exchange
// after that answer, not every earlier question and command in the Turn.
function exchangeItems(items) {
const questions = new Set(items.filter((x) => x.type === "function_call" && x.name === "ask_user").map((x) => x.call_id));
const boundary = items.findLastIndex((x) => x.type === "message" && x.role === "user" || x.type === "function_call_output" && questions.has(x.call_id));
return items.slice(boundary + 1);
}
const recentRows = 4;
// Scopes Feishu says the bot's app lacks, from the Agent's tool output: the
// platform's "One of the following scopes is required: [...]", lark-cli's
// "required scope(s): ...", and permission_violations subjects.
export function missingScopes(items) {
const found = new Set();
const scope = /^[a-z][a-z0-9_]*:[a-z0-9_.:-]+$/;
for (const item of items) {
if (!["command_execution", "function_call_output", "mcp_call"].includes(item.type)) continue;
const output = [item.output, item.error].map((value) => (typeof value === "string" ? value : JSON.stringify(value ?? ""))).join("\n");
if (!/99991672|99991679|app_scope_not_applied|scopes? (?:is )?required|required scope/i.test(output)) continue;
for (const [, list] of output.matchAll(/(?:scopes is required: \[|required scope\(s\): )([^\]"\n]+)/g))
for (const name of list.split(/[,\s]+/)) if (scope.test(name)) found.add(name);
for (const [, name] of output.matchAll(/"subject":\s*"([^"]+)"/g)) if (scope.test(name)) found.add(name);
}
return [...found];
}
// What to tell people when the bot's app lacks scopes: which, and where to apply.
function scopeNotice(app, scopes) {
const host = app.brand === "lark" ? "open.larksuite.com" : "open.feishu.cn";
const url = `https://${host}/page/scope-apply?clientID=${encodeURIComponent(app.app_id)}&scopes=${encodeURIComponent(scopes.join(","))}`;
return [
`需要为机器人「${app.name || app.app_id}」开通:${scopes.map((name) => `\`${name}\``).join("、")}`,
`[申请开通权限](${url})`,
grey("管理员批准并发布新版本后,直接回复这条消息即可继续。"),
].join("\n\n");
}
export function formatTurnCard(status, items = [], error, turn, questions = [], app) {
items = exchangeItems(items);
const text = (item) => (item.content || []).filter((p) => p.type === "output_text").map((p) => (p.text || "").trim()).filter(Boolean).join("\n");
const messages = items.filter((x) => x.type === "message" && x.role === "assistant");
const latest = messages.at(-1);
// Feishu reads any Markdown image as an image key and rejects the whole
// card, so images become text; the files themselves are sent as messages.
const readable = (value) => value
.replace(/!\[[^\]\n]*\]\((\/app\/feishu\/provision\/[a-f0-9-]{36}\/qrcode)\)/g, "(授权二维码见图片消息)")
.replace(/!?\[([^\]]*)\]\((?:\/workspace\/|\.\/)?outputs\/[^)]*\)/g, "$1(见附件)")
.replace(/!\[([^\]\n]*)\]\([^)\n]*\)/g, (_, alt) => alt ? `(图片:${alt})` : "(图片)");
const authorization = messages.filter((item) => qrImages(text(item)).length);
const authorizationText = authorization.map((item) => readable(text(item))).join("\n\n");
const answer = latest?.phase === "commentary" || authorization.includes(latest) ? "" : latest ? readable(text(latest)) : "";
const outputs = new Map(items.filter((x) => x.type === "function_call_output").map((x) => [x.call_id, x]));
// Thinking, commentary and tool calls in the order they happened.
const entries = items.flatMap((x) => {
if (x.type === "reasoning") {
const thought = readable((x.summary || x.content || []).map((p) => typeof p === "string" ? p : p?.text || "").filter(Boolean).join("\n\n").trim());
return thought ? [{ type: "think", text: thought }] : [];
}
if (x.type === "message") {
const said = x.role === "assistant" && !authorization.includes(x) && (status === "in_progress" || x !== latest || x.phase === "commentary") ? readable(text(x)) : "";
return said ? [{ type: "say", text: said }] : [];
}
if (["agent_message", "function_call_output"].includes(x.type) || (x.type === "function_call" && x.name === "ask_user")) return [];
const output = x.type === "function_call" ? outputs.get(x.call_id) : undefined;
return [{ type: "tool", item: output ? { ...x, status: output.status, output: output.output, error: output.error } : x }];
});
const grouped = entries.reduce((rows, entry) => {
const last = rows.at(-1);
if (entry.type === "tool" && last?.type === "tools") last.items.push(entry.item);
else rows.push(entry.type === "tool" ? { type: "tools", items: [entry.item] } : entry);
return rows;
}, []);
const rows = grouped;
const tools = entries.filter((entry) => entry.type === "tool").map((entry) => entry.item);
if (status === "in_progress") {
const last = items.filter((x) => x.role !== "user" && x.type !== "function_call_output").at(-1);
const current = !last ? waitingHeadline(turn) : last.type === "message" ? "正在整理回复" : last.type === "reasoning" ? "正在思考" : last.status === "in_progress" ? `正在${step(last)[0]}` : "正在整理结果";
const subtitle = [current, rows.length ? `${rows.length} 步` : ""].filter(Boolean).join(" · ");
const body = authorizationText ? excerpt(authorizationText, 8000) : "";
const fitted = fitRows(rows, cardBudget - bytes(body) - 600);
const earlier = fitted.slice(0, -recentRows), shown = fitted.slice(-recentRows);
// Earlier steps sit in a tinted block above a rule that separates the latest ones.
const fold = earlier.length
? [panel({ title: grey(`更早的 ${earlier.length} 步`), elements: earlier, block: true }), { tag: "hr" }]
: [];
return statusCard(status, body, [...fold, ...shown], subtitle);
}
const context = questions.some((action) => questionText(action, false).trim() === answer.trim()) ? "" : answer;
// Put the decision first; keep its explanation available without filling the chat.
// Authorization instructions stay visible alongside the separately sent QR.
const foldContext = status === "requires_action" && questions.length && context;
const body = excerpt(status === "requires_action"
? [...questions.map((action) => questionText(action)), authorizationText, foldContext ? "" : context, grey("直接回复这条消息即可继续。")].filter(Boolean).join("\n\n")
: status === "completed" ? [authorizationText, answer].filter(Boolean).join("\n\n") || "已完成处理。"
: status === "cancelled" ? [authorizationText, answer].filter(Boolean).join("\n\n") || "已按你的要求停止。"
: [authorizationText, answer || "这次没有完成。", error ? `<font color='red'>${error}</font>` : "", grey("直接回复即可重试。")].filter(Boolean).join("\n\n"), status === "requires_action" ? 8000 : 12000);
const elements = [];
// Scopes the Agent's reply names as missing get a link to apply for them,
// under the reply; scopes it only ran into while exploring do not.
const said = [answer, ...questions.map((action) => questionText(action))].join("\n");
const scopes = app ? missingScopes(items).filter((name) => said.includes(name)) : [];
if (foldContext) elements.push(panel({ title: grey("补充说明"), content: excerpt(context, 4000), block: true }));
if (scopes.length) {
if (rows.length) elements.push(panel({ title: grey(`处理过程 · ${rows.length} 步`), elements: fitRows(rows, cardBudget - bytes(body) - 3000), block: true }));
return statusCard("missing_scopes", [body, scopeNotice(app, scopes)].join("\n\n"), [{ tag: "hr" }, ...elements]);
}
// A failure shows the step that failed right under its cause.
const failedTool = status === "failed" ? tools.findLast((item) => item.status === "failed") : undefined;
if (failedTool) elements.push(toolRow(failedTool));
if (rows.length) {
const budget = cardBudget - bytes(body) - bytes(elements);
elements.push(panel({ title: grey(`处理过程 · ${rows.length} 步`), elements: fitRows(rows, budget), block: true }));
}
return statusCard(status, body, elements.length ? [{ tag: "hr" }, ...elements] : []);
}
export async function createFeishuTransport(settings, receive) {
const { Client, WSClient, EventDispatcher, normalize, Domain } = await import(
"@larksuiteoapi/node-sdk"
);
// SDK diagnostics may contain authenticated WebSocket URLs and message bodies.
const logger = { error() {}, warn() {}, info() {}, debug() {}, trace() {} };
const options = {
appId: settings.app_id,
appSecret: settings.app_secret,
domain: settings.brand === "lark" ? Domain.Lark : Domain.Feishu,
logger,
};
const client = new Client(options);
const ws = new WSClient({ ...options, handshakeTimeoutMs: 15000 });
let readContext;
return {
...feishuOperations(client),
readContext: (row) => readContext(row),
async connect() {
const result = await client.request({
method: "GET",
url: "/open-apis/bot/v3/info",
});
const bot = result.bot || result.data?.bot;
if (result.code !== 0 || !bot?.open_id)
throw new Error("Cannot resolve Feishu bot identity");
// The name people see in Feishu.
this.name = bot.app_name;
readContext = feishuContextReader(client, {
openId: bot.open_id,
name: bot.app_name || "Parsar",
});
const dispatcher = new EventDispatcher({ logger }).register({
"im.message.receive_v1": async (event) => {
if (
event.sender?.sender_type !== "user" ||
// The bot serves its own tenant; external contacts are ignored.
(event.tenant_key &&
event.sender.tenant_key &&
event.sender.tenant_key !== event.tenant_key) ||
![
"text",
"post",
"image",
"file",
"audio",
"media",
"merge_forward",
].includes(event.message?.message_type)
)
return;
const message = await normalize(event, {
botIdentity: {
openId: bot.open_id,
name: bot.app_name || "Parsar",
},
stripBotMentions: true,
});
// Unlike the SDK's convenience Channel queue, the dispatcher awaits
// this commit before acknowledging. Storage failure returns a retryable ACK.
receive(message);
},
});
await ws.start({ eventDispatcher: dispatcher });
},
async disconnect() {
ws.close({ force: true });
},
getConnectionStatus() {
return ws.getConnectionStatus();
},
};
}
export function feishuOperations(client) {
const confirmed = (result) => {
if (result.code !== 0)
throw new Error("Feishu did not confirm the operation");
return result.data;
};
return {
async upload(bytes, name) {
const image = !!imageMime(bytes);
const key = image ? "image_key" : "file_key";
const failure = (status, code) => {
// Feishu common error codes: generic-error-code; 99991400 is rate limiting.
const temporary = status >= 500 || [408, 409, 425, 429].includes(status) || [1500, 1503, 1551, 99991400].includes(code);
const definite = !temporary && (status >= 400 || (Number.isInteger(code) && code !== 0));
return new AppError(definite ? 422 : 503, definite
? `飞书拒绝上传附件${Number.isInteger(code) ? `(错误码 ${code})` : ""},请检查机器人上传权限、文件格式和大小后重试。`
: "飞书附件上传暂未确认,将重试。");
};
let result;
try {
// The generated upload methods discard error codes. Keep the SDK's full envelope.
result = await client.request({
method: "POST", url: image ? "/open-apis/im/v1/images" : "/open-apis/im/v1/files",
headers: { "Content-Type": "multipart/form-data" },
data: image ? { image_type: "message", image: bytes } : { file_type: "stream", file_name: name, file: bytes },
});
} catch (error) { throw failure(error.response?.status, error.response?.data?.code); }
if (result?.code !== 0 || typeof result.data?.[key] !== "string" || !result.data[key])
throw failure(200, result?.code);
return { msg_type: image ? "image" : "file", content: JSON.stringify({ [key]: result.data[key] }) };
},
async send(row) {
const text =
row.plain_text && /^ou_[a-zA-Z0-9_-]+$/.test(row.sender_id || "")
? `<at user_id="${row.sender_id}">user</at> ${row.payload}`
: row.payload;
const data = {
msg_type: row.plain_text ? "text" : "interactive",
content: JSON.stringify(row.plain_text ? { text } : feishuCard(text)),
...row.uploaded_media,
uuid: row.id,
};
const result = row.reply_to
? await client.im.message.reply({
path: { message_id: row.reply_to },
data: { ...data, reply_in_thread: row.chat_type !== "p2p" },
})
: await client.im.message.create({
params: { receive_id_type: "chat_id" },
data: { ...data, receive_id: row.chat_id },
});
const value = confirmed(result);
if (!value?.message_id)
throw new Error("Feishu did not return a message identifier");
return { id: value.message_id };
},
async edit(id, text) {
const result = await client.im.message.patch({
path: { message_id: id },
data: { content: JSON.stringify(feishuCard(text)) },
}).catch((error) => {
if (error.response?.data?.code) return error.response.data;
throw error;
});
// Documented PATCH errors: recalled, outside the edit window, deleted.
if ([230011, 230031, 230110].includes(result.code))
throw new AppError(410, "飞书卡片已不可更新。", "feishu_card_unavailable");
confirmed(result);
},
async resource(row, resource) {
return (
await client.im.messageResource.get({
path: {
message_id: resource.message_id || row.message_id,
file_key: resource.fileKey,
},
params: { type: resource.type === "image" ? "image" : "file" },
})
).getReadableStream();
},
async beginTyping(row) {
return confirmed(
await client.im.messageReaction.create({
path: { message_id: row.message_id },
data: { reaction_type: { emoji_type: "Typing" } },
}),
)?.reaction_id;
},
async endTyping(row) {
confirmed(
await client.im.messageReaction.delete({
path: {
message_id: row.message_id,
reaction_id: row.typing_reaction_id,
},
}),
);
},
};
}
// The maintained SDK owns authentication, mention parsing and WebSocket lifecycle.
// SQLite owns delivery receipts across reconnects and process restarts.
export function feishuWorker(store, core, product, makeChannel, configId) {
let channel,
active,
timer,
stopping = false,
running;
const health = (state) =>
store.put("feishu_health", {
id: configId,
state,
updated_at: stamp(),
});
const sessions = product.sessions;
// The Turn ledger, bound to this worker's Core client like every other call here.
const ledger = turnsAPI(store, core);
const allowed = (appId, chatType = "group") => {
const config = store.get("feishu_bots", configId);
return Boolean(
config?.enabled &&
config.app_id === appId &&
(chatType === "p2p" ? config.direct : config.groups),
);
};
const threadFor = (appId, message) =>
store
.list("feishu_threads")
.find(
(row) =>
row.app_id === appId &&
row.chat_id === message.chatId &&
(row.root_id ===
(message.rootId || message.replyToMessageId || message.messageId) ||
(message.threadId && row.thread_id === message.threadId) ||
store
.list("feishu_outbound")
.some(
(out) =>
out.thread_id === row.id &&
out.sent_message_id === message.replyToMessageId,
)),
);
// A topic's participants are the people who mentioned the bot in it.
const participates = (thread, senderId) =>
thread.sender_id === senderId || (thread.participants || []).includes(senderId);
const receive = (appId, message) => {
const topic = message.chatType === "group" && threadFor(appId, message);
if (
!allowed(appId, message.chatType) ||
!["group", "p2p"].includes(message.chatType) ||
(message.chatType === "group" &&
!message.mentionedBot &&
// Without a mention, only a participant's reply in the topic reaches the
// bot, and not one that mentions only other people.
(message.mentions?.length || !topic || !participates(topic, message.senderId))) ||
!message.senderId ||
message.mentionAll
)
return;
if (!message.content?.trim() || message.content.length > 40000) return;
const id = stableId(`${appId}:${message.messageId}`);
if (store.get("feishu_inbound", id)) return;
const content = asCommand(message.content.trim());
// A private chat is one thread per sender; /clear starts a new conversation
// in it. The newest one wins if earlier versions left several.
let thread =
message.chatType === "p2p"
? store
.list("feishu_threads")
.filter(
(row) =>
row.app_id === appId &&
row.chat_id === message.chatId &&
row.sender_id === message.senderId &&
row.chat_type === "p2p",
)
.sort((a, b) => (b.created_at || 0) - (a.created_at || 0))[0]
: threadFor(appId, message);
if (
thread &&
!store.get("sessions", thread.session_id) &&
!message.content.trim().startsWith("/") &&
(store
.get("feishu_inbound", thread.first_message_id)
?.text.startsWith("/") ||
["rejected", "delivered"].includes(
store.get("feishu_inbound", thread.first_message_id)?.state,
))
) {
thread = { ...thread, first_message_id: id };
}
const root =
message.rootId || message.replyToMessageId || message.messageId;
const threadId =
thread?.id || stableId(`${appId}:${message.chatId}:${root}`);
store.transaction(() => {
if (thread)
store.put("feishu_threads", {
...thread,
settled_at: undefined,
...(message.chatType === "group" && !participates(thread, message.senderId) && {
participants: [...(thread.participants || []), message.senderId],
}),
});
if (!thread)
store.put("feishu_threads", {
id: threadId,
app_id: appId,
chat_id: message.chatId,
chat_type: message.chatType,
root_id: root,
thread_id: message.threadId,
context_data: message.context,
session_id: randomUUID(),
agent_id: store.get("feishu_bots", configId).agent_id,
first_message_id: id,
sender_id: message.senderId,
created_at: stamp(),
});
store.put("feishu_inbound", {
id,
app_id: appId,
chat_id: message.chatId,
chat_type: message.chatType,
thread_id: threadId,
message_id: message.messageId,
sender_id: message.senderId,
text: content,
raw_content_type: message.rawContentType,
reply_to_message_id: message.replyToMessageId,
occurred_at: message.createTime || stamp(),
context_data: message.context,
resources: (message.resources || []).map(
({ type, fileKey, fileName }) => ({ type, fileKey, fileName }),
),
state: "queued",
attempts: 0,
created_at: stamp(),
next_at: 0,
});
});
};
const queueReply = (
id,
thread,
payload,
notify = false,
replyTo = thread.root_id,
) => {
if (!store.get("feishu_outbound", id))
store.put("feishu_outbound", {
id,
app_id: thread.app_id,
chat_id: thread.chat_id,
chat_type: thread.chat_type,
thread_id: thread.id,
reply_to: replyTo,
payload,
notify,
state: "queued",
attempts: 0,
created_at: stamp(),
next_at: 0,
});
};
// A Turn's files reply to the message it answers. Only files its reply names
// reach the chat; every file stays downloadable in the Web conversation.
// A Turn's card is the newest card one of its inputs opened that has not moved.
const turnCard = (thread, entry, except) =>
entry && [entry.kind === "first" ? thread.first_message_id : entry.id, ...(entry.steers || []).map((steer) => steer.id)]
.filter((id) => id !== except)
.map((id) => store.get("feishu_outbound", stableId(`${id}:accepted`)))
.filter((card) => card && !card.moved)
.at(-1);
const queueMedia = (thread, items, artifacts = [], replyTo = thread.root_id) => {
const replies = items
.filter((item) => item.type === "message" && item.role === "assistant")
.map((item) => ({ item, text: (item.content || []).filter((part) => part.type === "output_text").map((part) => part.text).join("\n") }));
const said = replies.map(({ text }) => text).join("\n");
const sources = artifacts
.map((file) => ({ file, name: file.path.split("/").at(-1) || "attachment" }))
.filter(({ name }) => said.includes(name))
.map(({ file, name }) => ({ id: `artifact:${file.id}`, path: artifactContentPath(file.session_id, file.id), name }));
for (const { item, text } of replies)
for (const path of qrImages(text))
sources.push({ id: `${item.turn_id}:${path}`, path, name: "feishu-authorization.png" });
for (const source of sources) {
const id = stableId(`${thread.id}:media:${source.id}`);
if (store.get("feishu_outbound", id)) continue;
store.transaction(() => {
queueReply(id, thread, "", false, replyTo);
store.put("feishu_outbound", { ...store.get("feishu_outbound", id), media: source });
});
}
};
const reject = (row, reason) => {
store.put("feishu_inbound", {
...row,
state: "rejected",
media: undefined,
context: undefined,
error: reason,
});
const thread = store.get("feishu_threads", row.thread_id);
if (thread) queueReply(stableId(`${row.id}:rejected`), thread, reason);
};
const cancel = async (row) => {
const thread = store.get("feishu_threads", row.thread_id);
if (!thread) return reject(row, "这条消息没能接上对话,请重新发送。");
let run = store.get("sessions", thread.session_id);
// Resolve an uncertain initial creation before cancelling its actual Session.
if (run && !run.core_session_id && !run.deleted_at)
run = await sessions(run.id, {});
store.transaction(() => {
for (const previous of store.list("feishu_inbound").reverse()) {
if (previous.id === row.id) break;
if (
previous.thread_id === row.thread_id &&
!["delivered", "rejected"].includes(previous.state)
)
store.put("feishu_inbound", {
...previous,
state: "rejected",
error: "已被后续取消请求撤回,不会重新提交。",
});
}
if (!run) {
queueReply(
stableId(`${row.id}:cancel`),
thread,
"已撤回此前等待处理的消息;此话题没有已启动的执行。",
);
store.put("feishu_inbound", {
...row,
state: "delivered",
error: undefined,
});
}
});
if (run) await inbound(row);
};
const mediaFor = async (row) => {
if (row.media) return row.media;
const thread = store.get("feishu_threads", row.thread_id);
const context =
row.context ||
(await channel.readContext(row));
row = { ...row, context };
store.put("feishu_inbound", row);
let input = context.text.replace(
/<(?:file|audio|video) key="[^"]*"[^>]*\/>/g,
"",
);
for (const resource of context.resources || [])
if (resource.type === "image")
input = input.split(``).join("");
const title =
row.text
.replace(/!\[image\]\([^)]*\)/g, "")
.replace(/<(?:file|audio|video) key="[^"]*"[^>]*\/>/g, "")
.trim() ||
((context.resources || []).some((resource) => resource.type === "image")
? "图片消息"
: "文件消息");
// The Agent sees where the message came from, so Skills can key work to it.
const source = feishuSource(row);
const media = {
images: [],
files: [],
text: `${source}\n${input.trim() || title}`,
title,
notice: context.notice,
};
if ((context.resources?.length || 0) > 8)
throw new AppError(400, "每条消息最多支持 8 个附件。");
let total = 0;
for (const resource of context.resources || []) {
const response = await channel.resource(row, resource);
const chunks = [];
for await (const chunk of response) {
total += chunk.length;
if (total > maxUploadBytes)
throw new AppError(413, "附件合计不能超过 50 MiB。");
chunks.push(chunk);
}
const bytes = Buffer.concat(chunks);
if (resource.type === "image") {
const mime = bytes
.subarray(0, 8)
.equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))
? "png"
: bytes[0] === 255 && bytes[1] === 216
? "jpeg"
: bytes.toString("ascii", 8, 12) === "WEBP"
? "webp"
: "";
if (!mime) throw new AppError(400, "图片需为 PNG、JPEG 或 WebP。");
media.images.push(
`data:image/${mime};base64,${bytes.toString("base64")}`,
);
if (JSON.stringify(media.images).length > 900000)
throw new AppError(
413,
"图片超过公开消息接口大小限制,请缩小后重试。",
);
} else {
const filename = (resource.fileName || "attachment")
.replace(/[^a-zA-Z0-9_.-]/g, "_")
.slice(-100);
const path = `/workspace/inputs/${row.id}-${media.files.length}-${filename}`;
// Uploaded once: the message keeps only the File ID across retries.
const form = new FormData();
form.append("file", new Blob([bytes]), filename);
form.append("purpose", "user_data");
const file = await core("/v1/files", "POST", form);
media.files.push({ type: "file_id", path, file_id: file.id });