@eum-agent/channel-feishu 0.0.0-stage → 1.0.0

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 (4) hide show
  1. package/dist/index.js +3621 -0
  2. package/package.json +52 -3
  3. package/ui/ui.js +2045 -0
  4. package/README.md +0 -3
package/dist/index.js ADDED
@@ -0,0 +1,3621 @@
1
+ import { existsSync } from "node:fs";
2
+ import { fileURLToPath } from "node:url";
3
+ import { z } from "zod";
4
+ import { randomInt, randomUUID } from "node:crypto";
5
+ import * as Lark from "@larksuiteoapi/node-sdk";
6
+ import { HttpsProxyAgent } from "https-proxy-agent";
7
+ //#region src/cards/parts.ts
8
+ /** Where a text is cut, so a card stays well under the platform's size cap. */
9
+ const REPLY_LIMIT = 12e3;
10
+ /** `text` cut to `limit` characters, with a mark where it was cut. */
11
+ function clip(text, limit) {
12
+ const chars = [...text];
13
+ return chars.length <= limit ? text : `${chars.slice(0, limit).join("")}…`;
14
+ }
15
+ /** One line of text, whitespace folded, cut to `limit`. */
16
+ function oneLine(text, limit = 160) {
17
+ return clip(text.replace(/\s+/g, " ").trim(), limit);
18
+ }
19
+ /** Text the platform's markdown shows as typed: its markup characters escaped. */
20
+ function plain(text) {
21
+ return text.replace(/([\\`*_~[\]<>#|])/g, "\\$1");
22
+ }
23
+ function markdown(content) {
24
+ return {
25
+ tag: "markdown",
26
+ content
27
+ };
28
+ }
29
+ function card(input) {
30
+ return {
31
+ schema: "2.0",
32
+ config: {
33
+ update_multi: true,
34
+ width_mode: "fill",
35
+ summary: { content: input.summary ?? input.title }
36
+ },
37
+ header: {
38
+ title: {
39
+ tag: "plain_text",
40
+ content: input.title
41
+ },
42
+ template: input.tone
43
+ },
44
+ body: { elements: input.elements.length === 0 ? [markdown(" ")] : [...input.elements] }
45
+ };
46
+ }
47
+ function panel(title, elements, expanded = false) {
48
+ return {
49
+ tag: "collapsible_panel",
50
+ expanded,
51
+ header: { title: {
52
+ tag: "markdown",
53
+ content: title
54
+ } },
55
+ elements: elements.length === 0 ? [markdown(" ")] : [...elements]
56
+ };
57
+ }
58
+ /** A button that calls back with `value`. */
59
+ function button(label, value, type = "default") {
60
+ return {
61
+ tag: "button",
62
+ text: {
63
+ tag: "plain_text",
64
+ content: label
65
+ },
66
+ type,
67
+ behaviors: [{
68
+ type: "callback",
69
+ value
70
+ }]
71
+ };
72
+ }
73
+ /** A button that opens an address. */
74
+ function link(label, url) {
75
+ return {
76
+ tag: "button",
77
+ text: {
78
+ tag: "plain_text",
79
+ content: label
80
+ },
81
+ type: "default",
82
+ behaviors: [{
83
+ type: "open_url",
84
+ default_url: url
85
+ }]
86
+ };
87
+ }
88
+ /** Buttons side by side, wrapping on a narrow screen. */
89
+ function buttons(items) {
90
+ return {
91
+ tag: "column_set",
92
+ flex_mode: "flow",
93
+ horizontal_spacing: "8px",
94
+ columns: items.map((element) => ({
95
+ tag: "column",
96
+ width: "auto",
97
+ elements: [element]
98
+ }))
99
+ };
100
+ }
101
+ /** The address that opens one session in the WebUI, or `undefined` without one. */
102
+ function sessionUrl(webuiUrl, sessionId) {
103
+ if (webuiUrl === "") return void 0;
104
+ const url = new URL(webuiUrl);
105
+ url.searchParams.set("session", sessionId);
106
+ return url.toString();
107
+ }
108
+ //#endregion
109
+ //#region src/cards/session.ts
110
+ const STATE = {
111
+ active: {
112
+ label: "同步中",
113
+ tone: "wathet"
114
+ },
115
+ paused: {
116
+ label: "已暂停(会话已归档)",
117
+ tone: "grey"
118
+ },
119
+ broken: {
120
+ label: "已失效",
121
+ tone: "red"
122
+ },
123
+ unbound: {
124
+ label: "已解绑",
125
+ tone: "grey"
126
+ }
127
+ };
128
+ function renderTopic(input) {
129
+ const state = STATE[input.state];
130
+ const elements = [markdown([
131
+ `**工作空间**:${plain(input.workspace)}`,
132
+ `**智能体**:${plain(input.agent)}`,
133
+ `**状态**:${state.label}`,
134
+ "",
135
+ "<font color='grey'>在本群里发消息即与该会话对话;可用命令:/stop 停止、/compact 压缩上下文、/model 切换模型与思考、/help 帮助。</font>"
136
+ ].join("\n"))];
137
+ if (input.url !== void 0) elements.push(buttons([link("在 WebUI 打开", input.url)]));
138
+ return card({
139
+ title: input.title,
140
+ tone: state.tone,
141
+ elements
142
+ });
143
+ }
144
+ /** The `/model` card, or a line saying there is nothing to choose. */
145
+ function renderModel(input) {
146
+ const { options } = input;
147
+ const models = options.endpoints.flatMap((endpoint) => endpoint.models.map((model) => ({
148
+ value: `${endpoint.providerId}\u0000${model.model}`,
149
+ label: `${endpoint.label} · ${model.label}`,
150
+ model
151
+ })));
152
+ if (models.length === 0) return card({
153
+ title: "切换模型",
154
+ tone: "grey",
155
+ elements: [markdown("没有可用的模型接入点,请在 WebUI 的模型设置里添加。")]
156
+ });
157
+ const current = options.current.model === null ? void 0 : models.find((one) => one.value === `${options.current.model?.providerId}\u0000${options.current.model?.model}`);
158
+ const efforts = current?.model.efforts ?? [];
159
+ const fields = [markdown(`**当前**:${current === void 0 ? "未设置" : plain(current.label)}`), {
160
+ tag: "select_static",
161
+ name: "model",
162
+ placeholder: {
163
+ tag: "plain_text",
164
+ content: "选择模型"
165
+ },
166
+ ...current === void 0 ? {} : { initial_option: current.value },
167
+ options: models.map((one) => ({
168
+ text: {
169
+ tag: "plain_text",
170
+ content: one.label
171
+ },
172
+ value: one.value
173
+ }))
174
+ }];
175
+ if (current?.model.thinking === "switchable") fields.push({
176
+ tag: "select_static",
177
+ name: "thinking",
178
+ placeholder: {
179
+ tag: "plain_text",
180
+ content: "深度思考"
181
+ },
182
+ initial_option: current.model.on ? "on" : "off",
183
+ options: [{
184
+ text: {
185
+ tag: "plain_text",
186
+ content: "开启深度思考"
187
+ },
188
+ value: "on"
189
+ }, {
190
+ text: {
191
+ tag: "plain_text",
192
+ content: "关闭深度思考"
193
+ },
194
+ value: "off"
195
+ }]
196
+ });
197
+ if (efforts.length > 0 && current?.model.on === true) {
198
+ const stored = options.current.params.effort;
199
+ fields.push({
200
+ tag: "select_static",
201
+ name: "effort",
202
+ placeholder: {
203
+ tag: "plain_text",
204
+ content: "思考强度"
205
+ },
206
+ ...typeof stored === "string" && efforts.some((one) => one.value === stored) ? { initial_option: stored } : {},
207
+ options: efforts.map((one) => ({
208
+ text: {
209
+ tag: "plain_text",
210
+ content: one.label ?? one.value
211
+ },
212
+ value: one.value
213
+ }))
214
+ });
215
+ }
216
+ fields.push({
217
+ tag: "button",
218
+ name: "submit",
219
+ text: {
220
+ tag: "plain_text",
221
+ content: "应用"
222
+ },
223
+ type: "primary",
224
+ form_action_type: "submit",
225
+ behaviors: [{
226
+ type: "callback",
227
+ value: {
228
+ k: "model",
229
+ s: input.sessionId,
230
+ m: input.ref
231
+ }
232
+ }]
233
+ });
234
+ return card({
235
+ title: "切换模型与思考",
236
+ tone: "blue",
237
+ elements: [{
238
+ tag: "form",
239
+ name: "model",
240
+ elements: fields
241
+ }, markdown("<font color='grey'>换了模型后,思考与强度按新模型重新提供,可再发一次 /model 调整。</font>")]
242
+ });
243
+ }
244
+ /** The `/model` card once applied. */
245
+ function renderModelApplied(label) {
246
+ return card({
247
+ title: "已切换",
248
+ tone: "green",
249
+ elements: [markdown(`已切换到 **${plain(label)}**`)]
250
+ });
251
+ }
252
+ //#endregion
253
+ //#region src/lark/errors.ts
254
+ /**
255
+ * What a failed Feishu call means for the plugin, read from the open
256
+ * platform's error code. The codes come from the platform's documentation
257
+ * and the SDK; the scope and credential codes were seen on a real tenant.
258
+ */
259
+ /** One failed call, with the platform's own code and words. */
260
+ var LarkError = class extends Error {
261
+ name = "LarkError";
262
+ code;
263
+ status;
264
+ constructor(code, message, status) {
265
+ super(message);
266
+ this.code = code;
267
+ this.status = status;
268
+ }
269
+ };
270
+ const CREDENTIALS = /* @__PURE__ */ new Set([
271
+ 10003,
272
+ 10014,
273
+ 99991661,
274
+ 99991663,
275
+ 99991664,
276
+ 99991665
277
+ ]);
278
+ const GONE = /* @__PURE__ */ new Set([
279
+ 230001,
280
+ 230002,
281
+ 230011,
282
+ 230019,
283
+ 232006,
284
+ 232009,
285
+ 232010,
286
+ 232011,
287
+ 230035
288
+ ]);
289
+ const RATE = /* @__PURE__ */ new Set([
290
+ 99991400,
291
+ 11232,
292
+ 230020,
293
+ 11233
294
+ ]);
295
+ /** How the plugin should treat `error`. */
296
+ function classify(error) {
297
+ if (!(error instanceof LarkError)) return { kind: "transient" };
298
+ if (error.code === 99991672 || error.code === 99991679) return {
299
+ kind: "scope",
300
+ scopes: scopesIn(error.message)
301
+ };
302
+ if (CREDENTIALS.has(error.code)) return { kind: "credentials" };
303
+ if (GONE.has(error.code)) return { kind: "gone" };
304
+ if (RATE.has(error.code) || error.status === 429) return { kind: "rate-limited" };
305
+ if (error.code === 200750) return { kind: "card-expired" };
306
+ if (error.code === 300317) return { kind: "sequence" };
307
+ return { kind: "transient" };
308
+ }
309
+ /** The scope names a "scope is required" message lists, in its brackets. */
310
+ function scopesIn(message) {
311
+ const found = /\[([^\]]*)\]/.exec(message);
312
+ if (found === null) return [];
313
+ return (found[1] ?? "").split(",").map((one) => one.trim()).filter((one) => /^[a-z][\w:.-]*$/i.test(one));
314
+ }
315
+ /** One line a person reads for `error`. */
316
+ function reasonOf(error) {
317
+ if (error instanceof LarkError) return error.code === 0 ? error.message : `${error.message}(${error.code})`;
318
+ return error instanceof Error ? error.message : String(error);
319
+ }
320
+ //#endregion
321
+ //#region src/bindings.ts
322
+ /** Owns ordinary-group bindings, durable creation attempts and group history. */
323
+ /** Serializes forward creation with incoming bot events across all configured bots. */
324
+ function createBindings(deps) {
325
+ let chain = Promise.resolve(void 0);
326
+ const reconciled = /* @__PURE__ */ new Set();
327
+ const serial = (work) => {
328
+ const current = () => {
329
+ deps.signal.throwIfAborted();
330
+ return work();
331
+ };
332
+ const next = chain.then(current, current);
333
+ chain = next.catch(() => {});
334
+ return next;
335
+ };
336
+ const channel = () => {
337
+ deps.signal.throwIfAborted();
338
+ const ctx = deps.channel();
339
+ if (ctx === void 0) throw new Error("飞书通道尚未启动");
340
+ return ctx;
341
+ };
342
+ const sessionOf = async (id) => {
343
+ if (id === "") return void 0;
344
+ try {
345
+ await channel().ensureReadingReady(id, { signal: deps.signal });
346
+ return channel().getReadingSessionSummary(id);
347
+ } catch (error) {
348
+ if (error instanceof Error && "code" in error && error.code === "session_unavailable") return void 0;
349
+ throw error;
350
+ }
351
+ };
352
+ const titleOf = (session) => session.name ?? session.title ?? session.preview ?? "新会话";
353
+ const ready = (botId) => deps.channel() !== void 0 && reconciled.has(botId) && deps.bots.status(botId).state === "online" && deps.store.bot(botId)?.enabled === true;
354
+ const view = (binding) => {
355
+ const status = deps.bots.status(binding.botId);
356
+ const memberError = deps.store.group(binding.botId, binding.sessionId)?.memberError;
357
+ const unavailable = binding.state === "active" && (status.state !== "online" || memberError != null);
358
+ const session = channel().getReadingSessionSummary(binding.sessionId);
359
+ return {
360
+ sessionId: binding.sessionId,
361
+ botId: binding.botId,
362
+ botName: deps.store.bot(binding.botId)?.name ?? binding.botId,
363
+ chatId: binding.chatId,
364
+ chatName: session === void 0 ? binding.chatId : titleOf(session),
365
+ state: unavailable ? "broken" : binding.state,
366
+ reason: unavailable ? memberError ?? status.reason ?? "机器人未连接,绑定关系已保留" : binding.reason,
367
+ chatUrl: `https://applink.feishu.cn/client/chat/open?openChatId=${encodeURIComponent(binding.chatId)}`
368
+ };
369
+ };
370
+ const stop = (sessionId) => {
371
+ deps.relay.detach(sessionId);
372
+ deps.withdrawAdmissions(sessionId);
373
+ deps.streamer.cancelBinding(sessionId);
374
+ };
375
+ const release = (binding) => {
376
+ stop(binding.sessionId);
377
+ deps.store.transaction(() => {
378
+ deps.store.setGroupState(binding.chatId, "unbound", binding.botId);
379
+ deps.store.acceptLifecycle(binding.botId, binding.chatId, deps.store.now());
380
+ deps.store.deleteBinding(binding.sessionId);
381
+ });
382
+ deps.changed(binding.sessionId);
383
+ };
384
+ async function finish(session, botId, chatId) {
385
+ const occupied = deps.store.bindingsOfChat(chatId)[0];
386
+ if (occupied !== void 0 && (occupied.botId !== botId || occupied.sessionId !== session.sessionId)) throw new Error("这个群已绑定另一个机器人或会话");
387
+ const existing = deps.store.binding(session.sessionId);
388
+ if (existing !== void 0 && existing.chatId !== chatId) throw new Error("这个会话已绑定其他群,请先解绑");
389
+ const api = deps.bots.api(botId);
390
+ if (api === void 0) throw new Error("机器人未连接");
391
+ if (existing === void 0) {
392
+ const cardId = await api.createCard(renderTopic({
393
+ title: titleOf(session),
394
+ workspace: session.workspaceId,
395
+ agent: session.agentId,
396
+ state: session.archived ? "paused" : "active",
397
+ url: sessionUrl(channel().webuiUrl, session.sessionId)
398
+ }));
399
+ deps.signal.throwIfAborted();
400
+ if (deps.bots.api(botId) !== api) throw new Error("bot activation changed");
401
+ const sent = await api.sendCard(chatId, cardId);
402
+ deps.signal.throwIfAborted();
403
+ if (deps.bots.api(botId) !== api) throw new Error("bot activation changed");
404
+ deps.store.transaction(() => {
405
+ deps.store.insertGroup({
406
+ botId,
407
+ sessionId: session.sessionId,
408
+ chatId,
409
+ owner: null
410
+ });
411
+ deps.store.putBinding({
412
+ sessionId: session.sessionId,
413
+ botId,
414
+ workspaceId: session.workspaceId,
415
+ chatId,
416
+ rootMessageId: sent.messageId,
417
+ rootCardId: cardId
418
+ });
419
+ deps.store.setBindingState(session.sessionId, session.archived ? "paused" : "active");
420
+ });
421
+ }
422
+ await deps.groupMade(botId);
423
+ deps.signal.throwIfAborted();
424
+ reconciled.add(botId);
425
+ const group = deps.store.group(botId, session.sessionId);
426
+ if (group?.memberError !== null && group?.memberError !== void 0) {
427
+ deps.store.setBindingState(session.sessionId, "broken", `成员同步失败:${group.memberError}`);
428
+ deps.changed(session.sessionId);
429
+ throw new Error(`成员同步失败:${group.memberError}`);
430
+ }
431
+ deps.store.setBindingState(session.sessionId, session.archived ? "paused" : "active");
432
+ const binding = deps.store.binding(session.sessionId);
433
+ if (!session.archived) await deps.relay.attach(binding, { fresh: existing === void 0 });
434
+ deps.signal.throwIfAborted();
435
+ deps.changed(session.sessionId);
436
+ return view(binding);
437
+ }
438
+ async function receive(botId, chatId) {
439
+ const key = `incoming:${botId}:${chatId}`;
440
+ let operation = deps.store.operation(key);
441
+ deps.store.putOperation(key, botId, operation?.sessionId ?? null, chatId, null);
442
+ try {
443
+ const occupied = deps.store.bindingsOfChat(chatId)[0];
444
+ if (occupied !== void 0) {
445
+ if (occupied.botId !== botId) throw new Error("绑定冲突:这个群已绑定另一个瑶光机器人");
446
+ const session = await sessionOf(occupied.sessionId);
447
+ if (session !== void 0) {
448
+ if (occupied.state === "broken" || deps.store.group(botId, occupied.sessionId)?.memberError != null) await finish(session, botId, chatId);
449
+ deps.signal.throwIfAborted();
450
+ deps.store.deleteOperation(key);
451
+ return;
452
+ }
453
+ release(occupied);
454
+ }
455
+ const api = deps.bots.api(botId);
456
+ const bot = deps.store.bot(botId);
457
+ if (bot === void 0 || !bot.enabled || api === void 0) throw new Error("机器人未启用或尚未连接");
458
+ const info = await api.getChat(chatId);
459
+ deps.signal.throwIfAborted();
460
+ if (deps.bots.api(botId) !== api) throw new Error("bot activation changed");
461
+ if (!info.ordinary) throw new Error("仅支持普通消息群,请将机器人添加到普通群");
462
+ if (deps.store.operationsOf(botId).find((one) => one.key.startsWith("outgoing:") && one.chatId === null) !== void 0) throw new Error("有建群结果待核实,请先恢复原会话的建群操作");
463
+ const history = deps.store.history(botId, chatId);
464
+ const forward = deps.store.operationsOf(botId).find((one) => one.key.startsWith("outgoing:") && one.chatId === chatId);
465
+ let session = await sessionOf(forward?.sessionId ?? operation?.sessionId ?? history?.sessionId ?? "");
466
+ if (forward !== void 0 && session === void 0) throw new Error("原建群会话不可用,请先核实会话");
467
+ if (session !== void 0 && deps.store.binding(session.sessionId) !== void 0) throw new Error("历史会话已绑定其他群,请先在对应会话解绑后重试");
468
+ if (session === void 0) {
469
+ if (bot.defaultAgentId === null || !channel().listAgents().some((one) => one.agentId === bot.defaultAgentId && one.startsSessions !== false)) throw new Error("请先在管理配置中选择有效的默认智能体");
470
+ if (bot.defaultWorkspaceId === null || !channel().listWorkspaces().some((one) => one.workspaceId === bot.defaultWorkspaceId)) throw new Error("请先在管理配置中选择有效的默认工作空间");
471
+ const creationKey = operation?.sessionId ?? randomUUID();
472
+ deps.store.putOperation(key, botId, creationKey, chatId, null);
473
+ session = channel().createSession({
474
+ agentId: bot.defaultAgentId,
475
+ workspaceId: bot.defaultWorkspaceId,
476
+ title: info.name,
477
+ creationKey
478
+ });
479
+ deps.store.putOperation(key, botId, session.sessionId, chatId, null);
480
+ }
481
+ await finish(session, botId, chatId);
482
+ deps.signal.throwIfAborted();
483
+ if (forward !== void 0) deps.store.deleteOperation(forward.key);
484
+ deps.store.deleteOperation(key);
485
+ } catch (error) {
486
+ deps.signal.throwIfAborted();
487
+ operation = deps.store.operation(key);
488
+ deps.store.putOperation(key, botId, operation?.sessionId ?? null, chatId, error instanceof Error ? error.message : String(error));
489
+ deps.changed(operation?.sessionId ?? "");
490
+ }
491
+ }
492
+ return {
493
+ ready,
494
+ view(sessionId) {
495
+ const row = deps.store.binding(sessionId);
496
+ return row === void 0 ? null : view(row);
497
+ },
498
+ bind(sessionId, botId) {
499
+ return serial(async () => {
500
+ const session = await sessionOf(sessionId);
501
+ if (session === void 0) throw new Error("找不到这个会话");
502
+ const bot = deps.store.bot(botId);
503
+ const api = deps.bots.api(botId);
504
+ if (bot === void 0 || !bot.enabled || api === void 0) throw new Error("机器人未连接");
505
+ if (bot.ownerOpenId === null) throw new Error("机器人还没有配对所有者,请先在设置里配对");
506
+ const existing = deps.store.binding(sessionId);
507
+ if (existing !== void 0) {
508
+ if (existing.botId !== botId) throw new Error("请先解除当前绑定");
509
+ if (existing.state !== "broken" && deps.store.group(botId, sessionId)?.memberError == null) return view(existing);
510
+ return finish(session, botId, existing.chatId);
511
+ }
512
+ const key = `outgoing:${sessionId}`;
513
+ const operation = deps.store.operation(key);
514
+ if (operation !== void 0 && operation.botId !== botId) throw new Error("之前的建群操作尚未完成,请使用原机器人恢复");
515
+ if (operation !== void 0 && operation.chatId === null) throw new Error("上次建群结果待核实,请确认飞书中的群并在群管理中恢复,不能重复创建");
516
+ let chatId = operation?.chatId ?? void 0;
517
+ try {
518
+ if (chatId === void 0) {
519
+ deps.store.putOperation(key, botId, sessionId, null, "正在创建群,结果尚未确认");
520
+ chatId = await api.createChat(titleOf(session), [bot.ownerOpenId], randomUUID());
521
+ deps.signal.throwIfAborted();
522
+ if (deps.bots.api(botId) !== api) throw new Error("bot activation changed");
523
+ deps.store.putOperation(key, botId, sessionId, chatId, null);
524
+ }
525
+ const result = await finish(session, botId, chatId);
526
+ deps.signal.throwIfAborted();
527
+ deps.signal.throwIfAborted();
528
+ deps.store.deleteOperation(key);
529
+ return result;
530
+ } catch (error) {
531
+ deps.signal.throwIfAborted();
532
+ if (deps.bots.api(botId) !== api) throw error;
533
+ const reason = `飞书拒绝了操作:${deps.bots.noteFailure(botId, error)}`;
534
+ if (chatId === void 0 && ["scope", "credentials"].includes(classify(error).kind)) deps.store.deleteOperation(key);
535
+ else deps.store.putOperation(key, botId, sessionId, chatId ?? null, reason);
536
+ deps.changed(sessionId);
537
+ throw new Error(reason);
538
+ }
539
+ });
540
+ },
541
+ unbind(sessionId) {
542
+ return serial(async () => {
543
+ const binding = deps.store.binding(sessionId);
544
+ if (binding !== void 0) release(binding);
545
+ });
546
+ },
547
+ botAdded(botId, chatId, eventId, eventAt) {
548
+ return serial(async () => {
549
+ if (!deps.store.rememberEvent(`added:${botId}:${eventId}`)) return;
550
+ if (!deps.store.acceptLifecycle(botId, chatId, eventAt ?? deps.store.now())) return;
551
+ await receive(botId, chatId);
552
+ });
553
+ },
554
+ recoverGroup(sessionId, botId, chatId) {
555
+ return serial(async () => {
556
+ const key = `outgoing:${sessionId}`;
557
+ const operation = deps.store.operation(key);
558
+ if (operation?.botId !== botId || operation.chatId !== null && operation.chatId !== chatId) throw new Error("没有待核实的建群操作");
559
+ const session = await sessionOf(sessionId);
560
+ if (session === void 0) throw new Error("会话不存在");
561
+ const api = deps.bots.api(botId);
562
+ if (api === void 0) throw new Error("机器人未连接");
563
+ const info = await api.getChat(chatId);
564
+ deps.signal.throwIfAborted();
565
+ if (deps.bots.api(botId) !== api) throw new Error("bot activation changed");
566
+ if (!info.ordinary) throw new Error("普通群不可用");
567
+ deps.store.putOperation(key, botId, sessionId, chatId, null);
568
+ const result = await finish(session, botId, chatId);
569
+ deps.signal.throwIfAborted();
570
+ deps.store.deleteOperation(key);
571
+ deps.store.deleteOperation(`incoming:${botId}:${chatId}`);
572
+ return result;
573
+ });
574
+ },
575
+ retryGroup: (botId, chatId) => serial(() => receive(botId, chatId)),
576
+ markBroken(sessionId, reason) {
577
+ if (deps.store.binding(sessionId) === void 0) return;
578
+ stop(sessionId);
579
+ deps.store.setBindingState(sessionId, "broken", reason);
580
+ deps.changed(sessionId);
581
+ },
582
+ chatGone(chatId, botId, eventAt) {
583
+ return serial(async () => {
584
+ if (!deps.store.acceptLifecycle(botId, chatId, eventAt ?? deps.store.now())) return;
585
+ for (const binding of deps.store.bindingsOfChat(chatId)) if (binding.botId === botId) release(binding);
586
+ deps.store.deleteOperation(`incoming:${botId}:${chatId}`);
587
+ });
588
+ },
589
+ sessionUpdated(session) {
590
+ const binding = deps.store.binding(session.sessionId);
591
+ if (binding === void 0 || binding.state === "broken") return;
592
+ const state = session.archived ? "paused" : "active";
593
+ if (state === binding.state) return;
594
+ stop(session.sessionId);
595
+ deps.store.resetBoundary(session.sessionId);
596
+ deps.store.setBindingState(session.sessionId, state);
597
+ if (state === "active" && ready(binding.botId)) deps.relay.attach(deps.store.binding(session.sessionId), { fresh: true });
598
+ deps.changed(session.sessionId);
599
+ },
600
+ async resume(botId) {
601
+ if (deps.channel() === void 0) return;
602
+ for (const bot of deps.store.bots()) {
603
+ if (botId !== void 0 && bot.id !== botId) continue;
604
+ reconciled.delete(bot.id);
605
+ await deps.groupMade(bot.id);
606
+ deps.signal.throwIfAborted();
607
+ reconciled.add(bot.id);
608
+ for (const binding of deps.store.bindingsOfBot(bot.id)) {
609
+ if (binding.state !== "active" || deps.store.group(bot.id, binding.sessionId)?.memberError !== null) continue;
610
+ deps.relay.detach(binding.sessionId);
611
+ if (ready(bot.id)) await deps.relay.attach(binding);
612
+ deps.signal.throwIfAborted();
613
+ deps.changed(binding.sessionId);
614
+ }
615
+ }
616
+ }
617
+ };
618
+ }
619
+ //#endregion
620
+ //#region src/bots.ts
621
+ /** The credential name the AppSecret is stored under, scoped by bot id. */
622
+ const APP_SECRET = "appSecret";
623
+ function createBots(deps) {
624
+ const live = /* @__PURE__ */ new Map();
625
+ function safeReason(botId, reason, appSecret) {
626
+ let secret = appSecret;
627
+ if (secret === void 0) try {
628
+ secret = deps.credentials.get(botId, APP_SECRET);
629
+ } catch {
630
+ return "无法安全读取连接异常详情,请检查 AppSecret。";
631
+ }
632
+ if (!secret) return "无法安全读取连接异常详情,请检查 AppSecret。";
633
+ return reason.split(secret).join("****");
634
+ }
635
+ const entry = (botId) => {
636
+ let one = live.get(botId);
637
+ if (one === void 0) {
638
+ one = {
639
+ api: void 0,
640
+ state: "off",
641
+ reason: null,
642
+ missing: /* @__PURE__ */ new Set()
643
+ };
644
+ live.set(botId, one);
645
+ }
646
+ return one;
647
+ };
648
+ function set(botId, state, reason = null) {
649
+ const one = entry(botId);
650
+ const was = one.state;
651
+ one.state = state;
652
+ one.reason = reason;
653
+ deps.onChanged();
654
+ if (state === "online" && was !== "online") deps.onOnline(botId);
655
+ }
656
+ function stop(botId) {
657
+ const one = live.get(botId);
658
+ one?.api?.close();
659
+ if (one !== void 0) one.api = void 0;
660
+ set(botId, "off");
661
+ }
662
+ function start(botId) {
663
+ stop(botId);
664
+ const bot = deps.store.bot(botId);
665
+ if (bot === void 0 || !bot.enabled) return;
666
+ let secret;
667
+ try {
668
+ secret = deps.credentials.get(botId, APP_SECRET);
669
+ } catch {
670
+ set(botId, "failed", "AppSecret 无法读取,请重新设置凭证。");
671
+ return;
672
+ }
673
+ if (secret === void 0) {
674
+ set(botId, "failed", "尚未填写 AppSecret");
675
+ return;
676
+ }
677
+ const api = deps.createApi(bot, secret);
678
+ const one = entry(botId);
679
+ one.api = api;
680
+ one.missing.clear();
681
+ api.connect(deps.events(botId), (state, reason) => {
682
+ if (live.get(botId)?.api !== api) return;
683
+ set(botId, state, state === "failed" ? safeReason(botId, reason ?? "连接失败", secret) : null);
684
+ });
685
+ }
686
+ return {
687
+ start,
688
+ stop,
689
+ startAll() {
690
+ for (const bot of deps.store.bots()) start(bot.id);
691
+ },
692
+ stopAll() {
693
+ for (const botId of [...live.keys()]) live.get(botId)?.api?.close();
694
+ live.clear();
695
+ },
696
+ /** The client of a bot that is connected or connecting; `undefined` otherwise. */
697
+ api(botId) {
698
+ const one = live.get(botId);
699
+ return one?.state === "online" || one?.state === "reconnecting" || one?.state === "connecting" ? one.api : void 0;
700
+ },
701
+ status(botId) {
702
+ const one = live.get(botId);
703
+ return {
704
+ state: one?.state ?? "off",
705
+ reason: one?.reason ?? null,
706
+ missingScopes: [...one?.missing ?? []]
707
+ };
708
+ },
709
+ /**
710
+ * Notes what a failed call says about the app. A missing scope is kept
711
+ * until the next connection; wrong credentials turn the bot `failed`.
712
+ * Returns an AppSecret-sanitized reason. Pass the actual call's AppSecret
713
+ * when known so a credential rotation cannot expose the previous secret.
714
+ * Unreadable credentials select a fixed safe explanation.
715
+ */
716
+ noteFailure(botId, error, appSecret) {
717
+ const failure = classify(error);
718
+ const reason = safeReason(botId, reasonOf(error), appSecret);
719
+ if (failure.kind === "scope") {
720
+ const one = entry(botId);
721
+ for (const scope of failure.scopes) one.missing.add(scope);
722
+ deps.onChanged();
723
+ return failure.scopes.length === 0 ? `应用缺少权限:${reason}` : safeReason(botId, `应用缺少权限:${failure.scopes.join("、")}`, appSecret);
724
+ }
725
+ if (failure.kind === "credentials") set(botId, "failed", `凭证无效:${reason}`);
726
+ return reason;
727
+ }
728
+ };
729
+ }
730
+ //#endregion
731
+ //#region src/cards/streamer.ts
732
+ const SYSTEM_CLOCK = {
733
+ now: () => Date.now(),
734
+ setTimeout: (run, ms) => setTimeout(run, ms),
735
+ clearTimeout: (handle) => clearTimeout(handle)
736
+ };
737
+ /** Retries a final state gets before it is left to the next start. */
738
+ const FINAL_ATTEMPTS = 8;
739
+ function createCardStreamer(deps) {
740
+ const clock = deps.clock ?? SYSTEM_CLOCK;
741
+ const throttle = deps.throttleMs ?? 500;
742
+ const queues = /* @__PURE__ */ new Map();
743
+ const cancelled = /* @__PURE__ */ new Set();
744
+ const idle = /* @__PURE__ */ new Set();
745
+ let stopped = false;
746
+ const settleIdle = () => {
747
+ if ([...queues.values()].some((one) => one.inFlight || one.latest !== void 0)) return;
748
+ for (const resolve of [...idle]) resolve();
749
+ idle.clear();
750
+ };
751
+ function schedule(queue, delay) {
752
+ if (stopped || queue.inFlight || queue.latest === void 0) return;
753
+ if (queue.timer !== void 0) clock.clearTimeout(queue.timer);
754
+ const wait = delay ?? Math.max(0, queue.lastSentAt + throttle - clock.now());
755
+ queue.timer = clock.setTimeout(() => {
756
+ queue.timer = void 0;
757
+ send(queue);
758
+ }, wait);
759
+ }
760
+ function drop(queue) {
761
+ if (queue.timer !== void 0) clock.clearTimeout(queue.timer);
762
+ queues.delete(queue.handle.messageId);
763
+ settleIdle();
764
+ }
765
+ async function send(queue) {
766
+ const json = queue.latest;
767
+ if (stopped) return;
768
+ const api = deps.apiOf(queue.handle.botId);
769
+ if (queues.get(queue.handle.messageId) !== queue) return;
770
+ if (json === void 0 || stopped) return settleIdle();
771
+ if (api === void 0) return settleIdle();
772
+ queue.latest = void 0;
773
+ const final = queue.final;
774
+ queue.inFlight = true;
775
+ let retryIn;
776
+ try {
777
+ const sequence = deps.store.reserveSequence(queue.handle.messageId);
778
+ await api.updateCard(queue.handle.cardId, json, sequence);
779
+ queue.failures = 0;
780
+ } catch (error) {
781
+ const failure = classify(error);
782
+ if (failure.kind === "card-expired") {
783
+ deps.store.closeCard(queue.handle.messageId);
784
+ queue.inFlight = false;
785
+ return drop(queue);
786
+ }
787
+ if (failure.kind === "gone") {
788
+ queue.inFlight = false;
789
+ drop(queue);
790
+ deps.onGone(queue.handle.bindingId);
791
+ return;
792
+ }
793
+ queue.failures += 1;
794
+ queue.latest ??= json;
795
+ if (final) queue.final = true;
796
+ retryIn = failure.kind === "sequence" ? 0 : Math.min(6e4, 1e3 * 2 ** (queue.failures - 1));
797
+ if (queue.failures >= FINAL_ATTEMPTS) {
798
+ deps.log.warn(`card ${queue.handle.messageId} could not be updated after ${queue.failures} attempts; it stays open for the next start`);
799
+ queue.inFlight = false;
800
+ return drop(queue);
801
+ }
802
+ } finally {
803
+ queue.inFlight = false;
804
+ queue.lastSentAt = clock.now();
805
+ }
806
+ if (queues.get(queue.handle.messageId) !== queue) return settleIdle();
807
+ if (retryIn !== void 0) return schedule(queue, retryIn);
808
+ if (queue.latest !== void 0) return schedule(queue);
809
+ if (!final) return settleIdle();
810
+ deps.store.closeCard(queue.handle.messageId);
811
+ drop(queue);
812
+ }
813
+ return {
814
+ /** Shows `json` on the card, soon; `final` marks the state it ends in. */
815
+ update(handle, json, options = {}) {
816
+ if (stopped || cancelled.has(handle.messageId) || deps.store.card(handle.messageId)?.state !== "open") return;
817
+ let queue = queues.get(handle.messageId);
818
+ if (queue === void 0) {
819
+ queue = {
820
+ handle,
821
+ latest: void 0,
822
+ final: false,
823
+ inFlight: false,
824
+ lastSentAt: Number.NEGATIVE_INFINITY,
825
+ timer: void 0,
826
+ failures: 0
827
+ };
828
+ queues.set(handle.messageId, queue);
829
+ }
830
+ queue.latest = json;
831
+ if (options.final === true) queue.final = true;
832
+ if (queue.timer === void 0) schedule(queue);
833
+ },
834
+ /** Whether a card still has an update waiting or in flight. */
835
+ busy(messageId) {
836
+ return queues.has(messageId);
837
+ },
838
+ /** Resolves once nothing waits and nothing is in flight. */
839
+ idle() {
840
+ return new Promise((resolve) => {
841
+ idle.add(resolve);
842
+ settleIdle();
843
+ });
844
+ },
845
+ /** Sends what waits for one bot's cards again, after it reconnects. */
846
+ resume(botId) {
847
+ for (const queue of queues.values()) if (queue.handle.botId === botId) schedule(queue);
848
+ },
849
+ /** Cancels queued updates when the binding stops or changes generation. */
850
+ cancelBinding(bindingId) {
851
+ for (const row of deps.store.openCards()) if (row.bindingId === bindingId) cancelled.add(row.messageId);
852
+ for (const queue of [...queues.values()]) {
853
+ if (queue.handle.bindingId !== bindingId) continue;
854
+ if (queue.timer !== void 0) clock.clearTimeout(queue.timer);
855
+ drop(queue);
856
+ }
857
+ },
858
+ stop() {
859
+ stopped = true;
860
+ for (const queue of queues.values()) if (queue.timer !== void 0) clock.clearTimeout(queue.timer);
861
+ queues.clear();
862
+ for (const resolve of [...idle]) resolve();
863
+ idle.clear();
864
+ }
865
+ };
866
+ }
867
+ //#endregion
868
+ //#region src/cards/request.ts
869
+ const ACCESS = {
870
+ read: "读",
871
+ write: "写",
872
+ network: "网络",
873
+ connect: "连接",
874
+ listen: "监听",
875
+ execute: "执行"
876
+ };
877
+ function header(view) {
878
+ const lines = [`来自 **${plain(view.requester)}**${view.from === void 0 ? "" : ` · 子智能体 **${plain(view.from)}**`}`];
879
+ if (view.reason !== void 0 && view.reason !== "") lines.push(plain(view.reason));
880
+ for (const target of view.targets ?? []) lines.push(`- ${ACCESS[target.access]}:\`${target.target.replaceAll("`", "'")}\``);
881
+ if (view.warning !== void 0 && view.warning !== "") lines.push(`<font color='orange'>${plain(view.warning)}</font>`);
882
+ return lines;
883
+ }
884
+ function titleOf(view) {
885
+ return view.title ?? (view.kind === "approval" ? "需要你批准" : "有问题要问你");
886
+ }
887
+ /** A question one press answers: one choice, no text. */
888
+ function oneTap(question) {
889
+ return question.options.length > 0 && question.multiple !== true && !question.freeText;
890
+ }
891
+ /** The open card: every question answerable on it. */
892
+ function renderRequest(view) {
893
+ const elements = [markdown(header(view).join("\n"))];
894
+ const base = {
895
+ k: "answer",
896
+ s: view.sessionId,
897
+ r: view.requestId
898
+ };
899
+ const only = view.questions.length === 1 ? view.questions[0] : void 0;
900
+ if (only !== void 0 && oneTap(only)) {
901
+ if (view.questions.length > 1 || only.text !== view.title) elements.push(markdown(plain(only.text)));
902
+ elements.push(buttons(only.options.map((option, index) => button(option.label, {
903
+ ...base,
904
+ q: only.id,
905
+ o: option.id
906
+ }, view.kind === "approval" && index === only.options.length - 1 ? "danger" : index === 0 ? "primary" : "default"))));
907
+ } else {
908
+ const fields = [];
909
+ for (const question of view.questions) {
910
+ fields.push(markdown(`**${plain(question.text)}**`));
911
+ if (question.options.length > 0) fields.push({
912
+ tag: question.multiple === true ? "multi_select_static" : "select_static",
913
+ name: `o_${question.id}`,
914
+ placeholder: {
915
+ tag: "plain_text",
916
+ content: question.multiple === true ? "选择一项或多项" : "选择一项"
917
+ },
918
+ options: question.options.map((option) => ({
919
+ text: {
920
+ tag: "plain_text",
921
+ content: option.label
922
+ },
923
+ value: option.id
924
+ }))
925
+ });
926
+ if (question.freeText) fields.push({
927
+ tag: "input",
928
+ name: `t_${question.id}`,
929
+ placeholder: {
930
+ tag: "plain_text",
931
+ content: "输入回答"
932
+ }
933
+ });
934
+ }
935
+ fields.push({
936
+ tag: "button",
937
+ name: "submit",
938
+ text: {
939
+ tag: "plain_text",
940
+ content: "提交"
941
+ },
942
+ type: "primary",
943
+ form_action_type: "submit",
944
+ behaviors: [{
945
+ type: "callback",
946
+ value: base
947
+ }]
948
+ });
949
+ elements.push({
950
+ tag: "form",
951
+ name: "answer",
952
+ elements: fields
953
+ });
954
+ }
955
+ return card({
956
+ title: titleOf(view),
957
+ tone: "orange",
958
+ elements
959
+ });
960
+ }
961
+ function answerText(question, answer) {
962
+ return [...(answer.optionIds ?? []).map((id) => question?.options.find((option) => option.id === id)?.label ?? id), ...answer.text === void 0 || answer.text === "" ? [] : [answer.text]].join(";");
963
+ }
964
+ /** The settled card: what was answered, and where. */
965
+ function renderSettled(view, settled) {
966
+ const lines = header(view);
967
+ if (settled.kind === "withdrawn") {
968
+ lines.push("<font color='grey'>请求已撤回</font>");
969
+ return card({
970
+ title: `${titleOf(view)} · 已撤回`,
971
+ tone: "grey",
972
+ elements: [markdown(lines.join("\n"))]
973
+ });
974
+ }
975
+ for (const answer of settled.reply.answers) {
976
+ const question = view.questions.find((one) => one.id === answer.questionId);
977
+ const text = answerText(question, answer);
978
+ lines.push(`**${plain(oneLine(question?.text ?? answer.questionId, 80))}**:${plain(text === "" ? "(未作答)" : text)}`);
979
+ }
980
+ lines.push(`<font color='grey'>${settled.here ? "已在飞书回答" : "已在别处回答"}</font>`);
981
+ return card({
982
+ title: `${titleOf(view)} · 已回答`,
983
+ tone: "green",
984
+ elements: [markdown(lines.join("\n"))]
985
+ });
986
+ }
987
+ /**
988
+ * A reply read from a submitted form or a pressed button, or the reason it
989
+ * cannot be one. Checked against the request's own questions, so a value the
990
+ * card did not offer is refused before anything is answered.
991
+ */
992
+ function replyFrom(view, input) {
993
+ if (input.question !== void 0 && input.option !== void 0) {
994
+ const question = view.questions.find((one) => one.id === input.question);
995
+ if (question === void 0 || !question.options.some((one) => one.id === input.option)) return "这个选项已不在请求里";
996
+ return {
997
+ requestId: view.requestId,
998
+ answers: [{
999
+ questionId: question.id,
1000
+ optionIds: [input.option]
1001
+ }]
1002
+ };
1003
+ }
1004
+ const form = input.form ?? {};
1005
+ const answers = [];
1006
+ for (const question of view.questions) {
1007
+ const raw = form[`o_${question.id}`];
1008
+ const picked = (Array.isArray(raw) ? raw : raw === void 0 || raw === "" ? [] : [raw]).map(String);
1009
+ if (picked.some((id) => !question.options.some((option) => option.id === id))) return "选项已不在请求里";
1010
+ if (question.multiple !== true && picked.length > 1) return `“${question.text}”只能选一项`;
1011
+ const typed = form[`t_${question.id}`];
1012
+ const text = typeof typed === "string" && typed.trim() !== "" ? typed.trim() : void 0;
1013
+ if (picked.length === 0 && text === void 0) return `请回答“${oneLine(question.text, 40)}”`;
1014
+ answers.push({
1015
+ questionId: question.id,
1016
+ ...picked.length === 0 ? {} : { optionIds: picked },
1017
+ ...text === void 0 ? {} : { text }
1018
+ });
1019
+ }
1020
+ return {
1021
+ requestId: view.requestId,
1022
+ answers
1023
+ };
1024
+ }
1025
+ //#endregion
1026
+ //#region src/cards/run.ts
1027
+ function newRun(key, startedAt) {
1028
+ return {
1029
+ key,
1030
+ startedAt,
1031
+ status: "running",
1032
+ thinking: "",
1033
+ reply: "",
1034
+ pendingReply: "",
1035
+ pendingThinking: "",
1036
+ tools: [],
1037
+ subagents: []
1038
+ };
1039
+ }
1040
+ /** The one input a tool call is best known by, on one line. */
1041
+ function summaryOf(input) {
1042
+ if (typeof input !== "object" || input === null) return "";
1043
+ const record = input;
1044
+ for (const key of [
1045
+ "command",
1046
+ "path",
1047
+ "url",
1048
+ "query",
1049
+ "pattern",
1050
+ "task",
1051
+ "title",
1052
+ "text"
1053
+ ]) if (typeof record[key] === "string") return oneLine(record[key], 80);
1054
+ const first = Object.values(record).find((value) => typeof value === "string");
1055
+ return typeof first === "string" ? oneLine(first, 80) : "";
1056
+ }
1057
+ /** A message the run's agent produced, folded in: its thinking, words and
1058
+ * calls; a tool-results message settles the calls it answers. */
1059
+ function withMessage(run, message, renderedText) {
1060
+ let next = run;
1061
+ if (message.role === "assistant") {
1062
+ let thinking = run.thinking;
1063
+ let reply = run.reply;
1064
+ let usedRenderedText = false;
1065
+ const tools = [...run.tools];
1066
+ for (const part of message.content) if (part.type === "thinking" && part.text !== "") thinking = thinking === "" ? part.text : `${thinking}\n\n${part.text}`;
1067
+ else if (part.type === "text" && part.text !== "") {
1068
+ const text = renderedText === void 0 ? part.text : usedRenderedText ? "" : renderedText;
1069
+ usedRenderedText = true;
1070
+ if (text !== "") reply = reply === "" ? text : `${reply}\n\n${text}`;
1071
+ } else if (part.type === "tool-use") tools.push({
1072
+ id: part.id,
1073
+ name: part.name,
1074
+ summary: summaryOf(part.input),
1075
+ status: "running"
1076
+ });
1077
+ next = {
1078
+ ...run,
1079
+ thinking: thinking.slice(0, 4e3),
1080
+ reply: reply.slice(0, REPLY_LIMIT),
1081
+ tools: tools.slice(-128),
1082
+ pendingReply: "",
1083
+ pendingThinking: ""
1084
+ };
1085
+ } else {
1086
+ const results = /* @__PURE__ */ new Map();
1087
+ for (const part of message.content) if (part.type === "tool-result") results.set(part.toolUseId, {
1088
+ content: part.content,
1089
+ isError: part.isError === true
1090
+ });
1091
+ if (results.size === 0) return run;
1092
+ next = {
1093
+ ...run,
1094
+ tools: run.tools.map((tool) => {
1095
+ const result = results.get(tool.id);
1096
+ return result === void 0 ? tool : {
1097
+ ...tool,
1098
+ status: result.isError ? "failed" : "done",
1099
+ result: oneLine(result.content, 160)
1100
+ };
1101
+ })
1102
+ };
1103
+ }
1104
+ return next;
1105
+ }
1106
+ const STATUS = {
1107
+ running: {
1108
+ label: "运行中",
1109
+ tone: "blue"
1110
+ },
1111
+ done: {
1112
+ label: "完成",
1113
+ tone: "green"
1114
+ },
1115
+ stopped: {
1116
+ label: "已停止",
1117
+ tone: "grey"
1118
+ },
1119
+ failed: {
1120
+ label: "失败",
1121
+ tone: "red"
1122
+ },
1123
+ interrupted: {
1124
+ label: "中断",
1125
+ tone: "grey"
1126
+ }
1127
+ };
1128
+ function seconds(run, now) {
1129
+ const end = run.endedAt ?? now;
1130
+ const total = Math.max(0, Math.round((end - run.startedAt) / 1e3));
1131
+ return total < 60 ? `${total} 秒` : `${Math.floor(total / 60)} 分 ${total % 60} 秒`;
1132
+ }
1133
+ function toolMark(status) {
1134
+ return status === "running" ? "⏳" : status === "done" ? "✅" : "❌";
1135
+ }
1136
+ /** The card for `run`, in session `sessionId`; `url` opens the session in the WebUI. */
1137
+ function renderRun(run, input) {
1138
+ const status = STATUS[run.status];
1139
+ const elements = [];
1140
+ const thinking = [run.thinking, run.pendingThinking].filter((one) => one !== "").join("\n\n");
1141
+ if (thinking !== "") elements.push(panel("💭 思考", [markdown(plain(clip(thinking, 4e3)))]));
1142
+ if (run.tools.length > 0) {
1143
+ const lines = run.tools.map((tool) => {
1144
+ const head = `${toolMark(tool.status)} **${plain(tool.name)}** ${plain(tool.summary)}`;
1145
+ return tool.result === void 0 || tool.result === "" ? head : `${head}\n<font color='grey'>${plain(tool.result)}</font>`;
1146
+ });
1147
+ elements.push(panel(`🔧 工具调用 ${run.tools.length} 次`, [markdown(lines.join("\n"))]));
1148
+ }
1149
+ if (run.subagents.length > 0) elements.push(markdown(run.subagents.map((one) => `🤖 **${plain(one.agent)}** · ${plain(one.state)}${one.summary === "" ? "" : ` · ${plain(one.summary)}`}`).join("\n")));
1150
+ const reply = [run.reply, run.pendingReply].filter((one) => one !== "").join("\n\n");
1151
+ if (reply !== "") {
1152
+ const clipped = [...reply].length > REPLY_LIMIT;
1153
+ elements.push(markdown(clip(reply, REPLY_LIMIT)));
1154
+ if (clipped) elements.push(markdown("<font color='grey'>回复较长,完整内容请在 WebUI 查看</font>"));
1155
+ }
1156
+ if (run.status === "failed" && run.failure !== void 0) elements.push(markdown(`<font color='red'>${plain(oneLine(run.failure, 400))}</font>`));
1157
+ const actions = [];
1158
+ if (run.status === "running") actions.push(button("停止", {
1159
+ k: "stop",
1160
+ s: input.sessionId
1161
+ }, "danger"));
1162
+ if (input.url !== void 0) actions.push(link("在 WebUI 查看过程", input.url));
1163
+ if (actions.length > 0) elements.push(buttons(actions));
1164
+ return card({
1165
+ title: `${status.label} · ${seconds(run, input.now)}`,
1166
+ tone: status.tone,
1167
+ summary: reply === "" ? status.label : oneLine(reply, 60),
1168
+ elements
1169
+ });
1170
+ }
1171
+ //#endregion
1172
+ //#region src/reading.ts
1173
+ /** Reads one immutable source, checking that every byte range has the same identity. */
1174
+ function readCardContent(port, ref, maxBytes = ref.byteLength) {
1175
+ const chunks = [];
1176
+ let offset = 0;
1177
+ while (offset < Math.min(ref.byteLength, maxBytes)) {
1178
+ const range = port.messageContent({
1179
+ scope: ref.scope,
1180
+ contentRefId: ref.id,
1181
+ offset,
1182
+ maxBytes: Math.max(4, Math.min(65536, maxBytes - offset))
1183
+ });
1184
+ if (range.sha256 !== ref.sha256 || range.offset !== offset || range.byteLength !== ref.byteLength || range.nextOffset <= offset) throw new Error("Card content source changed");
1185
+ chunks.push(Buffer.from(range.base64, "base64"));
1186
+ offset = range.nextOffset;
1187
+ if (range.complete) break;
1188
+ }
1189
+ return Buffer.concat(chunks).toString("utf8");
1190
+ }
1191
+ /** Walks request descriptors one page at a time without retaining a history array. */
1192
+ function* readCardItems(port, sessionId, historyGeneration, collection) {
1193
+ let cursor;
1194
+ do {
1195
+ const page = port.livePage({
1196
+ sessionId,
1197
+ historyGeneration,
1198
+ collection,
1199
+ limit: 64,
1200
+ ...cursor ? { cursor } : {}
1201
+ });
1202
+ for (const item of page.items) if ("contentRef" in item) yield JSON.parse(readCardContent(port, item.contentRef));
1203
+ cursor = page.hasMore ? page.nextCursor : void 0;
1204
+ if (page.hasMore && !cursor) throw new Error("Card collection cursor is unavailable");
1205
+ } while (cursor);
1206
+ }
1207
+ /** Hydrates the original message and its framework-rendered text for a single visible card. */
1208
+ async function readCardMessage(channel, sessionId, messageId, historyGeneration) {
1209
+ const message = await channel.readMessage(sessionId, messageId, historyGeneration);
1210
+ return {
1211
+ message,
1212
+ text: message.role === "assistant" ? await channel.readMessageText(sessionId, messageId, historyGeneration) : void 0
1213
+ };
1214
+ }
1215
+ //#endregion
1216
+ //#region src/relay.ts
1217
+ /** The channel id this plugin registers under; a message stamped with it came from here. */
1218
+ const CHANNEL_ID = "feishu";
1219
+ const TARGET_PREFIX = "feishu:";
1220
+ function statusOf(outcome) {
1221
+ if (outcome === null || outcome === void 0) return { status: "interrupted" };
1222
+ if (outcome.kind === "completed") return { status: "done" };
1223
+ if (outcome.kind === "interrupted") return { status: "stopped" };
1224
+ return {
1225
+ status: "failed",
1226
+ failure: outcome.reason
1227
+ };
1228
+ }
1229
+ function viewOfSync(request, sessionId, from) {
1230
+ return {
1231
+ requestId: request.requestId,
1232
+ sessionId,
1233
+ kind: request.kind,
1234
+ title: void 0,
1235
+ requester: request.toolName,
1236
+ ...from === void 0 ? {} : { from },
1237
+ ...request.reason === void 0 ? {} : { reason: request.reason },
1238
+ ...request.targets === void 0 ? {} : { targets: request.targets },
1239
+ ...request.warning === void 0 ? {} : { warning: request.warning },
1240
+ questions: request.questions
1241
+ };
1242
+ }
1243
+ function viewOfAsync(request, sessionId, from) {
1244
+ return {
1245
+ requestId: request.requestId,
1246
+ sessionId,
1247
+ kind: request.kind,
1248
+ title: request.title,
1249
+ requester: request.plugin,
1250
+ ...from === void 0 ? {} : { from },
1251
+ ...request.reason === void 0 ? {} : { reason: request.reason },
1252
+ ...request.targets === void 0 ? {} : { targets: request.targets },
1253
+ ...request.warning === void 0 ? {} : { warning: request.warning },
1254
+ questions: request.questions
1255
+ };
1256
+ }
1257
+ /** A person's own words in a message: its text parts, joined. */
1258
+ function wordsOf(message) {
1259
+ return message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n").trim();
1260
+ }
1261
+ function createRelay(deps) {
1262
+ const watched = /* @__PURE__ */ new Map();
1263
+ const generations = /* @__PURE__ */ new Map();
1264
+ /** Requests this plugin's own card submitted, so their record says "here". */
1265
+ const answeredHere = /* @__PURE__ */ new Set();
1266
+ const bindingOf = (bindingId) => {
1267
+ if (deps.channel() === void 0) return void 0;
1268
+ const row = deps.store.binding(bindingId);
1269
+ return row?.state === "active" && deps.store.group(row.botId, row.sessionId)?.memberError == null ? row : void 0;
1270
+ };
1271
+ const urlOf = (sessionId) => sessionUrl(deps.channel()?.webuiUrl ?? "", sessionId);
1272
+ async function post(binding, kind, ref, sessionId, json) {
1273
+ const api = deps.apiOf(binding.botId);
1274
+ const origin = watched.get(sessionId);
1275
+ if (api === void 0) return void 0;
1276
+ try {
1277
+ const cardId = await api.createCard(json);
1278
+ const current = bindingOf(binding.sessionId);
1279
+ if (current?.rootMessageId !== binding.rootMessageId || current.createdAt !== binding.createdAt || watched.get(sessionId) !== origin) return void 0;
1280
+ const sent = await api.sendCard(binding.chatId, cardId);
1281
+ if (bindingOf(binding.sessionId)?.rootMessageId !== binding.rootMessageId || watched.get(sessionId) !== origin) return void 0;
1282
+ deps.store.insertCard({
1283
+ messageId: sent.messageId,
1284
+ sessionId,
1285
+ bindingId: binding.sessionId,
1286
+ kind,
1287
+ ref,
1288
+ cardId
1289
+ });
1290
+ return {
1291
+ botId: binding.botId,
1292
+ bindingId: binding.sessionId,
1293
+ messageId: sent.messageId,
1294
+ cardId
1295
+ };
1296
+ } catch (error) {
1297
+ if (classify(error).kind === "gone") deps.onGone(binding.sessionId, "群已不可用");
1298
+ else deps.log.warn(`posting a ${kind} card failed: ${error instanceof Error ? error.message : String(error)}`);
1299
+ return;
1300
+ }
1301
+ }
1302
+ function show(entry, options = {}) {
1303
+ const run = entry.run;
1304
+ if (run === void 0 || watched.get(entry.sessionId) !== entry) return;
1305
+ const binding = bindingOf(entry.bindingId);
1306
+ if (binding === void 0) return;
1307
+ const json = () => renderRun(run.state, {
1308
+ sessionId: entry.sessionId,
1309
+ url: urlOf(entry.sessionId),
1310
+ now: deps.clock.now()
1311
+ });
1312
+ if (run.handle !== void 0) {
1313
+ deps.streamer.update(run.handle, json(), options);
1314
+ return;
1315
+ }
1316
+ if (run.creating !== void 0) {
1317
+ if (options.final === true) run.creating.then((handle) => handle && deps.streamer.update(handle, json(), options));
1318
+ return;
1319
+ }
1320
+ run.creating = post(binding, "run", run.state.key, entry.sessionId, json()).then((handle) => {
1321
+ run.handle = handle;
1322
+ run.creating = void 0;
1323
+ if (handle !== void 0) {
1324
+ const final = run.state.status !== "running";
1325
+ deps.streamer.update(handle, json(), { final });
1326
+ }
1327
+ return handle;
1328
+ });
1329
+ }
1330
+ function startRun(entry, key) {
1331
+ const run = {
1332
+ state: newRun(key, deps.clock.now()),
1333
+ handle: void 0,
1334
+ creating: void 0
1335
+ };
1336
+ entry.run = run;
1337
+ return run;
1338
+ }
1339
+ function endRun(entry, status, failure) {
1340
+ const run = entry.run;
1341
+ if (run === void 0) return;
1342
+ run.state = {
1343
+ ...run.state,
1344
+ status,
1345
+ endedAt: deps.clock.now(),
1346
+ pendingReply: "",
1347
+ pendingThinking: "",
1348
+ ...failure === void 0 ? {} : { failure }
1349
+ };
1350
+ show(entry, { final: true });
1351
+ entry.run = void 0;
1352
+ }
1353
+ async function openRequest(entry, view, sync) {
1354
+ const binding = bindingOf(entry.bindingId);
1355
+ if (binding === void 0) return;
1356
+ deps.requests.set(view.requestId, {
1357
+ view,
1358
+ bindingId: entry.bindingId,
1359
+ sync
1360
+ });
1361
+ if (deps.store.cardByRef(entry.bindingId, "request", view.requestId) !== void 0) return;
1362
+ await post(binding, "request", view.requestId, view.sessionId, renderRequest(view));
1363
+ }
1364
+ function settleRequest(entry, requestId, settled) {
1365
+ const known = deps.requests.get(requestId);
1366
+ deps.requests.delete(requestId);
1367
+ const row = deps.store.cardByRef(entry.bindingId, "request", requestId);
1368
+ const binding = bindingOf(entry.bindingId);
1369
+ if (row === void 0 || binding === void 0 || known === void 0) return;
1370
+ const here = settled.kind === "answered" && answeredHere.delete(requestId);
1371
+ deps.streamer.update({
1372
+ botId: binding.botId,
1373
+ bindingId: entry.bindingId,
1374
+ messageId: row.messageId,
1375
+ cardId: row.cardId
1376
+ }, renderSettled(known.view, settled.kind === "answered" ? {
1377
+ ...settled,
1378
+ here
1379
+ } : settled), { final: true });
1380
+ }
1381
+ function subagentLine(entry, parentSessionId, task) {
1382
+ const run = entry.run;
1383
+ if (run === void 0 || parentSessionId !== entry.sessionId) return;
1384
+ const agent = deps.channel()?.listAgents().find((one) => one.agentId === task.agent)?.name ?? task.agent;
1385
+ const state = task.state === "finished" ? task.outcome?.kind === "failed" ? "失败" : "完成" : "进行中";
1386
+ const line = {
1387
+ taskId: task.taskId,
1388
+ agent,
1389
+ state,
1390
+ summary: oneLine(task.input, 60)
1391
+ };
1392
+ const others = run.state.subagents.filter((one) => one.taskId !== task.taskId);
1393
+ run.state = {
1394
+ ...run.state,
1395
+ subagents: [...others, line]
1396
+ };
1397
+ show(entry);
1398
+ }
1399
+ function followDescendant(root, task) {
1400
+ const child = task.childSessionId;
1401
+ if (task.state === "finished") return;
1402
+ if (watched.has(child)) return;
1403
+ const agent = deps.channel()?.listAgents().find((one) => one.agentId === task.agent)?.name ?? task.agent;
1404
+ watch(root.bindingId, child, {
1405
+ root: false,
1406
+ from: agent
1407
+ });
1408
+ }
1409
+ function accept(frame) {
1410
+ const entry = watched.get(frame.sessionId);
1411
+ const channel = deps.channel();
1412
+ if (!entry || !channel || bindingOf(entry.bindingId) === void 0) return;
1413
+ let requests = [];
1414
+ let request;
1415
+ let reply;
1416
+ try {
1417
+ if (frame.kind === "session.humanAsked") requests = [...readCardItems(channel, entry.sessionId, frame.historyGeneration, "wait")];
1418
+ if (frame.kind === "session.asyncAsked") request = JSON.parse(readCardContent(channel, frame.request.contentRef));
1419
+ if ((frame.kind === "session.humanAnswered" || frame.kind === "session.asyncSettled") && frame.replyRef) reply = JSON.parse(readCardContent(channel, frame.replyRef));
1420
+ } catch (error) {
1421
+ deps.log.warn(`reading a channel request failed: ${error instanceof Error ? error.message : String(error)}`);
1422
+ }
1423
+ entry.tail = entry.tail.then(() => acceptOrdered(entry, frame, requests, request, reply)).catch((error) => {
1424
+ deps.log.warn(`reading session activity failed: ${error instanceof Error ? error.message : String(error)}`);
1425
+ });
1426
+ }
1427
+ async function acceptOrdered(entry, frame, requests, request, reply) {
1428
+ if (watched.get(frame.sessionId) !== entry) return;
1429
+ const changed = deps.delegation?.()?.project(frame);
1430
+ if (changed) {
1431
+ const root = [...watched.values()].find((one) => one.root && one.bindingId === entry.bindingId);
1432
+ if (entry.root) subagentLine(entry, changed.parentSessionId, changed.task);
1433
+ if (root) followDescendant(root, changed.task);
1434
+ if (changed.task.state === "finished") {
1435
+ const child = watched.get(changed.task.childSessionId);
1436
+ if (child && !child.root) {
1437
+ child.unwatch();
1438
+ watched.delete(child.sessionId);
1439
+ }
1440
+ }
1441
+ return;
1442
+ }
1443
+ if (frame.kind === "session.historyReplaced") {
1444
+ entry.historyGeneration = frame.snapshot.window.view.historyGeneration;
1445
+ entry.messages = (frame.snapshot.window.messages.at(-1)?.ordinal ?? -1) + 1;
1446
+ entry.run = void 0;
1447
+ entry.ignoreTurn = false;
1448
+ await reconcile(entry, frame.snapshot);
1449
+ return;
1450
+ }
1451
+ if ("historyGeneration" in frame && frame.historyGeneration !== entry.historyGeneration) return;
1452
+ if (bindingOf(entry.bindingId) === void 0) return;
1453
+ if (entry.ignoreTurn) {
1454
+ if (frame.kind === "session.messageAppended") entry.messages += 1;
1455
+ if (frame.kind === "session.turnEnded") entry.ignoreTurn = false;
1456
+ return;
1457
+ }
1458
+ switch (frame.kind) {
1459
+ case "session.turnStarted":
1460
+ if (!entry.root) return;
1461
+ if (entry.run === void 0) startRun(entry, `turn:${entry.messages}`);
1462
+ show(entry);
1463
+ return;
1464
+ case "session.delta": {
1465
+ if (!entry.root) return;
1466
+ const run = entry.run ?? startRun(entry, `turn:${entry.messages}`);
1467
+ run.state = frame.part === "text" ? {
1468
+ ...run.state,
1469
+ pendingReply: (run.state.pendingReply + frame.text).slice(0, 8e3)
1470
+ } : {
1471
+ ...run.state,
1472
+ pendingThinking: (run.state.pendingThinking + frame.text).slice(0, 4e3)
1473
+ };
1474
+ show(entry);
1475
+ return;
1476
+ }
1477
+ case "session.deltaReset":
1478
+ if (!entry.root || entry.run === void 0) return;
1479
+ entry.run.state = {
1480
+ ...entry.run.state,
1481
+ pendingReply: "",
1482
+ pendingThinking: ""
1483
+ };
1484
+ show(entry);
1485
+ return;
1486
+ case "session.messageAppended": {
1487
+ const index = entry.messages;
1488
+ entry.messages += 1;
1489
+ if (!entry.root) return;
1490
+ const channel = deps.channel();
1491
+ if (!channel) return;
1492
+ const hydrated = await readCardMessage(channel, entry.sessionId, frame.message.messageId, frame.historyGeneration);
1493
+ if (watched.get(entry.sessionId) !== entry) return;
1494
+ const { message } = hydrated;
1495
+ if (message.role === "user" && message.source === void 0 && !message.content.some((one) => one.type === "tool-result")) {
1496
+ const started = entry.run?.state;
1497
+ const said = started !== void 0 && (started.reply !== "" || started.thinking !== "" || started.tools.length > 0 || started.pendingReply !== "");
1498
+ if (entry.run !== void 0 && entry.run.state.status === "running" && said) {
1499
+ const cut = entry.run;
1500
+ cut.state = {
1501
+ ...cut.state,
1502
+ status: "done",
1503
+ endedAt: deps.clock.now()
1504
+ };
1505
+ show(entry, { final: true });
1506
+ startRun(entry, `run:${index}`);
1507
+ }
1508
+ if (message.via?.channel !== "feishu") echo(entry, message);
1509
+ return;
1510
+ }
1511
+ if (message.role === "user" && message.source !== void 0) return;
1512
+ const run = entry.run ?? startRun(entry, `turn:${index}`);
1513
+ run.state = withMessage(run.state, message, hydrated.text);
1514
+ show(entry);
1515
+ return;
1516
+ }
1517
+ case "session.turnEnded": {
1518
+ for (const [requestId, one] of [...deps.requests]) if (one.sync && one.view.sessionId === entry.sessionId) settleRequest(entry, requestId, { kind: "withdrawn" });
1519
+ if (!entry.root) return;
1520
+ const { status, failure } = statusOf(frame.outcome);
1521
+ if (entry.run === void 0) return;
1522
+ endRun(entry, status, failure);
1523
+ return;
1524
+ }
1525
+ case "session.humanAsked":
1526
+ for (const request of requests) openRequest(entry, viewOfSync(request, entry.sessionId, entry.from), true);
1527
+ return;
1528
+ case "session.humanAnswered":
1529
+ if (!reply) return;
1530
+ settleRequest(entry, frame.requestId, {
1531
+ kind: "answered",
1532
+ reply,
1533
+ here: false
1534
+ });
1535
+ return;
1536
+ case "session.asyncAsked":
1537
+ if (request) openRequest(entry, viewOfAsync(request, entry.sessionId, entry.from), false);
1538
+ return;
1539
+ case "session.asyncSettled":
1540
+ settleRequest(entry, frame.requestId, reply === void 0 ? { kind: "withdrawn" } : {
1541
+ kind: "answered",
1542
+ reply,
1543
+ here: false
1544
+ });
1545
+ return;
1546
+ default: return;
1547
+ }
1548
+ }
1549
+ async function echo(entry, message) {
1550
+ const binding = bindingOf(entry.bindingId);
1551
+ const words = wordsOf(message);
1552
+ if (binding === void 0 || words === "") return;
1553
+ const who = message.via?.sender?.name ?? (message.via === void 0 ? "WebUI" : message.via.label);
1554
+ try {
1555
+ await deps.apiOf(binding.botId)?.sendText(binding.chatId, `💬 ${who}:${oneLine(words, 2e3)}`);
1556
+ } catch (error) {
1557
+ if (classify(error).kind === "gone") deps.onGone(binding.sessionId, "群已不可用");
1558
+ }
1559
+ }
1560
+ /** Rebuilds what the snapshot says about runs and requests, and brings every
1561
+ * open card of this binding for this session to it. */
1562
+ async function reconcile(entry, snapshot) {
1563
+ const binding = bindingOf(entry.bindingId);
1564
+ const channel = deps.channel();
1565
+ if (!binding || !channel || entry.ignoreTurn) return;
1566
+ const cards = deps.store.openCards().filter((one) => one.bindingId === entry.bindingId && one.sessionId === entry.sessionId);
1567
+ const pending = /* @__PURE__ */ new Map();
1568
+ for (const request of readCardItems(channel, entry.sessionId, entry.historyGeneration, "wait")) pending.set(request.requestId, {
1569
+ view: viewOfSync(request, entry.sessionId, entry.from),
1570
+ sync: true
1571
+ });
1572
+ for (const request of readCardItems(channel, entry.sessionId, entry.historyGeneration, "async")) pending.set(request.requestId, {
1573
+ view: viewOfAsync(request, entry.sessionId, entry.from),
1574
+ sync: false
1575
+ });
1576
+ const wanted = new Set(cards.filter((one) => one.kind === "request").map((one) => one.ref));
1577
+ const answered = /* @__PURE__ */ new Map();
1578
+ for (const item of readCardItems(channel, entry.sessionId, entry.historyGeneration, "answered")) if (wanted.has(item.requestId)) answered.set(item.requestId, {
1579
+ request: JSON.parse(readCardContent(channel, item.requestRef)),
1580
+ reply: item.reply
1581
+ });
1582
+ const lastTurn = snapshot.window.turns.at(-1);
1583
+ const running = snapshot.live.phase !== "idle" && snapshot.live.phase !== "awaiting-human";
1584
+ async function restore(key) {
1585
+ let state = newRun(key, lastTurn?.startedAt ?? deps.clock.now());
1586
+ let page = lastTurn?.openingMessageId ? channel.historyPage({
1587
+ sessionId: entry.sessionId,
1588
+ historyGeneration: entry.historyGeneration,
1589
+ aroundMessageId: lastTurn.openingMessageId,
1590
+ limit: 64
1591
+ }) : snapshot.window;
1592
+ let started = !lastTurn?.openingMessageId;
1593
+ do {
1594
+ for (const header of page.messages) {
1595
+ if (header.messageId === lastTurn?.openingMessageId) started = true;
1596
+ if (!started || header.role === "user" && header.kind !== "tool-results") continue;
1597
+ const hydrated = await readCardMessage(channel, entry.sessionId, header.messageId, entry.historyGeneration);
1598
+ if (watched.get(entry.sessionId) !== entry) return state;
1599
+ state = withMessage(state, hydrated.message, hydrated.text);
1600
+ }
1601
+ if (!page.hasNewer || !page.newerCursor) break;
1602
+ page = channel.historyPage({
1603
+ sessionId: entry.sessionId,
1604
+ historyGeneration: entry.historyGeneration,
1605
+ cursor: page.newerCursor,
1606
+ limit: 64
1607
+ });
1608
+ } while (watched.get(entry.sessionId) === entry);
1609
+ return state;
1610
+ }
1611
+ const prefix = (ref, limit) => ref ? readCardContent(channel, ref, limit) : "";
1612
+ for (const row of cards) {
1613
+ if (watched.get(entry.sessionId) !== entry) return;
1614
+ const handle = {
1615
+ botId: binding.botId,
1616
+ bindingId: entry.bindingId,
1617
+ messageId: row.messageId,
1618
+ cardId: row.cardId
1619
+ };
1620
+ if (row.kind === "run" && entry.root) {
1621
+ let state = await restore(row.ref);
1622
+ if (running && lastTurn?.endedAt === void 0) {
1623
+ state = {
1624
+ ...state,
1625
+ pendingReply: prefix(snapshot.live.pending?.text, 8e3),
1626
+ pendingThinking: prefix(snapshot.live.pending?.thinking, 4e3)
1627
+ };
1628
+ entry.run = {
1629
+ state,
1630
+ handle,
1631
+ creating: void 0
1632
+ };
1633
+ show(entry);
1634
+ } else {
1635
+ const { status, failure } = statusOf(snapshot.session.lastOutcome);
1636
+ state = {
1637
+ ...state,
1638
+ status,
1639
+ endedAt: lastTurn?.endedAt ?? deps.clock.now(),
1640
+ ...failure === void 0 ? {} : { failure }
1641
+ };
1642
+ deps.streamer.update(handle, renderRun(state, {
1643
+ sessionId: entry.sessionId,
1644
+ url: urlOf(entry.sessionId),
1645
+ now: deps.clock.now()
1646
+ }), { final: true });
1647
+ }
1648
+ } else if (row.kind === "request") {
1649
+ const open = pending.get(row.ref);
1650
+ if (open) {
1651
+ deps.requests.set(row.ref, {
1652
+ view: open.view,
1653
+ bindingId: entry.bindingId,
1654
+ sync: open.sync
1655
+ });
1656
+ continue;
1657
+ }
1658
+ const settled = answered.get(row.ref);
1659
+ if (!settled) {
1660
+ deps.store.closeCard(row.messageId);
1661
+ continue;
1662
+ }
1663
+ deps.streamer.update(handle, renderSettled(viewOfSync(settled.request, entry.sessionId, entry.from), {
1664
+ kind: "answered",
1665
+ reply: settled.reply,
1666
+ here: false
1667
+ }), { final: true });
1668
+ } else if (row.kind === "model") deps.store.closeCard(row.messageId);
1669
+ }
1670
+ if (!entry.root) for (const open of pending.values()) openRequest(entry, open.view, open.sync);
1671
+ if (entry.root && running && !entry.run && (lastTurn?.startedAt ?? 0) >= binding.createdAt) {
1672
+ const run = startRun(entry, `turn:${lastTurn?.openingMessageId ?? entry.messages}`);
1673
+ run.state = {
1674
+ ...await restore(run.state.key),
1675
+ pendingReply: prefix(snapshot.live.pending?.text, 8e3),
1676
+ pendingThinking: prefix(snapshot.live.pending?.thinking, 4e3)
1677
+ };
1678
+ show(entry);
1679
+ }
1680
+ }
1681
+ async function watch(bindingId, sessionId, options) {
1682
+ const channel = deps.channel();
1683
+ if (channel === void 0 || watched.has(sessionId)) return;
1684
+ const generation = generations.get(bindingId) ?? 0;
1685
+ await channel.ensureReadingReady(sessionId, { ownerId: `${TARGET_PREFIX}${bindingId}` });
1686
+ if ((generations.get(bindingId) ?? 0) !== generation) return;
1687
+ if (watched.has(sessionId) || bindingOf(bindingId) === void 0) return;
1688
+ const entry = {
1689
+ sessionId,
1690
+ bindingId,
1691
+ root: options.root,
1692
+ ...options.from === void 0 ? {} : { from: options.from },
1693
+ unwatch: () => {},
1694
+ messages: 0,
1695
+ historyGeneration: 0,
1696
+ tail: Promise.resolve(),
1697
+ run: void 0,
1698
+ ignoreTurn: false
1699
+ };
1700
+ watched.set(sessionId, entry);
1701
+ const { snapshot, unwatch } = channel.watch(`${TARGET_PREFIX}${bindingId}`, sessionId);
1702
+ entry.unwatch = unwatch;
1703
+ entry.messages = (snapshot.window.messages.at(-1)?.ordinal ?? -1) + 1;
1704
+ entry.historyGeneration = snapshot.window.view.historyGeneration;
1705
+ const boundary = bindingOf(bindingId)?.createdAt ?? Number.POSITIVE_INFINITY;
1706
+ entry.ignoreTurn = options.root && snapshot.live.phase !== "idle" && (options.fresh === true || (snapshot.window.turns.at(-1)?.startedAt ?? 0) < boundary);
1707
+ entry.tail = reconcile(entry, snapshot);
1708
+ await entry.tail;
1709
+ if (options.root) try {
1710
+ deps.delegation?.()?.list(sessionId);
1711
+ if (watched.get(sessionId) !== entry || entry.ignoreTurn) return;
1712
+ } catch {}
1713
+ }
1714
+ return {
1715
+ accept,
1716
+ /** Starts showing a bound session and its descendants in the group. */
1717
+ attach: (binding, options = {}) => watch(binding.sessionId, binding.sessionId, {
1718
+ root: true,
1719
+ ...options
1720
+ }),
1721
+ /** Stops showing a binding's sessions; its open cards stay as they are. */
1722
+ detach(bindingId) {
1723
+ generations.set(bindingId, (generations.get(bindingId) ?? 0) + 1);
1724
+ for (const entry of [...watched.values()]) {
1725
+ if (entry.bindingId !== bindingId) continue;
1726
+ entry.unwatch();
1727
+ watched.delete(entry.sessionId);
1728
+ }
1729
+ for (const [requestId, one] of [...deps.requests]) if (one.bindingId === bindingId) deps.requests.delete(requestId);
1730
+ },
1731
+ /** Which bound session a watched session belongs to. */
1732
+ bindingOf: (sessionId) => watched.get(sessionId)?.bindingId,
1733
+ /** Marks a request as answered from a card, so its record says so. */
1734
+ answeredHere: (requestId) => answeredHere.add(requestId),
1735
+ watching: (sessionId) => watched.has(sessionId),
1736
+ stop() {
1737
+ for (const entry of watched.values()) entry.unwatch();
1738
+ watched.clear();
1739
+ }
1740
+ };
1741
+ }
1742
+ //#endregion
1743
+ //#region src/channel.ts
1744
+ function createFeishuChannel(hooks) {
1745
+ return {
1746
+ id: CHANNEL_ID,
1747
+ label: "飞书",
1748
+ capabilities: {
1749
+ deliveryMode: "stream",
1750
+ asyncDelivery: true
1751
+ },
1752
+ async start(ctx) {
1753
+ hooks.started(ctx);
1754
+ },
1755
+ async stop() {
1756
+ hooks.stopped();
1757
+ },
1758
+ async deliver(_target, delivery) {
1759
+ if (delivery.kind === "frame") hooks.frame(delivery.frame);
1760
+ }
1761
+ };
1762
+ }
1763
+ //#endregion
1764
+ //#region src/commands.ts
1765
+ /** Session-scoped commands available to authorized members of a bound group. */
1766
+ const HELP = "可用命令:/stop 停止当前回合;/compact 压缩上下文;/model 切换模型与深度思考;/help 查看帮助。其他文字会作为消息发给智能体。";
1767
+ const COMPACT = {
1768
+ changed: "已压缩上下文。",
1769
+ unchanged: "上下文无需压缩。",
1770
+ failed: "压缩失败",
1771
+ cancelled: "压缩已取消。"
1772
+ };
1773
+ function createCommands(deps) {
1774
+ const channel = () => {
1775
+ const ctx = deps.channel();
1776
+ if (ctx === void 0) throw new Error("飞书通道尚未启动");
1777
+ return ctx;
1778
+ };
1779
+ const refusal = (error) => error instanceof Error ? error.message : String(error);
1780
+ async function model(binding) {
1781
+ const api = deps.bots.api(binding.botId);
1782
+ if (api === void 0) return "机器人未连接。";
1783
+ const ref = randomUUID();
1784
+ const service = deps.models();
1785
+ if (!service) return "模型配置功能不可用。";
1786
+ const options = service.options(binding.sessionId);
1787
+ const cardId = await api.createCard(renderModel({
1788
+ sessionId: binding.sessionId,
1789
+ ref,
1790
+ options
1791
+ }));
1792
+ const current = () => {
1793
+ if (deps.channel() === void 0) return false;
1794
+ const row = deps.store.binding(binding.sessionId);
1795
+ return row?.rootMessageId === binding.rootMessageId && row.createdAt === binding.createdAt && row.state === "active";
1796
+ };
1797
+ if (!current()) return null;
1798
+ const sent = await api.sendCard(binding.chatId, cardId);
1799
+ if (!current()) return null;
1800
+ deps.store.insertCard({
1801
+ messageId: sent.messageId,
1802
+ sessionId: binding.sessionId,
1803
+ bindingId: binding.sessionId,
1804
+ kind: "model",
1805
+ ref,
1806
+ cardId
1807
+ });
1808
+ return null;
1809
+ }
1810
+ return {
1811
+ /** Whether `text` is a command at all: a leading `/` on the first line. */
1812
+ isCommand: (text) => /^\/[a-z]/i.test(text.trimStart()),
1813
+ async run(binding, text) {
1814
+ const name = text.trimStart().slice(1).split(/\s+/, 1)[0]?.toLowerCase() ?? "";
1815
+ try {
1816
+ switch (name) {
1817
+ case "stop": {
1818
+ await channel().ensureReadingReady(binding.sessionId);
1819
+ const session = channel().getReadingSessionSummary(binding.sessionId);
1820
+ if (session === void 0 || session.phase === "idle") return "当前没有正在运行的回合。";
1821
+ await channel().cancel(binding.sessionId);
1822
+ return "已停止当前回合。";
1823
+ }
1824
+ case "compact": {
1825
+ const service = deps.context();
1826
+ if (!service) return "上下文压缩功能不可用。";
1827
+ const result = await service.compact(binding.sessionId);
1828
+ const line = COMPACT[result.status] ?? result.status;
1829
+ return result.status === "failed" && result.reason !== void 0 ? `${line}:${result.reason}` : line;
1830
+ }
1831
+ case "model": return await model(binding);
1832
+ case "help": return HELP;
1833
+ default: return `不认识的命令 /${name}。${HELP}`;
1834
+ }
1835
+ } catch (error) {
1836
+ return `操作被拒绝:${refusal(error)}`;
1837
+ }
1838
+ },
1839
+ /**
1840
+ * Applies a submitted `/model` card: the model first when it changed,
1841
+ * then the thinking and effort settings under the model it is now on.
1842
+ * Answers the label switched to; throws the refusal to show.
1843
+ */
1844
+ async applyModel(binding, ref, form) {
1845
+ const row = deps.store.cardByRef(binding.sessionId, "model", ref);
1846
+ if (row === void 0 || row.state !== "open") throw new Error("这张卡片已失效,请重新发送 /model");
1847
+ const ctx = channel();
1848
+ const service = deps.models();
1849
+ if (!service) throw new Error("模型配置功能不可用");
1850
+ const options = service.options(binding.sessionId);
1851
+ const [providerId, modelId] = (typeof form.model === "string" ? form.model : "").split("\0");
1852
+ const endpoint = options.endpoints.find((one) => one.providerId === providerId);
1853
+ const choice = endpoint?.models.find((one) => one.model === modelId);
1854
+ if (endpoint === void 0 || choice === void 0) throw new Error("请选择一个模型");
1855
+ const target = {
1856
+ providerId: endpoint.providerId,
1857
+ model: choice.model
1858
+ };
1859
+ const current = options.current.model;
1860
+ if (!(current !== null && current.providerId === target.providerId && current.model === target.model)) await ctx.setSessionModel(binding.sessionId, target);
1861
+ else {
1862
+ const params = { ...options.current.params };
1863
+ if (choice.thinking === "switchable" && (form.thinking === "on" || form.thinking === "off")) params.thinking = form.thinking === "on";
1864
+ if ((choice.thinking === "forced" || params.thinking !== false) && typeof form.effort === "string" && choice.efforts.some((one) => one.value === form.effort)) params.effort = form.effort;
1865
+ ctx.setSessionModelParams(binding.sessionId, target, params);
1866
+ }
1867
+ const label = `${endpoint.label} · ${choice.label}`;
1868
+ deps.streamer.update({
1869
+ botId: binding.botId,
1870
+ bindingId: binding.sessionId,
1871
+ messageId: row.messageId,
1872
+ cardId: row.cardId
1873
+ }, renderModelApplied(label), { final: true });
1874
+ return label;
1875
+ }
1876
+ };
1877
+ }
1878
+ //#endregion
1879
+ //#region src/inbound.ts
1880
+ /** The words of a message's content, or `undefined` for a kind that has none. */
1881
+ function textOf(event) {
1882
+ let content;
1883
+ try {
1884
+ content = JSON.parse(event.content);
1885
+ } catch {
1886
+ return;
1887
+ }
1888
+ if (typeof content !== "object" || content === null) return void 0;
1889
+ let text;
1890
+ if (event.messageType === "text") {
1891
+ const value = content.text;
1892
+ text = typeof value === "string" ? value : void 0;
1893
+ } else if (event.messageType === "post") {
1894
+ const root = content;
1895
+ const post = Array.isArray(root.content) ? root : Object.values(root).find((one) => typeof one === "object" && one !== null && Array.isArray(one.content));
1896
+ if (post !== void 0 && Array.isArray(post.content)) {
1897
+ const lines = post.content.map((line) => Array.isArray(line) ? line.map((node) => {
1898
+ const one = node;
1899
+ if (one.tag === "text" || one.tag === "md") return typeof one.text === "string" ? one.text : "";
1900
+ if (one.tag === "a") return typeof one.text === "string" ? one.text : typeof one.href === "string" ? one.href : "";
1901
+ if (one.tag === "code_block") return typeof one.text === "string" ? one.text : "";
1902
+ return "";
1903
+ }).join("") : "");
1904
+ text = [...typeof post.title === "string" && post.title !== "" ? [post.title] : [], ...lines].join("\n");
1905
+ }
1906
+ }
1907
+ if (text === void 0) return void 0;
1908
+ for (const mention of event.mentions ?? []) text = text.split(mention.key).join("");
1909
+ return text.replace(/@_user_\d+/g, "").trim();
1910
+ }
1911
+ function createInbound(deps) {
1912
+ /** Admission requests in flight: where each was raised and for whom. */
1913
+ const admissions = /* @__PURE__ */ new Map();
1914
+ const channel = () => deps.channel();
1915
+ const reply = async (binding, text) => {
1916
+ if (channel() === void 0) return;
1917
+ const current = deps.store.binding(binding.sessionId);
1918
+ if (current?.rootMessageId !== binding.rootMessageId || current.createdAt !== binding.createdAt) return;
1919
+ await deps.bots.api(binding.botId)?.sendText(binding.chatId, text).catch(() => {});
1920
+ };
1921
+ function bindingFor(botId, event) {
1922
+ return deps.store.bindingsOfChat(event.chatId).find((one) => one.botId === botId);
1923
+ }
1924
+ function senderOf(binding, openId) {
1925
+ const bot = deps.store.bot(binding.botId);
1926
+ const owner = bot?.ownerOpenId === openId;
1927
+ return {
1928
+ id: openId,
1929
+ name: oneLine(deps.members.member(binding.botId, binding.sessionId, openId)?.name || (owner ? bot?.ownerName ?? "所有者" : "成员"), 64) || "成员",
1930
+ role: owner ? "owner" : "member"
1931
+ };
1932
+ }
1933
+ async function speak(binding, openId, text) {
1934
+ const ctx = channel();
1935
+ if (ctx === void 0) return;
1936
+ try {
1937
+ await ctx.load(binding.sessionId);
1938
+ const current = deps.store.binding(binding.sessionId);
1939
+ if (current?.rootMessageId !== binding.rootMessageId || current.state !== "active" || !deps.bindings.ready(binding.botId) || deps.members.policyOf(binding.botId, binding.sessionId, openId) === "reject") return;
1940
+ ctx.send(`feishu:${binding.sessionId}`, binding.sessionId, { text }, senderOf(binding, openId));
1941
+ } catch (error) {
1942
+ await reply(binding, `消息未能发送:${error instanceof Error ? error.message : String(error)}`);
1943
+ }
1944
+ }
1945
+ async function admit(binding, openId, text) {
1946
+ const sender = senderOf(binding, openId);
1947
+ const controller = new AbortController();
1948
+ admissions.set(controller, {
1949
+ bindingId: binding.sessionId,
1950
+ botId: binding.botId,
1951
+ sessionId: binding.sessionId,
1952
+ openId
1953
+ });
1954
+ const request = {
1955
+ title: `${sender.name} 想发送一条消息`,
1956
+ kind: "approval",
1957
+ reason: "这位群成员的权限是 Ask:放行后,这条消息以他的名义进入会话。",
1958
+ questions: [{
1959
+ id: "admit",
1960
+ text: `${sender.name}:${oneLine(text, 1e3)}`,
1961
+ options: [{
1962
+ id: "allow",
1963
+ label: "放行"
1964
+ }, {
1965
+ id: "deny",
1966
+ label: "拒绝"
1967
+ }],
1968
+ freeText: false
1969
+ }]
1970
+ };
1971
+ await reply(binding, `已收到,等待有权限的成员放行。`);
1972
+ let answer;
1973
+ try {
1974
+ answer = await deps.sessions.ask(binding.sessionId, request, { signal: controller.signal });
1975
+ } catch (error) {
1976
+ const reason = error instanceof Error ? error.message : String(error);
1977
+ if (reason === "gateway stopped" || reason === "plugin unloaded") await reply(binding, `${sender.name} 的消息在放行前失效了,请重新发送。`);
1978
+ return;
1979
+ } finally {
1980
+ admissions.delete(controller);
1981
+ }
1982
+ if (!(answer.answers[0]?.optionIds?.[0] === "allow")) {
1983
+ await reply(binding, `${sender.name} 的消息未被放行。`);
1984
+ return;
1985
+ }
1986
+ const now = deps.store.binding(binding.sessionId);
1987
+ const policy = deps.members.policyOf(binding.botId, binding.sessionId, openId);
1988
+ if (now?.rootMessageId !== binding.rootMessageId || now.state !== "active") return;
1989
+ if (policy === "reject" || deps.members.member(binding.botId, binding.sessionId, openId) === void 0) {
1990
+ await reply(now, `${sender.name} 已不在群里或已被设为 Reject,消息未发送。`);
1991
+ return;
1992
+ }
1993
+ await speak(now, openId, text);
1994
+ }
1995
+ async function message(botId, event) {
1996
+ if (event.senderType === "app" || !deps.store.rememberEvent(`message:${botId}:${event.messageId}`)) return;
1997
+ if (!deps.store.rememberEvent(`message-event:${botId}:${event.eventId}`)) return;
1998
+ if (event.chatType === "p2p") {
1999
+ const text = textOf(event) ?? "";
2000
+ if (deps.pairing.take(botId, text)) {
2001
+ const bot = deps.store.bot(botId);
2002
+ deps.store.setOwner(botId, event.senderOpenId, null);
2003
+ deps.ownerChanged(botId);
2004
+ await deps.members.pullOwner(botId, event.senderOpenId, "");
2005
+ await deps.bots.api(botId)?.sendDirect(event.senderOpenId, `配对成功,你已是机器人“${bot?.name ?? ""}”的所有者。`).catch(() => {});
2006
+ return;
2007
+ }
2008
+ await deps.bots.api(botId)?.sendDirect(event.senderOpenId, "单聊只用于配对所有者;请在会话绑定的群里发消息。").catch(() => {});
2009
+ return;
2010
+ }
2011
+ const binding = bindingFor(botId, event);
2012
+ if (binding === void 0 || !deps.bindings.ready(botId)) return;
2013
+ if (event.createdAt !== void 0 && event.createdAt < binding.updatedAt) return;
2014
+ const policy = deps.members.policyOf(binding.botId, binding.sessionId, event.senderOpenId);
2015
+ if (policy === "reject") return;
2016
+ if (binding.state === "broken") return;
2017
+ if (binding.state === "paused") {
2018
+ await reply(binding, "这个会话已归档,本群暂停同步;取消归档后恢复。");
2019
+ return;
2020
+ }
2021
+ const text = textOf(event);
2022
+ if (text === void 0) {
2023
+ await reply(binding, "暂不支持此类消息,请发送文字。");
2024
+ return;
2025
+ }
2026
+ if (text === "") return;
2027
+ if (deps.commands.isCommand(text)) {
2028
+ if (policy !== "accept") {
2029
+ await reply(binding, "只有 Accept 成员能使用命令。");
2030
+ return;
2031
+ }
2032
+ const answer = await deps.commands.run(binding, text);
2033
+ if (answer !== null) await reply(binding, answer);
2034
+ return;
2035
+ }
2036
+ if (policy === "ask") {
2037
+ admit(binding, event.senderOpenId, text);
2038
+ return;
2039
+ }
2040
+ await speak(binding, event.senderOpenId, text);
2041
+ }
2042
+ async function cardAction(botId, event) {
2043
+ const toast = (type, content) => ({ toast: {
2044
+ type,
2045
+ content
2046
+ } });
2047
+ const card = deps.store.card(event.messageId);
2048
+ const binding = card === void 0 ? void 0 : deps.store.binding(card.bindingId);
2049
+ if (card === void 0 || binding === void 0 || binding.botId !== botId || binding.chatId !== event.chatId) return toast("warning", "这张卡片已失效");
2050
+ if (deps.members.policyOf(binding.botId, binding.sessionId, event.operatorOpenId) !== "accept") return toast("warning", "你没有操作权限");
2051
+ if (binding.state !== "active" || !deps.bindings.ready(botId)) return toast("warning", "这个会话当前不同步");
2052
+ const ctx = channel();
2053
+ if (ctx === void 0) return toast("error", "暂时无法提交");
2054
+ const value = event.value;
2055
+ try {
2056
+ switch (value.k) {
2057
+ case "answer": {
2058
+ const requestId = typeof value.r === "string" ? value.r : "";
2059
+ const known = deps.requests.get(requestId);
2060
+ if (known === void 0 || known.bindingId !== binding.sessionId || known.view.sessionId !== value.s) return toast("info", "这个请求已在别处回答或已撤回");
2061
+ const parsed = replyFrom(known.view, {
2062
+ ...typeof value.q === "string" ? { question: value.q } : {},
2063
+ ...typeof value.o === "string" ? { option: value.o } : {},
2064
+ ...event.formValue === void 0 ? {} : { form: event.formValue }
2065
+ });
2066
+ if (typeof parsed === "string") return toast("warning", parsed);
2067
+ deps.relay.answeredHere(requestId);
2068
+ ctx.answer(known.view.sessionId, parsed);
2069
+ return toast("success", "已提交");
2070
+ }
2071
+ case "stop":
2072
+ if (value.s !== binding.sessionId) return toast("warning", "这张卡片已失效");
2073
+ await ctx.cancel(binding.sessionId);
2074
+ return toast("success", "已停止");
2075
+ case "model":
2076
+ if (value.s !== binding.sessionId || typeof value.m !== "string") return toast("warning", "这张卡片已失效");
2077
+ return toast("success", `已切换到 ${await deps.commands.applyModel(binding, value.m, event.formValue ?? {})}`);
2078
+ default: return toast("warning", "这张卡片已失效");
2079
+ }
2080
+ } catch (error) {
2081
+ const reason = error instanceof Error ? error.message : String(error);
2082
+ return toast("warning", /answered|already|not waiting|no such request/i.test(reason) ? "已在别处回答" : reason);
2083
+ }
2084
+ }
2085
+ return {
2086
+ eventsFor(botId) {
2087
+ return {
2088
+ message: (event) => message(botId, event),
2089
+ cardAction: (event) => cardAction(botId, event),
2090
+ membersAdded: (chatId, users) => deps.store.groupByChat(chatId)?.botId === botId ? deps.members.added(chatId, users) : Promise.resolve(),
2091
+ membersRemoved: (chatId, openIds) => deps.store.groupByChat(chatId)?.botId === botId ? deps.members.removed(chatId, openIds) : Promise.resolve(),
2092
+ botAdded: (chatId, eventId, eventAt) => deps.bindings.botAdded(botId, chatId, eventId, eventAt),
2093
+ chatGone: (chatId, eventAt) => deps.bindings.chatGone(chatId, botId, eventAt)
2094
+ };
2095
+ },
2096
+ /** Withdraws every admission request waiting in one binding. */
2097
+ withdrawAdmissions(bindingId) {
2098
+ for (const [controller, one] of [...admissions]) if (one.bindingId === bindingId) controller.abort();
2099
+ },
2100
+ /** Withdraws what one person waits to have admitted in a group. */
2101
+ withdrawFor(botId, sessionId, openId) {
2102
+ for (const [controller, one] of [...admissions]) if (one.botId === botId && one.sessionId === sessionId && one.openId === openId) controller.abort();
2103
+ }
2104
+ };
2105
+ }
2106
+ //#endregion
2107
+ //#region src/lark/http.ts
2108
+ /**
2109
+ * The SDK's HTTP instance over the gateway's `network.fetch`, so every call
2110
+ * to the open platform takes the route the gateway's proxy settings decide.
2111
+ *
2112
+ * It keeps the shape the SDK's axios instance has: a call resolves with the
2113
+ * response body (or `{ data, headers }` when `$return_headers` is set), and a
2114
+ * response that is not 2xx rejects with an error carrying
2115
+ * `response.{ status, data }`, which is where the SDK and `LarkError` read
2116
+ * the platform's code.
2117
+ */
2118
+ /** A failed response in the shape the SDK inspects. */
2119
+ var HttpFailure = class extends Error {
2120
+ name = "HttpFailure";
2121
+ response;
2122
+ constructor(message, response) {
2123
+ super(message);
2124
+ this.response = response;
2125
+ }
2126
+ };
2127
+ function query(params) {
2128
+ if (params === void 0) return "";
2129
+ const search = new URLSearchParams();
2130
+ for (const [key, value] of Object.entries(params)) {
2131
+ if (value === void 0 || value === null) continue;
2132
+ if (Array.isArray(value)) for (const one of value) search.append(key, String(one));
2133
+ else search.append(key, String(value));
2134
+ }
2135
+ const text = search.toString();
2136
+ return text === "" ? "" : `?${text}`;
2137
+ }
2138
+ /** Binds SDK HTTP requests to timeout and activation cancellation. */
2139
+ function createFetchHttpInstance(fetch, lifetime) {
2140
+ async function request(opts) {
2141
+ const method = (opts.method ?? "get").toUpperCase();
2142
+ const headers = {};
2143
+ for (const [key, value] of Object.entries(opts.headers ?? {})) if (value !== void 0 && value !== null) headers[key] = String(value);
2144
+ let body;
2145
+ if (opts.data !== void 0 && method !== "GET" && method !== "HEAD") {
2146
+ body = typeof opts.data === "string" ? opts.data : JSON.stringify(opts.data);
2147
+ headers["Content-Type"] ??= "application/json; charset=utf-8";
2148
+ }
2149
+ lifetime?.throwIfAborted();
2150
+ const signals = [lifetime, opts.timeout === void 0 ? void 0 : AbortSignal.timeout(opts.timeout)].filter((one) => one !== void 0);
2151
+ const signal = signals.length ? AbortSignal.any(signals) : void 0;
2152
+ const response = await fetch(`${opts.url ?? ""}${query(opts.params)}`, {
2153
+ method,
2154
+ headers,
2155
+ ...body === void 0 ? {} : { body },
2156
+ ...signal === void 0 ? {} : { signal }
2157
+ });
2158
+ lifetime?.throwIfAborted();
2159
+ const text = await response.text();
2160
+ lifetime?.throwIfAborted();
2161
+ let data = text;
2162
+ try {
2163
+ data = text === "" ? {} : JSON.parse(text);
2164
+ } catch {}
2165
+ if (!response.ok) {
2166
+ const code = typeof data === "object" && data !== null ? Number(data.code ?? 0) : 0;
2167
+ const msg = typeof data === "object" && data !== null && typeof data.msg === "string" ? String(data.msg) : `HTTP ${response.status}`;
2168
+ const failure = new HttpFailure(msg, {
2169
+ status: response.status,
2170
+ data
2171
+ });
2172
+ Object.assign(failure, { lark: new LarkError(code, msg, response.status) });
2173
+ throw failure;
2174
+ }
2175
+ if (opts.$return_headers === true) return {
2176
+ data,
2177
+ headers: Object.fromEntries(response.headers.entries())
2178
+ };
2179
+ return data;
2180
+ }
2181
+ const withBody = (method) => (url, data, opts) => request({
2182
+ ...opts,
2183
+ url,
2184
+ method,
2185
+ data
2186
+ });
2187
+ const without = (method) => (url, opts) => request({
2188
+ ...opts,
2189
+ url,
2190
+ method
2191
+ });
2192
+ return {
2193
+ request,
2194
+ get: without("get"),
2195
+ delete: without("delete"),
2196
+ head: without("head"),
2197
+ options: without("options"),
2198
+ post: withBody("post"),
2199
+ put: withBody("put"),
2200
+ patch: withBody("patch")
2201
+ };
2202
+ }
2203
+ /** The `LarkError` inside whatever a call rejected with. */
2204
+ function larkErrorOf(error) {
2205
+ if (error instanceof LarkError) return error;
2206
+ if (typeof error === "object" && error !== null && "lark" in error) {
2207
+ const lark = error.lark;
2208
+ if (lark instanceof LarkError) return lark;
2209
+ }
2210
+ }
2211
+ //#endregion
2212
+ //#region src/lark/client.ts
2213
+ /** The proxy the gateway's environment names for HTTPS, if any. */
2214
+ async function proxyAgent(network) {
2215
+ const { env } = await network.environment();
2216
+ const url = env.https_proxy ?? env.HTTPS_PROXY ?? env.all_proxy ?? env.ALL_PROXY;
2217
+ return url === void 0 || url === "" ? void 0 : new HttpsProxyAgent(url);
2218
+ }
2219
+ const str = (value) => typeof value === "string" && value !== "" ? value : void 0;
2220
+ /** Event headers carry milliseconds; normalize second and microsecond variants as well. */
2221
+ function eventTime(data) {
2222
+ const value = Number(data.create_time ?? data.ts);
2223
+ if (!Number.isFinite(value) || value <= 0) return Date.now();
2224
+ return value > 0x5af3107a4000 ? Math.floor(value / 1e3) : value < 1e11 ? value * 1e3 : value;
2225
+ }
2226
+ function createLarkClient(options) {
2227
+ const requests = new AbortController();
2228
+ const lifetime = options.signal ? AbortSignal.any([requests.signal, options.signal]) : requests.signal;
2229
+ const httpInstance = createFetchHttpInstance(options.network.fetch, lifetime);
2230
+ const logger = {
2231
+ error: (...args) => options.log.error(`feishu sdk: ${args.map(String).join(" ")}`),
2232
+ warn: (...args) => options.log.warn(`feishu sdk: ${args.map(String).join(" ")}`),
2233
+ info: () => {},
2234
+ debug: () => {},
2235
+ trace: () => {}
2236
+ };
2237
+ const client = new Lark.Client({
2238
+ appId: options.appId,
2239
+ appSecret: options.appSecret,
2240
+ domain: Lark.Domain.Feishu,
2241
+ loggerLevel: Lark.LoggerLevel.warn,
2242
+ logger,
2243
+ httpInstance
2244
+ });
2245
+ let socket;
2246
+ let closed = false;
2247
+ async function call(method, url, data, params) {
2248
+ let body;
2249
+ try {
2250
+ body = await client.request({
2251
+ method,
2252
+ url,
2253
+ data,
2254
+ params
2255
+ });
2256
+ } catch (error) {
2257
+ throw larkErrorOf(error) ?? error;
2258
+ }
2259
+ lifetime.throwIfAborted();
2260
+ if (body.code !== void 0 && body.code !== 0) throw new LarkError(body.code, body.msg ?? "request failed");
2261
+ return body.data ?? {};
2262
+ }
2263
+ const sent = (data) => {
2264
+ const messageId = str(data.message_id);
2265
+ if (messageId === void 0) throw new LarkError(0, "the platform answered without a message id");
2266
+ const threadId = str(data.thread_id);
2267
+ return threadId === void 0 ? { messageId } : {
2268
+ messageId,
2269
+ threadId
2270
+ };
2271
+ };
2272
+ const cardContent = (cardId) => JSON.stringify({
2273
+ type: "card",
2274
+ data: { card_id: cardId }
2275
+ });
2276
+ return {
2277
+ connect(events, onState) {
2278
+ closed = false;
2279
+ onState("connecting");
2280
+ const dispatcher = new Lark.EventDispatcher({}).register({
2281
+ "im.message.receive_v1": async (data) => {
2282
+ const message = data.message ?? {};
2283
+ const sender = data.sender?.sender_id ?? {};
2284
+ const messageId = str(message.message_id);
2285
+ const chatId = str(message.chat_id);
2286
+ const senderOpenId = str(sender.open_id);
2287
+ if (messageId === void 0 || chatId === void 0 || senderOpenId === void 0) return;
2288
+ const mentions = Array.isArray(message.mentions) ? message.mentions.flatMap((one) => str(one.key) === void 0 ? [] : [{
2289
+ key: String(one.key),
2290
+ name: str(one.name) ?? ""
2291
+ }]) : [];
2292
+ const event = {
2293
+ senderType: str(data.sender?.sender_type) ?? "user",
2294
+ createdAt: Number(message.create_time) || Date.now(),
2295
+ eventId: str(data.event_id) ?? messageId,
2296
+ chatId,
2297
+ chatType: message.chat_type === "p2p" ? "p2p" : "group",
2298
+ senderOpenId,
2299
+ messageId,
2300
+ messageType: str(message.message_type) ?? "text",
2301
+ content: str(message.content) ?? "{}",
2302
+ mentions,
2303
+ ...str(message.root_id) === void 0 ? {} : { rootId: String(message.root_id) },
2304
+ ...str(message.thread_id) === void 0 ? {} : { threadId: String(message.thread_id) }
2305
+ };
2306
+ await events.message(event);
2307
+ },
2308
+ "card.action.trigger": async (data) => {
2309
+ const context = data.context ?? {};
2310
+ const operator = data.operator ?? {};
2311
+ const action = data.action ?? {};
2312
+ const messageId = str(context.open_message_id) ?? str(data.open_message_id);
2313
+ const chatId = str(context.open_chat_id) ?? str(data.open_chat_id);
2314
+ const operatorOpenId = str(operator.open_id);
2315
+ if (messageId === void 0 || chatId === void 0 || operatorOpenId === void 0) return;
2316
+ const value = typeof action.value === "object" && action.value !== null ? action.value : {};
2317
+ const formValue = typeof action.form_value === "object" && action.form_value !== null ? action.form_value : void 0;
2318
+ return events.cardAction({
2319
+ messageId,
2320
+ chatId,
2321
+ operatorOpenId,
2322
+ value,
2323
+ ...formValue === void 0 ? {} : { formValue },
2324
+ ...str(action.option) === void 0 ? {} : { option: String(action.option) }
2325
+ });
2326
+ },
2327
+ "im.chat.member.user.added_v1": async (data) => {
2328
+ const chatId = str(data.chat_id);
2329
+ if (chatId === void 0) return;
2330
+ const users = Array.isArray(data.users) ? data.users : [];
2331
+ await events.membersAdded(chatId, users.flatMap((one) => {
2332
+ const openId = str(one.user_id?.open_id);
2333
+ return openId === void 0 ? [] : [{
2334
+ openId,
2335
+ name: str(one.name) ?? ""
2336
+ }];
2337
+ }));
2338
+ },
2339
+ "im.chat.member.user.deleted_v1": async (data) => removed(events, data),
2340
+ "im.chat.member.user.withdrawn_v1": async (data) => removed(events, data),
2341
+ "im.chat.disbanded_v1": async (data) => {
2342
+ const chatId = str(data.chat_id);
2343
+ if (chatId !== void 0) await events.chatGone(chatId, eventTime(data));
2344
+ },
2345
+ "im.chat.member.bot.added_v1": async (data) => {
2346
+ const chatId = str(data.chat_id);
2347
+ const eventId = str(data.event_id) ?? str(data.uuid);
2348
+ if (chatId !== void 0 && eventId !== void 0) await events.botAdded(chatId, eventId, eventTime(data));
2349
+ },
2350
+ "im.chat.member.bot.deleted_v1": async (data) => {
2351
+ const chatId = str(data.chat_id);
2352
+ if (chatId !== void 0) await events.chatGone(chatId, eventTime(data));
2353
+ }
2354
+ });
2355
+ (async () => {
2356
+ let agent;
2357
+ try {
2358
+ agent = await proxyAgent(options.network);
2359
+ } catch (error) {
2360
+ onState("failed", error instanceof Error ? error.message : String(error));
2361
+ return;
2362
+ }
2363
+ if (closed) return;
2364
+ socket = new Lark.WSClient({
2365
+ appId: options.appId,
2366
+ appSecret: options.appSecret,
2367
+ domain: Lark.Domain.Feishu,
2368
+ loggerLevel: Lark.LoggerLevel.warn,
2369
+ logger,
2370
+ httpInstance,
2371
+ autoReconnect: true,
2372
+ ...agent === void 0 ? {} : { agent },
2373
+ onReady: () => onState("online"),
2374
+ onReconnecting: () => onState("reconnecting"),
2375
+ onReconnected: () => onState("online"),
2376
+ onError: (error) => onState("failed", error.message)
2377
+ });
2378
+ socket.start({ eventDispatcher: dispatcher }).catch((error) => {
2379
+ onState("failed", error instanceof Error ? error.message : String(error));
2380
+ });
2381
+ })();
2382
+ },
2383
+ close() {
2384
+ closed = true;
2385
+ requests.abort(/* @__PURE__ */ new Error("bot connection closed"));
2386
+ socket?.close({ force: true });
2387
+ socket = void 0;
2388
+ },
2389
+ async check() {
2390
+ await call("get", "open-apis/bot/v3/info");
2391
+ },
2392
+ async createChat(name, openIds, creationKey) {
2393
+ const data = await call("post", "open-apis/im/v1/chats", {
2394
+ name,
2395
+ user_id_list: [...openIds],
2396
+ group_message_type: "chat",
2397
+ chat_mode: "group"
2398
+ }, {
2399
+ user_id_type: "open_id",
2400
+ set_bot_manager: true,
2401
+ ...creationKey === void 0 ? {} : { uuid: creationKey }
2402
+ });
2403
+ const chatId = str(data.chat_id);
2404
+ if (chatId === void 0) throw new LarkError(0, "the platform answered without a chat id");
2405
+ return chatId;
2406
+ },
2407
+ async getChat(chatId) {
2408
+ const data = await call("get", `open-apis/im/v1/chats/${encodeURIComponent(chatId)}`);
2409
+ return {
2410
+ name: str(data.name) ?? chatId,
2411
+ ordinary: data.chat_mode === "group" && data.group_message_type === "chat"
2412
+ };
2413
+ },
2414
+ async sendText(chatId, text) {
2415
+ return sent(await call("post", "open-apis/im/v1/messages", {
2416
+ receive_id: chatId,
2417
+ msg_type: "text",
2418
+ content: JSON.stringify({ text })
2419
+ }, { receive_id_type: "chat_id" }));
2420
+ },
2421
+ async addMembers(chatId, openIds) {
2422
+ if (openIds.length === 0) return;
2423
+ await call("post", `open-apis/im/v1/chats/${encodeURIComponent(chatId)}/members`, { id_list: [...openIds] }, { member_id_type: "open_id" });
2424
+ },
2425
+ async removeMembers(chatId, openIds) {
2426
+ if (openIds.length === 0) return;
2427
+ await call("delete", `open-apis/im/v1/chats/${encodeURIComponent(chatId)}/members`, { id_list: [...openIds] }, { member_id_type: "open_id" });
2428
+ },
2429
+ async listMembers(chatId) {
2430
+ const found = [];
2431
+ let pageToken;
2432
+ for (let page = 0; page < 50; page += 1) {
2433
+ const data = await call("get", `open-apis/im/v1/chats/${encodeURIComponent(chatId)}/members`, void 0, {
2434
+ member_id_type: "open_id",
2435
+ page_size: 100,
2436
+ ...pageToken === void 0 ? {} : { page_token: pageToken }
2437
+ });
2438
+ const items = Array.isArray(data.items) ? data.items : [];
2439
+ for (const item of items) {
2440
+ const openId = str(item.member_id);
2441
+ if (openId !== void 0) found.push({
2442
+ openId,
2443
+ name: str(item.name) ?? ""
2444
+ });
2445
+ }
2446
+ pageToken = str(data.page_token);
2447
+ if (data.has_more !== true) return found;
2448
+ if (pageToken === void 0) throw new LarkError(0, "incomplete group member pagination");
2449
+ }
2450
+ throw new LarkError(0, "group member pagination exceeded 50 pages");
2451
+ },
2452
+ async userName(openId) {
2453
+ const user = (await call("get", `open-apis/contact/v3/users/${encodeURIComponent(openId)}`, void 0, { user_id_type: "open_id" })).user ?? {};
2454
+ return str(user.name) ?? str(user.en_name);
2455
+ },
2456
+ async createCard(card) {
2457
+ const data = await call("post", "open-apis/cardkit/v1/cards", {
2458
+ type: "card_json",
2459
+ data: JSON.stringify(card)
2460
+ });
2461
+ const cardId = str(data.card_id);
2462
+ if (cardId === void 0) throw new LarkError(0, "the platform answered without a card id");
2463
+ return cardId;
2464
+ },
2465
+ async updateCard(cardId, card, sequence) {
2466
+ await call("put", `open-apis/cardkit/v1/cards/${encodeURIComponent(cardId)}`, {
2467
+ card: {
2468
+ type: "card_json",
2469
+ data: JSON.stringify(card)
2470
+ },
2471
+ sequence
2472
+ });
2473
+ },
2474
+ async sendCard(chatId, cardId) {
2475
+ return sent(await call("post", "open-apis/im/v1/messages", {
2476
+ receive_id: chatId,
2477
+ msg_type: "interactive",
2478
+ content: cardContent(cardId)
2479
+ }, { receive_id_type: "chat_id" }));
2480
+ },
2481
+ async sendDirect(openId, text) {
2482
+ await call("post", "open-apis/im/v1/messages", {
2483
+ receive_id: openId,
2484
+ msg_type: "text",
2485
+ content: JSON.stringify({ text })
2486
+ }, { receive_id_type: "open_id" });
2487
+ }
2488
+ };
2489
+ }
2490
+ async function removed(events, data) {
2491
+ const chatId = str(data.chat_id);
2492
+ if (chatId === void 0) return;
2493
+ const users = Array.isArray(data.users) ? data.users : [];
2494
+ await events.membersRemoved(chatId, users.flatMap((one) => {
2495
+ const openId = str(one.user_id?.open_id);
2496
+ return openId === void 0 ? [] : [openId];
2497
+ }));
2498
+ }
2499
+ //#endregion
2500
+ //#region src/members.ts
2501
+ function createMembers(deps) {
2502
+ const queues = /* @__PURE__ */ new Map();
2503
+ const serial = (chatId, work) => {
2504
+ const before = queues.get(chatId) ?? Promise.resolve();
2505
+ const current = () => {
2506
+ deps.signal.throwIfAborted();
2507
+ return work();
2508
+ };
2509
+ const next = before.then(current, current);
2510
+ queues.set(chatId, next.catch(() => {}));
2511
+ return next;
2512
+ };
2513
+ const ownerOf = (botId) => deps.store.bot(botId)?.ownerOpenId ?? null;
2514
+ /** Names read from the directory, per bot and person, so each is asked once. */
2515
+ const names = /* @__PURE__ */ new Map();
2516
+ /** The directory's name for a person, else `fallback`; a refusal is noted on the bot. */
2517
+ async function nameOf(botId, openId, fallback) {
2518
+ const known = names.get(`${botId}:${openId}`);
2519
+ if (known !== void 0) return known;
2520
+ const api = deps.bots.api(botId);
2521
+ if (api === void 0) return fallback;
2522
+ try {
2523
+ const name = await api.userName(openId);
2524
+ deps.signal.throwIfAborted();
2525
+ if (deps.bots.api(botId) !== api) throw new Error("bot activation changed");
2526
+ if (name === void 0 || name === "") return fallback;
2527
+ names.set(`${botId}:${openId}`, name);
2528
+ return name;
2529
+ } catch (error) {
2530
+ deps.signal.throwIfAborted();
2531
+ if (deps.bots.api(botId) !== api) throw error;
2532
+ deps.bots.noteFailure(botId, error);
2533
+ return fallback;
2534
+ }
2535
+ }
2536
+ const defaultPolicy = (botId, openId) => ownerOf(botId) === openId ? "accept" : "ask";
2537
+ function refreshOwnerName(botId, openId, name) {
2538
+ const bot = deps.store.bot(botId);
2539
+ if (bot?.ownerOpenId === openId && name !== "" && bot.ownerName !== name) deps.store.setOwnerName(botId, name);
2540
+ }
2541
+ return {
2542
+ /** The policy a person has in a group: the owner is always `accept`,
2543
+ * anybody not on the list `reject`. */
2544
+ policyOf(botId, sessionId, openId) {
2545
+ if (deps.store.group(botId, sessionId)?.memberError != null) return "reject";
2546
+ if (deps.store.member(botId, sessionId, openId) === void 0) return "reject";
2547
+ if (ownerOf(botId) === openId) return "accept";
2548
+ return deps.store.member(botId, sessionId, openId)?.policy ?? "reject";
2549
+ },
2550
+ member: (botId, sessionId, openId) => deps.store.member(botId, sessionId, openId),
2551
+ added(chatId, users) {
2552
+ return serial(chatId, async () => {
2553
+ const group = deps.store.groupByChat(chatId);
2554
+ if (group === void 0) return;
2555
+ for (const user of users) {
2556
+ const name = await nameOf(group.botId, user.openId, user.name);
2557
+ deps.signal.throwIfAborted();
2558
+ deps.store.putMember({
2559
+ botId: group.botId,
2560
+ sessionId: group.sessionId,
2561
+ openId: user.openId,
2562
+ name,
2563
+ policy: defaultPolicy(group.botId, user.openId)
2564
+ });
2565
+ refreshOwnerName(group.botId, user.openId, name);
2566
+ }
2567
+ deps.changed(group.botId, group.sessionId);
2568
+ });
2569
+ },
2570
+ removed(chatId, openIds) {
2571
+ return serial(chatId, () => {
2572
+ const group = deps.store.groupByChat(chatId);
2573
+ if (group === void 0) return;
2574
+ for (const openId of openIds) {
2575
+ deps.store.deleteMember(group.botId, group.sessionId, openId);
2576
+ deps.left(group.botId, group.sessionId, openId);
2577
+ }
2578
+ deps.changed(group.botId, group.sessionId);
2579
+ });
2580
+ },
2581
+ /** Lists every group of a bot and makes the rows match. */
2582
+ async reconcile(botId) {
2583
+ const api = deps.bots.api(botId);
2584
+ if (api === void 0) return;
2585
+ await Promise.all(deps.store.groupsOf(botId).map((group) => group.state !== "active" ? void 0 : serial(group.chatId, async () => {
2586
+ try {
2587
+ const listed = await api.listMembers(group.chatId);
2588
+ deps.signal.throwIfAborted();
2589
+ const present = await Promise.all(listed.map(async (one) => ({
2590
+ ...one,
2591
+ name: await nameOf(botId, one.openId, one.name)
2592
+ })));
2593
+ deps.signal.throwIfAborted();
2594
+ if (deps.bots.api(botId) !== api || deps.store.groupByChat(group.chatId)?.botId !== botId) return;
2595
+ const seen = new Set(present.map((one) => one.openId));
2596
+ deps.store.transaction(() => {
2597
+ for (const one of present) {
2598
+ deps.store.putMember({
2599
+ botId,
2600
+ sessionId: group.sessionId,
2601
+ openId: one.openId,
2602
+ name: one.name,
2603
+ policy: defaultPolicy(botId, one.openId)
2604
+ });
2605
+ refreshOwnerName(botId, one.openId, one.name);
2606
+ }
2607
+ for (const row of deps.store.members(botId, group.sessionId)) if (!seen.has(row.openId)) {
2608
+ deps.store.deleteMember(botId, group.sessionId, row.openId);
2609
+ deps.left(botId, group.sessionId, row.openId);
2610
+ }
2611
+ });
2612
+ deps.store.setMemberError(group.chatId, null);
2613
+ } catch (error) {
2614
+ if (deps.signal.aborted) return;
2615
+ if (deps.bots.api(botId) !== api) return;
2616
+ deps.store.setMemberError(group.chatId, deps.bots.noteFailure(botId, error));
2617
+ }
2618
+ deps.changed(botId, group.sessionId);
2619
+ })));
2620
+ },
2621
+ setPolicy(botId, sessionId, openId, policy) {
2622
+ if (ownerOf(botId) === openId) throw new Error("所有者在各群固定为 Accept");
2623
+ if (deps.store.member(botId, sessionId, openId) === void 0) throw new Error("这个人已不在群里");
2624
+ deps.store.setPolicy(botId, sessionId, openId, policy);
2625
+ if (policy === "reject") deps.left(botId, sessionId, openId);
2626
+ deps.changed(botId, sessionId);
2627
+ return deps.store.member(botId, sessionId, openId);
2628
+ },
2629
+ /** Takes a person out of the Feishu group, then off the list. A refusal
2630
+ * leaves them there as `reject`, with the reason recorded. */
2631
+ remove(botId, sessionId, openId) {
2632
+ if (ownerOf(botId) === openId) return Promise.reject(/* @__PURE__ */ new Error("所有者在各群固定为 Accept"));
2633
+ const group = deps.store.group(botId, sessionId);
2634
+ if (group === void 0) return Promise.reject(/* @__PURE__ */ new Error("这个普通群不存在"));
2635
+ return serial(group.chatId, async () => {
2636
+ const api = deps.bots.api(botId);
2637
+ try {
2638
+ if (api === void 0) throw new Error("机器人未连接");
2639
+ await api.removeMembers(group.chatId, [openId]);
2640
+ deps.signal.throwIfAborted();
2641
+ if (deps.bots.api(botId) !== api) throw new Error("bot activation changed");
2642
+ deps.store.deleteMember(botId, sessionId, openId);
2643
+ deps.left(botId, sessionId, openId);
2644
+ deps.store.setMemberError(group.chatId, null);
2645
+ deps.changed(botId, sessionId);
2646
+ } catch (error) {
2647
+ deps.signal.throwIfAborted();
2648
+ if (deps.bots.api(botId) !== api) throw error;
2649
+ const reason = error instanceof Error && api === void 0 ? error.message : deps.bots.noteFailure(botId, error);
2650
+ deps.store.setPolicy(botId, sessionId, openId, "reject");
2651
+ deps.left(botId, sessionId, openId);
2652
+ deps.store.setMemberError(group.chatId, `移出失败:${reason}`);
2653
+ deps.changed(botId, sessionId);
2654
+ throw new Error(`移出失败,已改为 Reject:${reason}`);
2655
+ }
2656
+ });
2657
+ },
2658
+ /** The bot's new owner, `accept` in every group, pulled into each. */
2659
+ async pullOwner(botId, openId, fallback) {
2660
+ const name = await nameOf(botId, openId, fallback);
2661
+ deps.signal.throwIfAborted();
2662
+ if (name !== "") refreshOwnerName(botId, openId, name);
2663
+ for (const group of deps.store.groupsOf(botId)) {
2664
+ if (group.state !== "active") continue;
2665
+ if (deps.store.member(botId, group.sessionId, openId) !== void 0) {
2666
+ deps.store.setPolicy(botId, group.sessionId, openId, "accept");
2667
+ deps.changed(botId, group.sessionId);
2668
+ }
2669
+ }
2670
+ }
2671
+ };
2672
+ }
2673
+ //#endregion
2674
+ //#region src/methods.ts
2675
+ /**
2676
+ * The wire methods and frames the browser module calls. No credential crosses any of them: the AppSecret is written by
2677
+ * the page through `WebContext.credentials` and read here where it is used.
2678
+ */
2679
+ const Empty = z.object({}).strict();
2680
+ const MemberSchema = z.object({
2681
+ openId: z.string(),
2682
+ name: z.string(),
2683
+ isOwner: z.boolean(),
2684
+ policy: z.enum([
2685
+ "accept",
2686
+ "ask",
2687
+ "reject"
2688
+ ]),
2689
+ joinedAt: z.number()
2690
+ }).strict();
2691
+ const BotSchema = z.object({
2692
+ id: z.string(),
2693
+ name: z.string(),
2694
+ appId: z.string(),
2695
+ defaultAgentId: z.string().nullable(),
2696
+ defaultWorkspaceId: z.string().nullable(),
2697
+ enabled: z.boolean(),
2698
+ owner: z.object({
2699
+ openId: z.string(),
2700
+ name: z.string().nullable()
2701
+ }).strict().nullable(),
2702
+ secret: z.object({
2703
+ set: z.boolean(),
2704
+ hint: z.string().nullable()
2705
+ }).strict(),
2706
+ status: z.enum([
2707
+ "off",
2708
+ "connecting",
2709
+ "online",
2710
+ "reconnecting",
2711
+ "failed"
2712
+ ]),
2713
+ reason: z.string().nullable(),
2714
+ missingScopes: z.array(z.string()),
2715
+ bindings: z.number(),
2716
+ pending: z.array(z.object({
2717
+ key: z.string(),
2718
+ chatId: z.string().nullable(),
2719
+ sessionId: z.string().nullable(),
2720
+ error: z.string().nullable()
2721
+ }).strict()),
2722
+ groups: z.array(z.object({
2723
+ sessionId: z.string(),
2724
+ sessionName: z.string(),
2725
+ members: z.number(),
2726
+ memberError: z.string().nullable(),
2727
+ state: z.enum([
2728
+ "active",
2729
+ "broken",
2730
+ "unbound"
2731
+ ])
2732
+ }).strict())
2733
+ }).strict();
2734
+ const BindingSchema = z.object({
2735
+ sessionId: z.string(),
2736
+ botId: z.string(),
2737
+ botName: z.string(),
2738
+ chatName: z.string(),
2739
+ chatId: z.string(),
2740
+ state: z.enum([
2741
+ "active",
2742
+ "paused",
2743
+ "broken"
2744
+ ]),
2745
+ reason: z.string().nullable(),
2746
+ chatUrl: z.string()
2747
+ }).strict();
2748
+ const SaveBot = z.object({
2749
+ id: z.string().min(1).optional(),
2750
+ name: z.string().trim().min(1).max(40),
2751
+ appId: z.string().trim().regex(/^cli_[A-Za-z0-9]{8,64}$/, "AppID 形如 cli_ 开头的一串字母数字"),
2752
+ enabled: z.boolean(),
2753
+ defaultAgentId: z.string().min(1).nullable().optional(),
2754
+ defaultWorkspaceId: z.string().min(1).nullable().optional()
2755
+ }).strict();
2756
+ const Id = z.object({ id: z.string().min(1) }).strict();
2757
+ const BotId = z.object({ botId: z.string().min(1) }).strict();
2758
+ const Group = z.object({
2759
+ botId: z.string().min(1),
2760
+ sessionId: z.string().min(1)
2761
+ }).strict();
2762
+ const MemberKey = Group.extend({ openId: z.string().min(1) }).strict();
2763
+ const Session = z.object({ sessionId: z.string().min(1) }).strict();
2764
+ function registerMethods(deps) {
2765
+ const { ctx, store } = deps;
2766
+ const botsChanged = ctx.client.registerFrame({
2767
+ name: "botsChanged",
2768
+ delivery: "broadcast",
2769
+ payload: z.object({
2770
+ bots: z.array(BotSchema),
2771
+ pairedBotId: z.string().optional()
2772
+ }).strict()
2773
+ });
2774
+ const membersChanged = ctx.client.registerFrame({
2775
+ name: "membersChanged",
2776
+ delivery: "broadcast",
2777
+ payload: Group
2778
+ });
2779
+ const bindingChanged = ctx.client.registerFrame({
2780
+ name: "bindingChanged",
2781
+ delivery: "broadcast",
2782
+ payload: z.object({
2783
+ sessionId: z.string(),
2784
+ binding: BindingSchema.nullable()
2785
+ }).strict()
2786
+ });
2787
+ const sessionName = (sessionId) => deps.channel()?.getReadingSessionSummary(sessionId)?.name ?? sessionId;
2788
+ function secretOf(botId) {
2789
+ try {
2790
+ const status = deps.credentials.list(botId).find((one) => one.name === APP_SECRET);
2791
+ return status === void 0 ? {
2792
+ set: false,
2793
+ hint: null
2794
+ } : {
2795
+ set: true,
2796
+ hint: status.hint
2797
+ };
2798
+ } catch {
2799
+ return {
2800
+ set: false,
2801
+ hint: null
2802
+ };
2803
+ }
2804
+ }
2805
+ function summary(bot) {
2806
+ const status = deps.bots.status(bot.id);
2807
+ return {
2808
+ id: bot.id,
2809
+ name: bot.name,
2810
+ appId: bot.appId,
2811
+ defaultAgentId: bot.defaultAgentId,
2812
+ defaultWorkspaceId: bot.defaultWorkspaceId,
2813
+ pending: store.operationsOf(bot.id),
2814
+ enabled: bot.enabled,
2815
+ owner: bot.ownerOpenId === null ? null : {
2816
+ openId: bot.ownerOpenId,
2817
+ name: bot.ownerName
2818
+ },
2819
+ secret: secretOf(bot.id),
2820
+ status: status.state,
2821
+ reason: status.reason,
2822
+ missingScopes: [...status.missingScopes],
2823
+ bindings: store.bindingsOfBot(bot.id).length,
2824
+ groups: store.groupsOf(bot.id).map((group) => ({
2825
+ sessionId: group.sessionId,
2826
+ sessionName: sessionName(group.sessionId),
2827
+ members: store.members(bot.id, group.sessionId).length,
2828
+ memberError: group.memberError,
2829
+ state: group.state
2830
+ }))
2831
+ };
2832
+ }
2833
+ const summaries = () => store.bots().map(summary);
2834
+ const require = (id) => {
2835
+ const bot = store.bot(id);
2836
+ if (bot === void 0) throw new Error("找不到这个机器人");
2837
+ return bot;
2838
+ };
2839
+ const member = (botId, sessionId, openId) => {
2840
+ const row = store.member(botId, sessionId, openId);
2841
+ if (row === void 0) throw new Error("这个人已不在群里");
2842
+ return {
2843
+ openId: row.openId,
2844
+ name: row.name,
2845
+ isOwner: store.bot(botId)?.ownerOpenId === row.openId,
2846
+ policy: store.bot(botId)?.ownerOpenId === row.openId ? "accept" : row.policy,
2847
+ joinedAt: row.joinedAt
2848
+ };
2849
+ };
2850
+ ctx.client.registerMethod({
2851
+ name: "listDefaults",
2852
+ params: Empty,
2853
+ result: z.object({
2854
+ agents: z.array(z.object({
2855
+ id: z.string(),
2856
+ name: z.string()
2857
+ })),
2858
+ workspaces: z.array(z.object({
2859
+ id: z.string(),
2860
+ name: z.string()
2861
+ }))
2862
+ }),
2863
+ handle: () => ({
2864
+ agents: (deps.channel()?.listAgents() ?? []).filter((one) => one.startsSessions !== false).map((one) => ({
2865
+ id: one.agentId,
2866
+ name: one.name
2867
+ })),
2868
+ workspaces: (deps.channel()?.listWorkspaces() ?? []).map((one) => ({
2869
+ id: one.workspaceId,
2870
+ name: one.name
2871
+ }))
2872
+ })
2873
+ });
2874
+ ctx.client.registerMethod({
2875
+ name: "recoverGroup",
2876
+ params: z.object({
2877
+ botId: z.string(),
2878
+ sessionId: z.string(),
2879
+ chatId: z.string().trim().min(1)
2880
+ }).strict(),
2881
+ result: BindingSchema,
2882
+ handle: ({ sessionId, botId, chatId }) => deps.bindings.recoverGroup(sessionId, botId, chatId)
2883
+ });
2884
+ ctx.client.registerMethod({
2885
+ name: "retryGroup",
2886
+ params: z.object({
2887
+ botId: z.string(),
2888
+ chatId: z.string()
2889
+ }).strict(),
2890
+ result: Empty,
2891
+ async handle({ botId, chatId }) {
2892
+ require(botId);
2893
+ await deps.bindings.retryGroup(botId, chatId);
2894
+ ctx.signal.throwIfAborted();
2895
+ botsChanged.emit({ bots: summaries() });
2896
+ return {};
2897
+ }
2898
+ });
2899
+ ctx.client.registerMethod({
2900
+ name: "listBots",
2901
+ params: Empty,
2902
+ result: z.array(BotSchema),
2903
+ handle: () => summaries()
2904
+ });
2905
+ ctx.client.registerMethod({
2906
+ name: "saveBot",
2907
+ params: SaveBot,
2908
+ result: BotSchema,
2909
+ handle(input) {
2910
+ if (input.defaultAgentId != null && !deps.channel()?.listAgents().some((one) => one.agentId === input.defaultAgentId && one.startsSessions !== false)) throw new Error("默认智能体不可用");
2911
+ if (input.defaultWorkspaceId != null && !deps.channel()?.listWorkspaces().some((one) => one.workspaceId === input.defaultWorkspaceId)) throw new Error("默认工作空间不可用");
2912
+ const clash = store.botByAppId(input.appId);
2913
+ if (clash !== void 0 && clash.id !== input.id) throw new Error(`这个 AppID 已配置在“${clash.name}”`);
2914
+ const saved = input.id === void 0 ? store.insertBot({
2915
+ id: randomUUID(),
2916
+ name: input.name,
2917
+ appId: input.appId,
2918
+ enabled: input.enabled
2919
+ }) : (() => {
2920
+ const before = require(input.id);
2921
+ if (before.appId !== input.appId && store.groupsOf(before.id).length > 0) throw new Error("此机器人已有群关联,请为另一个 AppID 新增通道");
2922
+ return store.updateBot(before.id, input);
2923
+ })();
2924
+ if (input.defaultAgentId !== void 0 || input.defaultWorkspaceId !== void 0) store.setDefaults(saved.id, input.defaultAgentId === void 0 ? saved.defaultAgentId : input.defaultAgentId, input.defaultWorkspaceId === void 0 ? saved.defaultWorkspaceId : input.defaultWorkspaceId);
2925
+ deps.bots.start(saved.id);
2926
+ botsChanged.emit({ bots: summaries() });
2927
+ return summary(store.bot(saved.id));
2928
+ }
2929
+ });
2930
+ ctx.client.registerMethod({
2931
+ name: "removeBot",
2932
+ params: Id,
2933
+ result: Empty,
2934
+ async handle({ id }) {
2935
+ require(id);
2936
+ const sessions = store.bindingsOfBot(id).map((one) => one.sessionId);
2937
+ for (const sessionId of sessions) {
2938
+ await deps.bindings.unbind(sessionId);
2939
+ ctx.signal.throwIfAborted();
2940
+ }
2941
+ deps.bots.stop(id);
2942
+ store.removeBot(id);
2943
+ deps.credentials.clear(id);
2944
+ for (const sessionId of sessions) bindingChanged.emit({
2945
+ sessionId,
2946
+ binding: null
2947
+ });
2948
+ botsChanged.emit({ bots: summaries() });
2949
+ return {};
2950
+ }
2951
+ });
2952
+ ctx.client.registerMethod({
2953
+ name: "testBot",
2954
+ params: Id,
2955
+ result: z.union([z.object({ ok: z.literal(true) }).strict(), z.object({
2956
+ ok: z.literal(false),
2957
+ reason: z.string()
2958
+ }).strict()]),
2959
+ async handle({ id }) {
2960
+ const bot = require(id);
2961
+ let secret;
2962
+ try {
2963
+ secret = deps.credentials.get(id, APP_SECRET);
2964
+ } catch {
2965
+ return {
2966
+ ok: false,
2967
+ reason: "AppSecret 无法读取,请重新设置凭证。"
2968
+ };
2969
+ }
2970
+ if (secret === void 0) return {
2971
+ ok: false,
2972
+ reason: "尚未填写 AppSecret"
2973
+ };
2974
+ try {
2975
+ await deps.createApi(bot, secret).check();
2976
+ ctx.signal.throwIfAborted();
2977
+ return { ok: true };
2978
+ } catch (error) {
2979
+ ctx.signal.throwIfAborted();
2980
+ return {
2981
+ ok: false,
2982
+ reason: deps.bots.noteFailure(id, error, secret)
2983
+ };
2984
+ }
2985
+ }
2986
+ });
2987
+ ctx.client.registerMethod({
2988
+ name: "startPairing",
2989
+ params: BotId,
2990
+ result: z.object({
2991
+ code: z.string(),
2992
+ expiresAt: z.number()
2993
+ }).strict(),
2994
+ handle({ botId }) {
2995
+ const bot = require(botId);
2996
+ if (deps.bots.status(botId).state !== "online") throw new Error(`机器人“${bot.name}”未在线,连上后才能配对`);
2997
+ return deps.pairing.start(botId);
2998
+ }
2999
+ });
3000
+ ctx.client.registerMethod({
3001
+ name: "listMembers",
3002
+ params: Group,
3003
+ result: z.object({
3004
+ members: z.array(MemberSchema),
3005
+ memberError: z.string().nullable()
3006
+ }).strict(),
3007
+ handle({ botId, sessionId }) {
3008
+ require(botId);
3009
+ return {
3010
+ members: store.members(botId, sessionId).map((row) => member(botId, sessionId, row.openId)),
3011
+ memberError: store.group(botId, sessionId)?.memberError ?? null
3012
+ };
3013
+ }
3014
+ });
3015
+ ctx.client.registerMethod({
3016
+ name: "setMemberPolicy",
3017
+ params: MemberKey.extend({ policy: z.enum([
3018
+ "accept",
3019
+ "ask",
3020
+ "reject"
3021
+ ]) }).strict(),
3022
+ result: MemberSchema,
3023
+ handle({ botId, sessionId, openId, policy }) {
3024
+ deps.members.setPolicy(botId, sessionId, openId, policy);
3025
+ return member(botId, sessionId, openId);
3026
+ }
3027
+ });
3028
+ ctx.client.registerMethod({
3029
+ name: "removeMember",
3030
+ params: MemberKey,
3031
+ result: Empty,
3032
+ async handle({ botId, sessionId, openId }) {
3033
+ await deps.members.remove(botId, sessionId, openId);
3034
+ return {};
3035
+ }
3036
+ });
3037
+ ctx.client.registerMethod({
3038
+ name: "listBindings",
3039
+ params: Empty,
3040
+ result: z.array(BindingSchema),
3041
+ handle: () => store.bindings().map((one) => deps.bindings.view(one.sessionId)).filter((one) => one !== null)
3042
+ });
3043
+ ctx.client.registerMethod({
3044
+ name: "getBinding",
3045
+ params: Session,
3046
+ result: BindingSchema.nullable(),
3047
+ handle: ({ sessionId }) => deps.bindings.view(sessionId)
3048
+ });
3049
+ ctx.client.registerMethod({
3050
+ name: "bind",
3051
+ params: Session.extend({ botId: z.string().min(1) }).strict(),
3052
+ result: BindingSchema,
3053
+ handle: ({ sessionId, botId }) => deps.bindings.bind(sessionId, botId)
3054
+ });
3055
+ ctx.client.registerMethod({
3056
+ name: "unbind",
3057
+ params: Session,
3058
+ result: Empty,
3059
+ async handle({ sessionId }) {
3060
+ await deps.bindings.unbind(sessionId);
3061
+ return {};
3062
+ }
3063
+ });
3064
+ return {
3065
+ botsChanged: () => botsChanged.emit({ bots: summaries() }),
3066
+ /** Marks successful code consumption, including pairing with the same owner. */
3067
+ ownerPaired: (botId) => botsChanged.emit({
3068
+ bots: summaries(),
3069
+ pairedBotId: botId
3070
+ }),
3071
+ membersChanged: (botId, sessionId) => membersChanged.emit({
3072
+ botId,
3073
+ sessionId
3074
+ }),
3075
+ bindingChanged: (sessionId) => bindingChanged.emit({
3076
+ sessionId,
3077
+ binding: deps.bindings.view(sessionId)
3078
+ })
3079
+ };
3080
+ }
3081
+ //#endregion
3082
+ //#region src/pairing.ts
3083
+ /**
3084
+ * Pairing a bot with its owner: the settings page asks for a code, and
3085
+ * whoever sends that code to the bot in a direct chat within five minutes
3086
+ * becomes the bot's one owner, replacing any before. A code is single-use and
3087
+ * belongs to one bot; a new one replaces the old.
3088
+ */
3089
+ /** How long a code stays good. */
3090
+ const PAIRING_TTL_MS = 3e5;
3091
+ function createPairing(now = Date.now) {
3092
+ const codes = /* @__PURE__ */ new Map();
3093
+ return {
3094
+ /** A fresh six-digit code for a bot, replacing its previous one. */
3095
+ start(botId) {
3096
+ const issued = {
3097
+ code: String(randomInt(0, 1e6)).padStart(6, "0"),
3098
+ expiresAt: now() + PAIRING_TTL_MS
3099
+ };
3100
+ codes.set(botId, issued);
3101
+ return issued;
3102
+ },
3103
+ /** Whether `text` is the bot's live code; a match uses it up. */
3104
+ take(botId, text) {
3105
+ const issued = codes.get(botId);
3106
+ if (issued === void 0) return false;
3107
+ if (issued.expiresAt <= now()) {
3108
+ codes.delete(botId);
3109
+ return false;
3110
+ }
3111
+ if (text.replace(/\s+/g, "") !== issued.code) return false;
3112
+ codes.delete(botId);
3113
+ return true;
3114
+ },
3115
+ pending(botId) {
3116
+ const issued = codes.get(botId);
3117
+ return issued === void 0 || issued.expiresAt <= now() ? void 0 : issued;
3118
+ }
3119
+ };
3120
+ }
3121
+ function createFeishuStore(storage, now = Date.now) {
3122
+ const { db, tableName } = storage;
3123
+ const bots = tableName("bot");
3124
+ const groups = tableName("session_group");
3125
+ const members = tableName("member");
3126
+ const bindings = tableName("binding");
3127
+ const cards = tableName("card");
3128
+ const columns = db.prepare(`PRAGMA table_info(${bots})`).all();
3129
+ if (columns.length > 0 && !columns.some((row) => row.name === "default_agent_id")) throw new Error("Feishu storage uses the former topic-group schema. Use a new isolated state root; existing data has not been changed.");
3130
+ db.exec(`CREATE TABLE IF NOT EXISTS ${bots} (
3131
+ id TEXT NOT NULL PRIMARY KEY,
3132
+ name TEXT NOT NULL,
3133
+ app_id TEXT NOT NULL UNIQUE,
3134
+ owner_open_id TEXT,
3135
+ owner_name TEXT,
3136
+ default_agent_id TEXT,
3137
+ default_workspace_id TEXT,
3138
+ enabled INTEGER NOT NULL DEFAULT 1,
3139
+ created_at INTEGER NOT NULL,
3140
+ updated_at INTEGER NOT NULL
3141
+ ) STRICT;
3142
+ CREATE TABLE IF NOT EXISTS ${groups} (
3143
+ bot_id TEXT NOT NULL,
3144
+ session_id TEXT NOT NULL,
3145
+ chat_id TEXT NOT NULL,
3146
+ member_error TEXT,
3147
+ state TEXT NOT NULL DEFAULT 'active',
3148
+ created_at INTEGER NOT NULL,
3149
+ PRIMARY KEY (bot_id, chat_id)
3150
+ ) STRICT;
3151
+ CREATE TABLE IF NOT EXISTS ${members} (
3152
+ bot_id TEXT NOT NULL,
3153
+ session_id TEXT NOT NULL,
3154
+ open_id TEXT NOT NULL,
3155
+ name TEXT NOT NULL,
3156
+ policy TEXT NOT NULL,
3157
+ joined_at INTEGER NOT NULL,
3158
+ updated_at INTEGER NOT NULL,
3159
+ PRIMARY KEY (bot_id, session_id, open_id)
3160
+ ) STRICT;
3161
+ CREATE TABLE IF NOT EXISTS ${bindings} (
3162
+ session_id TEXT NOT NULL PRIMARY KEY,
3163
+ bot_id TEXT NOT NULL,
3164
+ workspace_id TEXT NOT NULL,
3165
+ chat_id TEXT NOT NULL UNIQUE,
3166
+ root_message_id TEXT NOT NULL UNIQUE,
3167
+ state TEXT NOT NULL DEFAULT 'active',
3168
+ reason TEXT,
3169
+ created_at INTEGER NOT NULL,
3170
+ updated_at INTEGER NOT NULL
3171
+ ) STRICT;
3172
+ CREATE INDEX IF NOT EXISTS ${tableName("binding_by_bot")} ON ${bindings} (bot_id);
3173
+ CREATE TABLE IF NOT EXISTS ${cards} (
3174
+ message_id TEXT NOT NULL PRIMARY KEY,
3175
+ session_id TEXT NOT NULL,
3176
+ binding_id TEXT NOT NULL,
3177
+ kind TEXT NOT NULL,
3178
+ ref TEXT NOT NULL,
3179
+ card_id TEXT NOT NULL,
3180
+ sequence INTEGER NOT NULL DEFAULT 0,
3181
+ state TEXT NOT NULL DEFAULT 'open',
3182
+ updated_at INTEGER NOT NULL
3183
+ ) STRICT;
3184
+ CREATE INDEX IF NOT EXISTS ${tableName("card_open")} ON ${cards} (state, binding_id);
3185
+ CREATE UNIQUE INDEX IF NOT EXISTS ${tableName("card_ref")} ON ${cards} (binding_id, kind, ref);`);
3186
+ const operations = tableName("group_operation");
3187
+ const events = tableName("group_event");
3188
+ const lifecycle = tableName("group_lifecycle");
3189
+ db.exec(`CREATE TABLE IF NOT EXISTS ${lifecycle} (
3190
+ bot_id TEXT NOT NULL,
3191
+ chat_id TEXT NOT NULL,
3192
+ event_at INTEGER NOT NULL,
3193
+ PRIMARY KEY (bot_id, chat_id)
3194
+ ) STRICT;
3195
+ CREATE UNIQUE INDEX IF NOT EXISTS ${tableName("current_group")} ON ${groups} (chat_id) WHERE state != 'unbound';
3196
+ CREATE TABLE IF NOT EXISTS ${operations} (
3197
+ operation_key TEXT NOT NULL PRIMARY KEY,
3198
+ bot_id TEXT NOT NULL,
3199
+ session_id TEXT,
3200
+ chat_id TEXT,
3201
+ error TEXT,
3202
+ updated_at INTEGER NOT NULL
3203
+ ) STRICT;
3204
+ CREATE TABLE IF NOT EXISTS ${events} (
3205
+ event_key TEXT NOT NULL PRIMARY KEY,
3206
+ received_at INTEGER NOT NULL
3207
+ ) STRICT;`);
3208
+ const transaction = (write) => {
3209
+ if (db.isTransaction) return write();
3210
+ db.exec("BEGIN IMMEDIATE");
3211
+ try {
3212
+ const result = write();
3213
+ db.exec("COMMIT");
3214
+ return result;
3215
+ } catch (error) {
3216
+ db.exec("ROLLBACK");
3217
+ throw error;
3218
+ }
3219
+ };
3220
+ const str = (value) => value === null ? null : String(value);
3221
+ const bot = (row) => ({
3222
+ id: String(row.id),
3223
+ name: String(row.name),
3224
+ appId: String(row.app_id),
3225
+ ownerOpenId: str(row.owner_open_id),
3226
+ ownerName: str(row.owner_name),
3227
+ defaultAgentId: str(row.default_agent_id),
3228
+ defaultWorkspaceId: str(row.default_workspace_id),
3229
+ enabled: Number(row.enabled) === 1,
3230
+ createdAt: Number(row.created_at),
3231
+ updatedAt: Number(row.updated_at)
3232
+ });
3233
+ const group = (row) => ({
3234
+ botId: String(row.bot_id),
3235
+ sessionId: String(row.session_id),
3236
+ chatId: String(row.chat_id),
3237
+ memberError: str(row.member_error),
3238
+ state: row.state === "unbound" ? "unbound" : row.state === "broken" ? "broken" : "active",
3239
+ createdAt: Number(row.created_at)
3240
+ });
3241
+ const member = (row) => ({
3242
+ botId: String(row.bot_id),
3243
+ sessionId: String(row.session_id),
3244
+ openId: String(row.open_id),
3245
+ name: String(row.name),
3246
+ policy: row.policy === "accept" || row.policy === "reject" ? row.policy : "ask",
3247
+ joinedAt: Number(row.joined_at),
3248
+ updatedAt: Number(row.updated_at)
3249
+ });
3250
+ const binding = (row) => ({
3251
+ sessionId: String(row.session_id),
3252
+ botId: String(row.bot_id),
3253
+ workspaceId: String(row.workspace_id),
3254
+ chatId: String(row.chat_id),
3255
+ rootMessageId: String(row.root_message_id),
3256
+ state: row.state === "paused" || row.state === "broken" ? row.state : "active",
3257
+ reason: str(row.reason),
3258
+ createdAt: Number(row.created_at),
3259
+ updatedAt: Number(row.updated_at)
3260
+ });
3261
+ const card = (row) => ({
3262
+ messageId: String(row.message_id),
3263
+ sessionId: String(row.session_id),
3264
+ bindingId: String(row.binding_id),
3265
+ kind: String(row.kind),
3266
+ ref: String(row.ref),
3267
+ cardId: String(row.card_id),
3268
+ sequence: Number(row.sequence),
3269
+ state: row.state === "closed" ? "closed" : "open",
3270
+ updatedAt: Number(row.updated_at)
3271
+ });
3272
+ const rows = (sql, ...params) => db.prepare(sql).all(...params);
3273
+ const first = (sql, ...params) => db.prepare(sql).get(...params);
3274
+ const getBot = (id) => {
3275
+ const row = first(`SELECT * FROM ${bots} WHERE id = ?`, id);
3276
+ return row === void 0 ? void 0 : bot(row);
3277
+ };
3278
+ const getGroup = (botId, sessionId) => {
3279
+ const row = first(`SELECT * FROM ${groups} WHERE bot_id = ? AND session_id = ? AND state != 'unbound'`, botId, sessionId);
3280
+ return row === void 0 ? void 0 : group(row);
3281
+ };
3282
+ const getBinding = (sessionId) => {
3283
+ const row = first(`SELECT * FROM ${bindings} WHERE session_id = ?`, sessionId);
3284
+ return row === void 0 ? void 0 : binding(row);
3285
+ };
3286
+ return {
3287
+ transaction,
3288
+ now,
3289
+ acceptLifecycle(botId, chatId, at) {
3290
+ const row = first(`SELECT event_at FROM ${lifecycle} WHERE bot_id = ? AND chat_id = ?`, botId, chatId);
3291
+ if (row !== void 0 && Number(row.event_at) > at) return false;
3292
+ db.prepare(`INSERT INTO ${lifecycle} (bot_id, chat_id, event_at) VALUES (?, ?, ?) ON CONFLICT (bot_id, chat_id) DO UPDATE SET event_at = excluded.event_at`).run(botId, chatId, at);
3293
+ return true;
3294
+ },
3295
+ rememberEvent(key) {
3296
+ return db.prepare(`INSERT OR IGNORE INTO ${events} (event_key, received_at) VALUES (?, ?)`).run(key, now()).changes === 1;
3297
+ },
3298
+ operation(key) {
3299
+ const row = first(`SELECT * FROM ${operations} WHERE operation_key = ?`, key);
3300
+ return row === void 0 ? void 0 : {
3301
+ key,
3302
+ botId: String(row.bot_id),
3303
+ sessionId: str(row.session_id),
3304
+ chatId: str(row.chat_id),
3305
+ error: str(row.error)
3306
+ };
3307
+ },
3308
+ operationsOf(botId) {
3309
+ return rows(`SELECT * FROM ${operations} WHERE bot_id = ?`, botId).map((row) => ({
3310
+ key: String(row.operation_key),
3311
+ chatId: str(row.chat_id),
3312
+ sessionId: str(row.session_id),
3313
+ error: str(row.error)
3314
+ }));
3315
+ },
3316
+ putOperation(key, botId, sessionId, chatId, error) {
3317
+ db.prepare(`INSERT INTO ${operations} (operation_key, bot_id, session_id, chat_id, error, updated_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (operation_key) DO UPDATE SET session_id = excluded.session_id, chat_id = excluded.chat_id, error = excluded.error, updated_at = excluded.updated_at`).run(key, botId, sessionId, chatId, error, now());
3318
+ },
3319
+ deleteOperation(key) {
3320
+ db.prepare(`DELETE FROM ${operations} WHERE operation_key = ?`).run(key);
3321
+ },
3322
+ bots: () => rows(`SELECT * FROM ${bots} ORDER BY created_at, id`).map(bot),
3323
+ bot: getBot,
3324
+ botByAppId(appId) {
3325
+ const row = first(`SELECT * FROM ${bots} WHERE app_id = ?`, appId);
3326
+ return row === void 0 ? void 0 : bot(row);
3327
+ },
3328
+ insertBot(input) {
3329
+ const at = now();
3330
+ db.prepare(`INSERT INTO ${bots} (id, name, app_id, enabled, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)`).run(input.id, input.name, input.appId, input.enabled ? 1 : 0, at, at);
3331
+ return getBot(input.id);
3332
+ },
3333
+ updateBot(id, input) {
3334
+ db.prepare(`UPDATE ${bots} SET name = ?, app_id = ?, enabled = ?, updated_at = ? WHERE id = ?`).run(input.name, input.appId, input.enabled ? 1 : 0, now(), id);
3335
+ return getBot(id);
3336
+ },
3337
+ setDefaults(id, agentId, workspaceId) {
3338
+ db.prepare(`UPDATE ${bots} SET default_agent_id = ?, default_workspace_id = ?, updated_at = ? WHERE id = ?`).run(agentId, workspaceId, now(), id);
3339
+ },
3340
+ setOwner(id, openId, name) {
3341
+ db.prepare(`UPDATE ${bots} SET owner_open_id = ?, owner_name = ?, updated_at = ? WHERE id = ?`).run(openId, name, now(), id);
3342
+ },
3343
+ setOwnerName(id, name) {
3344
+ db.prepare(`UPDATE ${bots} SET owner_name = ? WHERE id = ?`).run(name, id);
3345
+ },
3346
+ /** Everything the bot holds, in one transaction; the groups stay in Feishu. */
3347
+ removeBot(id) {
3348
+ transaction(() => {
3349
+ const ids = rows(`SELECT session_id FROM ${bindings} WHERE bot_id = ?`, id).map((row) => String(row.session_id));
3350
+ for (const sessionId of ids) db.prepare(`DELETE FROM ${cards} WHERE binding_id = ?`).run(sessionId);
3351
+ db.prepare(`DELETE FROM ${bindings} WHERE bot_id = ?`).run(id);
3352
+ db.prepare(`DELETE FROM ${members} WHERE bot_id = ?`).run(id);
3353
+ db.prepare(`DELETE FROM ${groups} WHERE bot_id = ?`).run(id);
3354
+ db.prepare(`DELETE FROM ${operations} WHERE bot_id = ?`).run(id);
3355
+ db.prepare(`DELETE FROM ${lifecycle} WHERE bot_id = ?`).run(id);
3356
+ db.prepare(`DELETE FROM ${bots} WHERE id = ?`).run(id);
3357
+ });
3358
+ },
3359
+ group: getGroup,
3360
+ history(botId, chatId) {
3361
+ const row = first(`SELECT * FROM ${groups} WHERE bot_id = ? AND chat_id = ?`, botId, chatId);
3362
+ return row === void 0 ? void 0 : group(row);
3363
+ },
3364
+ groupByChat(chatId) {
3365
+ const row = first(`SELECT * FROM ${groups} WHERE chat_id = ? AND state != 'unbound'`, chatId);
3366
+ return row === void 0 ? void 0 : group(row);
3367
+ },
3368
+ groupsOf: (botId) => rows(`SELECT * FROM ${groups} WHERE bot_id = ? ORDER BY created_at`, botId).map(group),
3369
+ /** A new group with its owner's row, one transaction; a broken row for
3370
+ * the same pair is replaced with its members. */
3371
+ insertGroup(input) {
3372
+ transaction(() => {
3373
+ db.prepare(`DELETE FROM ${members} WHERE bot_id = ? AND session_id = ?`).run(input.botId, input.sessionId);
3374
+ const at = now();
3375
+ db.prepare(`INSERT INTO ${groups} (bot_id, session_id, chat_id, created_at) VALUES (?, ?, ?, ?) ON CONFLICT (bot_id, chat_id) DO UPDATE SET session_id = excluded.session_id, state = 'active', member_error = NULL`).run(input.botId, input.sessionId, input.chatId, at);
3376
+ if (input.owner !== null) db.prepare(`INSERT INTO ${members} (bot_id, session_id, open_id, name, policy, joined_at, updated_at) VALUES (?, ?, ?, ?, 'accept', ?, ?)`).run(input.botId, input.sessionId, input.owner.openId, input.owner.name, at, at);
3377
+ });
3378
+ return getGroup(input.botId, input.sessionId);
3379
+ },
3380
+ setGroupState(chatId, state, botId) {
3381
+ db.prepare(`UPDATE ${groups} SET state = ? WHERE chat_id = ? AND bot_id = ?`).run(state, chatId, botId);
3382
+ },
3383
+ setMemberError(chatId, error) {
3384
+ db.prepare(`UPDATE ${groups} SET member_error = ? WHERE chat_id = ?`).run(error, chatId);
3385
+ },
3386
+ member(botId, sessionId, openId) {
3387
+ const row = first(`SELECT * FROM ${members} WHERE bot_id = ? AND session_id = ? AND open_id = ?`, botId, sessionId, openId);
3388
+ return row === void 0 ? void 0 : member(row);
3389
+ },
3390
+ members: (botId, sessionId) => rows(`SELECT * FROM ${members} WHERE bot_id = ? AND session_id = ? ORDER BY joined_at, open_id`, botId, sessionId).map(member),
3391
+ /** Inserts a member with `policy`, or refreshes the name of one already there. */
3392
+ putMember(input) {
3393
+ const at = now();
3394
+ db.prepare(`INSERT INTO ${members} (bot_id, session_id, open_id, name, policy, joined_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)
3395
+ ON CONFLICT (bot_id, session_id, open_id) DO UPDATE SET name = CASE WHEN excluded.name = '' THEN name ELSE excluded.name END, updated_at = excluded.updated_at`).run(input.botId, input.sessionId, input.openId, input.name, input.policy, at, at);
3396
+ },
3397
+ setPolicy(botId, sessionId, openId, policy) {
3398
+ db.prepare(`UPDATE ${members} SET policy = ?, updated_at = ? WHERE bot_id = ? AND session_id = ? AND open_id = ?`).run(policy, now(), botId, sessionId, openId);
3399
+ },
3400
+ deleteMember(botId, sessionId, openId) {
3401
+ db.prepare(`DELETE FROM ${members} WHERE bot_id = ? AND session_id = ? AND open_id = ?`).run(botId, sessionId, openId);
3402
+ },
3403
+ binding: getBinding,
3404
+ bindings: () => rows(`SELECT * FROM ${bindings} ORDER BY created_at`).map(binding),
3405
+ bindingsOfBot: (botId) => rows(`SELECT * FROM ${bindings} WHERE bot_id = ? ORDER BY created_at`, botId).map(binding),
3406
+ bindingsOfChat: (chatId) => rows(`SELECT * FROM ${bindings} WHERE chat_id = ?`, chatId).map(binding),
3407
+ /** Writes a binding and its topic's root card in one transaction,
3408
+ * replacing any binding the session held with all its cards. */
3409
+ putBinding(input) {
3410
+ transaction(() => {
3411
+ db.prepare(`DELETE FROM ${cards} WHERE binding_id = ?`).run(input.sessionId);
3412
+ db.prepare(`DELETE FROM ${bindings} WHERE session_id = ?`).run(input.sessionId);
3413
+ const at = now();
3414
+ db.prepare(`INSERT INTO ${bindings} (session_id, bot_id, workspace_id, chat_id, root_message_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)`).run(input.sessionId, input.botId, input.workspaceId, input.chatId, input.rootMessageId, at, at);
3415
+ db.prepare(`INSERT INTO ${cards} (message_id, session_id, binding_id, kind, ref, card_id, sequence, state, updated_at) VALUES (?, ?, ?, 'session', ?, ?, 0, 'open', ?)`).run(input.rootMessageId, input.sessionId, input.sessionId, input.sessionId, input.rootCardId, at);
3416
+ });
3417
+ return getBinding(input.sessionId);
3418
+ },
3419
+ deleteBinding(sessionId) {
3420
+ transaction(() => {
3421
+ db.prepare(`DELETE FROM ${cards} WHERE binding_id = ?`).run(sessionId);
3422
+ db.prepare(`DELETE FROM ${bindings} WHERE session_id = ?`).run(sessionId);
3423
+ });
3424
+ },
3425
+ setBindingState(sessionId, state, reason = null) {
3426
+ db.prepare(`UPDATE ${bindings} SET state = ?, reason = ?, updated_at = ? WHERE session_id = ?`).run(state, reason, now(), sessionId);
3427
+ },
3428
+ resetBoundary(sessionId) {
3429
+ db.prepare(`UPDATE ${bindings} SET created_at = ?, updated_at = ? WHERE session_id = ?`).run(now(), now(), sessionId);
3430
+ db.prepare(`UPDATE ${cards} SET state = 'closed' WHERE binding_id = ? AND kind != 'session'`).run(sessionId);
3431
+ },
3432
+ card(messageId) {
3433
+ const row = first(`SELECT * FROM ${cards} WHERE message_id = ?`, messageId);
3434
+ return row === void 0 ? void 0 : card(row);
3435
+ },
3436
+ cardByRef(bindingId, kind, ref) {
3437
+ const row = first(`SELECT * FROM ${cards} WHERE binding_id = ? AND kind = ? AND ref = ?`, bindingId, kind, ref);
3438
+ return row === void 0 ? void 0 : card(row);
3439
+ },
3440
+ openCards: () => rows(`SELECT * FROM ${cards} WHERE state = 'open' ORDER BY updated_at`).map(card),
3441
+ insertCard(input) {
3442
+ transaction(() => {
3443
+ db.prepare(`INSERT OR REPLACE INTO ${cards} (message_id, session_id, binding_id, kind, ref, card_id, sequence, state, updated_at) VALUES (?, ?, ?, ?, ?, ?, 0, 'open', ?)`).run(input.messageId, input.sessionId, input.bindingId, input.kind, input.ref, input.cardId, now());
3444
+ db.prepare(`DELETE FROM ${cards} WHERE binding_id = ? AND state = 'closed' AND kind != 'session' AND message_id NOT IN (SELECT message_id FROM ${cards} WHERE binding_id = ? AND state = 'closed' AND kind != 'session' ORDER BY updated_at DESC LIMIT ?)`).run(input.bindingId, input.bindingId, 200);
3445
+ });
3446
+ },
3447
+ /** Reserves the next sequence number for one card before it is sent. */
3448
+ reserveSequence(messageId) {
3449
+ db.prepare(`UPDATE ${cards} SET sequence = sequence + 1, updated_at = ? WHERE message_id = ?`).run(now(), messageId);
3450
+ return Number(first(`SELECT sequence FROM ${cards} WHERE message_id = ?`, messageId)?.sequence ?? 0);
3451
+ },
3452
+ closeCard(messageId) {
3453
+ db.prepare(`UPDATE ${cards} SET state = 'closed', updated_at = ? WHERE message_id = ?`).run(now(), messageId);
3454
+ }
3455
+ };
3456
+ }
3457
+ //#endregion
3458
+ //#region src/index.ts
3459
+ /** The Feishu plugin: independent ordinary groups, reverse session creation and member authorization. */
3460
+ const Config = z.object({}).strict().default({});
3461
+ function createFeishuPlugin(options = {}) {
3462
+ return {
3463
+ name: "@eum-agent/channel-feishu",
3464
+ configSchema: Config,
3465
+ requires: ["credentials", "network"],
3466
+ optionalServices: [
3467
+ "session-model-controls",
3468
+ "session-context-maintenance",
3469
+ "session-delegation-observer"
3470
+ ],
3471
+ apply(ctx) {
3472
+ const clock = options.clock ?? SYSTEM_CLOCK;
3473
+ const store = createFeishuStore(ctx.storage.open(), () => clock.now());
3474
+ const credentials = ctx.services.get("credentials");
3475
+ const network = ctx.services.get("network");
3476
+ const createApi = options.createApi ?? ((bot, appSecret) => createLarkClient({
3477
+ appId: bot.appId,
3478
+ appSecret,
3479
+ network,
3480
+ signal: ctx.signal,
3481
+ log: ctx.log
3482
+ }));
3483
+ let channel;
3484
+ let announce;
3485
+ const requests = /* @__PURE__ */ new Map();
3486
+ const resumeBindings = (botId) => {
3487
+ bindings.resume(botId).catch((error) => {
3488
+ if (ctx.signal.aborted && error === ctx.signal.reason) return;
3489
+ ctx.log.warn("Feishu binding resume failed");
3490
+ });
3491
+ };
3492
+ const bots = createBots({
3493
+ store,
3494
+ credentials,
3495
+ createApi,
3496
+ events: (botId) => inbound.eventsFor(botId),
3497
+ onOnline: (botId) => {
3498
+ resumeBindings(botId);
3499
+ },
3500
+ onChanged: () => {
3501
+ announce?.botsChanged();
3502
+ if (channel !== void 0) for (const binding of store.bindings()) announce?.bindingChanged(binding.sessionId);
3503
+ },
3504
+ log: ctx.log
3505
+ });
3506
+ const streamer = createCardStreamer({
3507
+ store,
3508
+ apiOf: (botId) => bindings.ready(botId) ? bots.api(botId) : void 0,
3509
+ onGone: (bindingId) => bindings.markBroken(bindingId, "群已不可用"),
3510
+ log: ctx.log,
3511
+ clock,
3512
+ ...options.throttleMs === void 0 ? {} : { throttleMs: options.throttleMs }
3513
+ });
3514
+ const relay = createRelay({
3515
+ delegation: () => ctx.services.find("session-delegation-observer"),
3516
+ store,
3517
+ streamer,
3518
+ apiOf: (botId) => bindings.ready(botId) ? bots.api(botId) : void 0,
3519
+ channel: () => channel,
3520
+ clock,
3521
+ log: ctx.log,
3522
+ onGone: (bindingId, reason) => bindings.markBroken(bindingId, reason),
3523
+ requests
3524
+ });
3525
+ const members = createMembers({
3526
+ signal: ctx.signal,
3527
+ store,
3528
+ bots,
3529
+ changed: (botId, workspaceId) => {
3530
+ announce?.membersChanged(botId, workspaceId);
3531
+ if (channel !== void 0) announce?.bindingChanged(workspaceId);
3532
+ announce?.botsChanged();
3533
+ },
3534
+ left: (botId, workspaceId, openId) => inbound.withdrawFor(botId, workspaceId, openId),
3535
+ log: ctx.log
3536
+ });
3537
+ const bindings = createBindings({
3538
+ signal: ctx.signal,
3539
+ store,
3540
+ bots,
3541
+ relay,
3542
+ streamer,
3543
+ channel: () => channel,
3544
+ changed: (sessionId) => {
3545
+ announce?.bindingChanged(sessionId);
3546
+ announce?.botsChanged();
3547
+ },
3548
+ withdrawAdmissions: (bindingId) => inbound.withdrawAdmissions(bindingId),
3549
+ groupMade: (botId) => members.reconcile(botId),
3550
+ log: ctx.log
3551
+ });
3552
+ const pairing = createPairing(() => clock.now());
3553
+ const inbound = createInbound({
3554
+ store,
3555
+ bots,
3556
+ members,
3557
+ bindings,
3558
+ relay,
3559
+ requests,
3560
+ commands: createCommands({
3561
+ store,
3562
+ bots,
3563
+ streamer,
3564
+ channel: () => channel,
3565
+ models: () => ctx.services.find("session-model-controls"),
3566
+ context: () => ctx.services.find("session-context-maintenance")
3567
+ }),
3568
+ pairing,
3569
+ channel: () => channel,
3570
+ sessions: ctx.sessions,
3571
+ ownerChanged: (botId) => announce?.ownerPaired(botId),
3572
+ log: ctx.log
3573
+ });
3574
+ announce = registerMethods({
3575
+ ctx,
3576
+ store,
3577
+ bots,
3578
+ members,
3579
+ bindings,
3580
+ relay,
3581
+ pairing,
3582
+ credentials,
3583
+ createApi,
3584
+ channel: () => channel
3585
+ });
3586
+ let offSessions;
3587
+ ctx.channels.register(createFeishuChannel({
3588
+ started: (context) => {
3589
+ channel = context;
3590
+ offSessions = context.onSessionUpdated((session) => bindings.sessionUpdated(session));
3591
+ resumeBindings();
3592
+ },
3593
+ stopped: () => {
3594
+ offSessions?.();
3595
+ offSessions = void 0;
3596
+ relay.stop();
3597
+ channel = void 0;
3598
+ },
3599
+ frame: (frame) => relay.accept(frame)
3600
+ }));
3601
+ const offCredentials = credentials.onChanged((scope) => {
3602
+ if (store.bot(scope) === void 0) return;
3603
+ bots.start(scope);
3604
+ announce?.botsChanged();
3605
+ });
3606
+ bots.startAll();
3607
+ ctx.onDispose(() => {
3608
+ offCredentials();
3609
+ offSessions?.();
3610
+ streamer.stop();
3611
+ relay.stop();
3612
+ bots.stopAll();
3613
+ });
3614
+ const ui = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
3615
+ if (!options.withoutUi && existsSync(ui)) ctx.client.registerUi({ module: ui });
3616
+ }
3617
+ };
3618
+ }
3619
+ const feishuPlugin = createFeishuPlugin();
3620
+ //#endregion
3621
+ export { createFeishuPlugin, feishuPlugin as default, feishuPlugin };