openclaw-lark-multi-agent 1.8.18 → 1.8.20

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.
@@ -1,3 +1,4 @@
1
+ import { INPUT_DISPLAY_LIMITS, LIVE_CARD_BYTES, displayClip, hintDetail, hintLabel, inertInputText, inputPreview, visibleInputPreview, selectInputHints } from "./input-status-display.js";
1
2
  import { createHash, randomUUID } from 'node:crypto';
2
3
  import { AsyncLocalStorage } from "node:async_hooks";
3
4
  import * as lark from "@larksuiteoapi/node-sdk";
@@ -7,17 +8,18 @@ import { getI18n, normalizeLocale } from "./i18n.js";
7
8
  import { InactiveRunObservation, AdmissionUnconfirmed, CollectorStalledError, FollowupAdmissionRefused } from "./openclaw-client.js";
8
9
  import { SessionWaitPaused, isWaitTimeout, normalizeSessionRuntimeStatus, formatSessionFooter, FOREGROUND_WAIT_MS } from "./session-status.js";
9
10
  import { SupersededObservation } from "./openclaw-client.js";
10
- import { LiveStatusController, LiveStatusEffectRejectedError, LiveStatusEffectUnknownError } from "./live-status.js";
11
+ import { LiveStatusController, LiveStatusEffectRejectedError, LiveStatusEffectUnknownError, LiveStatusEffectSuppressedError } from "./live-status.js";
11
12
  import { QueuedPresentations } from "./queued-presentation.js";
12
13
  import { CompactProgressController } from "./compact-progress.js";
13
14
  import { GoController } from "./go-controller.js";
14
- import { errorIdentity } from "./terminal-errors.js";
15
+ import { RunTerminalError, closedStopReason, errorNoticeIdentity, errorIdentity } from "./terminal-errors.js";
15
16
  import { formatProviderError, safeErrorSummary } from "./provider-errors.js";
16
17
  import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "fs";
17
18
  import { basename, extname, join, resolve } from "path";
18
19
  import { getBridgeAttachmentsDir, getDataDir } from "./paths.js";
19
20
  import { buildFeishuCardElements } from "./markdown.js";
20
21
  import { discussionManager } from "./discussion-manager.js";
22
+ import { requestBotIdentity, trustedBotOpenId } from "./bot-identity.js";
21
23
  /** Observation deadline, never a claim that the underlying SDK was cancelled. */
22
24
  export class SendDeadlineError extends Error {
23
25
  chatId;
@@ -34,6 +36,9 @@ const canonicalPhysicalSessionKey = (key) => /^agent:[^:]+:/.test(key) ? key : `
34
36
  const require = createRequire(import.meta.url);
35
37
  const LMA_VERSION = require("../package.json").version;
36
38
  const MAX_BOT_STREAK = 10;
39
+ const IDENTITY_DEADLINE_MS = 2_000;
40
+ const IDENTITY_RETRY_BASE_MS = 5_000;
41
+ const IDENTITY_RETRY_CAP_MS = 5 * 60_000;
37
42
  const MAX_MERGED_TRIGGER_MESSAGES = Number(process.env.OPENCLAW_LARK_MULTI_AGENT_MAX_MERGED_TRIGGER_MESSAGES || 100);
38
43
  const MAX_MERGED_TRIGGER_BYTES = Number(process.env.OPENCLAW_LARK_MULTI_AGENT_MAX_MERGED_TRIGGER_BYTES || 128 * 1024);
39
44
  const BRIDGE_ATTACHMENTS_DIR = getBridgeAttachmentsDir();
@@ -134,6 +139,21 @@ export class FeishuBot {
134
139
  openclawClient;
135
140
  store;
136
141
  botOpenId = null;
142
+ identityClosed = false;
143
+ identityRetryTimer;
144
+ identityFlight;
145
+ identityAbort;
146
+ identityNextProbeAt = 0;
147
+ identityFailures = 0;
148
+ identityDrain;
149
+ identityDrainRetry = false;
150
+ identityDrainNextAt = 0;
151
+ identityDrainFailures = 0;
152
+ identityCaptures = new Map();
153
+ identityTargetRepairs = new Map();
154
+ identitySessionWaiters = new Set();
155
+ identityEffects = new AsyncLocalStorage();
156
+ requestIdentity = (signal) => requestBotIdentity(this.config, signal, IDENTITY_DEADLINE_MS);
137
157
  /** Tracks which chatId sessions have been initialized */
138
158
  initializedSessions = new Set();
139
159
  /** Per-chat busy lock: timestamp when became busy (0 = not busy) */
@@ -333,6 +353,15 @@ export class FeishuBot {
333
353
  this.config = config;
334
354
  this.openclawClient = openclawClient;
335
355
  this.store = store;
356
+ this.store.onClose(() => {
357
+ this.identityClosed = true;
358
+ clearTimeout(this.identityRetryTimer);
359
+ this.identityRetryTimer = undefined;
360
+ this.identityAbort?.();
361
+ for (const cancel of this.identitySessionWaiters)
362
+ cancel();
363
+ this.identityTargetRepairs.clear();
364
+ });
336
365
  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
366
  this.store.onClose(() => this.queuedPresentations.dispose());
338
367
  this.openclawClient.bindRecoveryStore?.(store);
@@ -416,6 +445,10 @@ export class FeishuBot {
416
445
  if (!rowId)
417
446
  return;
418
447
  this.store.clearPendingTrigger(this.config.name, chatId, rowId);
448
+ // Privacy invalidation starts before reaction SDK I/O: unrelated lookup
449
+ // latency must not retain a recalled preview on a frozen/terminal card.
450
+ void this.queuedPresentations.refreshRecalledInput(chatId, rowId, messageId)
451
+ .catch(err => console.warn(`[${this.config.name}] Recalled-input UI redaction unavailable:`, this.errorSummary(err)));
419
452
  const pendingAcks = this.pendingAckMessages.get(chatId) || [];
420
453
  const remainingAcks = [];
421
454
  for (const ack of pendingAcks) {
@@ -461,11 +494,22 @@ export class FeishuBot {
461
494
  * Ensure the session for a given chatId exists with the correct model.
462
495
  * Lazy: only creates on first message in that chat.
463
496
  */
464
- async ensureSession(chatId) {
497
+ async ensureSession(chatId, setupFence) {
465
498
  const sessionKey = this.getSessionKey(chatId);
499
+ await this.assertIdentityEffect();
500
+ const held = this.identityEffects?.getStore();
501
+ const expectedSessionId = held?.item.target.sessionId || setupFence?.sessionId;
502
+ const setupGuard = () => { this.assertIdentityCurrent(); setupFence?.guard(); };
503
+ if (setupFence) {
504
+ const info = await this.identitySessionInfo(sessionKey);
505
+ setupGuard();
506
+ if (info?.session?.sessionId !== setupFence.sessionId || info.session.archived)
507
+ throw new SupersededObservation('retained setup physical target changed');
508
+ }
466
509
  if (this.initializedSessions.has(sessionKey)) {
467
510
  // Already initialized this process lifetime, just ensure model
468
- const corrected = await this.openclawClient.ensureModel(sessionKey, this.config.model);
511
+ const corrected = (expectedSessionId ? await this.openclawClient.ensureModel(sessionKey, this.config.model, { sessionId: expectedSessionId, guard: setupGuard }) : await this.openclawClient.ensureModel(sessionKey, this.config.model));
512
+ setupGuard();
469
513
  if (corrected) {
470
514
  console.log(`[${this.config.name}] Model auto-corrected to ${this.config.model}`);
471
515
  }
@@ -474,10 +518,14 @@ export class FeishuBot {
474
518
  try {
475
519
  // Check if session already exists in OpenClaw
476
520
  const existing = await this.openclawClient.getSessionInfo(sessionKey).catch(() => null);
521
+ setupGuard();
522
+ if (expectedSessionId && (existing?.session?.sessionId !== expectedSessionId || existing.session.archived))
523
+ throw new SupersededObservation('retained session setup changed');
477
524
  if (existing?.session) {
478
525
  // Session exists — preserve it, only ensure model is correct
479
526
  console.log(`[${this.config.name}] Session exists: ${sessionKey} (tokens: ${existing.session.totalTokens || 0})`);
480
- const corrected = await this.openclawClient.ensureModel(sessionKey, this.config.model);
527
+ const corrected = (expectedSessionId ? await this.openclawClient.ensureModel(sessionKey, this.config.model, { sessionId: expectedSessionId, guard: setupGuard }) : await this.openclawClient.ensureModel(sessionKey, this.config.model));
528
+ setupGuard();
481
529
  if (corrected) {
482
530
  console.log(`[${this.config.name}] Model auto-corrected to ${this.config.model}`);
483
531
  }
@@ -501,6 +549,7 @@ export class FeishuBot {
501
549
  console.warn(`[${this.config.name}] ensureSession error:`, safeErrorSummary(err));
502
550
  throw err;
503
551
  }
552
+ setupGuard();
504
553
  this.initializedSessions.add(sessionKey);
505
554
  // Subscribe to session events (proactive messages + tool calls)
506
555
  this.openclawClient.setVerboseTranscriptDelivery(sessionKey, this.store.getBotVerbose(this.config.name, chatId));
@@ -517,7 +566,7 @@ export class FeishuBot {
517
566
  }
518
567
  if (meta?.sourceType === "run_error" || provenance) {
519
568
  if (provenance) {
520
- this.store.observeRunError(this.config.name, chatId, provenance);
569
+ this.store.observeRunError(this.config.name, chatId, this.scopeRunError(chatId, provenance));
521
570
  await this.reconcileErrorNotices(chatId);
522
571
  }
523
572
  else
@@ -606,32 +655,255 @@ export class FeishuBot {
606
655
  */
607
656
  async start() {
608
657
  await this.probeBotIdentity();
658
+ if (this.identityClosed)
659
+ return;
609
660
  await this.wsClient.start({ eventDispatcher: this.eventDispatcher });
661
+ if (this.identityClosed)
662
+ return;
610
663
  console.log(`[${this.config.name}] Bot started (model: ${this.config.model}, open_id: ${this.botOpenId || "unknown"})`);
611
664
  // Drain any unsynced messages left from previous run
612
665
  this.drainOnStartup();
666
+ void this.drainIdentityIngress().catch(err => console.warn(`[${this.config.name}] Identity ingress recovery failed:`, err.message));
613
667
  }
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})`);
668
+ /** Local custody repair only. This never authorizes replay of a claimed event
669
+ * or re-probes an already known identity. The journal remains the sole owner. */
670
+ retryIdentityIngress(error) {
671
+ if (this.identityClosed)
672
+ return;
673
+ const code = error?.code;
674
+ console.warn(`[${this.config.name}] Identity custody recovery deferred:`, code === "SQLITE_BUSY" || code === "SQLITE_LOCKED" ? code : safeErrorSummary(error));
675
+ this.identityDrainRetry = true;
676
+ this.identityDrainNextAt = Date.now() + Math.min(IDENTITY_RETRY_CAP_MS, IDENTITY_RETRY_BASE_MS * 2 ** Math.min(this.identityDrainFailures++, 6));
677
+ this.scheduleIdentityProbe();
678
+ }
679
+ /** Bounded, read-only public metadata. Late responses never write custody. */
680
+ identitySessionInfo(key) {
681
+ if (this.identityClosed)
682
+ return Promise.resolve(null);
683
+ return new Promise(resolve => {
684
+ let done = false;
685
+ const finish = (value) => { if (done)
686
+ return; done = true; clearTimeout(timer); this.identitySessionWaiters.delete(cancel); resolve(value); };
687
+ const cancel = () => finish(null);
688
+ const timer = setTimeout(cancel, IDENTITY_DEADLINE_MS);
689
+ timer.unref?.();
690
+ this.identitySessionWaiters.add(cancel);
691
+ void Promise.resolve().then(() => this.identityClosed ? null : this.openclawClient.getSessionInfo(key, IDENTITY_DEADLINE_MS))
692
+ .then(finish, () => finish(null));
693
+ });
694
+ }
695
+ captureIdentityTarget(messageId, chatId) {
696
+ const key = this.getSessionKey(chatId);
697
+ const work = (async () => {
698
+ const info = await this.identitySessionInfo(key);
699
+ if (this.identityClosed)
700
+ return;
701
+ const session = info?.session;
702
+ const target = typeof session?.sessionId === 'string' && session.sessionId.trim() && session.sessionId.length <= 256 && session.archived !== true
703
+ && (!session.key || typeof session.key === 'string' && canonicalPhysicalSessionKey(session.key) === canonicalPhysicalSessionKey(key))
704
+ ? { state: 'bound', sessionKey: key, sessionId: session.sessionId } : { state: 'unbound', sessionKey: key };
705
+ if (target.state === 'unbound')
706
+ console.warn(`[${this.config.name}] Identity input ${messageId} has no proven original physical session; retained without retargeting`);
707
+ this.identityTargetRepairs.set(messageId, target);
708
+ this.store.finishIdentityTarget(this.config.name, this.config.appId, messageId, target);
709
+ this.identityTargetRepairs.delete(messageId);
710
+ })().catch(err => this.retryIdentityIngress(err)).finally(() => this.identityCaptures.delete(messageId));
711
+ this.identityCaptures.set(messageId, work);
712
+ return work;
713
+ }
714
+ assertIdentityCurrent() {
715
+ const fence = this.identityEffects?.getStore();
716
+ if (!fence)
717
+ return;
718
+ if (this.identityClosed || this.stopGeneration(fence.item.chatId) !== fence.epoch || this.store.isMessageRecalled(fence.item.messageId))
719
+ throw new SupersededObservation('retained identity input cancelled');
720
+ }
721
+ async assertIdentityEffect() {
722
+ const fence = this.identityEffects?.getStore();
723
+ if (!fence)
724
+ return;
725
+ this.assertIdentityCurrent();
726
+ const info = await this.identitySessionInfo(fence.item.target.sessionKey);
727
+ this.assertIdentityCurrent();
728
+ if (info?.session?.archived === true || info?.session?.sessionId !== fence.item.target.sessionId)
729
+ throw new SupersededObservation('retained identity physical session unavailable or changed');
730
+ }
731
+ /** One background timer per bot covers both discovery and local journal
732
+ * repair; every asynchronous AND synchronous timer effect is owned. */
733
+ scheduleIdentityProbe() {
734
+ if (this.identityClosed || (this.botOpenId && !this.identityDrainRetry) || this.identityRetryTimer)
735
+ return;
736
+ this.identityRetryTimer = setTimeout(() => {
737
+ this.identityRetryTimer = undefined;
738
+ if (this.identityClosed)
739
+ return;
740
+ void Promise.resolve().then(async () => {
741
+ if (this.identityClosed)
742
+ return;
743
+ if (!this.botOpenId) {
744
+ this.store.pruneIdentityIngress(this.config.name, this.config.appId);
745
+ await this.probeBotIdentity();
746
+ }
747
+ await this.drainIdentityIngress();
748
+ }).catch(err => this.retryIdentityIngress(err))
749
+ .finally(() => this.scheduleIdentityProbe());
750
+ }, Math.max(IDENTITY_RETRY_BASE_MS, Math.max(this.botOpenId ? 0 : this.identityNextProbeAt, this.identityDrainNextAt) - Date.now()));
751
+ this.identityRetryTimer.unref?.();
752
+ }
753
+ /** Bounded observation AND cancellable HTTP (including token discovery).
754
+ * Even a nonconforming transport ignoring abort retains single-flight custody
755
+ * until it settles; we never accumulate timed-out requests or trust late data. */
756
+ probeBotIdentity() {
757
+ if (this.identityClosed || this.botOpenId)
758
+ return Promise.resolve();
759
+ if (this.identityFlight) {
760
+ // While the initial observation is active its completion owns scheduling.
761
+ // Only a timed-out, still-owned raw request needs another liveness check.
762
+ if (this.identityNextProbeAt)
763
+ this.scheduleIdentityProbe();
764
+ return this.identityFlight;
765
+ }
766
+ if (Date.now() < this.identityNextProbeAt) {
767
+ this.scheduleIdentityProbe();
768
+ return Promise.resolve();
769
+ }
770
+ clearTimeout(this.identityRetryTimer);
771
+ this.identityRetryTimer = undefined;
772
+ this.identityNextProbeAt = 0;
773
+ const controller = new AbortController();
774
+ let live = true;
775
+ let finish;
776
+ const observed = new Promise(resolve => { finish = resolve; });
777
+ this.identityFlight = observed;
778
+ const expire = () => {
779
+ if (live && !this.identityClosed)
780
+ console.warn(`[${this.config.name}] Bot identity probe exceeded ${IDENTITY_DEADLINE_MS}ms; retaining unresolved mentions`);
781
+ live = false;
782
+ controller.abort();
783
+ finish();
784
+ };
785
+ this.identityAbort = expire;
786
+ const deadline = setTimeout(expire, IDENTITY_DEADLINE_MS);
787
+ deadline.unref?.();
788
+ const raw = Promise.resolve().then(() => {
789
+ if (this.identityClosed || controller.signal.aborted)
790
+ throw new Error("identity probe cancelled");
791
+ return this.requestIdentity(controller.signal);
792
+ });
793
+ void raw.then(response => {
794
+ if (!live || this.identityClosed || this.botOpenId)
795
+ return;
796
+ const openId = trustedBotOpenId(response, this.config.appId);
797
+ if (!openId)
798
+ throw new Error("bot-info response contained no valid original-account identity");
799
+ this.botOpenId = openId;
800
+ console.log(`[${this.config.name}] Bot identity resolved: ${openId}`);
801
+ }).catch(err => {
802
+ if (live && !this.identityClosed)
803
+ console.warn(`[${this.config.name}] Bot identity probe failed:`, err.message);
804
+ }).finally(() => {
805
+ clearTimeout(deadline);
806
+ live = false;
807
+ if (this.identityFlight === observed)
808
+ this.identityFlight = undefined;
809
+ this.identityAbort = undefined;
810
+ finish();
811
+ });
812
+ void observed.then(() => {
813
+ clearTimeout(deadline);
814
+ if (this.identityClosed)
815
+ return;
816
+ if (!this.botOpenId) {
817
+ this.identityNextProbeAt = Date.now() + Math.min(IDENTITY_RETRY_CAP_MS, IDENTITY_RETRY_BASE_MS * 2 ** Math.min(this.identityFailures++, 6));
818
+ this.scheduleIdentityProbe();
627
819
  }
628
820
  else {
629
- console.warn(`[${this.config.name}] Bot identity probe returned no botID`);
821
+ clearTimeout(this.identityRetryTimer);
822
+ this.identityRetryTimer = undefined;
823
+ void this.drainIdentityIngress().catch(err => console.warn(`[${this.config.name}] Identity ingress recovery failed:`, err.message));
824
+ }
825
+ }).catch(err => this.retryIdentityIngress(err));
826
+ return observed;
827
+ }
828
+ /** Metadata may say who was targeted, but can never say who THIS bot is. */
829
+ needsIdentityRecovery(message) {
830
+ if (message.chat_type === "p2p" || this.botOpenId)
831
+ return false;
832
+ let mentions = Array.isArray(message.mentions) ? message.mentions : [];
833
+ if (!mentions.length && message.message_type === "post") {
834
+ try {
835
+ const content = JSON.parse(message.content);
836
+ const posts = content.content ? [content] : Object.values(content);
837
+ mentions = posts.flatMap((post) => (post?.content || []).flat())
838
+ .filter((node) => node?.tag === "at").map((node) => ({ id: { open_id: node.user_id } }));
839
+ }
840
+ catch {
841
+ return false;
630
842
  }
631
843
  }
632
- catch (err) {
633
- console.warn(`[${this.config.name}] Bot identity probe failed:`, err.message);
634
- }
844
+ // An app-only self mention is already an independent proof, including a
845
+ // mixed self+human message. But if a self app_id also supplies an open_id,
846
+ // resolve first: an unknown identity must not hide a conflicting pair.
847
+ const selfPair = mentions.some((mention) => mention.id?.app_id === this.config.appId && mention.id?.open_id);
848
+ if (!selfPair && mentions.some((mention) => this.mentionedBotName(mention) === this.config.name))
849
+ return false;
850
+ return mentions.some((mention) => !this.isAllMentionItem(mention)
851
+ && typeof mention.id?.open_id === "string" && !!mention.id.open_id
852
+ && (!mention.id.app_id || mention.id.app_id === this.config.appId));
853
+ }
854
+ drainIdentityIngress() {
855
+ if (this.identityClosed || !this.botOpenId)
856
+ return Promise.resolve();
857
+ if (this.identityDrain)
858
+ return this.identityDrain;
859
+ if (this.identityDrainRetry && Date.now() < this.identityDrainNextAt) {
860
+ this.scheduleIdentityProbe();
861
+ return Promise.resolve();
862
+ }
863
+ this.identityDrain = (async () => {
864
+ for (const [messageId, target] of this.identityTargetRepairs) {
865
+ if (this.identityClosed)
866
+ return;
867
+ this.store.finishIdentityTarget(this.config.name, this.config.appId, messageId, target);
868
+ this.identityTargetRepairs.delete(messageId);
869
+ }
870
+ for (const item of this.store.listIdentityIngress(this.config.name, this.config.appId)) {
871
+ if (this.identityClosed)
872
+ return;
873
+ const capture = this.identityCaptures.get(item.messageId);
874
+ if (capture)
875
+ await capture;
876
+ if (this.identityClosed)
877
+ return;
878
+ // Capture owns a paced retry of its SAME proof. Do not clear that
879
+ // repair intent just because this drain began before capture settled.
880
+ if (this.identityTargetRepairs.has(item.messageId))
881
+ return;
882
+ item.target = this.store.getIdentityTarget(this.config.name, this.config.appId, item.messageId);
883
+ if (item.target.state !== 'bound' || !item.target.sessionId || item.target.sessionKey !== this.getSessionKey(item.chatId))
884
+ continue;
885
+ const info = await this.identitySessionInfo(item.target.sessionKey);
886
+ if (this.identityClosed)
887
+ return;
888
+ if (!info?.session?.sessionId)
889
+ throw new Error('retained physical session check unavailable');
890
+ if (info.session.archived === true || info.session.sessionId !== item.target.sessionId) {
891
+ this.store.claimIdentityIngress(this.config.name, this.config.appId, item);
892
+ this.store.clearIdentityIngress(this.config.name, this.config.appId, item.messageId);
893
+ continue;
894
+ }
895
+ await this.identityEffects.run({ item, epoch: item.stopEpoch }, () => this.handleResolvedMessage(item.event, item));
896
+ }
897
+ if (this.identityTargetRepairs.size)
898
+ return;
899
+ this.identityDrainRetry = false;
900
+ this.identityDrainNextAt = 0;
901
+ this.identityDrainFailures = 0;
902
+ clearTimeout(this.identityRetryTimer);
903
+ this.identityRetryTimer = undefined;
904
+ })().catch(err => this.retryIdentityIngress(err))
905
+ .finally(() => { this.identityDrain = undefined; this.scheduleIdentityProbe(); });
906
+ return this.identityDrain;
635
907
  }
