@eum-agent/channel-feishu 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +651 -169
- package/package.json +4 -4
- package/ui/ui.js +4735 -108
package/dist/index.js
CHANGED
|
@@ -4,6 +4,7 @@ import { z } from "zod";
|
|
|
4
4
|
import { randomInt, randomUUID } from "node:crypto";
|
|
5
5
|
import * as Lark from "@larksuiteoapi/node-sdk";
|
|
6
6
|
import { HttpsProxyAgent } from "https-proxy-agent";
|
|
7
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
7
8
|
//#region src/cards/parts.ts
|
|
8
9
|
/** Where a text is cut, so a card stays well under the platform's size cap. */
|
|
9
10
|
const REPLY_LIMIT = 12e3;
|
|
@@ -250,6 +251,16 @@ function renderModelApplied(label) {
|
|
|
250
251
|
});
|
|
251
252
|
}
|
|
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
|
|
253
264
|
//#region src/lark/errors.ts
|
|
254
265
|
/**
|
|
255
266
|
* What a failed Feishu call means for the plugin, read from the open
|
|
@@ -336,7 +347,7 @@ function createBindings(deps) {
|
|
|
336
347
|
const channel = () => {
|
|
337
348
|
deps.signal.throwIfAborted();
|
|
338
349
|
const ctx = deps.channel();
|
|
339
|
-
if (ctx === void 0) throw new
|
|
350
|
+
if (ctx === void 0) throw new FeishuError("飞书通道尚未启动");
|
|
340
351
|
return ctx;
|
|
341
352
|
};
|
|
342
353
|
const sessionOf = async (id) => {
|
|
@@ -383,11 +394,11 @@ function createBindings(deps) {
|
|
|
383
394
|
};
|
|
384
395
|
async function finish(session, botId, chatId) {
|
|
385
396
|
const occupied = deps.store.bindingsOfChat(chatId)[0];
|
|
386
|
-
if (occupied !== void 0 && (occupied.botId !== botId || occupied.sessionId !== session.sessionId)) throw new
|
|
397
|
+
if (occupied !== void 0 && (occupied.botId !== botId || occupied.sessionId !== session.sessionId)) throw new FeishuError("这个群已绑定另一个机器人或会话");
|
|
387
398
|
const existing = deps.store.binding(session.sessionId);
|
|
388
|
-
if (existing !== void 0 && existing.chatId !== chatId) throw new
|
|
399
|
+
if (existing !== void 0 && existing.chatId !== chatId) throw new FeishuError("这个会话已绑定其他群,请先解绑");
|
|
389
400
|
const api = deps.bots.api(botId);
|
|
390
|
-
if (api === void 0) throw new
|
|
401
|
+
if (api === void 0) throw new FeishuError("机器人未连接");
|
|
391
402
|
if (existing === void 0) {
|
|
392
403
|
const cardId = await api.createCard(renderTopic({
|
|
393
404
|
title: titleOf(session),
|
|
@@ -397,10 +408,10 @@ function createBindings(deps) {
|
|
|
397
408
|
url: sessionUrl(channel().webuiUrl, session.sessionId)
|
|
398
409
|
}));
|
|
399
410
|
deps.signal.throwIfAborted();
|
|
400
|
-
if (deps.bots.api(botId) !== api) throw new
|
|
411
|
+
if (deps.bots.api(botId) !== api) throw new FeishuError("bot activation changed");
|
|
401
412
|
const sent = await api.sendCard(chatId, cardId);
|
|
402
413
|
deps.signal.throwIfAborted();
|
|
403
|
-
if (deps.bots.api(botId) !== api) throw new
|
|
414
|
+
if (deps.bots.api(botId) !== api) throw new FeishuError("bot activation changed");
|
|
404
415
|
deps.store.transaction(() => {
|
|
405
416
|
deps.store.insertGroup({
|
|
406
417
|
botId,
|
|
@@ -426,7 +437,7 @@ function createBindings(deps) {
|
|
|
426
437
|
if (group?.memberError !== null && group?.memberError !== void 0) {
|
|
427
438
|
deps.store.setBindingState(session.sessionId, "broken", `成员同步失败:${group.memberError}`);
|
|
428
439
|
deps.changed(session.sessionId);
|
|
429
|
-
throw new
|
|
440
|
+
throw new FeishuError(`成员同步失败:${group.memberError}`);
|
|
430
441
|
}
|
|
431
442
|
deps.store.setBindingState(session.sessionId, session.archived ? "paused" : "active");
|
|
432
443
|
const binding = deps.store.binding(session.sessionId);
|
|
@@ -442,7 +453,7 @@ function createBindings(deps) {
|
|
|
442
453
|
try {
|
|
443
454
|
const occupied = deps.store.bindingsOfChat(chatId)[0];
|
|
444
455
|
if (occupied !== void 0) {
|
|
445
|
-
if (occupied.botId !== botId) throw new
|
|
456
|
+
if (occupied.botId !== botId) throw new FeishuError("绑定冲突:这个群已绑定另一个瑶光机器人");
|
|
446
457
|
const session = await sessionOf(occupied.sessionId);
|
|
447
458
|
if (session !== void 0) {
|
|
448
459
|
if (occupied.state === "broken" || deps.store.group(botId, occupied.sessionId)?.memberError != null) await finish(session, botId, chatId);
|
|
@@ -454,20 +465,20 @@ function createBindings(deps) {
|
|
|
454
465
|
}
|
|
455
466
|
const api = deps.bots.api(botId);
|
|
456
467
|
const bot = deps.store.bot(botId);
|
|
457
|
-
if (bot === void 0 || !bot.enabled || api === void 0) throw new
|
|
468
|
+
if (bot === void 0 || !bot.enabled || api === void 0) throw new FeishuError("机器人未启用或尚未连接");
|
|
458
469
|
const info = await api.getChat(chatId);
|
|
459
470
|
deps.signal.throwIfAborted();
|
|
460
|
-
if (deps.bots.api(botId) !== api) throw new
|
|
461
|
-
if (!info.ordinary) throw new
|
|
462
|
-
if (deps.store.operationsOf(botId).find((one) => one.key.startsWith("outgoing:") && one.chatId === null) !== void 0) throw new
|
|
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("有建群结果待核实,请先恢复原会话的建群操作");
|
|
463
474
|
const history = deps.store.history(botId, chatId);
|
|
464
475
|
const forward = deps.store.operationsOf(botId).find((one) => one.key.startsWith("outgoing:") && one.chatId === chatId);
|
|
465
476
|
let session = await sessionOf(forward?.sessionId ?? operation?.sessionId ?? history?.sessionId ?? "");
|
|
466
|
-
if (forward !== void 0 && session === void 0) throw new
|
|
467
|
-
if (session !== void 0 && deps.store.binding(session.sessionId) !== void 0) throw new
|
|
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("历史会话已绑定其他群,请先在对应会话解绑后重试");
|
|
468
479
|
if (session === void 0) {
|
|
469
|
-
if (bot.defaultAgentId === null || !channel().listAgents().some((one) => one.agentId === bot.defaultAgentId && one.startsSessions !== false)) throw new
|
|
470
|
-
if (bot.defaultWorkspaceId === null || !channel().listWorkspaces().some((one) => one.workspaceId === bot.defaultWorkspaceId)) throw new
|
|
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("请先在管理配置中选择有效的默认工作空间");
|
|
471
482
|
const creationKey = operation?.sessionId ?? randomUUID();
|
|
472
483
|
deps.store.putOperation(key, botId, creationKey, chatId, null);
|
|
473
484
|
session = channel().createSession({
|
|
@@ -495,37 +506,37 @@ function createBindings(deps) {
|
|
|
495
506
|
const row = deps.store.binding(sessionId);
|
|
496
507
|
return row === void 0 ? null : view(row);
|
|
497
508
|
},
|
|
498
|
-
bind(sessionId, botId) {
|
|
509
|
+
bind(sessionId, botId, operationId) {
|
|
499
510
|
return serial(async () => {
|
|
500
511
|
const session = await sessionOf(sessionId);
|
|
501
|
-
if (session === void 0) throw new
|
|
512
|
+
if (session === void 0) throw new FeishuError("找不到这个会话");
|
|
502
513
|
const bot = deps.store.bot(botId);
|
|
503
514
|
const api = deps.bots.api(botId);
|
|
504
|
-
if (bot === void 0 || !bot.enabled || api === void 0) throw new
|
|
505
|
-
if (bot.ownerOpenId === null) throw new
|
|
515
|
+
if (bot === void 0 || !bot.enabled || api === void 0) throw new FeishuError("机器人未连接");
|
|
516
|
+
if (bot.ownerOpenId === null) throw new FeishuError("机器人还没有配对所有者,请先在设置里配对");
|
|
506
517
|
const existing = deps.store.binding(sessionId);
|
|
507
518
|
if (existing !== void 0) {
|
|
508
|
-
if (existing.botId !== botId) throw new
|
|
519
|
+
if (existing.botId !== botId) throw new FeishuError("请先解除当前绑定");
|
|
509
520
|
if (existing.state !== "broken" && deps.store.group(botId, sessionId)?.memberError == null) return view(existing);
|
|
510
521
|
return finish(session, botId, existing.chatId);
|
|
511
522
|
}
|
|
512
523
|
const key = `outgoing:${sessionId}`;
|
|
513
524
|
const operation = deps.store.operation(key);
|
|
514
|
-
if (operation !== void 0 && operation.botId !== botId) throw new
|
|
515
|
-
if (operation !== void 0 && operation.chatId === null) throw new
|
|
525
|
+
if (operation !== void 0 && operation.botId !== botId) throw new FeishuError("之前的建群操作尚未完成,请使用原机器人恢复");
|
|
526
|
+
if (operation !== void 0 && operation.chatId === null) throw new FeishuError("上次建群结果待核实,请确认飞书中的群并在群管理中恢复,不能重复创建");
|
|
516
527
|
let chatId = operation?.chatId ?? void 0;
|
|
517
528
|
try {
|
|
518
529
|
if (chatId === void 0) {
|
|
519
|
-
deps.store.putOperation(key, botId, sessionId, null, "正在创建群,结果尚未确认");
|
|
520
|
-
chatId = await api.createChat(titleOf(session), [bot.ownerOpenId], randomUUID());
|
|
530
|
+
deps.store.putOperation(key, botId, sessionId, null, "正在创建群,结果尚未确认", operationId);
|
|
531
|
+
chatId = await api.createChat(titleOf(session), [bot.ownerOpenId], operationId ?? randomUUID());
|
|
521
532
|
deps.signal.throwIfAborted();
|
|
522
|
-
if (deps.bots.api(botId) !== api) throw new
|
|
533
|
+
if (deps.bots.api(botId) !== api) throw new FeishuError("bot activation changed");
|
|
523
534
|
deps.store.putOperation(key, botId, sessionId, chatId, null);
|
|
524
535
|
}
|
|
525
536
|
const result = await finish(session, botId, chatId);
|
|
526
537
|
deps.signal.throwIfAborted();
|
|
527
538
|
deps.signal.throwIfAborted();
|
|
528
|
-
deps.store.deleteOperation(key);
|
|
539
|
+
if (operationId === void 0) deps.store.deleteOperation(key);
|
|
529
540
|
return result;
|
|
530
541
|
} catch (error) {
|
|
531
542
|
deps.signal.throwIfAborted();
|
|
@@ -534,7 +545,7 @@ function createBindings(deps) {
|
|
|
534
545
|
if (chatId === void 0 && ["scope", "credentials"].includes(classify(error).kind)) deps.store.deleteOperation(key);
|
|
535
546
|
else deps.store.putOperation(key, botId, sessionId, chatId ?? null, reason);
|
|
536
547
|
deps.changed(sessionId);
|
|
537
|
-
throw new
|
|
548
|
+
throw new FeishuError(reason);
|
|
538
549
|
}
|
|
539
550
|
});
|
|
540
551
|
},
|
|
@@ -555,19 +566,19 @@ function createBindings(deps) {
|
|
|
555
566
|
return serial(async () => {
|
|
556
567
|
const key = `outgoing:${sessionId}`;
|
|
557
568
|
const operation = deps.store.operation(key);
|
|
558
|
-
if (operation?.botId !== botId || operation.chatId !== null && operation.chatId !== chatId) throw new
|
|
569
|
+
if (operation?.botId !== botId || operation.chatId !== null && operation.chatId !== chatId) throw new FeishuError("没有待核实的建群操作");
|
|
559
570
|
const session = await sessionOf(sessionId);
|
|
560
|
-
if (session === void 0) throw new
|
|
571
|
+
if (session === void 0) throw new FeishuError("会话不存在");
|
|
561
572
|
const api = deps.bots.api(botId);
|
|
562
|
-
if (api === void 0) throw new
|
|
573
|
+
if (api === void 0) throw new FeishuError("机器人未连接");
|
|
563
574
|
const info = await api.getChat(chatId);
|
|
564
575
|
deps.signal.throwIfAborted();
|
|
565
|
-
if (deps.bots.api(botId) !== api) throw new
|
|
566
|
-
if (!info.ordinary) throw new
|
|
576
|
+
if (deps.bots.api(botId) !== api) throw new FeishuError("bot activation changed");
|
|
577
|
+
if (!info.ordinary) throw new FeishuError("普通群不可用");
|
|
567
578
|
deps.store.putOperation(key, botId, sessionId, chatId, null);
|
|
568
579
|
const result = await finish(session, botId, chatId);
|
|
569
580
|
deps.signal.throwIfAborted();
|
|
570
|
-
deps.store.deleteOperation(key);
|
|
581
|
+
if (!operation?.operationId) deps.store.deleteOperation(key);
|
|
571
582
|
deps.store.deleteOperation(`incoming:${botId}:${chatId}`);
|
|
572
583
|
return result;
|
|
573
584
|
});
|
|
@@ -639,7 +650,7 @@ function createBots(deps) {
|
|
|
639
650
|
api: void 0,
|
|
640
651
|
state: "off",
|
|
641
652
|
reason: null,
|
|
642
|
-
|
|
653
|
+
issues: /* @__PURE__ */ new Map()
|
|
643
654
|
};
|
|
644
655
|
live.set(botId, one);
|
|
645
656
|
}
|
|
@@ -677,7 +688,6 @@ function createBots(deps) {
|
|
|
677
688
|
const api = deps.createApi(bot, secret);
|
|
678
689
|
const one = entry(botId);
|
|
679
690
|
one.api = api;
|
|
680
|
-
one.missing.clear();
|
|
681
691
|
api.connect(deps.events(botId), (state, reason) => {
|
|
682
692
|
if (live.get(botId)?.api !== api) return;
|
|
683
693
|
set(botId, state, state === "failed" ? safeReason(botId, reason ?? "连接失败", secret) : null);
|
|
@@ -703,24 +713,46 @@ function createBots(deps) {
|
|
|
703
713
|
return {
|
|
704
714
|
state: one?.state ?? "off",
|
|
705
715
|
reason: one?.reason ?? null,
|
|
706
|
-
missingScopes: [...one?.
|
|
716
|
+
missingScopes: [...new Set([...one?.issues.values() ?? []].flatMap((issue) => issue.scopes))],
|
|
717
|
+
permissionIssues: [...one?.issues.values() ?? []]
|
|
707
718
|
};
|
|
708
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
|
+
},
|
|
709
732
|
/**
|
|
710
|
-
* Notes what a failed call says about the app. A
|
|
711
|
-
*
|
|
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`.
|
|
712
736
|
* Returns an AppSecret-sanitized reason. Pass the actual call's AppSecret
|
|
713
737
|
* when known so a credential rotation cannot expose the previous secret.
|
|
714
738
|
* Unreadable credentials select a fixed safe explanation.
|
|
715
739
|
*/
|
|
716
|
-
noteFailure(botId, error, appSecret) {
|
|
740
|
+
noteFailure(botId, error, appSecret, operation = "other") {
|
|
717
741
|
const failure = classify(error);
|
|
718
742
|
const reason = safeReason(botId, reasonOf(error), appSecret);
|
|
719
743
|
if (failure.kind === "scope") {
|
|
720
744
|
const one = entry(botId);
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
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);
|
|
724
756
|
}
|
|
725
757
|
if (failure.kind === "credentials") set(botId, "failed", `凭证无效:${reason}`);
|
|
726
758
|
return reason;
|
|
@@ -795,7 +827,11 @@ function createCardStreamer(deps) {
|
|
|
795
827
|
if (final) queue.final = true;
|
|
796
828
|
retryIn = failure.kind === "sequence" ? 0 : Math.min(6e4, 1e3 * 2 ** (queue.failures - 1));
|
|
797
829
|
if (queue.failures >= FINAL_ATTEMPTS) {
|
|
798
|
-
deps.log.
|
|
830
|
+
deps.log.emit({
|
|
831
|
+
level: "warn",
|
|
832
|
+
event: "plugin.event",
|
|
833
|
+
fields: { localCode: "CARD" }
|
|
834
|
+
});
|
|
799
835
|
queue.inFlight = false;
|
|
800
836
|
return drop(queue);
|
|
801
837
|
}
|
|
@@ -1175,12 +1211,18 @@ function readCardContent(port, ref, maxBytes = ref.byteLength) {
|
|
|
1175
1211
|
const chunks = [];
|
|
1176
1212
|
let offset = 0;
|
|
1177
1213
|
while (offset < Math.min(ref.byteLength, maxBytes)) {
|
|
1178
|
-
const
|
|
1214
|
+
const maxPartBytes = Math.max(4, Math.min(65536, maxBytes - offset));
|
|
1215
|
+
const member = port.messageContents({
|
|
1179
1216
|
scope: ref.scope,
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
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;
|
|
1184
1226
|
if (range.sha256 !== ref.sha256 || range.offset !== offset || range.byteLength !== ref.byteLength || range.nextOffset <= offset) throw new Error("Card content source changed");
|
|
1185
1227
|
chunks.push(Buffer.from(range.base64, "base64"));
|
|
1186
1228
|
offset = range.nextOffset;
|
|
@@ -1217,10 +1259,17 @@ async function readCardMessage(channel, sessionId, messageId, historyGeneration)
|
|
|
1217
1259
|
/** The channel id this plugin registers under; a message stamped with it came from here. */
|
|
1218
1260
|
const CHANNEL_ID = "feishu";
|
|
1219
1261
|
const TARGET_PREFIX = "feishu:";
|
|
1262
|
+
const TASK_STATUS = {
|
|
1263
|
+
running: "进行中",
|
|
1264
|
+
done: "完成",
|
|
1265
|
+
stopped: "已停止",
|
|
1266
|
+
failed: "失败",
|
|
1267
|
+
interrupted: "中断"
|
|
1268
|
+
};
|
|
1220
1269
|
function statusOf(outcome) {
|
|
1221
1270
|
if (outcome === null || outcome === void 0) return { status: "interrupted" };
|
|
1222
1271
|
if (outcome.kind === "completed") return { status: "done" };
|
|
1223
|
-
if (outcome.kind === "interrupted") return { status: "stopped" };
|
|
1272
|
+
if (outcome.kind === "interrupted" || outcome.kind === "stopped") return { status: "stopped" };
|
|
1224
1273
|
return {
|
|
1225
1274
|
status: "failed",
|
|
1226
1275
|
failure: outcome.reason
|
|
@@ -1261,6 +1310,8 @@ function wordsOf(message) {
|
|
|
1261
1310
|
function createRelay(deps) {
|
|
1262
1311
|
const watched = /* @__PURE__ */ new Map();
|
|
1263
1312
|
const generations = /* @__PURE__ */ new Map();
|
|
1313
|
+
let delegationRefreshScheduled = false;
|
|
1314
|
+
let stopped = false;
|
|
1264
1315
|
/** Requests this plugin's own card submitted, so their record says "here". */
|
|
1265
1316
|
const answeredHere = /* @__PURE__ */ new Set();
|
|
1266
1317
|
const bindingOf = (bindingId) => {
|
|
@@ -1295,7 +1346,11 @@ function createRelay(deps) {
|
|
|
1295
1346
|
};
|
|
1296
1347
|
} catch (error) {
|
|
1297
1348
|
if (classify(error).kind === "gone") deps.onGone(binding.sessionId, "群已不可用");
|
|
1298
|
-
else deps.log.
|
|
1349
|
+
else deps.log.emit({
|
|
1350
|
+
level: "warn",
|
|
1351
|
+
event: "plugin.event",
|
|
1352
|
+
fields: { localCode: "POSTING_A" }
|
|
1353
|
+
});
|
|
1299
1354
|
return;
|
|
1300
1355
|
}
|
|
1301
1356
|
}
|
|
@@ -1382,7 +1437,7 @@ function createRelay(deps) {
|
|
|
1382
1437
|
const run = entry.run;
|
|
1383
1438
|
if (run === void 0 || parentSessionId !== entry.sessionId) return;
|
|
1384
1439
|
const agent = deps.channel()?.listAgents().find((one) => one.agentId === task.agent)?.name ?? task.agent;
|
|
1385
|
-
const state = task.state === "finished" ? task.outcome
|
|
1440
|
+
const state = task.state === "finished" ? TASK_STATUS[statusOf(task.outcome).status] : "进行中";
|
|
1386
1441
|
const line = {
|
|
1387
1442
|
taskId: task.taskId,
|
|
1388
1443
|
agent,
|
|
@@ -1406,6 +1461,51 @@ function createRelay(deps) {
|
|
|
1406
1461
|
from: agent
|
|
1407
1462
|
});
|
|
1408
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
|
+
}
|
|
1409
1509
|
function accept(frame) {
|
|
1410
1510
|
const entry = watched.get(frame.sessionId);
|
|
1411
1511
|
const channel = deps.channel();
|
|
@@ -1418,26 +1518,26 @@ function createRelay(deps) {
|
|
|
1418
1518
|
if (frame.kind === "session.asyncAsked") request = JSON.parse(readCardContent(channel, frame.request.contentRef));
|
|
1419
1519
|
if ((frame.kind === "session.humanAnswered" || frame.kind === "session.asyncSettled") && frame.replyRef) reply = JSON.parse(readCardContent(channel, frame.replyRef));
|
|
1420
1520
|
} catch (error) {
|
|
1421
|
-
deps.log.
|
|
1521
|
+
deps.log.emit({
|
|
1522
|
+
level: "warn",
|
|
1523
|
+
event: "plugin.event",
|
|
1524
|
+
fields: { localCode: "READING_A_CHANNEL_REQUEST_FAILED" }
|
|
1525
|
+
});
|
|
1422
1526
|
}
|
|
1423
1527
|
entry.tail = entry.tail.then(() => acceptOrdered(entry, frame, requests, request, reply)).catch((error) => {
|
|
1424
|
-
deps.log.
|
|
1528
|
+
deps.log.emit({
|
|
1529
|
+
level: "warn",
|
|
1530
|
+
event: "plugin.event",
|
|
1531
|
+
fields: { localCode: "READING_SESSION_ACTIVITY_FAILED" }
|
|
1532
|
+
});
|
|
1425
1533
|
});
|
|
1426
1534
|
}
|
|
1427
1535
|
async function acceptOrdered(entry, frame, requests, request, reply) {
|
|
1428
1536
|
if (watched.get(frame.sessionId) !== entry) return;
|
|
1429
1537
|
const changed = deps.delegation?.()?.project(frame);
|
|
1430
1538
|
if (changed) {
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
if (root) followDescendant(root, changed.task);
|
|
1434
|
-
if (changed.task.state === "finished") {
|
|
1435
|
-
const child = watched.get(changed.task.childSessionId);
|
|
1436
|
-
if (child && !child.root) {
|
|
1437
|
-
child.unwatch();
|
|
1438
|
-
watched.delete(child.sessionId);
|
|
1439
|
-
}
|
|
1440
|
-
}
|
|
1539
|
+
if (changed.invalidated) refreshDelegation();
|
|
1540
|
+
else for (const change of changed.entries) projectTask(entry, change.task);
|
|
1441
1541
|
return;
|
|
1442
1542
|
}
|
|
1443
1543
|
if (frame.kind === "session.historyReplaced") {
|
|
@@ -1695,7 +1795,8 @@ function createRelay(deps) {
|
|
|
1695
1795
|
historyGeneration: 0,
|
|
1696
1796
|
tail: Promise.resolve(),
|
|
1697
1797
|
run: void 0,
|
|
1698
|
-
ignoreTurn: false
|
|
1798
|
+
ignoreTurn: false,
|
|
1799
|
+
delegationRevisions: /* @__PURE__ */ new Map()
|
|
1699
1800
|
};
|
|
1700
1801
|
watched.set(sessionId, entry);
|
|
1701
1802
|
const { snapshot, unwatch } = channel.watch(`${TARGET_PREFIX}${bindingId}`, sessionId);
|
|
@@ -1706,10 +1807,6 @@ function createRelay(deps) {
|
|
|
1706
1807
|
entry.ignoreTurn = options.root && snapshot.live.phase !== "idle" && (options.fresh === true || (snapshot.window.turns.at(-1)?.startedAt ?? 0) < boundary);
|
|
1707
1808
|
entry.tail = reconcile(entry, snapshot);
|
|
1708
1809
|
await entry.tail;
|
|
1709
|
-
if (options.root) try {
|
|
1710
|
-
deps.delegation?.()?.list(sessionId);
|
|
1711
|
-
if (watched.get(sessionId) !== entry || entry.ignoreTurn) return;
|
|
1712
|
-
} catch {}
|
|
1713
1810
|
}
|
|
1714
1811
|
return {
|
|
1715
1812
|
accept,
|
|
@@ -1734,6 +1831,7 @@ function createRelay(deps) {
|
|
|
1734
1831
|
answeredHere: (requestId) => answeredHere.add(requestId),
|
|
1735
1832
|
watching: (sessionId) => watched.has(sessionId),
|
|
1736
1833
|
stop() {
|
|
1834
|
+
stopped = true;
|
|
1737
1835
|
for (const entry of watched.values()) entry.unwatch();
|
|
1738
1836
|
watched.clear();
|
|
1739
1837
|
}
|
|
@@ -2135,6 +2233,50 @@ function query(params) {
|
|
|
2135
2233
|
const text = search.toString();
|
|
2136
2234
|
return text === "" ? "" : `?${text}`;
|
|
2137
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
|
+
}
|
|
2138
2280
|
/** Binds SDK HTTP requests to timeout and activation cancellation. */
|
|
2139
2281
|
function createFetchHttpInstance(fetch, lifetime) {
|
|
2140
2282
|
async function request(opts) {
|
|
@@ -2156,7 +2298,7 @@ function createFetchHttpInstance(fetch, lifetime) {
|
|
|
2156
2298
|
...signal === void 0 ? {} : { signal }
|
|
2157
2299
|
});
|
|
2158
2300
|
lifetime?.throwIfAborted();
|
|
2159
|
-
const text = await response
|
|
2301
|
+
const text = await boundedBody(response, signal);
|
|
2160
2302
|
lifetime?.throwIfAborted();
|
|
2161
2303
|
let data = text;
|
|
2162
2304
|
try {
|
|
@@ -2228,8 +2370,16 @@ function createLarkClient(options) {
|
|
|
2228
2370
|
const lifetime = options.signal ? AbortSignal.any([requests.signal, options.signal]) : requests.signal;
|
|
2229
2371
|
const httpInstance = createFetchHttpInstance(options.network.fetch, lifetime);
|
|
2230
2372
|
const logger = {
|
|
2231
|
-
error: (...args) => options.log.
|
|
2232
|
-
|
|
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
|
+
}),
|
|
2233
2383
|
info: () => {},
|
|
2234
2384
|
debug: () => {},
|
|
2235
2385
|
trace: () => {}
|
|
@@ -2522,14 +2672,15 @@ function createMembers(deps) {
|
|
|
2522
2672
|
try {
|
|
2523
2673
|
const name = await api.userName(openId);
|
|
2524
2674
|
deps.signal.throwIfAborted();
|
|
2525
|
-
if (deps.bots.api(botId) !== api) throw new
|
|
2675
|
+
if (deps.bots.api(botId) !== api) throw new FeishuError("bot activation changed");
|
|
2676
|
+
deps.bots.noteNameSuccess(botId);
|
|
2526
2677
|
if (name === void 0 || name === "") return fallback;
|
|
2527
2678
|
names.set(`${botId}:${openId}`, name);
|
|
2528
2679
|
return name;
|
|
2529
2680
|
} catch (error) {
|
|
2530
2681
|
deps.signal.throwIfAborted();
|
|
2531
2682
|
if (deps.bots.api(botId) !== api) throw error;
|
|
2532
|
-
deps.bots.noteFailure(botId, error);
|
|
2683
|
+
deps.bots.noteFailure(botId, error, void 0, "userName");
|
|
2533
2684
|
return fallback;
|
|
2534
2685
|
}
|
|
2535
2686
|
}
|
|
@@ -2618,9 +2769,36 @@ function createMembers(deps) {
|
|
|
2618
2769
|
deps.changed(botId, group.sessionId);
|
|
2619
2770
|
})));
|
|
2620
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
|
+
},
|
|
2621
2799
|
setPolicy(botId, sessionId, openId, policy) {
|
|
2622
|
-
if (ownerOf(botId) === openId) throw new
|
|
2623
|
-
if (deps.store.member(botId, sessionId, openId) === void 0) throw new
|
|
2800
|
+
if (ownerOf(botId) === openId) throw new FeishuError("所有者在各群固定为 Accept");
|
|
2801
|
+
if (deps.store.member(botId, sessionId, openId) === void 0) throw new FeishuError("这个人已不在群里");
|
|
2624
2802
|
deps.store.setPolicy(botId, sessionId, openId, policy);
|
|
2625
2803
|
if (policy === "reject") deps.left(botId, sessionId, openId);
|
|
2626
2804
|
deps.changed(botId, sessionId);
|
|
@@ -2629,16 +2807,16 @@ function createMembers(deps) {
|
|
|
2629
2807
|
/** Takes a person out of the Feishu group, then off the list. A refusal
|
|
2630
2808
|
* leaves them there as `reject`, with the reason recorded. */
|
|
2631
2809
|
remove(botId, sessionId, openId) {
|
|
2632
|
-
if (ownerOf(botId) === openId) return Promise.reject(
|
|
2810
|
+
if (ownerOf(botId) === openId) return Promise.reject(new FeishuError("所有者在各群固定为 Accept"));
|
|
2633
2811
|
const group = deps.store.group(botId, sessionId);
|
|
2634
|
-
if (group === void 0) return Promise.reject(
|
|
2812
|
+
if (group === void 0) return Promise.reject(new FeishuError("这个普通群不存在"));
|
|
2635
2813
|
return serial(group.chatId, async () => {
|
|
2636
2814
|
const api = deps.bots.api(botId);
|
|
2637
2815
|
try {
|
|
2638
|
-
if (api === void 0) throw new
|
|
2816
|
+
if (api === void 0) throw new FeishuError("机器人未连接");
|
|
2639
2817
|
await api.removeMembers(group.chatId, [openId]);
|
|
2640
2818
|
deps.signal.throwIfAborted();
|
|
2641
|
-
if (deps.bots.api(botId) !== api) throw new
|
|
2819
|
+
if (deps.bots.api(botId) !== api) throw new FeishuError("bot activation changed");
|
|
2642
2820
|
deps.store.deleteMember(botId, sessionId, openId);
|
|
2643
2821
|
deps.left(botId, sessionId, openId);
|
|
2644
2822
|
deps.store.setMemberError(group.chatId, null);
|
|
@@ -2651,7 +2829,7 @@ function createMembers(deps) {
|
|
|
2651
2829
|
deps.left(botId, sessionId, openId);
|
|
2652
2830
|
deps.store.setMemberError(group.chatId, `移出失败:${reason}`);
|
|
2653
2831
|
deps.changed(botId, sessionId);
|
|
2654
|
-
throw new
|
|
2832
|
+
throw new FeishuError(`移出失败,已改为 Reject:${reason}`);
|
|
2655
2833
|
}
|
|
2656
2834
|
});
|
|
2657
2835
|
},
|
|
@@ -2671,12 +2849,8 @@ function createMembers(deps) {
|
|
|
2671
2849
|
};
|
|
2672
2850
|
}
|
|
2673
2851
|
//#endregion
|
|
2674
|
-
//#region src/
|
|
2675
|
-
/**
|
|
2676
|
-
* The wire methods and frames the browser module calls. No credential crosses any of them: the AppSecret is written by
|
|
2677
|
-
* the page through `WebContext.credentials` and read here where it is used.
|
|
2678
|
-
*/
|
|
2679
|
-
const Empty = z.object({}).strict();
|
|
2852
|
+
//#region src/schema.ts
|
|
2853
|
+
/** Browser-safe authoritative Feishu collection and business declarations. */
|
|
2680
2854
|
const MemberSchema = z.object({
|
|
2681
2855
|
openId: z.string(),
|
|
2682
2856
|
name: z.string(),
|
|
@@ -2712,6 +2886,11 @@ const BotSchema = z.object({
|
|
|
2712
2886
|
]),
|
|
2713
2887
|
reason: z.string().nullable(),
|
|
2714
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()),
|
|
2715
2894
|
bindings: z.number(),
|
|
2716
2895
|
pending: z.array(z.object({
|
|
2717
2896
|
key: z.string(),
|
|
@@ -2745,6 +2924,140 @@ const BindingSchema = z.object({
|
|
|
2745
2924
|
reason: z.string().nullable(),
|
|
2746
2925
|
chatUrl: z.string()
|
|
2747
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();
|
|
2748
3061
|
const SaveBot = z.object({
|
|
2749
3062
|
id: z.string().min(1).optional(),
|
|
2750
3063
|
name: z.string().trim().min(1).max(40),
|
|
@@ -2753,14 +3066,11 @@ const SaveBot = z.object({
|
|
|
2753
3066
|
defaultAgentId: z.string().min(1).nullable().optional(),
|
|
2754
3067
|
defaultWorkspaceId: z.string().min(1).nullable().optional()
|
|
2755
3068
|
}).strict();
|
|
2756
|
-
const Id = z.object({ id: z.string().min(1) }).strict();
|
|
2757
3069
|
const BotId = z.object({ botId: z.string().min(1) }).strict();
|
|
2758
3070
|
const Group = z.object({
|
|
2759
3071
|
botId: z.string().min(1),
|
|
2760
3072
|
sessionId: z.string().min(1)
|
|
2761
3073
|
}).strict();
|
|
2762
|
-
const MemberKey = Group.extend({ openId: z.string().min(1) }).strict();
|
|
2763
|
-
const Session = z.object({ sessionId: z.string().min(1) }).strict();
|
|
2764
3074
|
function registerMethods(deps) {
|
|
2765
3075
|
const { ctx, store } = deps;
|
|
2766
3076
|
const botsChanged = ctx.client.registerFrame({
|
|
@@ -2784,6 +3094,88 @@ function registerMethods(deps) {
|
|
|
2784
3094
|
binding: BindingSchema.nullable()
|
|
2785
3095
|
}).strict()
|
|
2786
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
|
+
});
|
|
2787
3179
|
const sessionName = (sessionId) => deps.channel()?.getReadingSessionSummary(sessionId)?.name ?? sessionId;
|
|
2788
3180
|
function secretOf(botId) {
|
|
2789
3181
|
try {
|
|
@@ -2820,6 +3212,10 @@ function registerMethods(deps) {
|
|
|
2820
3212
|
status: status.state,
|
|
2821
3213
|
reason: status.reason,
|
|
2822
3214
|
missingScopes: [...status.missingScopes],
|
|
3215
|
+
permissionIssues: status.permissionIssues.map((issue) => ({
|
|
3216
|
+
...issue,
|
|
3217
|
+
scopes: [...issue.scopes]
|
|
3218
|
+
})),
|
|
2823
3219
|
bindings: store.bindingsOfBot(bot.id).length,
|
|
2824
3220
|
groups: store.groupsOf(bot.id).map((group) => ({
|
|
2825
3221
|
sessionId: group.sessionId,
|
|
@@ -2833,7 +3229,7 @@ function registerMethods(deps) {
|
|
|
2833
3229
|
const summaries = () => store.bots().map(summary);
|
|
2834
3230
|
const require = (id) => {
|
|
2835
3231
|
const bot = store.bot(id);
|
|
2836
|
-
if (bot === void 0) throw new
|
|
3232
|
+
if (bot === void 0) throw new FeishuError("找不到这个机器人");
|
|
2837
3233
|
return bot;
|
|
2838
3234
|
};
|
|
2839
3235
|
const member = (botId, sessionId, openId) => {
|
|
@@ -2847,6 +3243,20 @@ function registerMethods(deps) {
|
|
|
2847
3243
|
joinedAt: row.joinedAt
|
|
2848
3244
|
};
|
|
2849
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
|
+
};
|
|
2850
3260
|
ctx.client.registerMethod({
|
|
2851
3261
|
name: "listDefaults",
|
|
2852
3262
|
params: Empty,
|
|
@@ -2879,22 +3289,31 @@ function registerMethods(deps) {
|
|
|
2879
3289
|
chatId: z.string().trim().min(1)
|
|
2880
3290
|
}).strict(),
|
|
2881
3291
|
result: BindingSchema,
|
|
2882
|
-
handle
|
|
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
|
+
}
|
|
2883
3305
|
});
|
|
2884
3306
|
ctx.client.registerMethod({
|
|
2885
|
-
name: "
|
|
2886
|
-
params:
|
|
2887
|
-
|
|
2888
|
-
|
|
2889
|
-
}).strict(),
|
|
2890
|
-
result: Empty,
|
|
2891
|
-
async handle({ botId, chatId }) {
|
|
3307
|
+
name: "retryGroups",
|
|
3308
|
+
params: RetryGroupsParams,
|
|
3309
|
+
result: RetryGroupsResult,
|
|
3310
|
+
handle: ({ botId, chatIds }) => collection(chatIds, async (chatId) => {
|
|
2892
3311
|
require(botId);
|
|
2893
3312
|
await deps.bindings.retryGroup(botId, chatId);
|
|
2894
3313
|
ctx.signal.throwIfAborted();
|
|
2895
|
-
|
|
3314
|
+
announceBots();
|
|
2896
3315
|
return {};
|
|
2897
|
-
}
|
|
3316
|
+
})
|
|
2898
3317
|
});
|
|
2899
3318
|
ctx.client.registerMethod({
|
|
2900
3319
|
name: "listBots",
|
|
@@ -2928,10 +3347,10 @@ function registerMethods(deps) {
|
|
|
2928
3347
|
}
|
|
2929
3348
|
});
|
|
2930
3349
|
ctx.client.registerMethod({
|
|
2931
|
-
name: "
|
|
2932
|
-
params:
|
|
2933
|
-
result:
|
|
2934
|
-
|
|
3350
|
+
name: "removeBots",
|
|
3351
|
+
params: RemoveBotsParams,
|
|
3352
|
+
result: RemoveBotsResult,
|
|
3353
|
+
handle: ({ ids }) => collection(ids, async (id) => {
|
|
2935
3354
|
require(id);
|
|
2936
3355
|
const sessions = store.bindingsOfBot(id).map((one) => one.sessionId);
|
|
2937
3356
|
for (const sessionId of sessions) {
|
|
@@ -2940,23 +3359,20 @@ function registerMethods(deps) {
|
|
|
2940
3359
|
}
|
|
2941
3360
|
deps.bots.stop(id);
|
|
2942
3361
|
store.removeBot(id);
|
|
2943
|
-
deps.credentials.
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
3362
|
+
deps.credentials.clearMany([{
|
|
3363
|
+
scope: id,
|
|
3364
|
+
mode: "all"
|
|
3365
|
+
}]);
|
|
3366
|
+
for (const sessionId of sessions) announceBinding(sessionId);
|
|
3367
|
+
announceBots();
|
|
2949
3368
|
return {};
|
|
2950
|
-
}
|
|
3369
|
+
})
|
|
2951
3370
|
});
|
|
2952
3371
|
ctx.client.registerMethod({
|
|
2953
|
-
name: "
|
|
2954
|
-
params:
|
|
2955
|
-
result:
|
|
2956
|
-
|
|
2957
|
-
reason: z.string()
|
|
2958
|
-
}).strict()]),
|
|
2959
|
-
async handle({ id }) {
|
|
3372
|
+
name: "testBots",
|
|
3373
|
+
params: TestBotsParams,
|
|
3374
|
+
result: TestBotsResult,
|
|
3375
|
+
handle: ({ ids }) => collection(ids, async (id) => {
|
|
2960
3376
|
const bot = require(id);
|
|
2961
3377
|
let secret;
|
|
2962
3378
|
try {
|
|
@@ -2977,12 +3393,13 @@ function registerMethods(deps) {
|
|
|
2977
3393
|
return { ok: true };
|
|
2978
3394
|
} catch (error) {
|
|
2979
3395
|
ctx.signal.throwIfAborted();
|
|
3396
|
+
if (error instanceof Error && "code" in error && error.code === "read-limit") throw error;
|
|
2980
3397
|
return {
|
|
2981
3398
|
ok: false,
|
|
2982
|
-
reason:
|
|
3399
|
+
reason: reasonOf(error).replaceAll(secret, "****").slice(0, 512).replace(/[\uD800-\uDBFF]$/u, "")
|
|
2983
3400
|
};
|
|
2984
3401
|
}
|
|
2985
|
-
}
|
|
3402
|
+
})
|
|
2986
3403
|
});
|
|
2987
3404
|
ctx.client.registerMethod({
|
|
2988
3405
|
name: "startPairing",
|
|
@@ -3013,26 +3430,35 @@ function registerMethods(deps) {
|
|
|
3013
3430
|
}
|
|
3014
3431
|
});
|
|
3015
3432
|
ctx.client.registerMethod({
|
|
3016
|
-
name: "
|
|
3017
|
-
params:
|
|
3018
|
-
|
|
3019
|
-
|
|
3020
|
-
|
|
3021
|
-
|
|
3022
|
-
|
|
3023
|
-
|
|
3024
|
-
|
|
3025
|
-
|
|
3026
|
-
|
|
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
|
+
}))
|
|
3027
3452
|
});
|
|
3028
3453
|
ctx.client.registerMethod({
|
|
3029
|
-
name: "
|
|
3030
|
-
params:
|
|
3031
|
-
result:
|
|
3032
|
-
|
|
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 };
|
|
3033
3459
|
await deps.members.remove(botId, sessionId, openId);
|
|
3034
|
-
return {};
|
|
3035
|
-
}
|
|
3460
|
+
return { removed: true };
|
|
3461
|
+
})
|
|
3036
3462
|
});
|
|
3037
3463
|
ctx.client.registerMethod({
|
|
3038
3464
|
name: "listBindings",
|
|
@@ -3041,41 +3467,81 @@ function registerMethods(deps) {
|
|
|
3041
3467
|
handle: () => store.bindings().map((one) => deps.bindings.view(one.sessionId)).filter((one) => one !== null)
|
|
3042
3468
|
});
|
|
3043
3469
|
ctx.client.registerMethod({
|
|
3044
|
-
name: "
|
|
3045
|
-
params:
|
|
3046
|
-
result:
|
|
3047
|
-
handle: ({
|
|
3470
|
+
name: "getBindings",
|
|
3471
|
+
params: GetBindingsParams,
|
|
3472
|
+
result: GetBindingsResult,
|
|
3473
|
+
handle: ({ sessionIds, maxItemBytes }) => collection(sessionIds, (sessionId) => deps.bindings.view(sessionId), maxItemBytes)
|
|
3048
3474
|
});
|
|
3049
3475
|
ctx.client.registerMethod({
|
|
3050
|
-
name: "
|
|
3051
|
-
params:
|
|
3052
|
-
result:
|
|
3053
|
-
handle: ({
|
|
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
|
+
})
|
|
3054
3526
|
});
|
|
3055
3527
|
ctx.client.registerMethod({
|
|
3056
|
-
name: "
|
|
3057
|
-
params:
|
|
3058
|
-
result:
|
|
3059
|
-
|
|
3528
|
+
name: "unbindSessions",
|
|
3529
|
+
params: UnbindSessionsParams,
|
|
3530
|
+
result: UnbindSessionsResult,
|
|
3531
|
+
handle: ({ sessionIds }) => collection(sessionIds, async (sessionId) => {
|
|
3060
3532
|
await deps.bindings.unbind(sessionId);
|
|
3061
3533
|
return {};
|
|
3062
|
-
}
|
|
3534
|
+
})
|
|
3063
3535
|
});
|
|
3064
3536
|
return {
|
|
3065
|
-
botsChanged:
|
|
3537
|
+
botsChanged: announceBots,
|
|
3066
3538
|
/** Marks successful code consumption, including pairing with the same owner. */
|
|
3067
3539
|
ownerPaired: (botId) => botsChanged.emit({
|
|
3068
3540
|
bots: summaries(),
|
|
3069
3541
|
pairedBotId: botId
|
|
3070
3542
|
}),
|
|
3071
|
-
membersChanged:
|
|
3072
|
-
|
|
3073
|
-
sessionId
|
|
3074
|
-
}),
|
|
3075
|
-
bindingChanged: (sessionId) => bindingChanged.emit({
|
|
3076
|
-
sessionId,
|
|
3077
|
-
binding: deps.bindings.view(sessionId)
|
|
3078
|
-
})
|
|
3543
|
+
membersChanged: announceMembers,
|
|
3544
|
+
bindingChanged: announceBinding
|
|
3079
3545
|
};
|
|
3080
3546
|
}
|
|
3081
3547
|
//#endregion
|
|
@@ -3125,8 +3591,11 @@ function createFeishuStore(storage, now = Date.now) {
|
|
|
3125
3591
|
const members = tableName("member");
|
|
3126
3592
|
const bindings = tableName("binding");
|
|
3127
3593
|
const cards = tableName("card");
|
|
3594
|
+
const operations = tableName("group_operation");
|
|
3128
3595
|
const columns = db.prepare(`PRAGMA table_info(${bots})`).all();
|
|
3129
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.");
|
|
3130
3599
|
db.exec(`CREATE TABLE IF NOT EXISTS ${bots} (
|
|
3131
3600
|
id TEXT NOT NULL PRIMARY KEY,
|
|
3132
3601
|
name TEXT NOT NULL,
|
|
@@ -3183,7 +3652,6 @@ CREATE TABLE IF NOT EXISTS ${cards} (
|
|
|
3183
3652
|
) STRICT;
|
|
3184
3653
|
CREATE INDEX IF NOT EXISTS ${tableName("card_open")} ON ${cards} (state, binding_id);
|
|
3185
3654
|
CREATE UNIQUE INDEX IF NOT EXISTS ${tableName("card_ref")} ON ${cards} (binding_id, kind, ref);`);
|
|
3186
|
-
const operations = tableName("group_operation");
|
|
3187
3655
|
const events = tableName("group_event");
|
|
3188
3656
|
const lifecycle = tableName("group_lifecycle");
|
|
3189
3657
|
db.exec(`CREATE TABLE IF NOT EXISTS ${lifecycle} (
|
|
@@ -3195,6 +3663,7 @@ CREATE UNIQUE INDEX IF NOT EXISTS ${tableName("card_ref")} ON ${cards} (binding_
|
|
|
3195
3663
|
CREATE UNIQUE INDEX IF NOT EXISTS ${tableName("current_group")} ON ${groups} (chat_id) WHERE state != 'unbound';
|
|
3196
3664
|
CREATE TABLE IF NOT EXISTS ${operations} (
|
|
3197
3665
|
operation_key TEXT NOT NULL PRIMARY KEY,
|
|
3666
|
+
operation_uuid TEXT,
|
|
3198
3667
|
bot_id TEXT NOT NULL,
|
|
3199
3668
|
session_id TEXT,
|
|
3200
3669
|
chat_id TEXT,
|
|
@@ -3284,6 +3753,8 @@ CREATE UNIQUE INDEX IF NOT EXISTS ${tableName("card_ref")} ON ${cards} (binding_
|
|
|
3284
3753
|
return row === void 0 ? void 0 : binding(row);
|
|
3285
3754
|
};
|
|
3286
3755
|
return {
|
|
3756
|
+
/** Same physical host connection used by owner operation settlement. */
|
|
3757
|
+
connectionIdentity: storage.connectionIdentity,
|
|
3287
3758
|
transaction,
|
|
3288
3759
|
now,
|
|
3289
3760
|
acceptLifecycle(botId, chatId, at) {
|
|
@@ -3299,6 +3770,7 @@ CREATE UNIQUE INDEX IF NOT EXISTS ${tableName("card_ref")} ON ${cards} (binding_
|
|
|
3299
3770
|
const row = first(`SELECT * FROM ${operations} WHERE operation_key = ?`, key);
|
|
3300
3771
|
return row === void 0 ? void 0 : {
|
|
3301
3772
|
key,
|
|
3773
|
+
operationId: str(row.operation_uuid),
|
|
3302
3774
|
botId: String(row.bot_id),
|
|
3303
3775
|
sessionId: str(row.session_id),
|
|
3304
3776
|
chatId: str(row.chat_id),
|
|
@@ -3313,8 +3785,8 @@ CREATE UNIQUE INDEX IF NOT EXISTS ${tableName("card_ref")} ON ${cards} (binding_
|
|
|
3313
3785
|
error: str(row.error)
|
|
3314
3786
|
}));
|
|
3315
3787
|
},
|
|
3316
|
-
putOperation(key, botId, sessionId, chatId, error) {
|
|
3317
|
-
db.prepare(`INSERT INTO ${operations} (operation_key, bot_id, session_id, chat_id, error, updated_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (operation_key) DO UPDATE SET session_id = excluded.session_id, chat_id = excluded.chat_id, error = excluded.error, updated_at = excluded.updated_at`).run(key, botId, sessionId, chatId, error, now());
|
|
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());
|
|
3318
3790
|
},
|
|
3319
3791
|
deleteOperation(key) {
|
|
3320
3792
|
db.prepare(`DELETE FROM ${operations} WHERE operation_key = ?`).run(key);
|
|
@@ -3462,7 +3934,12 @@ function createFeishuPlugin(options = {}) {
|
|
|
3462
3934
|
return {
|
|
3463
3935
|
name: "@eum-agent/channel-feishu",
|
|
3464
3936
|
configSchema: Config,
|
|
3465
|
-
requires: [
|
|
3937
|
+
requires: [
|
|
3938
|
+
"credentials",
|
|
3939
|
+
"network",
|
|
3940
|
+
"owner-operations",
|
|
3941
|
+
"unit-of-work"
|
|
3942
|
+
],
|
|
3466
3943
|
optionalServices: [
|
|
3467
3944
|
"session-model-controls",
|
|
3468
3945
|
"session-context-maintenance",
|
|
@@ -3486,7 +3963,11 @@ function createFeishuPlugin(options = {}) {
|
|
|
3486
3963
|
const resumeBindings = (botId) => {
|
|
3487
3964
|
bindings.resume(botId).catch((error) => {
|
|
3488
3965
|
if (ctx.signal.aborted && error === ctx.signal.reason) return;
|
|
3489
|
-
ctx.log.
|
|
3966
|
+
ctx.log.emit({
|
|
3967
|
+
level: "warn",
|
|
3968
|
+
event: "plugin.event",
|
|
3969
|
+
fields: { localCode: "FEISHU_BINDING_RESUME_FAILED" }
|
|
3970
|
+
});
|
|
3490
3971
|
});
|
|
3491
3972
|
};
|
|
3492
3973
|
const bots = createBots({
|
|
@@ -3512,6 +3993,7 @@ function createFeishuPlugin(options = {}) {
|
|
|
3512
3993
|
...options.throttleMs === void 0 ? {} : { throttleMs: options.throttleMs }
|
|
3513
3994
|
});
|
|
3514
3995
|
const relay = createRelay({
|
|
3996
|
+
sameDelegation: (left, right) => ctx.services.same(left, right),
|
|
3515
3997
|
delegation: () => ctx.services.find("session-delegation-observer"),
|
|
3516
3998
|
store,
|
|
3517
3999
|
streamer,
|
|
@@ -3598,10 +4080,10 @@ function createFeishuPlugin(options = {}) {
|
|
|
3598
4080
|
},
|
|
3599
4081
|
frame: (frame) => relay.accept(frame)
|
|
3600
4082
|
}));
|
|
3601
|
-
const offCredentials = credentials.onChanged((
|
|
3602
|
-
|
|
3603
|
-
bots.start(scope);
|
|
3604
|
-
announce?.botsChanged();
|
|
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();
|
|
3605
4087
|
});
|
|
3606
4088
|
bots.startAll();
|
|
3607
4089
|
ctx.onDispose(() => {
|