openclaw-lark-multi-agent 1.8.18 → 1.8.19

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.
@@ -18,6 +18,7 @@ import { basename, extname, join, resolve } from "path";
18
18
  import { getBridgeAttachmentsDir, getDataDir } from "./paths.js";
19
19
  import { buildFeishuCardElements } from "./markdown.js";
20
20
  import { discussionManager } from "./discussion-manager.js";
21
+ import { requestBotIdentity, trustedBotOpenId } from "./bot-identity.js";
21
22
  /** Observation deadline, never a claim that the underlying SDK was cancelled. */
22
23
  export class SendDeadlineError extends Error {
23
24
  chatId;
@@ -34,6 +35,9 @@ const canonicalPhysicalSessionKey = (key) => /^agent:[^:]+:/.test(key) ? key : `
34
35
  const require = createRequire(import.meta.url);
35
36
  const LMA_VERSION = require("../package.json").version;
36
37
  const MAX_BOT_STREAK = 10;
38
+ const IDENTITY_DEADLINE_MS = 2_000;
39
+ const IDENTITY_RETRY_BASE_MS = 5_000;
40
+ const IDENTITY_RETRY_CAP_MS = 5 * 60_000;
37
41
  const MAX_MERGED_TRIGGER_MESSAGES = Number(process.env.OPENCLAW_LARK_MULTI_AGENT_MAX_MERGED_TRIGGER_MESSAGES || 100);
38
42
  const MAX_MERGED_TRIGGER_BYTES = Number(process.env.OPENCLAW_LARK_MULTI_AGENT_MAX_MERGED_TRIGGER_BYTES || 128 * 1024);
39
43
  const BRIDGE_ATTACHMENTS_DIR = getBridgeAttachmentsDir();
@@ -134,6 +138,21 @@ export class FeishuBot {
134
138
  openclawClient;
135
139
  store;
136
140
  botOpenId = null;
141
+ identityClosed = false;
142
+ identityRetryTimer;
143
+ identityFlight;
144
+ identityAbort;
145
+ identityNextProbeAt = 0;
146
+ identityFailures = 0;
147
+ identityDrain;
148
+ identityDrainRetry = false;
149
+ identityDrainNextAt = 0;
150
+ identityDrainFailures = 0;
151
+ identityCaptures = new Map();
152
+ identityTargetRepairs = new Map();
153
+ identitySessionWaiters = new Set();
154
+ identityEffects = new AsyncLocalStorage();
155
+ requestIdentity = (signal) => requestBotIdentity(this.config, signal, IDENTITY_DEADLINE_MS);
137
156
  /** Tracks which chatId sessions have been initialized */
138
157
  initializedSessions = new Set();
139
158
  /** Per-chat busy lock: timestamp when became busy (0 = not busy) */
@@ -333,6 +352,15 @@ export class FeishuBot {
333
352
  this.config = config;
334
353
  this.openclawClient = openclawClient;
335
354
  this.store = store;
355
+ this.store.onClose(() => {
356
+ this.identityClosed = true;
357
+ clearTimeout(this.identityRetryTimer);
358
+ this.identityRetryTimer = undefined;
359
+ this.identityAbort?.();
360
+ for (const cancel of this.identitySessionWaiters)
361
+ cancel();
362
+ this.identityTargetRepairs.clear();
363
+ });
336
364
  this.queuedPresentations = new QueuedPresentations(() => this.store, config.name, config.appId, (chat, replyTo) => ({ ...this.liveStatusCallbacks(chat, replyTo), warn: (message, err) => console.warn(`[${this.config.name}] ${message}:`, this.errorSummary(err)) }), chat => this.shouldUseLiveStatus(chat), chat => this.isEn(chat));
337
365
  this.store.onClose(() => this.queuedPresentations.dispose());
338
366
  this.openclawClient.bindRecoveryStore?.(store);
@@ -461,11 +489,22 @@ export class FeishuBot {
461
489
  * Ensure the session for a given chatId exists with the correct model.
462
490
  * Lazy: only creates on first message in that chat.
463
491
  */
464
- async ensureSession(chatId) {
492
+ async ensureSession(chatId, setupFence) {
465
493
  const sessionKey = this.getSessionKey(chatId);
494
+ await this.assertIdentityEffect();
495
+ const held = this.identityEffects?.getStore();
496
+ const expectedSessionId = held?.item.target.sessionId || setupFence?.sessionId;
497
+ const setupGuard = () => { this.assertIdentityCurrent(); setupFence?.guard(); };
498
+ if (setupFence) {
499
+ const info = await this.identitySessionInfo(sessionKey);
500
+ setupGuard();
501
+ if (info?.session?.sessionId !== setupFence.sessionId || info.session.archived)
502
+ throw new SupersededObservation('retained setup physical target changed');
503
+ }
466
504
  if (this.initializedSessions.has(sessionKey)) {
467
505
  // Already initialized this process lifetime, just ensure model
468
- const corrected = await this.openclawClient.ensureModel(sessionKey, this.config.model);
506
+ const corrected = (expectedSessionId ? await this.openclawClient.ensureModel(sessionKey, this.config.model, { sessionId: expectedSessionId, guard: setupGuard }) : await this.openclawClient.ensureModel(sessionKey, this.config.model));
507
+ setupGuard();
469
508
  if (corrected) {
470
509
  console.log(`[${this.config.name}] Model auto-corrected to ${this.config.model}`);
471
510
  }
@@ -474,10 +513,14 @@ export class FeishuBot {
474
513
  try {
475
514
  // Check if session already exists in OpenClaw
476
515
  const existing = await this.openclawClient.getSessionInfo(sessionKey).catch(() => null);
516
+ setupGuard();
517
+ if (expectedSessionId && (existing?.session?.sessionId !== expectedSessionId || existing.session.archived))
518
+ throw new SupersededObservation('retained session setup changed');
477
519
  if (existing?.session) {
478
520
  // Session exists — preserve it, only ensure model is correct
479
521
  console.log(`[${this.config.name}] Session exists: ${sessionKey} (tokens: ${existing.session.totalTokens || 0})`);
480
- const corrected = await this.openclawClient.ensureModel(sessionKey, this.config.model);
522
+ const corrected = (expectedSessionId ? await this.openclawClient.ensureModel(sessionKey, this.config.model, { sessionId: expectedSessionId, guard: setupGuard }) : await this.openclawClient.ensureModel(sessionKey, this.config.model));
523
+ setupGuard();
481
524
  if (corrected) {
482
525
  console.log(`[${this.config.name}] Model auto-corrected to ${this.config.model}`);
483
526
  }
@@ -501,6 +544,7 @@ export class FeishuBot {
501
544
  console.warn(`[${this.config.name}] ensureSession error:`, safeErrorSummary(err));
502
545
  throw err;
503
546
  }
547
+ setupGuard();
504
548
  this.initializedSessions.add(sessionKey);
505
549
  // Subscribe to session events (proactive messages + tool calls)
506
550
  this.openclawClient.setVerboseTranscriptDelivery(sessionKey, this.store.getBotVerbose(this.config.name, chatId));
@@ -606,32 +650,255 @@ export class FeishuBot {
606
650
  */
607
651
  async start() {
608
652
  await this.probeBotIdentity();
653
+ if (this.identityClosed)
654
+ return;
609
655
  await this.wsClient.start({ eventDispatcher: this.eventDispatcher });
656
+ if (this.identityClosed)
657
+ return;
610
658
  console.log(`[${this.config.name}] Bot started (model: ${this.config.model}, open_id: ${this.botOpenId || "unknown"})`);
611
659
  // Drain any unsynced messages left from previous run
612
660
  this.drainOnStartup();
661
+ void this.drainIdentityIngress().catch(err => console.warn(`[${this.config.name}] Identity ingress recovery failed:`, err.message));
613
662
  }
614
- /** Resolve this bot's open_id at startup so direct @bot mentions work even
615
- * when Feishu mention payloads omit app_id and only contain open_id/name. */
616
- async probeBotIdentity() {
617
- try {
618
- const res = await this.client.request({
619
- method: "POST",
620
- url: "/open-apis/bot/v1/openclaw_bot/ping",
621
- data: { needBotInfo: true },
622
- });
623
- const botInfo = res?.data?.pingBotInfo;
624
- if (botInfo?.botID) {
625
- this.botOpenId = botInfo.botID;
626
- console.log(`[${this.config.name}] Bot identity resolved: ${botInfo.botName || this.config.name} (${this.botOpenId})`);
663
+ /** Local custody repair only. This never authorizes replay of a claimed event
664
+ * or re-probes an already known identity. The journal remains the sole owner. */
665
+ retryIdentityIngress(error) {
666
+ if (this.identityClosed)
667
+ return;
668
+ const code = error?.code;
669
+ console.warn(`[${this.config.name}] Identity custody recovery deferred:`, code === "SQLITE_BUSY" || code === "SQLITE_LOCKED" ? code : safeErrorSummary(error));
670
+ this.identityDrainRetry = true;
671
+ this.identityDrainNextAt = Date.now() + Math.min(IDENTITY_RETRY_CAP_MS, IDENTITY_RETRY_BASE_MS * 2 ** Math.min(this.identityDrainFailures++, 6));
672
+ this.scheduleIdentityProbe();
673
+ }
674
+ /** Bounded, read-only public metadata. Late responses never write custody. */
675
+ identitySessionInfo(key) {
676
+ if (this.identityClosed)
677
+ return Promise.resolve(null);
678
+ return new Promise(resolve => {
679
+ let done = false;
680
+ const finish = (value) => { if (done)
681
+ return; done = true; clearTimeout(timer); this.identitySessionWaiters.delete(cancel); resolve(value); };
682
+ const cancel = () => finish(null);
683
+ const timer = setTimeout(cancel, IDENTITY_DEADLINE_MS);
684
+ timer.unref?.();
685
+ this.identitySessionWaiters.add(cancel);
686
+ void Promise.resolve().then(() => this.identityClosed ? null : this.openclawClient.getSessionInfo(key, IDENTITY_DEADLINE_MS))
687
+ .then(finish, () => finish(null));
688
+ });
689
+ }
690
+ captureIdentityTarget(messageId, chatId) {
691
+ const key = this.getSessionKey(chatId);
692
+ const work = (async () => {
693
+ const info = await this.identitySessionInfo(key);
694
+ if (this.identityClosed)
695
+ return;
696
+ const session = info?.session;
697
+ const target = typeof session?.sessionId === 'string' && session.sessionId.trim() && session.sessionId.length <= 256 && session.archived !== true
698
+ && (!session.key || typeof session.key === 'string' && canonicalPhysicalSessionKey(session.key) === canonicalPhysicalSessionKey(key))
699
+ ? { state: 'bound', sessionKey: key, sessionId: session.sessionId } : { state: 'unbound', sessionKey: key };
700
+ if (target.state === 'unbound')
701
+ console.warn(`[${this.config.name}] Identity input ${messageId} has no proven original physical session; retained without retargeting`);
702
+ this.identityTargetRepairs.set(messageId, target);
703
+ this.store.finishIdentityTarget(this.config.name, this.config.appId, messageId, target);
704
+ this.identityTargetRepairs.delete(messageId);
705
+ })().catch(err => this.retryIdentityIngress(err)).finally(() => this.identityCaptures.delete(messageId));
706
+ this.identityCaptures.set(messageId, work);
707
+ return work;
708
+ }
709
+ assertIdentityCurrent() {
710
+ const fence = this.identityEffects?.getStore();
711
+ if (!fence)
712
+ return;
713
+ if (this.identityClosed || this.stopGeneration(fence.item.chatId) !== fence.epoch || this.store.isMessageRecalled(fence.item.messageId))
714
+ throw new SupersededObservation('retained identity input cancelled');
715
+ }
716
+ async assertIdentityEffect() {
717
+ const fence = this.identityEffects?.getStore();
718
+ if (!fence)
719
+ return;
720
+ this.assertIdentityCurrent();
721
+ const info = await this.identitySessionInfo(fence.item.target.sessionKey);
722
+ this.assertIdentityCurrent();
723
+ if (info?.session?.archived === true || info?.session?.sessionId !== fence.item.target.sessionId)
724
+ throw new SupersededObservation('retained identity physical session unavailable or changed');
725
+ }
726
+ /** One background timer per bot covers both discovery and local journal
727
+ * repair; every asynchronous AND synchronous timer effect is owned. */
728
+ scheduleIdentityProbe() {
729
+ if (this.identityClosed || (this.botOpenId && !this.identityDrainRetry) || this.identityRetryTimer)
730
+ return;
731
+ this.identityRetryTimer = setTimeout(() => {
732
+ this.identityRetryTimer = undefined;
733
+ if (this.identityClosed)
734
+ return;
735
+ void Promise.resolve().then(async () => {
736
+ if (this.identityClosed)
737
+ return;
738
+ if (!this.botOpenId) {
739
+ this.store.pruneIdentityIngress(this.config.name, this.config.appId);
740
+ await this.probeBotIdentity();
741
+ }
742
+ await this.drainIdentityIngress();
743
+ }).catch(err => this.retryIdentityIngress(err))
744
+ .finally(() => this.scheduleIdentityProbe());
745
+ }, Math.max(IDENTITY_RETRY_BASE_MS, Math.max(this.botOpenId ? 0 : this.identityNextProbeAt, this.identityDrainNextAt) - Date.now()));
746
+ this.identityRetryTimer.unref?.();
747
+ }
748
+ /** Bounded observation AND cancellable HTTP (including token discovery).
749
+ * Even a nonconforming transport ignoring abort retains single-flight custody
750
+ * until it settles; we never accumulate timed-out requests or trust late data. */
751
+ probeBotIdentity() {
752
+ if (this.identityClosed || this.botOpenId)
753
+ return Promise.resolve();
754
+ if (this.identityFlight) {
755
+ // While the initial observation is active its completion owns scheduling.
756
+ // Only a timed-out, still-owned raw request needs another liveness check.
757
+ if (this.identityNextProbeAt)
758
+ this.scheduleIdentityProbe();
759
+ return this.identityFlight;
760
+ }
761
+ if (Date.now() < this.identityNextProbeAt) {
762
+ this.scheduleIdentityProbe();
763
+ return Promise.resolve();
764
+ }
765
+ clearTimeout(this.identityRetryTimer);
766
+ this.identityRetryTimer = undefined;
767
+ this.identityNextProbeAt = 0;
768
+ const controller = new AbortController();
769
+ let live = true;
770
+ let finish;
771
+ const observed = new Promise(resolve => { finish = resolve; });
772
+ this.identityFlight = observed;
773
+ const expire = () => {
774
+ if (live && !this.identityClosed)
775
+ console.warn(`[${this.config.name}] Bot identity probe exceeded ${IDENTITY_DEADLINE_MS}ms; retaining unresolved mentions`);
776
+ live = false;
777
+ controller.abort();
778
+ finish();
779
+ };
780
+ this.identityAbort = expire;
781
+ const deadline = setTimeout(expire, IDENTITY_DEADLINE_MS);
782
+ deadline.unref?.();
783
+ const raw = Promise.resolve().then(() => {
784
+ if (this.identityClosed || controller.signal.aborted)
785
+ throw new Error("identity probe cancelled");
786
+ return this.requestIdentity(controller.signal);
787
+ });
788
+ void raw.then(response => {
789
+ if (!live || this.identityClosed || this.botOpenId)
790
+ return;
791
+ const openId = trustedBotOpenId(response, this.config.appId);
792
+ if (!openId)
793
+ throw new Error("bot-info response contained no valid original-account identity");
794
+ this.botOpenId = openId;
795
+ console.log(`[${this.config.name}] Bot identity resolved: ${openId}`);
796
+ }).catch(err => {
797
+ if (live && !this.identityClosed)
798
+ console.warn(`[${this.config.name}] Bot identity probe failed:`, err.message);
799
+ }).finally(() => {
800
+ clearTimeout(deadline);
801
+ live = false;
802
+ if (this.identityFlight === observed)
803
+ this.identityFlight = undefined;
804
+ this.identityAbort = undefined;
805
+ finish();
806
+ });
807
+ void observed.then(() => {
808
+ clearTimeout(deadline);
809
+ if (this.identityClosed)
810
+ return;
811
+ if (!this.botOpenId) {
812
+ this.identityNextProbeAt = Date.now() + Math.min(IDENTITY_RETRY_CAP_MS, IDENTITY_RETRY_BASE_MS * 2 ** Math.min(this.identityFailures++, 6));
813
+ this.scheduleIdentityProbe();
627
814
  }
628
815
  else {
629
- console.warn(`[${this.config.name}] Bot identity probe returned no botID`);
816
+ clearTimeout(this.identityRetryTimer);
817
+ this.identityRetryTimer = undefined;
818
+ void this.drainIdentityIngress().catch(err => console.warn(`[${this.config.name}] Identity ingress recovery failed:`, err.message));
819
+ }
820
+ }).catch(err => this.retryIdentityIngress(err));
821
+ return observed;
822
+ }
823
+ /** Metadata may say who was targeted, but can never say who THIS bot is. */
824
+ needsIdentityRecovery(message) {
825
+ if (message.chat_type === "p2p" || this.botOpenId)
826
+ return false;
827
+ let mentions = Array.isArray(message.mentions) ? message.mentions : [];
828
+ if (!mentions.length && message.message_type === "post") {
829
+ try {
830
+ const content = JSON.parse(message.content);
831
+ const posts = content.content ? [content] : Object.values(content);
832
+ mentions = posts.flatMap((post) => (post?.content || []).flat())
833
+ .filter((node) => node?.tag === "at").map((node) => ({ id: { open_id: node.user_id } }));
834
+ }
835
+ catch {
836
+ return false;
630
837
  }
631
838
  }
632
- catch (err) {
633
- console.warn(`[${this.config.name}] Bot identity probe failed:`, err.message);
634
- }
839
+ // An app-only self mention is already an independent proof, including a
840
+ // mixed self+human message. But if a self app_id also supplies an open_id,
841
+ // resolve first: an unknown identity must not hide a conflicting pair.
842
+ const selfPair = mentions.some((mention) => mention.id?.app_id === this.config.appId && mention.id?.open_id);
843
+ if (!selfPair && mentions.some((mention) => this.mentionedBotName(mention) === this.config.name))
844
+ return false;
845
+ return mentions.some((mention) => !this.isAllMentionItem(mention)
846
+ && typeof mention.id?.open_id === "string" && !!mention.id.open_id
847
+ && (!mention.id.app_id || mention.id.app_id === this.config.appId));
848
+ }
849
+ drainIdentityIngress() {
850
+ if (this.identityClosed || !this.botOpenId)
851
+ return Promise.resolve();
852
+ if (this.identityDrain)
853
+ return this.identityDrain;
854
+ if (this.identityDrainRetry && Date.now() < this.identityDrainNextAt) {
855
+ this.scheduleIdentityProbe();
856
+ return Promise.resolve();
857
+ }
858
+ this.identityDrain = (async () => {
859
+ for (const [messageId, target] of this.identityTargetRepairs) {
860
+ if (this.identityClosed)
861
+ return;
862
+ this.store.finishIdentityTarget(this.config.name, this.config.appId, messageId, target);
863
+ this.identityTargetRepairs.delete(messageId);
864
+ }
865
+ for (const item of this.store.listIdentityIngress(this.config.name, this.config.appId)) {
866
+ if (this.identityClosed)
867
+ return;
868
+ const capture = this.identityCaptures.get(item.messageId);
869
+ if (capture)
870
+ await capture;
871
+ if (this.identityClosed)
872
+ return;
873
+ // Capture owns a paced retry of its SAME proof. Do not clear that
874
+ // repair intent just because this drain began before capture settled.
875
+ if (this.identityTargetRepairs.has(item.messageId))
876
+ return;
877
+ item.target = this.store.getIdentityTarget(this.config.name, this.config.appId, item.messageId);
878
+ if (item.target.state !== 'bound' || !item.target.sessionId || item.target.sessionKey !== this.getSessionKey(item.chatId))
879
+ continue;
880
+ const info = await this.identitySessionInfo(item.target.sessionKey);
881
+ if (this.identityClosed)
882
+ return;
883
+ if (!info?.session?.sessionId)
884
+ throw new Error('retained physical session check unavailable');
885
+ if (info.session.archived === true || info.session.sessionId !== item.target.sessionId) {
886
+ this.store.claimIdentityIngress(this.config.name, this.config.appId, item);
887
+ this.store.clearIdentityIngress(this.config.name, this.config.appId, item.messageId);
888
+ continue;
889
+ }
890
+ await this.identityEffects.run({ item, epoch: item.stopEpoch }, () => this.handleResolvedMessage(item.event, item));
891
+ }
892
+ if (this.identityTargetRepairs.size)
893
+ return;
894
+ this.identityDrainRetry = false;
895
+ this.identityDrainNextAt = 0;
896
+ this.identityDrainFailures = 0;
897
+ clearTimeout(this.identityRetryTimer);
898
+ this.identityRetryTimer = undefined;
899
+ })().catch(err => this.retryIdentityIngress(err))
900
+ .finally(() => { this.identityDrain = undefined; this.scheduleIdentityProbe(); });
901
+ return this.identityDrain;
635
902
  }
636
903
  /**
637
904
  * On startup, check all known chats for unsynced messages and process them.
@@ -697,6 +964,53 @@ export class FeishuBot {
697
964
  return undefined;
698
965
  }
699
966
  async handleMessage(data) {
967
+ try {
968
+ if (this.identityClosed)
969
+ return;
970
+ const message = data?.message;
971
+ if (!message?.chat_id || !message.message_id || !["text", "image", "file", "audio", "sticker", "post", "share_doc"].includes(message.message_type))
972
+ return;
973
+ if ((message.mentions || []).some((mention) => mention?.id && Object.hasOwn(mention.id, 'open_id') &&
974
+ (typeof mention.id.open_id !== 'string' || !mention.id.open_id.trim())))
975
+ return;
976
+ if (this.store.hasBotProcessed(this.config.name, message.message_id))
977
+ return;
978
+ // A duplicate must honor the original journal owner, even if its envelope
979
+ // differs or identity has resolved since the first receipt.
980
+ if (this.store.hasIdentityIngress(this.config.name, this.config.appId, message.message_id) || this.needsIdentityRecovery(message)) {
981
+ const retained = this.store.retainIdentityIngress(this.config.name, this.config.appId, data, this.getSessionKey(message.chat_id));
982
+ if (retained !== "retained" && retained !== "created") {
983
+ if (retained === "full")
984
+ console.warn(`[${this.config.name}] Identity ingress capacity exceeded; message ${message.message_id} was not admitted`);
985
+ return;
986
+ }
987
+ const capture = retained === 'created' ? this.captureIdentityTarget(message.message_id, message.chat_id) : this.identityCaptures.get(message.message_id);
988
+ const discovery = this.probeBotIdentity();
989
+ if (capture)
990
+ await capture;
991
+ await discovery;
992
+ if (!this.identityClosed)
993
+ await this.drainIdentityIngress();
994
+ return;
995
+ }
996
+ await this.handleResolvedMessage(data);
997
+ }
998
+ catch (err) {
999
+ // If journal preflight fails, only durable, still-unclaimed custody may
1000
+ // be retried. Never recreate this event from an in-memory business promise.
1001
+ this.retryIdentityIngress(err);
1002
+ }
1003
+ }
1004
+ async handleResolvedMessage(data, identityItem) {
1005
+ // Retained inputs may enter only through the drain's exact guarded owner,
1006
+ // never through an unbound helper call or a reconstructed replay envelope.
1007
+ if (identityItem && this.identityEffects?.getStore()?.item !== identityItem)
1008
+ return;
1009
+ // Claim failures must reach the drain's repair owner. The SQLite transaction
1010
+ // rolls back, preserving the original event. After a successful claim the
1011
+ // ordinary handler's at-most-once failure behavior remains unchanged.
1012
+ if (identityItem && (this.identityClosed || !this.store.claimIdentityIngress(this.config.name, this.config.appId, identityItem)))
1013
+ return;
700
1014
  try {
701
1015
  const event = data;
702
1016
  const message = event.message;
@@ -707,7 +1021,7 @@ export class FeishuBot {
707
1021
  const messageType = message.message_type;
708
1022
  const messageId = message.message_id;
709
1023
  const isBot = sender?.sender_type === "app";
710
- // Identity comes from the startup probe, never from message mentions:
1024
+ // Identity comes from original-account probes, never from message mentions:
711
1025
  // a conflicting app_id/open_id pair must not overwrite a known identity.
712
1026
  if (messageType !== "text" && messageType !== "image" && messageType !== "file" && messageType !== "audio" && messageType !== "sticker" && messageType !== "post" && messageType !== "share_doc")
713
1027
  return;
@@ -715,10 +1029,27 @@ export class FeishuBot {
715
1029
  // Feishu/WebSocket can deliver the same event more than once; a separate
716
1030
  // has-then-mark sequence races and can send the same user message into
717
1031
  // OpenClaw twice.
718
- if (!this.store.tryMarkBotProcessed(this.config.name, messageId))
1032
+ if (this.identityClosed)
1033
+ return;
1034
+ if (!identityItem && !this.store.tryMarkBotProcessed(this.config.name, messageId))
719
1035
  return;
1036
+ const identityCurrent = () => {
1037
+ if (this.identityClosed)
1038
+ return false;
1039
+ if (identityItem) {
1040
+ try {
1041
+ this.assertIdentityCurrent();
1042
+ }
1043
+ catch {
1044
+ return false;
1045
+ }
1046
+ }
1047
+ return true;
1048
+ };
720
1049
  // --- Cache chat info (lazy, at most once per hour) ---
721
1050
  await this.fetchAndCacheChatInfo(chatId, chatType);
1051
+ if (!identityCurrent())
1052
+ return;
722
1053
  // --- P2P isolation: only the owning bot processes p2p messages ---
723
1054
  if (chatType === "p2p") {
724
1055
  const chatInfo = this.store.getChatInfo(chatId);
@@ -796,6 +1127,10 @@ export class FeishuBot {
796
1127
  cleanText = `[Sticker: ${content.file_key || "unknown"}]`;
797
1128
  }
798
1129
  cleanText = await this.hydrateFeishuDocsInMessage(cleanText, content, messageId);
1130
+ if (!identityCurrent())
1131
+ return;
1132
+ if (identityItem)
1133
+ await this.assertIdentityEffect();
799
1134
  if (!cleanText.trim())
800
1135
  return;
801
1136
  const routing = this.getRoutingIntent(chatType, message, messageType === "text" ? (content.text || "") : "", content);
@@ -967,12 +1302,16 @@ export class FeishuBot {
967
1302
  }
968
1303
  }
969
1304
  const markCommandSynced = () => {
1305
+ if (!identityCurrent())
1306
+ return;
970
1307
  if (insertedId > 0) {
971
1308
  this.store.markSynced(this.config.name, chatId, insertedId);
972
1309
  // Bridge commands should only clear their own pending row. They
973
1310
  // must not clear earlier human triggers that are waiting after a
974
1311
  // failed/empty run; /status must be safe to use for debugging.
975
1312
  this.store.clearPendingTrigger(this.config.name, chatId, insertedId);
1313
+ if (identityItem)
1314
+ this.store.clearIdentityIngress(this.config.name, this.config.appId, messageId);
976
1315
  }
977
1316
  };
978
1317
  if (commandName === "/help") {
@@ -1022,12 +1361,18 @@ export class FeishuBot {
1022
1361
  }
1023
1362
  if (commandName === "/status") {
1024
1363
  await this.ensureSession(chatId);
1364
+ if (!identityCurrent())
1365
+ return;
1366
+ await this.assertIdentityEffect();
1025
1367
  await this.handleStatusCommand(chatId, chatType, messageId);
1026
1368
  markCommandSynced();
1027
1369
  return;
1028
1370
  }
1029
1371
  if (commandName === "/compact") {
1030
1372
  await this.ensureSession(chatId);
1373
+ if (!identityCurrent())
1374
+ return;
1375
+ await this.assertIdentityEffect();
1031
1376
  const compactArgs = cleanText.trim().split(/\s+/).slice(1).join(" ").trim();
1032
1377
  await this.handleCompactCommand(chatId, messageId, compactArgs);
1033
1378
  markCommandSynced();
@@ -1035,16 +1380,28 @@ export class FeishuBot {
1035
1380
  }
1036
1381
  if (commandName === "/reset") {
1037
1382
  await this.ensureSession(chatId);
1383
+ if (!identityCurrent())
1384
+ return;
1385
+ await this.assertIdentityEffect();
1038
1386
  await this.handleResetCommand(chatId, messageId);
1039
1387
  markCommandSynced();
1040
1388
  return;
1041
1389
  }
1042
1390
  if (commandName === "/stop") {
1391
+ await this.assertIdentityEffect();
1043
1392
  await this.handleStopCommand(chatId, messageId);
1044
1393
  markCommandSynced();
1045
1394
  return;
1046
1395
  }
1047
1396
  if (commandName === "/go") {
1397
+ // Go owns a separate multi-await supervisor/bootstrap protocol. Its
1398
+ // public entry point cannot carry this hold's original executor CAS;
1399
+ // never turn a delayed mutating command into a new supervisor target.
1400
+ if (identityItem && !/^\/go(?:\s+status)?\s*$/i.test(cleanText.trim())) {
1401
+ await this.replyMessage(messageId, "ℹ️ 这条 /go 在身份恢复前收到,未执行。监督初始化不能携带原会话的完整保护条件;请确认当前会话后重新发送。");
1402
+ markCommandSynced();
1403
+ return;
1404
+ }
1048
1405
  // Go supervision targets one bot's executor session: groups require an
1049
1406
  // explicit mention (single-bot group is the implicit target), p2p always.
1050
1407
  const groupBotCount = Array.from(FeishuBot.allBots.values()).filter((bot) => bot.store === this.store).length;
@@ -1056,11 +1413,15 @@ export class FeishuBot {
1056
1413
  const control = /^(?:status|pause|resume|stop|model)(?:\s|$)/i.test(goArgs) || !goArgs;
1057
1414
  if (!control)
1058
1415
  await this.ensureSession(chatId);
1416
+ if (!identityCurrent())
1417
+ return;
1418
+ await this.assertIdentityEffect();
1059
1419
  await this.goController?.handleGoCommand(chatId, messageId, goArgs);
1060
1420
  }
1061
1421
  finally {
1062
1422
  markCommandSynced();
1063
- this.goController?.onCommandSettled(chatId);
1423
+ if (identityCurrent())
1424
+ this.goController?.onCommandSettled(chatId);
1064
1425
  }
1065
1426
  return;
1066
1427
  }
@@ -1252,6 +1613,8 @@ export class FeishuBot {
1252
1613
  // --- Should this bot respond? ---
1253
1614
  if (!this.shouldRespond(chatType, message, isBot, chatId, routing))
1254
1615
  return;
1616
+ if (identityItem)
1617
+ await this.assertIdentityEffect();
1255
1618
  let reservedAtIngress = false;
1256
1619
  if (!isBot && insertedId > 0) {
1257
1620
  this.goController?.onHumanInput(chatId);
@@ -1267,7 +1630,7 @@ export class FeishuBot {
1267
1630
  if ((this.queueRuns.has(chatId) || ingressOwner) && !ingressOwner?.triggerIds?.has(insertedId)) {
1268
1631
  this.store.saveInsertion(this.config.name, chatId, insertedId, JSON.stringify([this.config.appId, chatId, messageId]), 'pending', {
1269
1632
  messageId, text: cleanText, stopEpoch: this.stopGeneration(chatId), expectedRunId: ingressOwner?.runId || '',
1270
- ownerId: ingressOwner?.id, batchId: ingressOwner?.batchId, sessionId: ingressOwner?.sessionId, sessionKey: this.getSessionKey(chatId)
1633
+ ownerId: ingressOwner?.id, batchId: ingressOwner?.batchId, sessionId: identityItem?.target.sessionId || ingressOwner?.sessionId, sessionKey: this.getSessionKey(chatId)
1271
1634
  });
1272
1635
  reservedAtIngress = true;
1273
1636
  }
@@ -1282,7 +1645,7 @@ export class FeishuBot {
1282
1645
  const pending = this.pendingAckMessages.get(chatId) || [];
1283
1646
  const inputStopEpoch = this.stopGeneration(chatId);
1284
1647
  const unhealthy = await this.getUnhealthySessionStatus(chatId);
1285
- if (this.stopGeneration(chatId) !== inputStopEpoch)
1648
+ if (!identityCurrent() || this.stopGeneration(chatId) !== inputStopEpoch)
1286
1649
  return;
1287
1650
  if (unhealthy) {
1288
1651
  await this.warnUnhealthySessionAndContinue(chatId, messageId, unhealthy);
@@ -1291,12 +1654,14 @@ export class FeishuBot {
1291
1654
  // positive idle, or bounded guarded-followup proof may hand off ONLY the
1292
1655
  // local scheduler; the original exact result observer/target survives.
1293
1656
  const dispatchReleased = await this.reconcileDispatchCustody(chatId);
1294
- if (this.stopGeneration(chatId) !== inputStopEpoch)
1657
+ if (!identityCurrent() || this.stopGeneration(chatId) !== inputStopEpoch)
1295
1658
  return;
1296
1659
  if (!isBot && insertedId > 0 && !dispatchReleased && !this.queueRuns.has(chatId) && !this.store.getDispatchCustody(this.config.name, chatId))
1297
1660
  await this.reconcileCurrentInputActivity(chatId, insertedId, messageId, cleanText);
1298
- if (this.stopGeneration(chatId) !== inputStopEpoch)
1661
+ if (!identityCurrent() || this.stopGeneration(chatId) !== inputStopEpoch)
1299
1662
  return;
1663
+ if (identityItem)
1664
+ await this.assertIdentityEffect();
1300
1665
  if (this.store.isInsertionReserved(this.config.name, chatId, insertedId))
1301
1666
  reservedAtIngress = true;
1302
1667
  if (reservedAtIngress && !this.store.isInsertionReserved(this.config.name, chatId, insertedId))
@@ -1321,7 +1686,7 @@ export class FeishuBot {
1321
1686
  if (isBusy) {
1322
1687
  const owner = this.queueOwners.get(chatId) || this.store.getDispatchCustody(this.config.name, chatId);
1323
1688
  const record = { messageId, text: cleanText, stopEpoch: this.stopGeneration(chatId),
1324
- expectedRunId: owner?.runId || '', ownerId: owner?.id, batchId: owner?.batchId, sessionId: owner?.sessionId, sessionKey: this.getSessionKey(chatId) };
1689
+ expectedRunId: owner?.runId || '', ownerId: owner?.id, batchId: owner?.batchId, sessionId: identityItem?.target.sessionId || owner?.sessionId, sessionKey: this.getSessionKey(chatId) };
1325
1690
  if (insertedId > 0 && !this.store.getInsertion(this.config.name, chatId, insertedId))
1326
1691
  this.store.saveInsertion(this.config.name, chatId, insertedId, JSON.stringify([this.config.appId, chatId, messageId]), 'pending', record);
1327
1692
  // Reservation is durable BEFORE any RPC. Ordinary drain cannot race a
@@ -1331,7 +1696,16 @@ export class FeishuBot {
1331
1696
  return;
1332
1697
  }
1333
1698
  // Not busy: admission callback, not local queueing, flips Typing -> Get.
1334
- await this.processQueue(chatId, true);
1699
+ const business = this.processQueue(chatId, true);
1700
+ if (identityItem) {
1701
+ // Existing pending-trigger/queue-owner custody now owns completion. Do
1702
+ // not hold identity ingress (and following /help, /stop or other chats)
1703
+ // behind the model's lifetime. No second queue or business replay path.
1704
+ void business.catch(err => console.error(`[${this.config.name}] Recovered business owner failed:`, safeErrorSummary(err)));
1705
+ }
1706
+ else {
1707
+ await business;
1708
+ }
1335
1709
  }
1336
1710
  catch (err) {
1337
1711
  console.error(`[${this.config.name}] Error:`, safeErrorSummary(err));
@@ -1373,6 +1747,7 @@ export class FeishuBot {
1373
1747
  * Read public activity and pin its exact root before choosing insertion. Missing
1374
1748
  * identity is durable unbound custody, never a fabricated run or blind send. */
1375
1749
  async reconcileCurrentInputActivity(chatId, rowId, messageId, text) {
1750
+ const heldSessionId = this.store.getIdentityTarget?.(this.config.name, this.config.appId, messageId)?.sessionId;
1376
1751
  if (!this.openclawClient.getSessionRuntimeStatus || !this.openclawClient.getSessionDispatchStatus)
1377
1752
  return;
1378
1753
  const epoch = this.stopGeneration(chatId), admissionEpoch = this.queueAdmissionEpoch.get(chatId) || 0;
@@ -1392,14 +1767,17 @@ export class FeishuBot {
1392
1767
  // missing describe response. A failed setup is not dispatch-idle evidence;
1393
1768
  // retain this never-attempted input for paced reconciliation as well.
1394
1769
  try {
1395
- await this.ensureSession(chatId);
1770
+ await (heldSessionId ? this.ensureSession(chatId, { sessionId: heldSessionId, guard: () => {
1771
+ if (this.identityClosed || !unsubmitted())
1772
+ throw new SupersededObservation('retained activity setup cancelled');
1773
+ } }) : this.ensureSession(chatId));
1396
1774
  }
1397
1775
  catch {
1398
- if (unsubmitted() && !this.queueRuns.has(chatId) && !this.store.getDispatchCustody(this.config.name, chatId)) {
1776
+ if (!this.identityClosed && unsubmitted() && !this.queueRuns.has(chatId) && !this.store.getDispatchCustody(this.config.name, chatId)) {
1399
1777
  const row = this.store.getInsertion(this.config.name, chatId, rowId);
1400
1778
  if (!row || row.state === 'pending' && row.activityUnbound && !row.attempted && !row.expectedRunId)
1401
1779
  this.store.saveInsertion(this.config.name, chatId, rowId, row?.insertionId || JSON.stringify([this.config.appId, chatId, messageId]), 'pending', {
1402
- messageId, text, stopEpoch: epoch, sessionKey: this.getSessionKey(chatId), activityUnbound: true, attempted: false, expectedRunId: '',
1780
+ messageId, text, stopEpoch: epoch, sessionKey: this.getSessionKey(chatId), sessionId: heldSessionId, activityUnbound: true, attempted: false, expectedRunId: '',
1403
1781
  reason: 'session setup unavailable; retained without dispatch-idle proof',
1404
1782
  }, Date.now() + 5000);
1405
1783
  }
@@ -1424,9 +1802,10 @@ export class FeishuBot {
1424
1802
  const fresh = this.store.getInsertion(this.config.name, chatId, rowId);
1425
1803
  if (current ? JSON.stringify(fresh) !== JSON.stringify(current) || fresh?.insertionId !== current.insertionId || fresh.state !== 'pending' || fresh.attempted === true || !fresh.activityUnbound || !!fresh.expectedRunId : !!fresh)
1426
1804
  return;
1427
- const compatible = !!status.sessionId && status.sessionId === activity.sessionId && (!current?.sessionId || current.sessionId === status.sessionId);
1805
+ const compatible = !!status.sessionId && status.sessionId === activity.sessionId && (!current?.sessionId || current.sessionId === status.sessionId)
1806
+ && (!heldSessionId || status.sessionId === heldSessionId);
1428
1807
  const archived = !!status.archived || !!activity.archived;
1429
- const generationConflict = activity.identityConflict === true || !!activity.sessionId && !!status.sessionId && activity.sessionId !== status.sessionId ||
1808
+ const generationConflict = !!heldSessionId && !!status.sessionId && status.sessionId !== heldSessionId || activity.identityConflict === true || !!activity.sessionId && !!status.sessionId && activity.sessionId !== status.sessionId ||
1430
1809
  !!current?.sessionId && !!status.sessionId && current.sessionId !== status.sessionId;
1431
1810
  const source = this.store.getMessageByMessageId(messageId);
1432
1811
  const ordinaryHuman = source?.id === rowId && source.chatId === chatId && source.senderType === 'human' && source.triggerKind === 'normal';
@@ -1469,7 +1848,7 @@ export class FeishuBot {
1469
1848
  : activity.busyConfirmed ? 'retained: positively-busy; guarded followup proof absent or observation window pending'
1470
1849
  : 'retained: genuinely unknown activity; fresh ordinary rescue observation pending';
1471
1850
  this.store.saveInsertion(this.config.name, chatId, rowId, current?.insertionId || JSON.stringify([this.config.appId, chatId, messageId]), 'pending', {
1472
- ...current, messageId, text, stopEpoch: epoch, sessionKey: this.getSessionKey(chatId), sessionId: current?.sessionId || activity.sessionId || status.sessionId,
1851
+ ...current, messageId, text, stopEpoch: epoch, sessionKey: this.getSessionKey(chatId), sessionId: heldSessionId || current?.sessionId || activity.sessionId || status.sessionId,
1473
1852
  expectedRunId: identified ? activity.activeRunId : '', ownerId: identified ? `external:${activity.activeRunId}` : undefined,
1474
1853
  batchId: identified ? activity.activeRunId : undefined, activityUnbound: !identified, attempted: false,
1475
1854
  ...(!identified ? { unboundSince: current?.unboundSince || Date.now() } : {}),
@@ -1634,6 +2013,11 @@ export class FeishuBot {
1634
2013
  this.scheduleInsertionRecovery();
1635
2014
  }
1636
2015
  async reconcileReactions(chatId) {
2016
+ // Shared durable owner, not the lifetime of the ingress that woke it.
2017
+ if (this.identityEffects?.getStore())
2018
+ return this.identityEffects.exit(() => this.reconcileReactions(chatId));
2019
+ if (this.identityClosed)
2020
+ return;
1637
2021
  if (this.reactionChecks.has(chatId))
1638
2022
  return;
1639
2023
  this.reactionChecks.add(chatId);
@@ -1682,6 +2066,11 @@ export class FeishuBot {
1682
2066
  insertionTimer;
1683
2067
  insertionChecks = new Set();
1684
2068
  scheduleInsertionRecovery() {
2069
+ // Shared durable owner, not the lifetime of the ingress that woke it.
2070
+ if (this.identityEffects?.getStore())
2071
+ return this.identityEffects.exit(() => this.scheduleInsertionRecovery());
2072
+ if (this.identityClosed)
2073
+ return;
1685
2074
  if (this.insertionTimer || (!this.store.listInsertions(this.config.name).length && !this.store.listReactionIntents(this.config.name).length))
1686
2075
  return;
1687
2076
  this.insertionTimer = setTimeout(() => {
@@ -1692,6 +2081,11 @@ export class FeishuBot {
1692
2081
  this.insertionTimer.unref?.();
1693
2082
  }
1694
2083
  async reconcileInsertions(chatId) {
2084
+ // Shared durable owner, not the lifetime of the ingress that woke it.
2085
+ if (this.identityEffects?.getStore())
2086
+ return this.identityEffects.exit(() => this.reconcileInsertions(chatId));
2087
+ if (this.identityClosed)
2088
+ return;
1695
2089
  if (this.insertionChecks.has(chatId))
1696
2090
  return;
1697
2091
  this.insertionChecks.add(chatId);
@@ -2025,6 +2419,11 @@ export class FeishuBot {
2025
2419
  }
2026
2420
  }
2027
2421
  async processQueue(chatId, activityChecked = false) {
2422
+ // A queue owner spans several independent inputs. Never inherit one
2423
+ // recovered ingress's ALS guard for later batches or delayed result sends;
2424
+ // retained inputs carry their own durable target/recall/epoch guards below.
2425
+ if (this.identityEffects?.getStore())
2426
+ return this.identityEffects.exit(() => this.processQueue(chatId, activityChecked));
2028
2427
  const existing = this.queueRuns.get(chatId);
2029
2428
  if (existing) {
2030
2429
  console.log(`[${this.config.name}] processQueue already running for ${chatId.slice(-8)}, joining existing run`);
@@ -2118,7 +2517,7 @@ export class FeishuBot {
2118
2517
  return true;
2119
2518
  }
2120
2519
  async processQueueInner(chatId, owner) {
2121
- const current = () => !owner.revoked && this.queueOwners.get(chatId) === owner && this.stopGeneration(chatId) === owner.stopEpoch;
2520
+ const current = () => !this.identityClosed && !owner.revoked && this.queueOwners.get(chatId) === owner && this.stopGeneration(chatId) === owner.stopEpoch;
2122
2521
  const guard = () => { if (!current())
2123
2522
  throw new SupersededObservation('queue owner revoked'); };
2124
2523
  while (current()) {
@@ -2313,16 +2712,33 @@ export class FeishuBot {
2313
2712
  this.presentation(() => this.queuedPresentations.receive(chatId, triggerId, lastHuman.messageId || "", false));
2314
2713
  const liveStatus = this.presentation(() => this.queuedPresentations.claim(chatId, mergedTriggerIds, owner.id, owner.batchId, isNativeCommandTrigger));
2315
2714
  let sessionKey;
2715
+ const identityTargets = mergedTriggers.map(message => ({ message, target: this.store.getIdentityTarget?.(this.config.name, this.config.appId, message.messageId) || {} }))
2716
+ .filter(entry => entry.target.expiresAt !== undefined);
2717
+ const expectedIdentitySessionId = identityTargets[0]?.target.sessionId;
2316
2718
  try {
2317
- sessionKey = await this.ensureSession(chatId);
2719
+ if (identityTargets.some(({ target }) => target.state !== 'bound' || !target.sessionId || target.sessionId !== expectedIdentitySessionId ||
2720
+ target.sessionKey !== this.getSessionKey(chatId) || (target.expiresAt ?? 0) <= Date.now()))
2721
+ throw new SupersededObservation('retained original target unavailable');
2722
+ sessionKey = await (expectedIdentitySessionId ? this.ensureSession(chatId, { sessionId: expectedIdentitySessionId, guard }) : this.ensureSession(chatId));
2318
2723
  guard();
2319
2724
  const generation = await this.openclawClient.getSessionInfo(sessionKey, 1500).catch(() => null);
2320
2725
  guard();
2321
2726
  owner.sessionId = generation?.session?.sessionId;
2727
+ if (expectedIdentitySessionId && (generation?.session?.archived || owner.sessionId !== expectedIdentitySessionId))
2728
+ throw new SupersededObservation('retained original target changed before queue admission');
2322
2729
  }
2323
2730
  catch (err) {
2324
2731
  if (!current())
2325
2732
  break;
2733
+ if (identityTargets.length && err instanceof SupersededObservation) {
2734
+ for (const { message } of identityTargets) {
2735
+ if (message.id)
2736
+ this.store.clearPendingTrigger(this.config.name, chatId, message.id);
2737
+ this.store.clearIdentityIngress(this.config.name, this.config.appId, message.messageId);
2738
+ }
2739
+ owner.continuePending = mergedTriggers.some(message => !identityTargets.some(entry => entry.message === message));
2740
+ break;
2741
+ }
2326
2742
  await liveStatus?.pauseForUnconfirmedResult(this.isEn(chatId) ? "Session setup failed before admission" : "会话准备失败,尚未提交 Gateway", this.isEn(chatId) ? `${this.config.name} setup unavailable` : `${this.config.name} 会话准备未完成`).catch(() => { });
2327
2743
  if (batchProof) {
2328
2744
  for (const id of mergedTriggerIds) {
@@ -2397,8 +2813,11 @@ export class FeishuBot {
2397
2813
  includeContext: !isNativeCommandTrigger,
2398
2814
  includeBridgeAttachmentHint: !isNativeCommandTrigger,
2399
2815
  followupAdmissionGuard: batchProof,
2816
+ ...(expectedIdentitySessionId ? { expectedSessionId: expectedIdentitySessionId } : {}),
2400
2817
  admissionGuard: () => {
2401
2818
  guard();
2819
+ if (identityTargets.some(({ message }) => this.store.isMessageRecalled(message.messageId)))
2820
+ throw new SupersededObservation('retained input recalled before admission');
2402
2821
  if (owner.batch !== batchToken || owner.batchId !== batchId || this.queueAdmissionEpoch.get(chatId) !== admissionEpoch)
2403
2822
  throw new SupersededObservation('batch admission epoch changed');
2404
2823
  if (!batchProof)
@@ -2433,6 +2852,8 @@ export class FeishuBot {
2433
2852
  }
2434
2853
  else
2435
2854
  markSubmittedBatch("send-attempt");
2855
+ for (const { message } of identityTargets)
2856
+ this.store.clearIdentityIngress(this.config.name, this.config.appId, message.messageId);
2436
2857
  },
2437
2858
  onRunIdentified: (runId, identity) => { guard(); owner.runId = runId; owner.sessionId = identity?.sessionId || owner.sessionId; foregroundRunId = runId; },
2438
2859
  onSubmitted: async (runId) => {
@@ -2967,6 +3388,8 @@ export class FeishuBot {
2967
3388
  if (this.isAllMentionItem(mention))
2968
3389
  return null;
2969
3390
  const id = mention.id || {};
3391
+ if (Object.hasOwn(id, 'open_id') && (typeof id.open_id !== 'string' || !id.open_id.trim()))
3392
+ return null;
2970
3393
  const candidates = [this, ...Array.from(FeishuBot.allBots.values()).filter((bot) => bot !== this && bot.store === this.store)];
2971
3394
  const matches = candidates.filter((bot) => {
2972
3395
  // Known conflicting app/open credentials veto, regardless of order. An
@@ -3666,6 +4089,11 @@ export class FeishuBot {
3666
4089
  this.scheduleErrorNoticeCheck(record.chatId);
3667
4090
  }
3668
4091
  scheduleErrorNoticeCheck(chatId) {
4092
+ // Shared durable owner, not the lifetime of the ingress that woke it.
4093
+ if (this.identityEffects?.getStore())
4094
+ return this.identityEffects.exit(() => this.scheduleErrorNoticeCheck(chatId));
4095
+ if (this.identityClosed)
4096
+ return;
3669
4097
  const previous = this.errorNoticeTimers.get(chatId);
3670
4098
  if (previous)
3671
4099
  clearTimeout(previous);
@@ -3682,6 +4110,11 @@ export class FeishuBot {
3682
4110
  }
3683
4111
  /** Bounded read-only diagnosis; known live tasks retain low-frequency observation. */
3684
4112
  async reconcileErrorNotices(chatId) {
4113
+ // Shared durable owner, not the lifetime of the ingress that woke it.
4114
+ if (this.identityEffects?.getStore())
4115
+ return this.identityEffects.exit(() => this.reconcileErrorNotices(chatId));
4116
+ if (this.identityClosed)
4117
+ return;
3685
4118
  const running = this.errorNoticeChecks.get(chatId);
3686
4119
  if (running)
3687
4120
  return running;
@@ -3736,6 +4169,11 @@ export class FeishuBot {
3736
4169
  return promise;
3737
4170
  }
3738
4171
  scheduleDeliveryRetry(chatId, attempt, local = false) {
4172
+ // Shared durable owner, not the lifetime of the ingress that woke it.
4173
+ if (this.identityEffects?.getStore())
4174
+ return this.identityEffects.exit(() => this.scheduleDeliveryRetry(chatId, attempt, local));
4175
+ if (this.identityClosed)
4176
+ return;
3739
4177
  if (this.deliveryRetryTimers.has(chatId))
3740
4178
  return;
3741
4179
  const delay = Math.min(local ? 300_000 : 30_000, DELIVERY_RETRY_BASE_MS * Math.max(1, 2 ** Math.min(16, Math.max(0, attempt - 1))));
@@ -3834,6 +4272,11 @@ export class FeishuBot {
3834
4272
  }
3835
4273
  }
3836
4274
  async dispatchPendingDeliveries(chatId, replyToMessageId) {
4275
+ // Shared durable owner, not the lifetime of the ingress that woke it.
4276
+ if (this.identityEffects?.getStore())
4277
+ return this.identityEffects.exit(() => this.dispatchPendingDeliveries(chatId, replyToMessageId));
4278
+ if (this.identityClosed)
4279
+ return;
3837
4280
  this.installGoReceiptCapture();
3838
4281
  for (const id of this.localDeliveryRetryCustody.get(chatId) || []) {
3839
4282
  try {
@@ -4517,6 +4960,7 @@ export class FeishuBot {
4517
4960
  };
4518
4961
  }
4519
4962
  async replyCompactCard(messageId, view, chatId) {
4963
+ this.assertIdentityCurrent();
4520
4964
  const res = await this.client.im.message.reply({
4521
4965
  path: { message_id: messageId },
4522
4966
  data: {
@@ -4527,6 +4971,7 @@ export class FeishuBot {
4527
4971
  return res?.data?.message_id || res?.message_id;
4528
4972
  }
4529
4973
  async patchCompactCard(messageId, view, chatId) {
4974
+ this.assertIdentityCurrent();
4530
4975
  await this.client.im.message.patch({
4531
4976
  path: { message_id: messageId },
4532
4977
  data: { content: JSON.stringify(this.buildCompactProgressCard(view, chatId)) },
@@ -4599,6 +5044,7 @@ export class FeishuBot {
4599
5044
  }
4600
5045
  }
4601
5046
  async replyMessage(messageId, text) {
5047
+ this.assertIdentityCurrent();
4602
5048
  // Use Feishu CardKit v2 markdown component for full Markdown rendering.
4603
5049
  const model = this.replyModelFooters.get(messageId);
4604
5050
  const status = this.replyStatusFooters.get(messageId);
@@ -5054,6 +5500,7 @@ export class FeishuBot {
5054
5500
  return firstId;
5055
5501
  }
5056
5502
  async sendMessage(chatId, text) {
5503
+ this.assertIdentityCurrent();
5057
5504
  const model = this.sendModelFooters.get(chatId);
5058
5505
  const status = this.sendStatusFooters.get(chatId);
5059
5506
  const card = this.buildMarkdownCard(text, model, status);
@@ -5123,7 +5570,7 @@ export class FeishuBot {
5123
5570
  */
5124
5571
  sendOrdered(chatId, fn) {
5125
5572
  const prev = this.sendQueue.get(chatId) || Promise.resolve();
5126
- const run = () => this.withSendDeadline(fn, chatId);
5573
+ const run = () => { this.assertIdentityCurrent(); return this.withSendDeadline(fn, chatId); };
5127
5574
  const next = prev.then(run, run); // run even if previous failed
5128
5575
  this.sendQueue.set(chatId, next.then(() => undefined, () => undefined));
5129
5576
  return next;
@@ -5360,16 +5807,21 @@ export class FeishuBot {
5360
5807
  }
5361
5808
  const previous = this.config.model;
5362
5809
  const sessionKey = await this.ensureSession(chatId);
5810
+ await this.assertIdentityEffect();
5363
5811
  try {
5364
5812
  // Validate/apply to the current session first. If OpenClaw rejects the
5365
5813
  // model, do not persist a bad config.
5366
- await this.openclawClient.patchSession({ key: sessionKey, model: nextModel });
5814
+ await this.openclawClient.patchSession({ key: sessionKey, model: nextModel,
5815
+ ...(this.identityEffects?.getStore() ? { expectedSessionId: this.identityEffects.getStore().item.target.sessionId } : {}) });
5816
+ await this.assertIdentityEffect();
5367
5817
  persistBotModel(this.configPath, this.config.name, nextModel);
5368
5818
  this.config.model = nextModel;
5369
5819
  await this.replyMessage(messageId, `✅ ${this.config.name} 模型已切换并持久化\n之前:${previous}\n现在:${nextModel}`);
5370
5820
  }
5371
5821
  catch (err) {
5372
- await this.openclawClient.patchSession({ key: sessionKey, model: previous }).catch(() => { });
5822
+ await this.assertIdentityEffect();
5823
+ await this.openclawClient.patchSession({ key: sessionKey, model: previous,
5824
+ ...(this.identityEffects?.getStore() ? { expectedSessionId: this.identityEffects.getStore().item.target.sessionId } : {}) }).catch(() => { });
5373
5825
  await this.replyMessage(messageId, `❌ 模型切换失败,配置未修改\n目标:${nextModel}\n原因:${err.message}`);
5374
5826
  }
5375
5827
  }
@@ -5388,6 +5840,7 @@ export class FeishuBot {
5388
5840
  catch {
5389
5841
  // session may not exist yet
5390
5842
  }
5843
+ this.assertIdentityCurrent();
5391
5844
  // Always show the configured model — session.model may show gateway-injected internal name
5392
5845
  const model = this.config.model;
5393
5846
  const totalTokens = session?.totalTokens || 0;
@@ -5449,7 +5902,7 @@ export class FeishuBot {
5449
5902
  if (mode === "tooltrim") {
5450
5903
  onPhase?.("tooltrim");
5451
5904
  try {
5452
- const res = await this.openclawClient.toolTrimCompact(sessionKey, 10);
5905
+ const res = this.identityEffects?.getStore() ? await this.openclawClient.toolTrimCompact(sessionKey, 10, () => this.assertIdentityEffect()) : await this.openclawClient.toolTrimCompact(sessionKey, 10);
5453
5906
  if (res?.compacted === true) {
5454
5907
  return {
5455
5908
  compacted: true,
@@ -5470,7 +5923,7 @@ export class FeishuBot {
5470
5923
  if (mode === "trim") {
5471
5924
  onPhase?.("trim");
5472
5925
  try {
5473
- const trimmed = await this.openclawClient.compactSession(sessionKey, { maxLines: trimMaxLines });
5926
+ const trimmed = await this.openclawClient.compactSession(sessionKey, { maxLines: trimMaxLines, ...(this.identityEffects?.getStore() ? { effectGuard: () => this.assertIdentityEffect() } : {}) });
5474
5927
  if (trimmed?.compacted === true) {
5475
5928
  const kept = typeof trimmed?.kept === "number" ? trimmed.kept : trimMaxLines;
5476
5929
  return { compacted: true, method: "transcript-trim", detail: `kept ${kept} transcript events` };
@@ -5485,7 +5938,7 @@ export class FeishuBot {
5485
5938
  // semantic mode: LLM summarize first, trim as fallback.
5486
5939
  let nativeReason;
5487
5940
  try {
5488
- const res = await this.openclawClient.semanticCompact(sessionKey);
5941
+ const res = this.identityEffects?.getStore() ? await this.openclawClient.semanticCompact(sessionKey, () => this.assertIdentityEffect()) : await this.openclawClient.semanticCompact(sessionKey);
5489
5942
  if (res?.compacted === true)
5490
5943
  return { compacted: true, method: "native" };
5491
5944
  nativeReason = typeof res?.reason === "string" ? res.reason : undefined;
@@ -5495,7 +5948,7 @@ export class FeishuBot {
5495
5948
  }
5496
5949
  onPhase?.("transcript-trim");
5497
5950
  try {
5498
- const trimmed = await this.openclawClient.compactSession(sessionKey, { maxLines: trimMaxLines });
5951
+ const trimmed = await this.openclawClient.compactSession(sessionKey, { maxLines: trimMaxLines, ...(this.identityEffects?.getStore() ? { effectGuard: () => this.assertIdentityEffect() } : {}) });
5499
5952
  if (trimmed?.compacted === true) {
5500
5953
  const kept = typeof trimmed?.kept === "number" ? trimmed.kept : trimMaxLines;
5501
5954
  return {
@@ -5626,10 +6079,14 @@ export class FeishuBot {
5626
6079
  async handleResetCommand(chatId, messageId) {
5627
6080
  const sessionKey = this.getSessionKey(chatId);
5628
6081
  try {
6082
+ await this.assertIdentityEffect();
5629
6083
  // Go supervision: a reset replaces the executor session generation; pause
5630
6084
  // supervision instead of letting the checker judge a wiped transcript.
5631
6085
  void this.goController?.onExecutorSessionChanged(chatId, "执行会话被 /reset");
5632
6086
  this.stopEpoch.set(chatId, this.store.bumpStopGeneration(this.config.name, chatId));
6087
+ const held = this.identityEffects?.getStore();
6088
+ if (held)
6089
+ held.epoch = this.stopGeneration(chatId);
5633
6090
  this.presentation(() => this.queuedPresentations.retire(chatId));
5634
6091
  this.store.stopInsertions(this.config.name, chatId);
5635
6092
  this.store.cancelReactionIntents(this.config.name, chatId, this.stopGeneration(chatId));
@@ -5641,9 +6098,11 @@ export class FeishuBot {
5641
6098
  this.openclawClient.resetSession(sessionKey).catch(() => { });
5642
6099
  // Wait a moment for it to take effect
5643
6100
  await new Promise((r) => setTimeout(r, 2000));
5644
- // Re-init session
6101
+ this.assertIdentityCurrent();
6102
+ // A held reset must not initialize an unobserved successor generation.
5645
6103
  this.initializedSessions.delete(sessionKey);
5646
- await this.ensureSession(chatId);
6104
+ if (!held)
6105
+ await this.ensureSession(chatId);
5647
6106
  await this.replyMessage(messageId, `✅ Session 已重置\n模型: ${this.config.model}`);
5648
6107
  }
5649
6108
  catch (err) {
@@ -5661,9 +6120,13 @@ export class FeishuBot {
5661
6120
  // cannot wake the just-stopped task back up with a follow-up.
5662
6121
  void this.goController?.pauseSilently(chatId, "用户执行了 /stop");
5663
6122
  try {
6123
+ await this.assertIdentityEffect();
5664
6124
  // Bump the stop generation FIRST so any in-flight auto-retry loop sees the
5665
6125
  // cancellation on its next iteration and stops retrying immediately.
5666
6126
  this.stopEpoch.set(chatId, this.store.bumpStopGeneration(this.config.name, chatId));
6127
+ const held = this.identityEffects?.getStore();
6128
+ if (held)
6129
+ held.epoch = this.stopGeneration(chatId);
5667
6130
  this.presentation(() => this.queuedPresentations.retire(chatId));
5668
6131
  this.store.cancelReactionIntents(this.config.name, chatId, this.stopGeneration(chatId));
5669
6132
  void this.reconcileReactions(chatId).catch(() => { });
@@ -5721,6 +6184,8 @@ export class FeishuBot {
5721
6184
  const chatResp = await this.client.im.chat.get({
5722
6185
  path: { chat_id: chatId },
5723
6186
  });
6187
+ if (this.identityClosed)
6188
+ return;
5724
6189
  const chatName = chatResp.data?.name || "";
5725
6190
  // Fetch members
5726
6191
  let members = [];
@@ -5741,6 +6206,8 @@ export class FeishuBot {
5741
6206
  catch {
5742
6207
  // Some bots may lack permission to list members
5743
6208
  }
6209
+ if (this.identityClosed)
6210
+ return;
5744
6211
  this.store.upsertChatInfo({
5745
6212
  chatId,
5746
6213
  chatType: "group",