636
908
  /**
637
909
  * On startup, check all known chats for unsynced messages and process them.
@@ -648,7 +920,7 @@ export class FeishuBot {
648
920
  const drainTasks = [];
649
921
  for (const chat of chats) {
650
922
  // Skip p2p chats that belong to other bots
651
- if (chat.chatType === "p2p" && chat.ownerBot && chat.ownerBot !== this.config.name) {
923
+ if (chat.chatType === "p2p" && !this.store.claimP2pOwner(chat.chatId, this.config.name, this.config.appId)) {
652
924
  continue;
653
925
  }
654
926
  // Re-subscribe to existing sessions
@@ -697,6 +969,55 @@ export class FeishuBot {
697
969
  return undefined;
698
970
  }
699
971
  async handleMessage(data) {
972
+ try {
973
+ if (this.identityClosed)
974
+ return;
975
+ const message = data?.message;
976
+ if (!message?.chat_id || !message.message_id || !["text", "image", "file", "audio", "sticker", "post", "share_doc"].includes(message.message_type))
977
+ return;
978
+ if ((message.mentions || []).some((mention) => mention?.id && Object.hasOwn(mention.id, 'open_id') &&
979
+ (typeof mention.id.open_id !== 'string' || !mention.id.open_id.trim())))
980
+ return;
981
+ // Private duplicates must reach the stable app/chat fence so an old
982
+ // name-scoped tombstone cannot disappear across a later bot rename.
983
+ if (message.chat_type !== "p2p" && this.store.hasBotProcessed(this.config.name, message.message_id))
984
+ return;
985
+ // A duplicate must honor the original journal owner, even if its envelope
986
+ // differs or identity has resolved since the first receipt.
987
+ if (this.store.hasIdentityIngress(this.config.name, this.config.appId, message.message_id) || this.needsIdentityRecovery(message)) {
988
+ const retained = this.store.retainIdentityIngress(this.config.name, this.config.appId, data, this.getSessionKey(message.chat_id));
989
+ if (retained !== "retained" && retained !== "created") {
990
+ if (retained === "full")
991
+ console.warn(`[${this.config.name}] Identity ingress capacity exceeded; message ${message.message_id} was not admitted`);
992
+ return;
993
+ }
994
+ const capture = retained === 'created' ? this.captureIdentityTarget(message.message_id, message.chat_id) : this.identityCaptures.get(message.message_id);
995
+ const discovery = this.probeBotIdentity();
996
+ if (capture)
997
+ await capture;
998
+ await discovery;
999
+ if (!this.identityClosed)
1000
+ await this.drainIdentityIngress();
1001
+ return;
1002
+ }
1003
+ await this.handleResolvedMessage(data);
1004
+ }
1005
+ catch (err) {
1006
+ // If journal preflight fails, only durable, still-unclaimed custody may
1007
+ // be retried. Never recreate this event from an in-memory business promise.
1008
+ this.retryIdentityIngress(err);
1009
+ }
1010
+ }
1011
+ async handleResolvedMessage(data, identityItem) {
1012
+ // Retained inputs may enter only through the drain's exact guarded owner,
1013
+ // never through an unbound helper call or a reconstructed replay envelope.
1014
+ if (identityItem && this.identityEffects?.getStore()?.item !== identityItem)
1015
+ return;
1016
+ // Claim failures must reach the drain's repair owner. The SQLite transaction
1017
+ // rolls back, preserving the original event. After a successful claim the
1018
+ // ordinary handler's at-most-once failure behavior remains unchanged.
1019
+ if (identityItem && (this.identityClosed || !this.store.claimIdentityIngress(this.config.name, this.config.appId, identityItem)))
1020
+ return;
700
1021
  try {
701
1022
  const event = data;
702
1023
  const message = event.message;
@@ -707,7 +1028,7 @@ export class FeishuBot {
707
1028
  const messageType = message.message_type;
708
1029
  const messageId = message.message_id;
709
1030
  const isBot = sender?.sender_type === "app";
710
- // Identity comes from the startup probe, never from message mentions:
1031
+ // Identity comes from original-account probes, never from message mentions:
711
1032
  // a conflicting app_id/open_id pair must not overwrite a known identity.
712
1033
  if (messageType !== "text" && messageType !== "image" && messageType !== "file" && messageType !== "audio" && messageType !== "sticker" && messageType !== "post" && messageType !== "share_doc")
713
1034
  return;
@@ -715,16 +1036,32 @@ export class FeishuBot {
715
1036
  // Feishu/WebSocket can deliver the same event more than once; a separate
716
1037
  // has-then-mark sequence races and can send the same user message into
717
1038
  // OpenClaw twice.
718
- if (!this.store.tryMarkBotProcessed(this.config.name, messageId))
1039
+ if (this.identityClosed)
1040
+ return;
1041
+ if (!identityItem && !(chatType === "p2p"
1042
+ ? this.store.tryMarkP2pProcessed(this.config.appId, chatId, this.config.name, messageId)
1043
+ : this.store.tryMarkBotProcessed(this.config.name, messageId)))
719
1044
  return;
1045
+ const identityCurrent = () => {
1046
+ if (this.identityClosed)
1047
+ return false;
1048
+ if (identityItem) {
1049
+ try {
1050
+ this.assertIdentityCurrent();
1051
+ }
1052
+ catch {
1053
+ return false;
1054
+ }
1055
+ }
1056
+ return true;
1057
+ };
720
1058
  // --- Cache chat info (lazy, at most once per hour) ---
721
1059
  await this.fetchAndCacheChatInfo(chatId, chatType);
1060
+ if (!identityCurrent())
1061
+ return;
722
1062
  // --- P2P isolation: only the owning bot processes p2p messages ---
723
- if (chatType === "p2p") {
724
- const chatInfo = this.store.getChatInfo(chatId);
725
- if (chatInfo?.ownerBot && chatInfo.ownerBot !== this.config.name) {
726
- return; // This p2p chat belongs to another bot
727
- }
1063
+ if (chatType === "p2p" && !this.store.claimP2pOwner(chatId, this.config.name, this.config.appId)) {
1064
+ return; // A display-name match cannot override a conflicting app pin.
728
1065
  }
729
1066
  let content;
730
1067
  try {
@@ -734,6 +1071,14 @@ export class FeishuBot {
734
1071
  console.warn(`[${this.config.name}] Failed to parse message content, skipping`);
735
1072
  return;
736
1073
  }
1074
+ // Original visible input for UI only; never use hydrated media paths,
1075
+ // synthetic routing prompts or model/history text as its body.
1076
+ const inputCaption = [content.text, content.caption].find(value => typeof value === 'string') || '';
1077
+ const inputDisplayText = messageType === 'text' ? (typeof content.text === 'string' ? content.text.replace(/@_user_\d+/g, (key) => { const mention = (message.mentions || []).find((item) => item.key === key); return typeof mention?.name === 'string' ? `@${mention.name}` : key; }) : '') :
1078
+ messageType === 'file' ? `[${this.isEn(chatId) ? 'File' : '文件'}: ${(typeof content.file_name === 'string' ? content.file_name : 'file').split(/[\\/]/).at(-1)}] ${inputCaption}` :
1079
+ messageType === 'image' ? `[${this.isEn(chatId) ? 'Image' : '图片'}] ${inputCaption}` : messageType === 'audio' ? `[${this.isEn(chatId) ? 'Audio' : '语音'}] ${inputCaption}` : messageType === 'sticker' ? (this.isEn(chatId) ? '[Sticker]' : '[贴纸]') :
1080
+ messageType === 'post' ? this.visiblePostInput(content, chatId) :
1081
+ [content.title, content.name, content.text, content.url].find(value => typeof value === 'string') || '';
737
1082
  // --- Extract text content based on message type ---
738
1083
  let cleanText = "";
739
1084
  let rawText = "";
@@ -796,6 +1141,10 @@ export class FeishuBot {
796
1141
  cleanText = `[Sticker: ${content.file_key || "unknown"}]`;
797
1142
  }
798
1143
  cleanText = await this.hydrateFeishuDocsInMessage(cleanText, content, messageId);
1144
+ if (!identityCurrent())
1145
+ return;
1146
+ if (identityItem)
1147
+ await this.assertIdentityEffect();
799
1148
  if (!cleanText.trim())
800
1149
  return;
801
1150
  const routing = this.getRoutingIntent(chatType, message, messageType === "text" ? (content.text || "") : "", content);
@@ -967,12 +1316,16 @@ export class FeishuBot {
967
1316
  }
968
1317
  }
969
1318
  const markCommandSynced = () => {
1319
+ if (!identityCurrent())
1320
+ return;
970
1321
  if (insertedId > 0) {
971
1322
  this.store.markSynced(this.config.name, chatId, insertedId);
972
1323
  // Bridge commands should only clear their own pending row. They
973
1324
  // must not clear earlier human triggers that are waiting after a
974
1325
  // failed/empty run; /status must be safe to use for debugging.
975
1326
  this.store.clearPendingTrigger(this.config.name, chatId, insertedId);
1327
+ if (identityItem)
1328
+ this.store.clearIdentityIngress(this.config.name, this.config.appId, messageId);
976
1329
  }
977
1330
  };
978
1331
  if (commandName === "/help") {
@@ -1022,12 +1375,18 @@ export class FeishuBot {
1022
1375
  }
1023
1376
  if (commandName === "/status") {
1024
1377
  await this.ensureSession(chatId);
1378
+ if (!identityCurrent())
1379
+ return;
1380
+ await this.assertIdentityEffect();
1025
1381
  await this.handleStatusCommand(chatId, chatType, messageId);
1026
1382
  markCommandSynced();
1027
1383
  return;
1028
1384
  }
1029
1385
  if (commandName === "/compact") {
1030
1386
  await this.ensureSession(chatId);
1387
+ if (!identityCurrent())
1388
+ return;
1389
+ await this.assertIdentityEffect();
1031
1390
  const compactArgs = cleanText.trim().split(/\s+/).slice(1).join(" ").trim();
1032
1391
  await this.handleCompactCommand(chatId, messageId, compactArgs);
1033
1392
  markCommandSynced();
@@ -1035,16 +1394,28 @@ export class FeishuBot {
1035
1394
  }
1036
1395
  if (commandName === "/reset") {
1037
1396
  await this.ensureSession(chatId);
1397
+ if (!identityCurrent())
1398
+ return;
1399
+ await this.assertIdentityEffect();
1038
1400
  await this.handleResetCommand(chatId, messageId);
1039
1401
  markCommandSynced();
1040
1402
  return;
1041
1403
  }
1042
1404
  if (commandName === "/stop") {
1405
+ await this.assertIdentityEffect();
1043
1406
  await this.handleStopCommand(chatId, messageId);
1044
1407
  markCommandSynced();
1045
1408
  return;
1046
1409
  }
1047
1410
  if (commandName === "/go") {
1411
+ // Go owns a separate multi-await supervisor/bootstrap protocol. Its
1412
+ // public entry point cannot carry this hold's original executor CAS;
1413
+ // never turn a delayed mutating command into a new supervisor target.
1414
+ if (identityItem && !/^\/go(?:\s+status)?\s*$/i.test(cleanText.trim())) {
1415
+ await this.replyMessage(messageId, "ℹ️ 这条 /go 在身份恢复前收到,未执行。监督初始化不能携带原会话的完整保护条件;请确认当前会话后重新发送。");
1416
+ markCommandSynced();
1417
+ return;
1418
+ }
1048
1419
  // Go supervision targets one bot's executor session: groups require an
1049
1420
  // explicit mention (single-bot group is the implicit target), p2p always.
1050
1421
  const groupBotCount = Array.from(FeishuBot.allBots.values()).filter((bot) => bot.store === this.store).length;
@@ -1056,11 +1427,15 @@ export class FeishuBot {
1056
1427
  const control = /^(?:status|pause|resume|stop|model)(?:\s|$)/i.test(goArgs) || !goArgs;
1057
1428
  if (!control)
1058
1429
  await this.ensureSession(chatId);
1430
+ if (!identityCurrent())
1431
+ return;
1432
+ await this.assertIdentityEffect();
1059
1433
  await this.goController?.handleGoCommand(chatId, messageId, goArgs);
1060
1434
  }
1061
1435
  finally {
1062
1436
  markCommandSynced();
1063
- this.goController?.onCommandSettled(chatId);
1437
+ if (identityCurrent())
1438
+ this.goController?.onCommandSettled(chatId);
1064
1439
  }
1065
1440
  return;
1066
1441
  }
@@ -1252,6 +1627,8 @@ export class FeishuBot {
1252
1627
  // --- Should this bot respond? ---
1253
1628
  if (!this.shouldRespond(chatType, message, isBot, chatId, routing))
1254
1629
  return;
1630
+ if (identityItem)
1631
+ await this.assertIdentityEffect();
1255
1632
  let reservedAtIngress = false;
1256
1633
  if (!isBot && insertedId > 0) {
1257
1634
  this.goController?.onHumanInput(chatId);
@@ -1259,7 +1636,7 @@ export class FeishuBot {
1259
1636
  // No health/setup/model/history await precedes this honest local receipt.
1260
1637
  // UI custody cannot reserve dispatch or claim Gateway/model acceptance.
1261
1638
  const presentationRoot = this.queueOwners.get(chatId)?.runId || this.store.getDispatchCustody(this.config.name, chatId)?.runId;
1262
- this.presentation(() => this.queuedPresentations.receive(chatId, insertedId, messageId, isNativeOpenClawCommand, presentationRoot));
1639
+ this.presentation(() => this.queuedPresentations.receive(chatId, insertedId, messageId, isNativeOpenClawCommand, presentationRoot, { source: 'visible', text: inputDisplayText }));
1263
1640
  // Reserve BEFORE the first health/reaction await. Otherwise an ending
1264
1641
  // owner can ordinary-drain this row while its handler is still waiting,
1265
1642
  // and the later steer would submit the same message a second time.
@@ -1267,7 +1644,7 @@ export class FeishuBot {
1267
1644
  if ((this.queueRuns.has(chatId) || ingressOwner) && !ingressOwner?.triggerIds?.has(insertedId)) {
1268
1645
  this.store.saveInsertion(this.config.name, chatId, insertedId, JSON.stringify([this.config.appId, chatId, messageId]), 'pending', {
1269
1646
  messageId, text: cleanText, stopEpoch: this.stopGeneration(chatId), expectedRunId: ingressOwner?.runId || '',
1270
- ownerId: ingressOwner?.id, batchId: ingressOwner?.batchId, sessionId: ingressOwner?.sessionId, sessionKey: this.getSessionKey(chatId)
1647
+ ownerId: ingressOwner?.id, batchId: ingressOwner?.batchId, sessionId: identityItem?.target.sessionId || ingressOwner?.sessionId, sessionKey: this.getSessionKey(chatId)
1271
1648
  });
1272
1649
  reservedAtIngress = true;
1273
1650
  }
@@ -1282,7 +1659,7 @@ export class FeishuBot {
1282
1659
  const pending = this.pendingAckMessages.get(chatId) || [];
1283
1660
  const inputStopEpoch = this.stopGeneration(chatId);
1284
1661
  const unhealthy = await this.getUnhealthySessionStatus(chatId);
1285
- if (this.stopGeneration(chatId) !== inputStopEpoch)
1662
+ if (!identityCurrent() || this.stopGeneration(chatId) !== inputStopEpoch)
1286
1663
  return;
1287
1664
  if (unhealthy) {
1288
1665
  await this.warnUnhealthySessionAndContinue(chatId, messageId, unhealthy);
@@ -1291,12 +1668,14 @@ export class FeishuBot {
1291
1668
  // positive idle, or bounded guarded-followup proof may hand off ONLY the
1292
1669
  // local scheduler; the original exact result observer/target survives.
1293
1670
  const dispatchReleased = await this.reconcileDispatchCustody(chatId);
1294
- if (this.stopGeneration(chatId) !== inputStopEpoch)
1671
+ if (!identityCurrent() || this.stopGeneration(chatId) !== inputStopEpoch)
1295
1672
  return;
1296
1673
  if (!isBot && insertedId > 0 && !dispatchReleased && !this.queueRuns.has(chatId) && !this.store.getDispatchCustody(this.config.name, chatId))
1297
1674
  await this.reconcileCurrentInputActivity(chatId, insertedId, messageId, cleanText);
1298
- if (this.stopGeneration(chatId) !== inputStopEpoch)
1675
+ if (!identityCurrent() || this.stopGeneration(chatId) !== inputStopEpoch)
1299
1676
  return;
1677
+ if (identityItem)
1678
+ await this.assertIdentityEffect();
1300
1679
  if (this.store.isInsertionReserved(this.config.name, chatId, insertedId))
1301
1680
  reservedAtIngress = true;
1302
1681
  if (reservedAtIngress && !this.store.isInsertionReserved(this.config.name, chatId, insertedId))
@@ -1321,7 +1700,7 @@ export class FeishuBot {
1321
1700
  if (isBusy) {
1322
1701
  const owner = this.queueOwners.get(chatId) || this.store.getDispatchCustody(this.config.name, chatId);
1323
1702
  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) };
1703
+ expectedRunId: owner?.runId || '', ownerId: owner?.id, batchId: owner?.batchId, sessionId: identityItem?.target.sessionId || owner?.sessionId, sessionKey: this.getSessionKey(chatId) };
1325
1704
  if (insertedId > 0 && !this.store.getInsertion(this.config.name, chatId, insertedId))
1326
1705
  this.store.saveInsertion(this.config.name, chatId, insertedId, JSON.stringify([this.config.appId, chatId, messageId]), 'pending', record);
1327
1706
  // Reservation is durable BEFORE any RPC. Ordinary drain cannot race a
@@ -1331,7 +1710,16 @@ export class FeishuBot {
1331
1710
  return;
1332
1711
  }
1333
1712
  // Not busy: admission callback, not local queueing, flips Typing -> Get.
1334
- await this.processQueue(chatId, true);
1713
+ const business = this.processQueue(chatId, true);
1714
+ if (identityItem) {
1715
+ // Existing pending-trigger/queue-owner custody now owns completion. Do
1716
+ // not hold identity ingress (and following /help, /stop or other chats)
1717
+ // behind the model's lifetime. No second queue or business replay path.
1718
+ void business.catch(err => console.error(`[${this.config.name}] Recovered business owner failed:`, safeErrorSummary(err)));
1719
+ }
1720
+ else {
1721
+ await business;
1722
+ }
1335
1723
  }
1336
1724
  catch (err) {
1337
1725
  console.error(`[${this.config.name}] Error:`, safeErrorSummary(err));
@@ -1373,6 +1761,7 @@ export class FeishuBot {
1373
1761
  * Read public activity and pin its exact root before choosing insertion. Missing
1374
1762
  * identity is durable unbound custody, never a fabricated run or blind send. */
