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