1375
1763
  async reconcileCurrentInputActivity(chatId, rowId, messageId, text) {
1764
+ const heldSessionId = this.store.getIdentityTarget?.(this.config.name, this.config.appId, messageId)?.sessionId;
1376
1765
  if (!this.openclawClient.getSessionRuntimeStatus || !this.openclawClient.getSessionDispatchStatus)
1377
1766
  return;
1378
1767
  const epoch = this.stopGeneration(chatId), admissionEpoch = this.queueAdmissionEpoch.get(chatId) || 0;
@@ -1392,14 +1781,17 @@ export class FeishuBot {
1392
1781
  // missing describe response. A failed setup is not dispatch-idle evidence;
1393
1782
  // retain this never-attempted input for paced reconciliation as well.
1394
1783
  try {
1395
- await this.ensureSession(chatId);
1784
+ await (heldSessionId ? this.ensureSession(chatId, { sessionId: heldSessionId, guard: () => {
1785
+ if (this.identityClosed || !unsubmitted())
1786
+ throw new SupersededObservation('retained activity setup cancelled');
1787
+ } }) : this.ensureSession(chatId));
1396
1788
  }
1397
1789
  catch {
1398
- if (unsubmitted() && !this.queueRuns.has(chatId) && !this.store.getDispatchCustody(this.config.name, chatId)) {
1790
+ if (!this.identityClosed && unsubmitted() && !this.queueRuns.has(chatId) && !this.store.getDispatchCustody(this.config.name, chatId)) {
1399
1791
  const row = this.store.getInsertion(this.config.name, chatId, rowId);
1400
1792
  if (!row || row.state === 'pending' && row.activityUnbound && !row.attempted && !row.expectedRunId)
1401
1793
  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: '',
1794
+ messageId, text, stopEpoch: epoch, sessionKey: this.getSessionKey(chatId), sessionId: heldSessionId, activityUnbound: true, attempted: false, expectedRunId: '',
1403
1795
  reason: 'session setup unavailable; retained without dispatch-idle proof',
1404
1796
  }, Date.now() + 5000);
1405
1797
  }
@@ -1424,9 +1816,10 @@ export class FeishuBot {
1424
1816
  const fresh = this.store.getInsertion(this.config.name, chatId, rowId);
1425
1817
  if (current ? JSON.stringify(fresh) !== JSON.stringify(current) || fresh?.insertionId !== current.insertionId || fresh.state !== 'pending' || fresh.attempted === true || !fresh.activityUnbound || !!fresh.expectedRunId : !!fresh)
1426
1818
  return;
1427
- const compatible = !!status.sessionId && status.sessionId === activity.sessionId && (!current?.sessionId || current.sessionId === status.sessionId);
1819
+ const compatible = !!status.sessionId && status.sessionId === activity.sessionId && (!current?.sessionId || current.sessionId === status.sessionId)
1820
+ && (!heldSessionId || status.sessionId === heldSessionId);
1428
1821
  const archived = !!status.archived || !!activity.archived;
1429
- const generationConflict = activity.identityConflict === true || !!activity.sessionId && !!status.sessionId && activity.sessionId !== status.sessionId ||
1822
+ const generationConflict = !!heldSessionId && !!status.sessionId && status.sessionId !== heldSessionId || activity.identityConflict === true || !!activity.sessionId && !!status.sessionId && activity.sessionId !== status.sessionId ||
1430
1823
  !!current?.sessionId && !!status.sessionId && current.sessionId !== status.sessionId;
1431
1824
  const source = this.store.getMessageByMessageId(messageId);
1432
1825
  const ordinaryHuman = source?.id === rowId && source.chatId === chatId && source.senderType === 'human' && source.triggerKind === 'normal';
@@ -1469,7 +1862,7 @@ export class FeishuBot {
1469
1862
  : activity.busyConfirmed ? 'retained: positively-busy; guarded followup proof absent or observation window pending'
1470
1863
  : 'retained: genuinely unknown activity; fresh ordinary rescue observation pending';
1471
1864
  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,
1865
+ ...current, messageId, text, stopEpoch: epoch, sessionKey: this.getSessionKey(chatId), sessionId: heldSessionId || current?.sessionId || activity.sessionId || status.sessionId,
1473
1866
  expectedRunId: identified ? activity.activeRunId : '', ownerId: identified ? `external:${activity.activeRunId}` : undefined,
1474
1867
  batchId: identified ? activity.activeRunId : undefined, activityUnbound: !identified, attempted: false,
1475
1868
  ...(!identified ? { unboundSince: current?.unboundSince || Date.now() } : {}),
@@ -1634,6 +2027,11 @@ export class FeishuBot {
1634
2027
  this.scheduleInsertionRecovery();
1635
2028
  }
1636
2029
  async reconcileReactions(chatId) {
2030
+ // Shared durable owner, not the lifetime of the ingress that woke it.
2031
+ if (this.identityEffects?.getStore())
2032
+ return this.identityEffects.exit(() => this.reconcileReactions(chatId));
2033
+ if (this.identityClosed)
2034
+ return;
1637
2035
  if (this.reactionChecks.has(chatId))
1638
2036
  return;
1639
2037
  this.reactionChecks.add(chatId);
@@ -1682,6 +2080,11 @@ export class FeishuBot {
1682
2080
  insertionTimer;
1683
2081
  insertionChecks = new Set();
1684
2082
  scheduleInsertionRecovery() {
2083
+ // Shared durable owner, not the lifetime of the ingress that woke it.
2084
+ if (this.identityEffects?.getStore())
2085
+ return this.identityEffects.exit(() => this.scheduleInsertionRecovery());
2086
+ if (this.identityClosed)
2087
+ return;
1685
2088
  if (this.insertionTimer || (!this.store.listInsertions(this.config.name).length && !this.store.listReactionIntents(this.config.name).length))
1686
2089
  return;
1687
2090
  this.insertionTimer = setTimeout(() => {
@@ -1692,6 +2095,11 @@ export class FeishuBot {
1692
2095
  this.insertionTimer.unref?.();
1693
2096
  }
1694
2097
  async reconcileInsertions(chatId) {
2098
+ // Shared durable owner, not the lifetime of the ingress that woke it.
2099
+ if (this.identityEffects?.getStore())
2100
+ return this.identityEffects.exit(() => this.reconcileInsertions(chatId));
2101
+ if (this.identityClosed)
2102
+ return;
1695
2103
  if (this.insertionChecks.has(chatId))
1696
2104
  return;
1697
2105
  this.insertionChecks.add(chatId);
@@ -2025,6 +2433,11 @@ export class FeishuBot {
2025
2433
  }
2026
2434
  }
2027
2435
  async processQueue(chatId, activityChecked = false) {
2436
+ // A queue owner spans several independent inputs. Never inherit one
2437
+ // recovered ingress's ALS guard for later batches or delayed result sends;
2438
+ // retained inputs carry their own durable target/recall/epoch guards below.
2439
+ if (this.identityEffects?.getStore())
2440
+ return this.identityEffects.exit(() => this.processQueue(chatId, activityChecked));
2028
2441
  const existing = this.queueRuns.get(chatId);
2029
2442
  if (existing) {
2030
2443
  console.log(`[${this.config.name}] processQueue already running for ${chatId.slice(-8)}, joining existing run`);
@@ -2118,7 +2531,7 @@ export class FeishuBot {
2118
2531
  return true;
2119
2532
  }
2120
2533
  async processQueueInner(chatId, owner) {
2121
- const current = () => !owner.revoked && this.queueOwners.get(chatId) === owner && this.stopGeneration(chatId) === owner.stopEpoch;
2534
+ const current = () => !this.identityClosed && !owner.revoked && this.queueOwners.get(chatId) === owner && this.stopGeneration(chatId) === owner.stopEpoch;
2122
2535
  const guard = () => { if (!current())
2123
2536
  throw new SupersededObservation('queue owner revoked'); };
2124
2537
  while (current()) {
@@ -2313,17 +2726,34 @@ export class FeishuBot {
2313
2726
  this.presentation(() => this.queuedPresentations.receive(chatId, triggerId, lastHuman.messageId || "", false));
2314
2727
  const liveStatus = this.presentation(() => this.queuedPresentations.claim(chatId, mergedTriggerIds, owner.id, owner.batchId, isNativeCommandTrigger));
2315
2728
  let sessionKey;
2729
+ const identityTargets = mergedTriggers.map(message => ({ message, target: this.store.getIdentityTarget?.(this.config.name, this.config.appId, message.messageId) || {} }))
2730
+ .filter(entry => entry.target.expiresAt !== undefined);
2731
+ const expectedIdentitySessionId = identityTargets[0]?.target.sessionId;
2316
2732
  try {
2317
- sessionKey = await this.ensureSession(chatId);
2733
+ if (identityTargets.some(({ target }) => target.state !== 'bound' || !target.sessionId || target.sessionId !== expectedIdentitySessionId ||
2734
+ target.sessionKey !== this.getSessionKey(chatId) || (target.expiresAt ?? 0) <= Date.now()))
2735
+ throw new SupersededObservation('retained original target unavailable');
2736
+ sessionKey = await (expectedIdentitySessionId ? this.ensureSession(chatId, { sessionId: expectedIdentitySessionId, guard }) : this.ensureSession(chatId));
2318
2737
  guard();
2319
2738
  const generation = await this.openclawClient.getSessionInfo(sessionKey, 1500).catch(() => null);
2320
2739
  guard();
2321
2740
  owner.sessionId = generation?.session?.sessionId;
2741
+ if (expectedIdentitySessionId && (generation?.session?.archived || owner.sessionId !== expectedIdentitySessionId))
2742
+ throw new SupersededObservation('retained original target changed before queue admission');
2322
2743
  }
2323
2744
  catch (err) {
2324
2745
  if (!current())
2325
2746
  break;
2326
- await liveStatus?.pauseForUnconfirmedResult(this.isEn(chatId) ? "Session setup failed before admission" : "会话准备失败,尚未提交 Gateway", this.isEn(chatId) ? `${this.config.name} setup unavailable` : `${this.config.name} 会话准备未完成`).catch(() => { });
2747
+ if (identityTargets.length && err instanceof SupersededObservation) {
2748
+ for (const { message } of identityTargets) {
2749
+ if (message.id)
2750
+ this.store.clearPendingTrigger(this.config.name, chatId, message.id);
2751
+ this.store.clearIdentityIngress(this.config.name, this.config.appId, message.messageId);
2752
+ }
2753
+ owner.continuePending = mergedTriggers.some(message => !identityTargets.some(entry => entry.message === message));
2754
+ break;
2755
+ }
2756
+ await liveStatus?.pauseForUnconfirmedResult(this.isEn(chatId) ? "Session setup failed before admission" : "会话准备失败,尚未提交 Gateway", this.isEn(chatId) ? `${this.config.name} setup unavailable` : `${this.config.name} 会话准备未完成`, "blocked").catch(() => { });
2327
2757
  if (batchProof) {
2328
2758
  for (const id of mergedTriggerIds) {
2329
2759
  const item = this.store.getInsertion(this.config.name, chatId, id);
@@ -2397,8 +2827,11 @@ export class FeishuBot {
2397
2827
  includeContext: !isNativeCommandTrigger,
2398
2828
  includeBridgeAttachmentHint: !isNativeCommandTrigger,
2399
2829
  followupAdmissionGuard: batchProof,
2830
+ ...(expectedIdentitySessionId ? { expectedSessionId: expectedIdentitySessionId } : {}),
2400
2831
  admissionGuard: () => {
2401
2832
  guard();
2833
+ if (identityTargets.some(({ message }) => this.store.isMessageRecalled(message.messageId)))
2834
+ throw new SupersededObservation('retained input recalled before admission');
2402
2835
  if (owner.batch !== batchToken || owner.batchId !== batchId || this.queueAdmissionEpoch.get(chatId) !== admissionEpoch)
2403
2836
  throw new SupersededObservation('batch admission epoch changed');
2404
2837
  if (!batchProof)
@@ -2433,6 +2866,8 @@ export class FeishuBot {
2433
2866
  }
2434
2867
  else
2435
2868
  markSubmittedBatch("send-attempt");
2869
+ for (const { message } of identityTargets)
2870
+ this.store.clearIdentityIngress(this.config.name, this.config.appId, message.messageId);
2436
2871
  },
2437
2872
  onRunIdentified: (runId, identity) => { guard(); owner.runId = runId; owner.sessionId = identity?.sessionId || owner.sessionId; foregroundRunId = runId; },
2438
2873
  onSubmitted: async (runId) => {
@@ -2608,7 +3043,7 @@ export class FeishuBot {
2608
3043
  const outcome = await this.enqueueAndDispatchDelivery(chatId, "assistant_visible", this.deliverySourceId("visible", `${triggerId}|${(shouldReply ? visibleReply : "").trim()}|${JSON.stringify(parsedReply.attachments)}`), shouldReply ? visibleReply : "", parsedReply.attachments, lastHuman.messageId, `trigger:${triggerId}`, this.config.model, foregroundRunId ? { runId: foregroundRunId, sessionKey, ...(foregroundSessionId ? { sessionId: foregroundSessionId } : {}), final: true } : undefined, undefined, mergedTriggerIds);
2609
3044
  visibleOutcomeConfirmed = outcome.state === 'delivered';
2610
3045
  if (!visibleOutcomeConfirmed) {
2611
- await liveStatus?.pauseForUnconfirmedResult("飞书投递回执尚未确认;保留原投递保管,不重复发送").catch(() => { });
3046
+ await liveStatus?.pauseForUnconfirmedResult("飞书投递回执尚未确认;保留原投递保管,不重复发送", undefined, "delivery_pending").catch(() => { });
2612
3047
  }
2613
3048
  else {
2614
3049
  await liveStatus?.complete();
@@ -2730,17 +3165,17 @@ export class FeishuBot {
2730
3165
  this.store.saveInsertion(this.config.name, chatId, id, row.insertionId, 'target_changed', { ...row, attempted: false, reason: err.message });
2731
3166
  }
2732
3167
  await this.enqueueAndDispatchDelivery(chatId, 'admission_status', `admission:${err.submissionId}:refused`, err.message, [], lastHuman.messageId, `admission:${err.submissionId}:refused`).catch(() => { });
2733
- await liveStatus?.pauseForUnconfirmedResult(err.message).catch(() => { });
3168
+ await liveStatus?.pauseForUnconfirmedResult(err.message, undefined, "blocked").catch(() => { });
2734
3169
  owner.continuePending = true; // independently proved newer cohorts may still be sent
2735
3170
  break;
2736
3171
  }
2737
3172
  if (err instanceof AdmissionUnconfirmed) {
2738
3173
  await this.enqueueAndDispatchDelivery(chatId, 'admission_status', `admission:${err.submissionId}:unknown`, err.message, [], lastHuman.messageId, `admission:${err.submissionId}:unknown`).catch(() => { });
2739
- await liveStatus?.pauseForUnconfirmedResult(err.message).catch(() => { });
3174
+ await liveStatus?.pauseForUnconfirmedResult(err.message, undefined, "submitting").catch(() => { });
2740
3175
  break;
2741
3176
  }
2742
3177
  let pause = err instanceof SessionWaitPaused ? err : undefined;
2743
- if (!pause && isWaitTimeout(err instanceof Error ? err.message : String(err))) {
3178
+ if (!pause && !(err instanceof RunTerminalError) && isWaitTimeout(err instanceof Error ? err.message : String(err))) {
2744
3179
  const state = await this.readSessionStatus(chatId);
2745
3180
  if (state.running)
2746
3181
  pause = new SessionWaitPaused(state, true);
@@ -2749,7 +3184,7 @@ export class FeishuBot {
2749
3184
  const target = this.activeDeliveryTargets.get(chatId);
2750
3185
  if (target?.triggerId === triggerId && target.runId)
2751
3186
  this.openclawClient.releasePausedWait?.(target.runId);
2752
- await liveStatus?.pauseForUnconfirmedResult(pause.message, `${this.config.name} 等待暂停 · ${pause.snapshot.status}`).catch(() => { });
3187
+ await liveStatus?.pauseForUnconfirmedResult(pause.message, `${this.config.name} 等待暂停 · ${pause.snapshot.status}`, "paused").catch(() => { });
2753
3188
  await this.sendWaitPaused(chatId, triggerId, lastHuman.messageId, pause).catch(() => { });
2754
3189
  // A wait notice is not the final answer and must never claim its key.
2755
3190
  // Do not mark DONE, retry this input, or abort the running session.
@@ -2805,7 +3240,7 @@ export class FeishuBot {
2805
3240
  if (row && !row.admissionSubmissionId && !row.admittedRunId)
2806
3241
  this.store.saveInsertion(this.config.name, chatId, id, row.insertionId, 'target_changed', { ...row, attempted: false, reason: 'guarded pre-admission failure; input retained without sync or new-ID retry' });
2807
3242
  }
2808
- await liveStatus?.pauseForUnconfirmedResult('Guarded admission unavailable; input custody retained without replay').catch(() => { });
3243
+ await liveStatus?.pauseForUnconfirmedResult('Guarded admission unavailable; input custody retained without replay', undefined, 'blocked').catch(() => { });
2809
3244
  break;
2810
3245
  }
2811
3246
  console.error(`[${this.config.name}] processQueue error:`, safeErrorSummary(err));
@@ -2815,13 +3250,23 @@ export class FeishuBot {
2815
3250
  if (lastHuman.messageId) {
2816
3251
  // Error message goes through the normal delivery path; the live status
2817
3252
  // is a separate message that we mark interrupted afterwards.
2818
- await this.enqueueAndDispatchDelivery(chatId, "provider_error", `trigger:${triggerId}:provider-error`, errorText, [], lastHuman.messageId, `trigger:${triggerId}:provider-error`)
2819
- .then(outcome => {
2820
- errorOutcomeConfirmed = outcome.state === 'delivered';
2821
- if (errorOutcomeConfirmed && current() && triggerId)
2822
- this.store.markDeliveredReply(this.config.name, chatId, triggerId, lastHuman.messageId);
2823
- })
2824
- .catch(() => { });
3253
+ if (err instanceof RunTerminalError) {
3254
+ const p = this.scopeRunError(chatId, err.provenance);
3255
+ this.store.observeRunError(this.config.name, chatId, p);
3256
+ await this.reconcileErrorNotices(chatId);
3257
+ errorOutcomeConfirmed = this.store.findRunErrorOwner(this.config.name, chatId, p)?.status === 'delivered';
3258
+ }
3259
+ else
3260
+ await this.enqueueAndDispatchDelivery(chatId, "provider_error", `trigger:${triggerId}:provider-error`, errorText, [], lastHuman.messageId, `trigger:${triggerId}:provider-error`, undefined, foregroundRunId ? (() => {
3261
+ const p = this.scopeRunError(chatId, { sessionKey: `agent:main:${this.getSessionKey(chatId).replace(/^agent:[^:]+:/, '')}`, sessionId: owner.sessionId, runId: foregroundRunId, source: 'chat', state: 'error', detail: err instanceof Error ? err.message : undefined });
3262
+ return { sessionKey: p.sessionKey, sessionId: p.sessionId, runId: p.runId, error: p };
3263
+ })() : undefined)
3264
+ .then(outcome => {
3265
+ errorOutcomeConfirmed = outcome.state === 'delivered';
3266
+ if (errorOutcomeConfirmed && current() && triggerId)
3267
+ this.store.markDeliveredReply(this.config.name, chatId, triggerId, lastHuman.messageId);
3268
+ })
3269
+ .catch(() => { });
2825
3270
  await liveStatus?.fail().catch(() => { });
2826
3271
  }
2827
3272
  else {
@@ -2967,6 +3412,8 @@ export class FeishuBot {
2967
3412
  if (this.isAllMentionItem(mention))
2968
3413
  return null;
2969
3414
  const id = mention.id || {};
3415
+ if (Object.hasOwn(id, 'open_id') && (typeof id.open_id !== 'string' || !id.open_id.trim()))
3416
+ return null;
2970
3417
  const candidates = [this, ...Array.from(FeishuBot.allBots.values()).filter((bot) => bot !== this && bot.store === this.store)];
2971
3418
  const matches = candidates.filter((bot) => {
2972
3419
  // Known conflicting app/open credentials veto, regardless of order. An
@@ -3062,6 +3509,7 @@ export class FeishuBot {
3062
3509
  thinkingLevel: meta.thinkingLevel,
3063
3510
  toolCalls: meta.toolCalls,
3064
3511
  noReply: Boolean(meta.noReply),
3512
+ inputStatus: meta.inputStatus ? { ...meta.inputStatus, items: meta.inputStatus.items.map(item => item.kind === 'delivery_pending' ? { ...item, kind: 'completed' } : item) } : { items: [{ kind: meta.noReply ? "no_reply" : "completed", at: 0 }] },
3065
3513
  state: "done",
3066
3514
  };
3067
3515
  await this.patchLiveStatusCard(messageId, view, chatId);
@@ -3356,7 +3804,12 @@ export class FeishuBot {
3356
3804
  const previous = this.deliveryTargetsByRun.get(key);
3357
3805
  if (previous?.timer)
3358
3806
  clearTimeout(previous.timer);
3359
- this.store.bindDeliveryRun(this.config.name, chatId, runId, { ...this.store.getDeliveryRunTarget(this.config.name, chatId, runId), triggerId: target.triggerId, messageId: target.messageId, runId, stopGeneration: this.stopGeneration(chatId), sessionKey: `agent:main:${this.getSessionKey(chatId).replace(/^agent:[^:]+:/, '')}` });
3807
+ const persisted = this.store.getDeliveryRunTarget(this.config.name, chatId, runId);
3808
+ const owner = this.queueOwners.get(chatId);
3809
+ this.store.bindDeliveryRun(this.config.name, chatId, runId, { ...persisted, triggerId: target.triggerId, messageId: target.messageId, runId,
3810
+ sessionId: persisted?.sessionId || (owner?.runId === runId ? owner.sessionId : undefined),
3811
+ botIdentity: persisted?.botIdentity || this.config.appId, stopGeneration: persisted?.stopGeneration ?? this.stopGeneration(chatId),
3812
+ sessionKey: persisted?.sessionKey || `agent:main:${this.getSessionKey(chatId).replace(/^agent:[^:]+:/, '')}` });
3360
3813
  this.deliveryTargetsByRun.set(key, {
3361
3814
  triggerId: target.triggerId,
3362
3815
  messageId: target.messageId,
@@ -3455,9 +3908,9 @@ export class FeishuBot {
3455
3908
  const contentHash = this.stableHash(normalizedPayload);
3456
3909
  const finalDeliveryKey = deliveryKey || sourceId;
3457
3910
  const deliveryMetaJson = JSON.stringify({
3458
- botIdentity: this.config.appId,
3911
+ botIdentity: provenance?.error?.botIdentity || this.config.appId,
3459
3912
  ...(completionTriggerIds?.length ? { completionTriggerIds } : {}),
3460
- deliveryStopEpoch: this.stopGeneration(chatId),
3913
+ deliveryStopEpoch: provenance?.error?.stopEpoch ?? this.stopGeneration(chatId),
3461
3914
  ...(finalReplyModel?.trim() ? { model: finalReplyModel.trim() } : {}),
3462
3915
  ...(provenance ? { provenance } : {}), ...(errorNoticeId ? { errorNoticeId } : {}),
3463
3916
  });
@@ -3612,13 +4065,52 @@ export class FeishuBot {
3612
4065
  }
3613
4066
  return this.store.getDeliveryDispatchOutcome(this.config.name, chatId, finalDeliveryKey);
3614
4067
  }
4068
+ scopeRunError(chatId, p) {
4069
+ const key = /^agent:[^:]+:/.test(p.sessionKey) ? p.sessionKey : `agent:main:${p.sessionKey}`;
4070
+ const target = this.store.getDeliveryRunTarget(this.config.name, chatId, p.runId);
4071
+ const observation = this.store.getRunObservation(key, p.runId);
4072
+ // Pre-upgrade targets may lack app/physical fields. A known exact legacy
4073
+ // outbox owner is original route evidence, never permission for the current
4074
+ // replacement app to take over its notice.
4075
+ const legacy = !target?.botIdentity ? this.store.findRunErrorOwner(this.config.name, chatId, { ...p, sessionKey: key }) : undefined;
4076
+ let meta;
4077
+ try {
4078
+ meta = JSON.parse(legacy?.deliveryMetaJson || '{}');
4079
+ }
4080
+ catch {
4081
+ meta = {};
4082
+ }
4083
+ return { ...p, sessionKey: key, sessionId: p.sessionId || target?.sessionId || observation?.sessionId || meta.provenance?.sessionId,
4084
+ botIdentity: p.botIdentity || target?.botIdentity || meta.botIdentity || this.config.appId,
4085
+ stopEpoch: p.stopEpoch ?? target?.stopGeneration ?? meta.deliveryStopEpoch ?? this.stopGeneration(chatId) };
4086
+ }
4087
+ /** Shared original-error authorization for journaled terminals AND ordinary
4088
+ * admitted provider errors. Current outbox/config metadata is not authority
4089
+ * to replace the retained admission route or physical target. */
4090
+ errorRouteRevocation(chatId, p) {
4091
+ const original = this.store.getDeliveryRunTarget(this.config.name, chatId, p.runId);
4092
+ if (original?.messageId && this.store.isMessageRecalled(original.messageId) ||
4093
+ original?.sessionId && p.sessionId && original.sessionId !== p.sessionId ||
4094
+ original?.sessionKey && canonicalPhysicalSessionKey(original.sessionKey) !== canonicalPhysicalSessionKey(p.sessionKey))
4095
+ return 'original_error_target_revoked';
4096
+ const epoch = this.stopGeneration(chatId);
4097
+ if (p.botIdentity && p.botIdentity !== this.config.appId || original?.botIdentity && original.botIdentity !== this.config.appId ||
4098
+ p.stopEpoch !== undefined && p.stopEpoch !== epoch || original?.stopGeneration !== undefined && original.stopGeneration !== epoch)
4099
+ return 'original_error_route_revoked';
4100
+ }
3615
4101
  async inspectErrorNotice(record) {
4102
+ const revoked = this.errorRouteRevocation(record.chatId, record.provenance);
4103
+ if (revoked)
4104
+ return { state: 'stopped', reason: revoked };
3616
4105
  if (this.store.hasRunFinalDelivery(this.config.name, record.chatId, record.provenance, true)) {
3617
4106
  return { state: "suppressed", reason: "exact_run_final_platform_delivery_confirmed" };
3618
4107
  }
3619
4108
  if (this.store.hasRunFinalDelivery(this.config.name, record.chatId, record.provenance, false)) {
3620
4109
  return { state: "pending", reason: "exact_run_final_delivery_pending" };
3621
4110
  }
4111
+ const existing = this.store.findRunErrorOwner(this.config.name, record.chatId, record.provenance);
4112
+ if (!record.provenance.runId.startsWith('announce:') && existing && existing.deliveryKey !== `run-error:${errorNoticeIdentity(record.provenance)}`)
4113
+ return { state: 'suppressed', reason: 'existing_exact_run_error_owner' };
3622
4114
  let verdict;
3623
4115
  try {
3624
4116
  verdict = await this.openclawClient.inspectRunError(record.provenance);
@@ -3628,8 +4120,13 @@ export class FeishuBot {
3628
4120
  }
3629
4121
  // Presentation only: leave exact-run finality, stop suppression and durable
3630
4122
  // outbox keys owned by the existing verdict; no retry/model fallback here.
3631
- if (verdict.state === "terminal" && verdict.reason === "ordinary_gateway_error") {
3632
- verdict = { ...verdict, text: this.formatUserVisibleError(record.provenance.detail, record.chatId) };
4123
+ if (verdict.state === "terminal" && ['ordinary_gateway_error', 'closed_gateway_terminal', 'exact_run_terminal_error'].includes(verdict.reason)) {
4124
+ const reason = closedStopReason(record.provenance.stopReason) || verdict.stopReason;
4125
+ const en = this.isEn(record.chatId);
4126
+ verdict = { ...verdict, text: reason === 'timeout' ? this.formatUserVisibleError({ code: 'execution_timeout' }, record.chatId)
4127
+ : reason === 'superseded' ? (en ? '⚠️ This run ended after being superseded by a newer session writer; no user stop is inferred.' : '⚠️ 本次运行已被新的会话写入者取代而终止;不据此认定用户停止。')
4128
+ : reason === 'restart' ? (en ? '⚠️ This run ended for a Gateway restart; no user stop is inferred.' : '⚠️ 本次运行因 Gateway 重启而终止;不据此认定用户停止。')
4129
+ : this.formatUserVisibleError(record.provenance.detail, record.chatId) };
3633
4130
  }
3634
4131
  // A stop or final may have arrived during the read-only lookup.
3635
4132
  const latest = this.store.getErrorNotice(this.config.name, record.chatId, record.noticeId);
@@ -3648,6 +4145,8 @@ export class FeishuBot {
3648
4145
  if (this.store.hasRunFinalDelivery(this.config.name, record.chatId, record.provenance, false)) {
3649
4146
  return { state: "pending", reason: "exact_run_final_delivery_pending" };
3650
4147
  }
4148
+ if (verdict.state === 'terminal' && verdict.stopReason && !record.provenance.stopReason)
4149
+ record.provenance = { ...record.provenance, stopReason: verdict.stopReason };
3651
4150
  return verdict;
3652
4151
  }
3653
4152
  deferErrorNotice(record, verdict) {
@@ -3666,6 +4165,11 @@ export class FeishuBot {
3666
4165
  this.scheduleErrorNoticeCheck(record.chatId);
3667
4166
  }
3668
4167
  scheduleErrorNoticeCheck(chatId) {
4168
+ // Shared durable owner, not the lifetime of the ingress that woke it.
4169
+ if (this.identityEffects?.getStore())
4170
+ return this.identityEffects.exit(() => this.scheduleErrorNoticeCheck(chatId));
4171
+ if (this.identityClosed)
4172
+ return;
3669
4173
  const previous = this.errorNoticeTimers.get(chatId);
3670
4174
  if (previous)
3671
4175
  clearTimeout(previous);
@@ -3682,6 +4186,11 @@ export class FeishuBot {
3682
4186
  }
3683
4187
  /** Bounded read-only diagnosis; known live tasks retain low-frequency observation. */
3684
4188
  async reconcileErrorNotices(chatId) {
4189
+ // Shared durable owner, not the lifetime of the ingress that woke it.
4190
+ if (this.identityEffects?.getStore())
4191
+ return this.identityEffects.exit(() => this.reconcileErrorNotices(chatId));
4192
+ if (this.identityClosed)
4193
+ return;
3685
4194
  const running = this.errorNoticeChecks.get(chatId);
3686
4195
  if (running)
3687
4196
  return running;
@@ -3720,7 +4229,7 @@ export class FeishuBot {
3720
4229
  this.store.saveErrorNotice(record);
3721
4230
  if (verdict.state === "terminal" && verdict.terminalKey && verdict.text) {
3722
4231
  // Independent identity: never take the result's trigger/final key.
3723
- await this.enqueueAndDispatchDelivery(chatId, "run_error", verdict.terminalKey, verdict.text, [], undefined, verdict.terminalKey, undefined, { sourceType: "run_error", sessionKey: record.provenance.sessionKey, runId: record.provenance.runId, error: record.provenance, terminalEvidence: verdict }, record.noticeId);
4232
+ await this.enqueueAndDispatchDelivery(chatId, "run_error", verdict.terminalKey, verdict.text, [], undefined, verdict.terminalKey, undefined, { sourceType: "run_error", sessionKey: record.provenance.sessionKey, sessionId: record.provenance.sessionId, runId: record.provenance.runId, error: record.provenance, terminalEvidence: verdict }, record.noticeId);
3724
4233
  // The send-time recheck may have parked or suppressed the observation.
3725
4234
  const refreshed = this.store.getErrorNotice(this.config.name, chatId, record.noticeId);
3726
4235
  if (refreshed?.verdict && ["pending", "suppressed", "stopped"].includes(refreshed.verdict.state))
@@ -3736,6 +4245,11 @@ export class FeishuBot {
3736
4245
  return promise;
3737
4246
  }
3738
4247
  scheduleDeliveryRetry(chatId, attempt, local = false) {
4248
+ // Shared durable owner, not the lifetime of the ingress that woke it.
4249
+ if (this.identityEffects?.getStore())
4250
+ return this.identityEffects.exit(() => this.scheduleDeliveryRetry(chatId, attempt, local));
4251
+ if (this.identityClosed)
4252
+ return;
3739
4253
  if (this.deliveryRetryTimers.has(chatId))
3740
4254
  return;
3741
4255
  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 +4348,11 @@ export class FeishuBot {
3834
4348
  }
3835
4349
  }
3836
4350
  async dispatchPendingDeliveries(chatId, replyToMessageId) {
4351
+ // Shared durable owner, not the lifetime of the ingress that woke it.
4352
+ if (this.identityEffects?.getStore())
4353
+ return this.identityEffects.exit(() => this.dispatchPendingDeliveries(chatId, replyToMessageId));
4354
+ if (this.identityClosed)
4355
+ return;
3837
4356
  this.installGoReceiptCapture();
3838
4357
  for (const id of this.localDeliveryRetryCustody.get(chatId) || []) {
3839
4358
  try {
@@ -3883,8 +4402,13 @@ export class FeishuBot {
3883
4402
  const meta = JSON.parse(item.deliveryMetaJson || '{}'), p = meta.provenance;
3884
4403
  if (!this.insertionNoticeCurrent(chatId, meta.insertionNotice))
3885
4404
  throw Object.assign(new Error('Insertion notice no longer current'), { deliveryStopped: true });
3886
- if ((p?.final || item.sourceType === 'run_error') &&
3887
- (typeof meta.deliveryStopEpoch === 'number' && meta.deliveryStopEpoch !== this.stopGeneration(chatId) ||
4405
+ if (p?.error) {
4406
+ const revoked = this.errorRouteRevocation(chatId, p.error);
4407
+ if (revoked)
4408
+ throw Object.assign(new Error(`Original error delivery revoked: ${revoked}`), { deliveryStopped: true });
4409
+ }
4410
+ if ((p?.final || p?.error || item.sourceType === 'run_error') &&
4411
+ (meta.botIdentity && meta.botIdentity !== this.config.appId || typeof meta.deliveryStopEpoch === 'number' && meta.deliveryStopEpoch !== this.stopGeneration(chatId) ||
3888
4412
  p?.sessionKey && p.runId && this.store.isStoppedObservation(p.sessionKey, p.runId))) {
3889
4413
  throw Object.assign(new Error('Delivery revoked by explicit stop before platform attempt'), { deliveryStopped: true });
3890
4414
  }
@@ -4256,7 +4780,7 @@ export class FeishuBot {
4256
4780
  }
4257
4781
  if (pause) {
4258
4782
  discussionWaitPaused = true;
4259
- await liveStatus?.pauseForUnconfirmedResult(pause.message, `${this.config.name} 等待暂停 · ${pause.snapshot.status}`).catch(() => { });
4783
+ await liveStatus?.pauseForUnconfirmedResult(pause.message, `${this.config.name} 等待暂停 · ${pause.snapshot.status}`, "paused").catch(() => { });
4260
4784
  await this.sendWaitPaused(chatId, 0, undefined, pause).catch(() => { });
4261
4785
  }
4262
4786
  else
@@ -4292,7 +4816,7 @@ export class FeishuBot {
4292
4816
  const outcome = await this.enqueueAndDispatchDelivery(chatId, "discussion", `discussion:${Date.now()}:${Math.random().toString(36).slice(2)}`, isVisible ? displayReply : "", parsedReply.attachments, undefined, undefined, this.config.model);
4293
4817
  discussionDeliveryConfirmed = outcome.state === 'delivered';
4294
4818
  if (!discussionDeliveryConfirmed)
4295
- await liveStatus?.pauseForUnconfirmedResult("飞书投递回执尚未确认;原投递仍受保管").catch(() => { });
4819
+ await liveStatus?.pauseForUnconfirmedResult("飞书投递回执尚未确认;原投递仍受保管", undefined, "delivery_pending").catch(() => { });
4296
4820
  }
4297
4821
  catch (err) {
4298
4822
  await liveStatus?.fail().catch(() => { });
@@ -4312,13 +4836,46 @@ export class FeishuBot {
4312
4836
  }
4313
4837
  return { botName: this.config.name, text: cleanVisibleReply, visible: isVisible && discussionDeliveryConfirmed };
4314
4838
  }
4315
- buildLiveStatusCard(view, chatId) {
4839
+ liveInputElements(view, chatId, limits) {
4840
+ const context = view.inputStatus;
4841
+ if (!context)
4842
+ return [];
4316
4843
  const en = this.isEn(chatId);
4844
+ const scoped = !!chatId && context.chatId === chatId && context.botName === this.config.name && context.appId === this.config.appId &&
4845
+ context.stopEpoch === this.stopGeneration(chatId);
4846
+ const preview = (hint) => {
4847
+ const source = scoped && hint.rowId ? this.store.getMessageByRowId(hint.rowId) : undefined;
4848
+ if (!source || source.chatId !== chatId || source.senderType !== 'human' || !hint.messageId || source.messageId !== hint.messageId)
4849
+ return en ? '[Message body unavailable]' : '[消息正文暂不可用]';
4850
+ if (this.store.isMessageRecalled(source.messageId))
4851
+ return en ? '[Message recalled]' : '[消息已撤回]';
4852
+ return hint.previewSource === 'visible' ? visibleInputPreview(hint.preview ?? '', limits.preview, en) : inputPreview(hint.preview ?? source.content, limits.preview, en);
4853
+ };
4854
+ const selected = selectInputHints(context.items, limits.members);
4855
+ const stamp = (at) => { const sec = Number.isFinite(at) ? Math.max(0, Math.floor(at)) : 0; return `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}`; };
4856
+ const lines = selected.map(hint => `${stamp(hint.at)} ${hintLabel(hint.kind, en)} ${inertInputText(preview(hint))}${hintDetail(hint.kind, en) ? '\n ↳ ' + inertInputText(hintDetail(hint.kind, en)) : ''}`);
4857
+ if (context.items.length > selected.length)
4858
+ lines.splice(Math.min(1, lines.length), 0, en ? `… ${context.items.length - selected.length} other inputs omitted; newest inputs retained` : `… 另有 ${context.items.length - selected.length} 条输入未展开,保留最新输入`);
4859
+ if (context.note)
4860
+ lines.push(`${stamp(context.note.at)} ${hintLabel(context.note.kind, en)} ${selected.map(hint => inertInputText(preview(hint))).join(' · ')}\n ↳ ${inertInputText(hintDetail(context.note.kind, en))}`);
4861
+ return lines.length ? [{ tag: 'markdown', content: lines.join('\n') }] : [];
4862
+ }
4863
+ liveStatusRequest(view, chatId, request) {
4864
+ for (const limits of INPUT_DISPLAY_LIMITS) {
4865
+ const value = request(this.buildLiveStatusCard(view, chatId, limits));
4866
+ if (Buffer.byteLength(JSON.stringify(value), 'utf8') <= LIVE_CARD_BYTES - 512)
4867
+ return value; // reserve SDK envelope overhead
4868
+ }
4869
+ throw new LiveStatusEffectSuppressedError('Live status request exceeds local outer JSON byte budget; no SDK call');
4870
+ }
4871
+ buildLiveStatusCard(view, chatId, limits = INPUT_DISPLAY_LIMITS[0]) {
4872
+ const en = this.isEn(chatId);
4873
+ const inputElements = this.liveInputElements(view, chatId, limits);
4317
4874
  if (view.state === "replied") {
4318
4875
  // Neutral UI-only closure, not a green business/input-completion claim.
4319
4876
  const summary = en ? `💬 Linked run replied · ⏱ ${view.elapsed}` : `💬 关联轮次已回复 · ⏱ 耗时${view.elapsed}`;
4320
4877
  return { schema: "2.0", config: { update_multi: true, width_mode: "fill" },
4321
- body: { elements: [{ tag: "markdown", content: `<font color='grey'>${summary}</font>` }] } };
4878
+ body: { elements: [...inputElements, { tag: "markdown", content: `<font color='grey'>${summary}</font>` }] } };
4322
4879
  }
4323
4880
  // Clean finish (done / NO_REPLY): keep it minimal — no header, no footer, just
4324
4881
  // one compact grey line (status emoji + tool-call count + total elapsed) so
@@ -4327,18 +4884,18 @@ export class FeishuBot {
4327
4884
  const statusEmoji = view.noReply ? "💤" : "✅";
4328
4885
  const summary = this.completionSummary({
4329
4886
  toolCalls: view.toolCalls,
4330
- elapsed: view.elapsed,
4331
- model: view.model,
4332
- thinkingLevel: view.thinkingLevel,
4887
+ elapsed: displayClip(view.elapsed, 32),
4888
+ model: view.model ? displayClip(view.model, 160) : undefined,
4889
+ thinkingLevel: view.thinkingLevel ? displayClip(view.thinkingLevel, 80) : undefined,
4333
4890
  locale: en ? "en" : "zh",
4334
4891
  }, statusEmoji);
4335
4892
  return {
4336
4893
  schema: "2.0",
4337
4894
  config: { update_multi: true, width_mode: "fill" },
4338
- body: { elements: [{ tag: "markdown", content: `<font color='grey'>${summary}</font>` }] },
4895
+ body: { elements: [...inputElements, { tag: "markdown", content: `<font color='grey'>${summary}</font>` }] },
4339
4896
  };
4340
4897
  }
4341
- const elements = [];
4898
+ const elements = [...inputElements];
4342
4899
  // Running OR failed: show the recent activity window (each line prefixed with
4343
4900
  // the relative time mm:ss). On failure we deliberately KEEP the last lines so
4344
4901
  // the steps leading up to the error/kill/timeout are visible for debugging.
@@ -4351,24 +4908,26 @@ export class FeishuBot {
4351
4908
  : "•";
4352
4909
  const fmtAt = (sec) => `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, "0")}`;
4353
4910
  const content = view.lines
4911
+ .filter(l => !l.inputHint && !(view.inputStatus?.botName && l.kind === 'lifecycle'))
4354
4912
  .map((l) => {
4355
4913
  const stamp = l.kind === "summary" ? "" : `\`${fmtAt(l.at)}\` `;
4356
- return `${stamp}${iconFor(l.kind)} ${this.escapeCardText(l.text)}`;
4914
+ return `${stamp}${iconFor(l.kind)} ${this.escapeCardText(displayClip(l.text, limits.activity))}`;
4357
4915
  })
4358
4916
  .join("\n");
4359
- elements.push({ tag: "markdown", content });
4917
+ if (content)
4918
+ elements.push({ tag: "markdown", content });
4360
4919
  }
4361
- else {
4920
+ else if (!inputElements.length) {
4362
4921
  elements.push({ tag: "markdown", content: view.state === "queued" ? (en ? "_Received locally; waiting for admission_" : "_本地已收件,等待提交确认_") : view.state === "admitted" ? (en ? "_Accepted; waiting for activity_" : "_已接收,等待活动_") : (en ? "_working…_" : "_正在启动…_") });
4363
4922
  }
4364
4923
  elements.push({ tag: "hr" });
4365
4924
  // Keep the active model visible while the run is in progress or failed.
4366
4925
  // The final reply also keeps model attribution so it remains self-contained.
4367
- const footerBits = [en ? `⏱ ${view.elapsed}` : `⏱ 已用 ${view.elapsed}`];
4926
+ const footerBits = [en ? `⏱ ${displayClip(view.elapsed, 32)}` : `⏱ 已用 ${displayClip(view.elapsed, 32)}`];
4368
4927
  if (view.model?.trim()) {
4369
4928
  const modelBit = view.thinkingLevel?.trim()
4370
- ? `🧠 ${this.escapeCardText(view.model.trim())} · ${this.escapeCardText(view.thinkingLevel.trim())}`
4371
- : `🧠 ${this.escapeCardText(view.model.trim())}`;
4929
+ ? `🧠 ${this.escapeCardText(displayClip(view.model.trim(), 160))} · ${this.escapeCardText(displayClip(view.thinkingLevel.trim(), 80))}`
4930
+ : `🧠 ${this.escapeCardText(displayClip(view.model.trim(), 160))}`;
4372
4931
  footerBits.push(modelBit);
4373
4932
  }
4374
4933
  elements.push({ tag: "markdown", content: `<font color='grey'>${footerBits.join(" · ")}</font>` });
@@ -4379,7 +4938,7 @@ export class FeishuBot {
4379
4938
  // rejects patches on cards that did not declare it before and after.
4380
4939
  config: { update_multi: true, width_mode: "fill" },
4381
4940
  header: {
4382
- title: { tag: "plain_text", content: view.title },
4941
+ title: { tag: "plain_text", content: displayClip(view.title, 160) },
4383
4942
  template,
4384
4943
  },
4385
4944
  body: { elements },
@@ -4416,14 +4975,8 @@ export class FeishuBot {
4416
4975
  }
4417
4976
  async sendLiveStatusCard(chatId, view) {
4418
4977
  try {
4419
- const res = await this.client.im.message.create({
4420
- params: { receive_id_type: "chat_id" },
4421
- data: {
4422
- receive_id: chatId,
4423
- content: JSON.stringify(this.buildLiveStatusCard(view, chatId)),
4424
- msg_type: "interactive",
4425
- },
4426
- });
4978
+ const request = this.liveStatusRequest(view, chatId, card => ({ params: { receive_id_type: "chat_id" }, data: { receive_id: chatId, content: JSON.stringify(card), msg_type: "interactive" } }));
4979
+ const res = await this.client.im.message.create(request);
4427
4980
  if (typeof res.code === "number" && res.code !== 0)
4428
4981
  throw new LiveStatusEffectRejectedError(`Feishu rejected card: ${res.code}`);
4429
4982
  if (res.code !== 0)
@@ -4438,13 +4991,8 @@ export class FeishuBot {
4438
4991
  }
4439
4992
  }
4440
4993
  async replyLiveStatusCard(messageId, view, chatId) {
4441
- const res = await this.client.im.message.reply({
4442
- path: { message_id: messageId },
4443
- data: {
4444
- content: JSON.stringify(this.buildLiveStatusCard(view, chatId)),
4445
- msg_type: "interactive",
4446
- },
4447
- });
4994
+ const request = this.liveStatusRequest(view, chatId, card => ({ path: { message_id: messageId }, data: { content: JSON.stringify(card), msg_type: "interactive" } }));
4995
+ const res = await this.client.im.message.reply(request);
4448
4996
  if (typeof res.code === "number" && res.code !== 0)
4449
4997
  throw new LiveStatusEffectRejectedError(`Feishu rejected card: ${res.code}`);
4450
4998
  if (res.code !== 0)
@@ -4452,10 +5000,8 @@ export class FeishuBot {
4452
5000
  return res?.data?.message_id || res?.message_id;
4453
5001
  }
4454
5002
  async patchLiveStatusCard(messageId, view, chatId) {
4455
- const res = await this.client.im.message.patch({
4456
- path: { message_id: messageId },
4457
- data: { content: JSON.stringify(this.buildLiveStatusCard(view, chatId)) },
4458
- });
5003
+ const request = this.liveStatusRequest(view, chatId, card => ({ path: { message_id: messageId }, data: { content: JSON.stringify(card) } }));
5004
+ const res = await this.client.im.message.patch(request);
4459
5005
  if (typeof res.code === "number" && res.code !== 0)
4460
5006
  throw new LiveStatusEffectRejectedError(`Feishu rejected card: ${res.code}`);
4461
5007
  if (res.code !== 0)
@@ -4517,6 +5063,7 @@ export class FeishuBot {
4517
5063
  };
4518
5064
  }
4519
5065
  async replyCompactCard(messageId, view, chatId) {
5066
+ this.assertIdentityCurrent();
4520
5067
  const res = await this.client.im.message.reply({
4521
5068
  path: { message_id: messageId },
4522
5069
  data: {
@@ -4527,6 +5074,7 @@ export class FeishuBot {
4527
5074
  return res?.data?.message_id || res?.message_id;
4528
5075
  }
4529
5076
  async patchCompactCard(messageId, view, chatId) {
5077
+ this.assertIdentityCurrent();
4530
5078
  await this.client.im.message.patch({
4531
5079
  path: { message_id: messageId },
4532
5080
  data: { content: JSON.stringify(this.buildCompactProgressCard(view, chatId)) },
@@ -4599,6 +5147,7 @@ export class FeishuBot {
4599
5147
  }
4600
5148
  }
4601
5149
  async replyMessage(messageId, text) {
5150
+ this.assertIdentityCurrent();
4602
5151
  // Use Feishu CardKit v2 markdown component for full Markdown rendering.
4603
5152
  const model = this.replyModelFooters.get(messageId);
4604
5153
  const status = this.replyStatusFooters.get(messageId);
@@ -5054,6 +5603,7 @@ export class FeishuBot {
5054
5603
  return firstId;
5055
5604
  }
5056
5605
  async sendMessage(chatId, text) {
5606
+ this.assertIdentityCurrent();
5057
5607
  const model = this.sendModelFooters.get(chatId);
5058
5608
  const status = this.sendStatusFooters.get(chatId);
5059
5609
  const card = this.buildMarkdownCard(text, model, status);
@@ -5123,7 +5673,7 @@ export class FeishuBot {
5123
5673
  */
5124
5674
  sendOrdered(chatId, fn) {
5125
5675
  const prev = this.sendQueue.get(chatId) || Promise.resolve();
5126
- const run = () => this.withSendDeadline(fn, chatId);
5676
+ const run = () => { this.assertIdentityCurrent(); return this.withSendDeadline(fn, chatId); };
5127
5677
  const next = prev.then(run, run); // run even if previous failed
5128
5678
  this.sendQueue.set(chatId, next.then(() => undefined, () => undefined));
5129
5679
  return next;
@@ -5360,16 +5910,21 @@ export class FeishuBot {
5360
5910
  }
5361
5911
  const previous = this.config.model;
5362
5912
  const sessionKey = await this.ensureSession(chatId);
5913
+ await this.assertIdentityEffect();
5363
5914
  try {
5364
5915
  // Validate/apply to the current session first. If OpenClaw rejects the
5365
5916
  // model, do not persist a bad config.
5366
- await this.openclawClient.patchSession({ key: sessionKey, model: nextModel });
5917
+ await this.openclawClient.patchSession({ key: sessionKey, model: nextModel,
5918
+ ...(this.identityEffects?.getStore() ? { expectedSessionId: this.identityEffects.getStore().item.target.sessionId } : {}) });
5919
+ await this.assertIdentityEffect();
5367
5920
  persistBotModel(this.configPath, this.config.name, nextModel);
5368
5921
  this.config.model = nextModel;
5369
5922
  await this.replyMessage(messageId, `✅ ${this.config.name} 模型已切换并持久化\n之前:${previous}\n现在:${nextModel}`);
5370
5923
  }
5371
5924
  catch (err) {
5372
- await this.openclawClient.patchSession({ key: sessionKey, model: previous }).catch(() => { });
5925
+ await this.assertIdentityEffect();
5926
+ await this.openclawClient.patchSession({ key: sessionKey, model: previous,
5927
+ ...(this.identityEffects?.getStore() ? { expectedSessionId: this.identityEffects.getStore().item.target.sessionId } : {}) }).catch(() => { });
5373
5928
  await this.replyMessage(messageId, `❌ 模型切换失败,配置未修改\n目标:${nextModel}\n原因:${err.message}`);
5374
5929
  }
5375
5930
  }
@@ -5388,6 +5943,7 @@ export class FeishuBot {
5388
5943
  catch {
5389
5944
  // session may not exist yet
5390
5945
  }
5946
+ this.assertIdentityCurrent();
5391
5947
  // Always show the configured model — session.model may show gateway-injected internal name
5392
5948
  const model = this.config.model;
5393
5949
  const totalTokens = session?.totalTokens || 0;
@@ -5449,7 +6005,7 @@ export class FeishuBot {
5449
6005
  if (mode === "tooltrim") {
5450
6006
  onPhase?.("tooltrim");
5451
6007
  try {
5452
- const res = await this.openclawClient.toolTrimCompact(sessionKey, 10);
6008
+ const res = this.identityEffects?.getStore() ? await this.openclawClient.toolTrimCompact(sessionKey, 10, () => this.assertIdentityEffect()) : await this.openclawClient.toolTrimCompact(sessionKey, 10);
5453
6009
  if (res?.compacted === true) {
5454
6010
  return {
5455
6011
  compacted: true,
@@ -5470,7 +6026,7 @@ export class FeishuBot {
5470
6026
  if (mode === "trim") {
5471
6027
  onPhase?.("trim");
5472
6028
  try {
5473
- const trimmed = await this.openclawClient.compactSession(sessionKey, { maxLines: trimMaxLines });
6029
+ const trimmed = await this.openclawClient.compactSession(sessionKey, { maxLines: trimMaxLines, ...(this.identityEffects?.getStore() ? { effectGuard: () => this.assertIdentityEffect() } : {}) });
5474
6030
  if (trimmed?.compacted === true) {
5475
6031
  const kept = typeof trimmed?.kept === "number" ? trimmed.kept : trimMaxLines;
5476
6032
  return { compacted: true, method: "transcript-trim", detail: `kept ${kept} transcript events` };
@@ -5485,7 +6041,7 @@ export class FeishuBot {
5485
6041
  // semantic mode: LLM summarize first, trim as fallback.
5486
6042
  let nativeReason;
5487
6043
  try {
5488
- const res = await this.openclawClient.semanticCompact(sessionKey);
6044
+ const res = this.identityEffects?.getStore() ? await this.openclawClient.semanticCompact(sessionKey, () => this.assertIdentityEffect()) : await this.openclawClient.semanticCompact(sessionKey);
5489
6045
  if (res?.compacted === true)
5490
6046
  return { compacted: true, method: "native" };
5491
6047
  nativeReason = typeof res?.reason === "string" ? res.reason : undefined;
@@ -5495,7 +6051,7 @@ export class FeishuBot {
5495
6051
  }
5496
6052
  onPhase?.("transcript-trim");
5497
6053
  try {
5498
- const trimmed = await this.openclawClient.compactSession(sessionKey, { maxLines: trimMaxLines });
6054
+ const trimmed = await this.openclawClient.compactSession(sessionKey, { maxLines: trimMaxLines, ...(this.identityEffects?.getStore() ? { effectGuard: () => this.assertIdentityEffect() } : {}) });
5499
6055
  if (trimmed?.compacted === true) {
5500
6056
  const kept = typeof trimmed?.kept === "number" ? trimmed.kept : trimMaxLines;
5501
6057
  return {
@@ -5626,10 +6182,14 @@ export class FeishuBot {
5626
6182
  async handleResetCommand(chatId, messageId) {
5627
6183
  const sessionKey = this.getSessionKey(chatId);
5628
6184
  try {
6185
+ await this.assertIdentityEffect();
5629
6186
  // Go supervision: a reset replaces the executor session generation; pause
5630
6187
  // supervision instead of letting the checker judge a wiped transcript.
5631
6188
  void this.goController?.onExecutorSessionChanged(chatId, "执行会话被 /reset");
5632
6189
  this.stopEpoch.set(chatId, this.store.bumpStopGeneration(this.config.name, chatId));
6190
+ const held = this.identityEffects?.getStore();
6191
+ if (held)
6192
+ held.epoch = this.stopGeneration(chatId);
5633
6193
  this.presentation(() => this.queuedPresentations.retire(chatId));
5634
6194
  this.store.stopInsertions(this.config.name, chatId);
5635
6195
  this.store.cancelReactionIntents(this.config.name, chatId, this.stopGeneration(chatId));
@@ -5641,9 +6201,11 @@ export class FeishuBot {
5641
6201
  this.openclawClient.resetSession(sessionKey).catch(() => { });
5642
6202
  // Wait a moment for it to take effect
5643
6203
  await new Promise((r) => setTimeout(r, 2000));
5644
- // Re-init session
6204
+ this.assertIdentityCurrent();
6205
+ // A held reset must not initialize an unobserved successor generation.
5645
6206
  this.initializedSessions.delete(sessionKey);
5646
- await this.ensureSession(chatId);
6207
+ if (!held)
6208
+ await this.ensureSession(chatId);
5647
6209
  await this.replyMessage(messageId, `✅ Session 已重置\n模型: ${this.config.model}`);
5648
6210
  }
5649
6211
  catch (err) {
@@ -5661,9 +6223,13 @@ export class FeishuBot {
5661
6223
  // cannot wake the just-stopped task back up with a follow-up.
5662
6224
  void this.goController?.pauseSilently(chatId, "用户执行了 /stop");
5663
6225
  try {
6226
+ await this.assertIdentityEffect();
5664
6227
  // Bump the stop generation FIRST so any in-flight auto-retry loop sees the
5665
6228
  // cancellation on its next iteration and stops retrying immediately.
5666
6229
  this.stopEpoch.set(chatId, this.store.bumpStopGeneration(this.config.name, chatId));
6230
+ const held = this.identityEffects?.getStore();
6231
+ if (held)
6232
+ held.epoch = this.stopGeneration(chatId);
5667
6233
  this.presentation(() => this.queuedPresentations.retire(chatId));
5668
6234
  this.store.cancelReactionIntents(this.config.name, chatId, this.stopGeneration(chatId));
5669
6235
  void this.reconcileReactions(chatId).catch(() => { });
@@ -5695,32 +6261,23 @@ export class FeishuBot {
5695
6261
  * Called once per chat on first message.
5696
6262
  */
5697
6263
  async fetchAndCacheChatInfo(chatId, chatType) {
6264
+ if (chatType === "p2p") {
6265
+ // Private ownership is not hourly metadata. Check/pin the stable SDK app
6266
+ // identity even on a fresh cache; never replace an unknown legacy owner.
6267
+ this.store.claimP2pOwner(chatId, this.config.name, this.config.appId);
6268
+ return;
6269
+ }
5698
6270
  const existing = this.store.getChatInfo(chatId);
5699
6271
  // Refresh at most once per hour
5700
6272
  if (existing && Date.now() - existing.updatedAt < 3600_000)
5701
6273
  return;
5702
6274
  try {
5703
- if (chatType === "p2p") {
5704
- // For p2p, we don't have a group name or member list from chat API
5705
- this.store.upsertChatInfo({
5706
- chatId,
5707
- chatType: "p2p",
5708
- chatName: "私聊",
5709
- members: "",
5710
- memberNames: "",
5711
- ownerBot: existing?.ownerBot || this.config.name,
5712
- freeDiscussion: this.store.getChatInfo(chatId)?.freeDiscussion || false,
5713
- verbose: this.store.getChatInfo(chatId)?.verbose || false,
5714
- discuss: this.store.getChatInfo(chatId)?.discuss || false,
5715
- discussMaxRounds: this.store.getChatInfo(chatId)?.discussMaxRounds || 10,
5716
- updatedAt: Date.now(),
5717
- });
5718
- return;
5719
- }
5720
6275
  // Fetch group info
5721
6276
  const chatResp = await this.client.im.chat.get({
5722
6277
  path: { chat_id: chatId },
5723
6278
  });
6279
+ if (this.identityClosed)
6280
+ return;
5724
6281
  const chatName = chatResp.data?.name || "";
5725
6282
  // Fetch members
5726
6283
  let members = [];
@@ -5741,6 +6298,8 @@ export class FeishuBot {
5741
6298
  catch {
5742
6299
  // Some bots may lack permission to list members
5743
6300
  }
6301
+ if (this.identityClosed)
6302
+ return;
5744
6303
  this.store.upsertChatInfo({
5745
6304
  chatId,
5746
6305
  chatType: "group",
@@ -5961,6 +6520,28 @@ export class FeishuBot {
5961
6520
  /**
5962
6521
  * Extract text content from a rich text (post) message.
5963
6522
  */
6523
+ /** Visible rich-post fragments only. Text nodes remain literal; only actual
6524
+ * media nodes become type markers, never a regex over the user's prose. */
6525
+ visiblePostInput(content, chatId) {
6526
+ const parts = [];
6527
+ if (typeof content.title === 'string')
6528
+ parts.push(content.title);
6529
+ for (const paragraph of Array.isArray(content.content) ? content.content : []) {
6530
+ if (!Array.isArray(paragraph))
6531
+ continue;
6532
+ for (const node of paragraph) {
6533
+ if (node?.tag === 'text' && typeof node.text === 'string')
6534
+ parts.push(node.text);
6535
+ else if (node?.tag === 'a' && typeof node.text === 'string')
6536
+ parts.push(`${node.text}${typeof node.href === 'string' ? `(${node.href})` : ''}`);
6537
+ else if (node?.tag === 'at' && typeof node.user_name === 'string')
6538
+ parts.push(`@${node.user_name}`);
6539
+ else if (node?.tag === 'img')
6540
+ parts.push(this.isEn(chatId) ? '[Image]' : '[图片]');
6541
+ }
6542
+ }
6543
+ return parts.join(' ');
6544
+ }
5964
6545
  extractPostText(content) {
5965
6546
  const parts = [];
5966
6547
  const title = content.title;