@agent-wechat/agent-wechat 2.7.0 → 2.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +11 -9
  2. package/dist/index.js +745 -302
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -2657,41 +2657,6 @@ function validateNativeRecall(value) {
2657
2657
  validateNativeRecallMetadata(value);
2658
2658
  if (!value || typeof value.threadId !== "string" || !value.threadId || value.threadId.length > 4096 || typeof value.serverId !== "string" || !/^[1-9]\d{0,19}$/.test(value.serverId) || BigInt(value.serverId) > 18446744073709551615n || typeof value.observedAt !== "string" || value.observedAt.length > 128 || !Number.isFinite(Date.parse(value.observedAt)) || value.recalledAt !== void 0 && (typeof value.recalledAt !== "string" || value.recalledAt.length > 128 || !Number.isFinite(Date.parse(value.recalledAt))) || value.messageId !== void 0 && (typeof value.messageId !== "string" || !value.messageId || value.messageId.length > 4096)) throw Error("Invalid native recall observation; cursor retained");
2659
2659
  }
2660
- function mergeNativeRecall(prior, next) {
2661
- validateNativeRecall(prior);
2662
- validateNativeRecall(next);
2663
- if (prior.threadId !== next.threadId || prior.serverId !== next.serverId) throw Error("Conflicting native recall identity; cursor retained");
2664
- return {
2665
- threadId: prior.threadId,
2666
- serverId: prior.serverId,
2667
- observedAt: prior.observedAt,
2668
- ...prior.messageId ?? next.messageId ? { messageId: prior.messageId ?? next.messageId } : {},
2669
- ...prior.recalledAt ?? next.recalledAt ? { recalledAt: prior.recalledAt ?? next.recalledAt } : {},
2670
- ...(prior.replacementText ?? next.replacementText) != null ? { replacementText: prior.replacementText ?? next.replacementText } : {}
2671
- };
2672
- }
2673
- function recalledNativeMessage(message, recall) {
2674
- validateNativeRecall(recall);
2675
- const previous = nativeRecallInfo(message);
2676
- const replacementText = previous?.replacementText ?? recall.replacementText;
2677
- return {
2678
- ...message,
2679
- type: 1e4,
2680
- body: "[Message recalled]",
2681
- quote: void 0,
2682
- link: void 0,
2683
- location: void 0,
2684
- media: [],
2685
- senderId: message.senderId || null,
2686
- direction: message.senderId ? message.direction : null,
2687
- mentions: { state: "unknown", userIds: [], self: null, all: null, source: null },
2688
- recall: {
2689
- observedAt: previous?.observedAt ?? recall.observedAt,
2690
- ...previous?.recalledAt ?? recall.recalledAt ? { recalledAt: previous?.recalledAt ?? recall.recalledAt } : {},
2691
- ...replacementText != null ? { replacementText } : {}
2692
- }
2693
- };
2694
- }
2695
2660
 
2696
2661
  // src/native-quote.ts
2697
2662
  function sameEmbeddedQuote(stored, current) {
@@ -3908,33 +3873,41 @@ import { toInboundMediaFacts } from "openclaw/plugin-sdk/channel-inbound";
3908
3873
  import { createHash as createHash11, randomUUID as randomUUID5 } from "node:crypto";
3909
3874
  import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3910
3875
  import { dirname as dirname2, isAbsolute as isAbsolute3, join as join3 } from "node:path";
3876
+ var NATIVE_CATCH_UP_WINDOW_MS = 24 * 60 * 60 * 1e3;
3877
+ var NATIVE_CATCH_UP_LIMIT = 100;
3878
+ var OPEN_LIMIT = 5e3;
3879
+ var AWAITING_HANDOFF_LIMIT = 100;
3880
+ var BOUNDARY_LIMIT = 5e3;
3881
+ var READ_MESSAGE_LIMIT = 100;
3882
+ var RECALL_MEMORY_LIMIT = 1e4;
3883
+ var OPEN_STATES = ["received", "dispatching", "handed_off", "awaiting_handoff"];
3884
+ var decimal2 = (value) => typeof value === "string" && /^\d+$/.test(value);
3885
+ var optionalServerId = (value) => value === null || typeof value === "string" && /^\d+$/.test(value);
3911
3886
  var NativeConsumerState = class {
3912
3887
  file;
3888
+ /** Messages whose turn or reply was in progress when the consumer last stopped. They are not retried. */
3889
+ heldOnOpen = [];
3890
+ /** Messages not queued since the last report: older than the catch-up window, beyond the catch-up limit, or the queue was full. */
3891
+ skipped = { old: 0, limit: 0, full: 0 };
3913
3892
  value;
3914
- constructor(directory, serverId, accountId) {
3893
+ dirty = false;
3894
+ /** Recalls seen while running. Messages read later from the daemon carry their own recall state. */
3895
+ recalls = /* @__PURE__ */ new Set();
3896
+ constructor(directory, serverId, accountId, options = {}) {
3915
3897
  if (!isAbsolute3(directory) || !serverId || !accountId) throw new Error("Native consumer state requires absolute storage and bound server/account identities");
3916
3898
  this.file = join3(directory, `${createHash11("sha256").update(`${serverId}\0${accountId}`).digest("hex")}.json`);
3917
- this.value = { schemaVersion: 1, serverId, accountId, cursor: "0", items: {} };
3899
+ this.value = { schemaVersion: 2, serverId, accountId, cursor: "0", open: {}, reads: {}, boundaries: {} };
3918
3900
  if (existsSync(this.file)) {
3919
3901
  const stat = lstatSync(this.file);
3920
3902
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 16 * 1024 * 1024 || stat.mode & 63) throw new Error("Native consumer state is not a bounded private regular file");
3921
- const parsed = JSON.parse(readFileSync(this.file, "utf8"));
3922
- if (parsed.schemaVersion !== 1 || parsed.serverId !== serverId || parsed.accountId !== accountId || !/^\d+$/.test(parsed.cursor) || !parsed.items || typeof parsed.items !== "object") throw new Error("Native consumer identity or schema mismatch; state was preserved");
3923
- for (const [id2, item] of Object.entries(parsed.items)) {
3924
- if (item.message?.id !== id2 || item.message.accountId !== accountId || typeof item.message.threadId !== "string" || !["received", "dispatching", "handed_off", "completed", "ignored", "needs_review"].includes(item.state)) throw new Error("Invalid native custody record; state was preserved");
3925
- nativeRecallInfo(item.message);
3926
- if (item.cursor != null && !/^\d+$/.test(item.cursor) || item.groupContext != null && typeof item.groupContext !== "boolean") throw new Error("Invalid native group context record; state was preserved");
3927
- if (item.revision != null && (typeof item.revision !== "string" || !item.revision || item.revision.length > 64)) throw Error("Invalid native custody revision; state was preserved");
3928
- item.revision ??= randomUUID5();
3929
- if (item.groupContext && (!item.cursor || item.origin !== "live" || item.state !== "ignored" || item.message.direction !== "incoming" || !item.message.threadId.endsWith("@chatroom"))) throw new Error("Invalid native buffered group context; state was preserved");
3930
- if (item.state === "dispatching") item.state = "needs_review";
3931
- }
3932
- if (parsed.recalls != null && (!parsed.recalls || typeof parsed.recalls !== "object" || Array.isArray(parsed.recalls))) throw Error("Invalid native recall state; state was preserved");
3933
- for (const [key2, recall] of Object.entries(parsed.recalls ?? {})) {
3934
- validateNativeRecall(recall);
3935
- if (key2 !== nativeRecallIdentity(recall.threadId, recall.serverId)) throw Error("Invalid native recall identity; state was preserved");
3936
- }
3937
- this.value = parsed;
3903
+ const bytes = readFileSync(this.file, "utf8");
3904
+ const parsed = JSON.parse(bytes);
3905
+ if (parsed?.serverId !== serverId || parsed.accountId !== accountId || !decimal2(parsed.cursor)) throw new Error("Native consumer identity or schema mismatch; state was preserved");
3906
+ if (parsed.schemaVersion === 1) {
3907
+ this.value = migrateVersion1(parsed, this.heldOnOpen, this.skipped, options.now ?? Date.now());
3908
+ if (!existsSync(`${this.file}.v1-backup`)) this.write(`${this.file}.v1-backup`, bytes);
3909
+ } else if (parsed.schemaVersion === 2) this.value = loadVersion2(parsed, this.heldOnOpen);
3910
+ else throw new Error("Native consumer identity or schema mismatch; state was preserved");
3938
3911
  this.persist();
3939
3912
  }
3940
3913
  }
@@ -3945,26 +3918,39 @@ var NativeConsumerState = class {
3945
3918
  return this.value.accountId;
3946
3919
  }
3947
3920
  items() {
3948
- return Object.values(this.value.items);
3921
+ return Object.values(this.value.open);
3949
3922
  }
3950
3923
  get(messageId) {
3951
- return this.value.items[messageId];
3924
+ return this.value.open[messageId];
3952
3925
  }
3953
3926
  isRecalled(message) {
3954
- return !!nativeRecallInfo(message) || !!(message.serverId && this.value.recalls?.[nativeRecallIdentity(message.threadId, message.serverId)]);
3927
+ return !!(message.recall && nativeRecallInfo(message)) || this.recalledIdentity(message.threadId, message.serverId);
3955
3928
  }
3929
+ /** A queued message can still be handled by the work that holds this revision. */
3956
3930
  isCurrent(message, revision) {
3957
- const current = this.get(message.id);
3958
- return !!current && (revision === void 0 || current.revision === revision) && !this.isRecalled(message) && JSON.stringify(current.message) === JSON.stringify(message);
3931
+ const item = this.get(message.id);
3932
+ return !!item && (revision === void 0 || item.revision === revision) && item.threadId === message.threadId && item.serverId === (message.serverId ?? null) && !item.invalidatedByRecall && !this.isRecalled(message);
3933
+ }
3934
+ /** A context message is still usable: neither it nor the quote it carries was recalled. */
3935
+ isAvailable(message) {
3936
+ return !this.isRecalled(message) && !(message.quote && this.recalledIdentity(message.threadId, message.quote.serverId));
3937
+ }
3938
+ recalledIdentity(threadId2, serverId) {
3939
+ return !!serverId && this.recalls.has(nativeRecallIdentity(threadId2, serverId));
3959
3940
  }
3960
3941
  persist() {
3961
- const directory = dirname2(this.file);
3942
+ const bytes = JSON.stringify(this.value);
3943
+ if (Buffer.byteLength(bytes) > 16 * 1024 * 1024) throw new Error("Native custody state is full; intake paused without advancing acknowledgement");
3944
+ this.write(this.file, bytes);
3945
+ this.dirty = false;
3946
+ }
3947
+ /** Replace a private file in the consumer directory in one durable step. */
3948
+ write(file, bytes) {
3949
+ const directory = dirname2(file);
3962
3950
  mkdirSync(directory, { recursive: true, mode: 448 });
3963
3951
  const stat = lstatSync(directory);
3964
3952
  if (!stat.isDirectory() || stat.isSymbolicLink() || stat.mode & 63) throw new Error("Native consumer directory must be private (0700)");
3965
- const bytes = JSON.stringify(this.value);
3966
- if (Buffer.byteLength(bytes) > 16 * 1024 * 1024) throw new Error("Native custody state is full; intake paused without advancing acknowledgement");
3967
- const temporary = `${this.file}.${randomUUID5()}.tmp`;
3953
+ const temporary = `${file}.${randomUUID5()}.tmp`;
3968
3954
  let fd;
3969
3955
  try {
3970
3956
  fd = openSync(temporary, "wx", 384);
@@ -3972,7 +3958,7 @@ var NativeConsumerState = class {
3972
3958
  fsyncSync(fd);
3973
3959
  closeSync(fd);
3974
3960
  fd = void 0;
3975
- renameSync(temporary, this.file);
3961
+ renameSync(temporary, file);
3976
3962
  const directoryFd = openSync(directory, "r");
3977
3963
  try {
3978
3964
  fsyncSync(directoryFd);
@@ -3997,167 +3983,322 @@ var NativeConsumerState = class {
3997
3983
  throw error;
3998
3984
  }
3999
3985
  }
3986
+ checkCursor(cursor) {
3987
+ if (!decimal2(cursor) || BigInt(cursor) < BigInt(this.value.cursor)) throw new Error("Native journal cursor cannot move backward");
3988
+ return BigInt(cursor) > BigInt(this.value.cursor);
3989
+ }
3990
+ /** Move past events that need no work. Written with the next change or {@link commit}. */
3991
+ advance(cursor) {
3992
+ if (this.checkCursor(cursor)) {
3993
+ this.value.cursor = cursor;
3994
+ this.dirty = true;
3995
+ }
3996
+ }
3997
+ /** Write an advanced cursor before it is acknowledged to the daemon. */
3998
+ commit() {
3999
+ if (this.dirty) this.persist();
4000
+ }
4001
+ /** Queue a live incoming message. Returns true when it replaces another message under the same source-local ID. */
4000
4002
  accept(cursor, message, origin = "unknown") {
4001
- if (!/^\d+$/.test(cursor) || BigInt(cursor) < BigInt(this.value.cursor)) throw new Error("Native journal cursor cannot move backward");
4002
- if (message && (!message.id || message.accountId !== this.value.accountId)) throw new Error("Native journal message crosses account boundary");
4003
+ if (!this.checkCursor(cursor)) return false;
4004
+ if (!message?.id || message.accountId !== this.value.accountId || typeof message.threadId !== "string" || !message.threadId) throw new Error("Native journal message crosses account boundary");
4003
4005
  let replaced = false;
4004
4006
  this.mutate(() => {
4005
- if (message?.serverId && nativeRecallInfo(message)) this.rememberRecall({ messageId: message.id, threadId: message.threadId, serverId: message.serverId, ...nativeRecallInfo(message) });
4006
- if (message?.serverId) {
4007
- const recall = this.value.recalls?.[nativeRecallIdentity(message.threadId, message.serverId)];
4008
- if (recall) message = recalledNativeMessage(message, recall);
4009
- }
4010
- const existing = message ? this.value.items[message.id] : void 0;
4011
- replaced = !!message && !nativeRecallInfo(message) && !!existing && (existing.message.threadId !== message.threadId || existing.message.serverId !== message.serverId);
4012
- if (message && (!existing || replaced)) {
4013
- const completed = Object.entries(this.value.items).filter(([, item]) => !item.readPending && !item.groupContext && ["completed", "ignored", "needs_review"].includes(item.state));
4014
- for (const [key2] of completed.slice(0, Math.max(0, completed.length - 1e3))) delete this.value.items[key2];
4015
- if (!existing && Object.keys(this.value.items).length >= 5e3) throw new Error("Native custody queue is full; operator review required");
4016
- if (replaced) {
4017
- for (const item of this.items()) {
4018
- const manifest = item.dispatchManifest;
4019
- if (!manifest || ![
4020
- ...manifest.messageIds,
4021
- ...(manifest.historyInputs ?? []).map((input) => input.id),
4022
- ...manifest.assets.flatMap((asset) => asset.sourceMessageId ? [asset.sourceMessageId] : [])
4023
- ].includes(message.id)) continue;
4024
- if (["dispatching", "handed_off"].includes(item.state)) item.state = "needs_review";
4025
- item.dispatchManifest = void 0;
4026
- item.manifestHash = void 0;
4027
- item.readPending = false;
4028
- }
4029
- }
4030
- this.value.items[message.id] = { message, revision: randomUUID5(), origin, state: nativeRecallInfo(message) ? "ignored" : "received", cursor };
4031
- }
4032
4007
  this.value.cursor = cursor;
4008
+ if (this.isRecalled(message)) return;
4009
+ const existing = this.value.open[message.id];
4010
+ const serverId = message.serverId ?? null;
4011
+ if (existing && existing.threadId === message.threadId && existing.serverId === serverId) return;
4012
+ replaced = !!existing;
4013
+ if (replaced) this.revokeReferences(message.id);
4014
+ else if (Object.keys(this.value.open).length >= OPEN_LIMIT) {
4015
+ this.skipped.full++;
4016
+ return;
4017
+ }
4018
+ this.value.open[message.id] = {
4019
+ id: message.id,
4020
+ threadId: message.threadId,
4021
+ serverId,
4022
+ ...message.quote?.serverId ? { quoteServerId: message.quote.serverId } : {},
4023
+ origin,
4024
+ cursor,
4025
+ revision: randomUUID5(),
4026
+ state: "received"
4027
+ };
4033
4028
  });
4034
4029
  return replaced;
4035
4030
  }
4036
- /** Persist invalidation and the event cursor together, before consumer ACK. */
4031
+ /** Turns that offered a replaced message lose their manifest, so a late model callback cannot confirm them. */
4032
+ revokeReferences(messageId) {
4033
+ for (const item of this.items()) {
4034
+ if (!item.dispatchManifest || !manifestReferences(item.dispatchManifest).includes(messageId)) continue;
4035
+ if (item.state === "awaiting_handoff") {
4036
+ delete this.value.open[item.id];
4037
+ continue;
4038
+ }
4039
+ item.dispatchManifest = void 0;
4040
+ item.manifestHash = void 0;
4041
+ }
4042
+ }
4043
+ /** Apply a recall event and advance the cursor in one write, before acknowledgement. */
4037
4044
  acceptRecall(cursor, recall) {
4038
4045
  validateNativeRecall(recall);
4039
- if (!/^\d+$/.test(cursor) || BigInt(cursor) < BigInt(this.value.cursor)) throw Error("Native journal cursor cannot move backward");
4046
+ if (!this.checkCursor(cursor)) return [];
4040
4047
  let affected = [];
4041
4048
  this.mutate(() => {
4042
- affected = this.rememberRecall(recall);
4049
+ affected = this.applyRecall(recall);
4043
4050
  this.value.cursor = cursor;
4044
4051
  });
4045
4052
  return affected;
4046
4053
  }
4047
- rememberRecall(recall) {
4048
- const hinted = recall.messageId ? this.get(recall.messageId)?.message : void 0;
4049
- if (hinted && (hinted.threadId !== recall.threadId || hinted.serverId !== recall.serverId)) {
4050
- const { messageId: _stale, ...exact } = recall;
4051
- recall = exact;
4052
- }
4054
+ /** Apply a recall found by re-reading a message. */
4055
+ noteRecall(recall) {
4056
+ validateNativeRecall(recall);
4057
+ let affected = [];
4058
+ this.mutate(() => {
4059
+ affected = this.applyRecall(recall);
4060
+ });
4061
+ return affected;
4062
+ }
4063
+ applyRecall(recall) {
4053
4064
  const key2 = nativeRecallIdentity(recall.threadId, recall.serverId);
4054
- this.value.recalls ??= {};
4055
- const remembered = mergeNativeRecall(this.value.recalls[key2] ?? recall, recall);
4056
- this.value.recalls[key2] = remembered;
4057
- const affected = /* @__PURE__ */ new Set();
4065
+ this.recalls.delete(key2);
4066
+ this.recalls.add(key2);
4067
+ for (const old of this.recalls) {
4068
+ if (this.recalls.size <= RECALL_MEMORY_LIMIT) break;
4069
+ this.recalls.delete(old);
4070
+ }
4071
+ const hinted = recall.messageId ? this.value.open[recall.messageId] : void 0;
4072
+ const hint = recall.messageId && (!hinted || hinted.threadId === recall.threadId && hinted.serverId === recall.serverId) ? recall.messageId : void 0;
4073
+ const affected = new Set(hint ? [hint] : []);
4058
4074
  for (const item of this.items()) {
4059
- if (item.message.threadId !== recall.threadId) continue;
4060
- const target = item.message.serverId === recall.serverId;
4061
- const quote = item.message.quote?.serverId === recall.serverId;
4062
- if (!target && !quote) continue;
4063
- affected.add(item.message.id);
4064
- item.message = target ? recalledNativeMessage(item.message, remembered) : { ...item.message, quote: void 0 };
4065
- if (target) item.groupContext = false;
4066
- item.readPending = false;
4067
- if (["dispatching", "handed_off"].includes(item.state)) item.state = "needs_review";
4068
- else if (target && item.state === "received") item.state = "ignored";
4069
- item.invalidatedByRecall = true;
4070
- item.dispatchManifest = void 0;
4071
- item.manifestHash = void 0;
4075
+ if (item.threadId !== recall.threadId) continue;
4076
+ const target = item.serverId === recall.serverId;
4077
+ if (!target && item.quoteServerId !== recall.serverId && !item.inputServerIds?.includes(recall.serverId) && !(hint && item.dispatchManifest && manifestReferences(item.dispatchManifest).includes(hint))) continue;
4078
+ affected.add(item.id);
4079
+ if (item.state === "received") {
4080
+ if (target) delete this.value.open[item.id];
4081
+ else item.revision = randomUUID5();
4082
+ } else if (item.state === "awaiting_handoff") delete this.value.open[item.id];
4083
+ else {
4084
+ item.invalidatedByRecall = true;
4085
+ item.dispatchManifest = void 0;
4086
+ item.manifestHash = void 0;
4087
+ }
4072
4088
  }
4073
- for (const item of this.items()) {
4074
- const manifest = item.dispatchManifest;
4075
- if (item.message.threadId !== recall.threadId || !manifest) continue;
4076
- const references = [
4077
- ...manifest.messageIds,
4078
- ...(manifest.historyInputs ?? []).map((input) => input.id),
4079
- ...manifest.assets.flatMap((asset) => asset.sourceMessageId ? [asset.sourceMessageId] : [])
4080
- ];
4081
- if (!references.some((id2) => affected.has(id2) || id2 === recall.messageId)) continue;
4082
- affected.add(item.message.id);
4083
- item.invalidatedByRecall = true;
4084
- item.readPending = false;
4085
- if (["dispatching", "handed_off"].includes(item.state)) item.state = "needs_review";
4086
- item.dispatchManifest = void 0;
4087
- item.manifestHash = void 0;
4089
+ const read = this.value.reads[recall.threadId];
4090
+ if (read) {
4091
+ read.messages = read.messages.filter((message) => message.serverId !== recall.serverId && !affected.has(message.id));
4092
+ if (!read.messages.length) delete this.value.reads[recall.threadId];
4088
4093
  }
4089
4094
  return [...affected];
4090
4095
  }
4091
4096
  update(messageId, update, revision) {
4092
- const item = this.value.items[messageId];
4097
+ const item = this.value.open[messageId];
4093
4098
  if (revision !== void 0 && item?.revision !== revision) return false;
4094
4099
  if (!item) throw new Error("Unknown native custody message");
4095
- this.mutate(() => Object.assign(this.value.items[messageId], update));
4100
+ this.mutate(() => Object.assign(this.value.open[messageId], update));
4096
4101
  return true;
4097
4102
  }
4098
- groupHistory(threadId2, beforeId, limit) {
4099
- const before = this.value.items[beforeId]?.cursor;
4100
- if (!before || limit <= 0) return [];
4101
- return this.items().filter((item) => item.groupContext && item.state === "ignored" && item.origin === "live" && item.message.threadId === threadId2 && item.cursor && BigInt(item.cursor) < BigInt(before)).sort((a, b) => BigInt(a.cursor) < BigInt(b.cursor) ? -1 : BigInt(a.cursor) > BigInt(b.cursor) ? 1 : 0).slice(-limit);
4103
+ /** Drop queued messages in one write, skipping any another occupant or a started turn now holds. */
4104
+ dropQueued(entries) {
4105
+ const dropped = entries.filter(({ id: id2, revision }) => this.value.open[id2]?.revision === revision && this.value.open[id2].state === "received");
4106
+ if (dropped.length) this.mutate(() => {
4107
+ for (const { id: id2 } of dropped) delete this.value.open[id2];
4108
+ });
4109
+ return dropped.length;
4102
4110
  }
4103
- bufferGroupMessage(messageId, limit, revision) {
4104
- const item = this.value.items[messageId];
4105
- if (revision !== void 0 && item?.revision !== revision) return false;
4106
- if (!item || item.state !== "received" || item.origin !== "live" || item.message.direction !== "incoming" || !item.cursor || !item.message.threadId.endsWith("@chatroom") || !Number.isInteger(limit) || limit < 0 || limit > 200) throw new Error("Invalid native group history admission");
4111
+ /** Remove a message that needs no more work. Ignored when another occupant now holds the ID. */
4112
+ finish(messageId, revision) {
4113
+ const item = this.value.open[messageId];
4114
+ if (!item || revision !== void 0 && item.revision !== revision) return false;
4107
4115
  this.mutate(() => {
4108
- Object.assign(this.value.items[messageId], { state: "ignored", groupContext: limit > 0 });
4109
- const history = this.items().filter((value) => value.groupContext).sort((a, b) => BigInt(a.cursor) < BigInt(b.cursor) ? -1 : 1);
4110
- const thread3 = history.filter((value) => value.message.threadId === item.message.threadId);
4111
- for (const value of thread3.slice(0, Math.max(0, thread3.length - limit))) value.groupContext = false;
4112
- const retained = history.filter((value) => value.groupContext);
4113
- for (const value of retained.slice(0, Math.max(0, retained.length - 1e3))) value.groupContext = false;
4116
+ delete this.value.open[messageId];
4114
4117
  });
4115
4118
  return true;
4116
4119
  }
4117
- beginDispatch(messageId, dispatchManifest, historyIds = []) {
4118
- if (this.value.items[messageId]?.state !== "received" || this.isRecalled(this.value.items[messageId].message) || historyIds.some((id2) => !this.value.items[id2]?.groupContext || this.value.items[id2].message.threadId !== this.value.items[messageId].message.threadId)) throw new Error("Invalid native context dispatch custody");
4120
+ /**
4121
+ * Record the turn before any model side effect. In a group, also move the
4122
+ * context boundary in the same write, so a crash cannot offer that context again.
4123
+ */
4124
+ beginDispatch(messageId, dispatchManifest, options = {}) {
4125
+ const item = this.value.open[messageId];
4126
+ if (!item || item.state !== "received" || item.invalidatedByRecall || this.recalledIdentity(item.threadId, item.serverId) || options.revision !== void 0 && item.revision !== options.revision) throw new Error("Invalid native context dispatch custody");
4127
+ const inputServerIds = [...new Set((options.inputServerIds ?? []).filter((id2) => typeof id2 === "string" && id2))].slice(0, 1e3);
4119
4128
  this.mutate(() => {
4120
- Object.assign(this.value.items[messageId], { state: "dispatching", dispatchManifest, invalidatedByRecall: false });
4121
- for (const id2 of historyIds) this.value.items[id2].groupContext = false;
4129
+ Object.assign(item, { state: "dispatching", dispatchManifest, invalidatedByRecall: false, ...inputServerIds.length ? { inputServerIds } : {} });
4130
+ const prior = this.value.boundaries[item.threadId];
4131
+ if (options.boundary && (!prior || BigInt(item.cursor) > BigInt(prior.cursor))) {
4132
+ const createdAt = typeof options.boundary.createdAt === "string" ? options.boundary.createdAt : void 0;
4133
+ const earlier = !!prior?.createdAt && !!createdAt && Date.parse(createdAt) < Date.parse(prior.createdAt);
4134
+ delete this.value.boundaries[item.threadId];
4135
+ this.value.boundaries[item.threadId] = earlier ? { ...prior, cursor: item.cursor } : { cursor: item.cursor, messageId, ...createdAt ? { createdAt } : {} };
4136
+ const threads = Object.keys(this.value.boundaries);
4137
+ for (const thread3 of threads.slice(0, Math.max(0, threads.length - BOUNDARY_LIMIT))) delete this.value.boundaries[thread3];
4138
+ }
4122
4139
  });
4123
4140
  }
4141
+ /**
4142
+ * Finish a turn. A read requested by the turn is kept until it is sent. When
4143
+ * the host has not yet confirmed the model run, a bounded record waits for its callback.
4144
+ */
4145
+ complete(messageId, revision, outcome) {
4146
+ const item = this.value.open[messageId];
4147
+ if (!item || item.revision !== revision) return false;
4148
+ this.mutate(() => {
4149
+ if (outcome.requestRead && !outcome.failed) this.addRead(item);
4150
+ if (outcome.failed || !outcome.awaitHandoff) {
4151
+ delete this.value.open[messageId];
4152
+ return;
4153
+ }
4154
+ Object.assign(item, { state: "awaiting_handoff", handoffUnconfirmed: true });
4155
+ const waiting = this.items().filter((value) => value.state === "awaiting_handoff");
4156
+ for (const value of waiting.slice(0, Math.max(0, waiting.length - AWAITING_HANDOFF_LIMIT))) delete this.value.open[value.id];
4157
+ });
4158
+ return true;
4159
+ }
4160
+ addRead(item) {
4161
+ const messages = (this.value.reads[item.threadId]?.messages ?? []).filter((message) => message.id !== item.id);
4162
+ messages.push({ id: item.id, serverId: item.serverId });
4163
+ this.value.reads[item.threadId] = { token: randomUUID5(), messages: messages.slice(-READ_MESSAGE_LIMIT) };
4164
+ }
4165
+ /** Threads waiting for a read receipt. Pass the token back to {@link clearRead}. */
4166
+ pendingReads() {
4167
+ return Object.entries(this.value.reads).map(([threadId2, read]) => ({ threadId: threadId2, token: read.token }));
4168
+ }
4169
+ readPending(threadId2) {
4170
+ return !!this.value.reads[threadId2];
4171
+ }
4172
+ /** Clear a sent read, unless another message asked for one since it was started. */
4173
+ clearRead(threadId2, token) {
4174
+ if (this.value.reads[threadId2]?.token !== token) return false;
4175
+ this.mutate(() => {
4176
+ delete this.value.reads[threadId2];
4177
+ });
4178
+ return true;
4179
+ }
4180
+ groupBoundary(threadId2) {
4181
+ return this.value.boundaries[threadId2];
4182
+ }
4124
4183
  /** Synchronous bounded receipt at the SDK's prepared-run callback boundary. */
4125
4184
  preparedCallback(messageIds, readPolicy, previous) {
4126
4185
  if (!messageIds.length || messageIds.length > 1e3) throw new Error("Invalid native prepared input manifest");
4127
4186
  const exact = [...new Set(messageIds)];
4128
4187
  const items = exact.map((id2) => {
4129
- const item = this.value.items[id2];
4188
+ const item = this.value.open[id2];
4130
4189
  if (!item || item.state !== "dispatching") throw new Error("Prepared input manifest is not in dispatch custody");
4131
4190
  return item;
4132
4191
  });
4133
4192
  const revisions = items.map((item) => item.revision);
4134
- if (new Set(items.map((item) => item.message.threadId)).size !== 1) throw new Error("Prepared input manifest crosses threads");
4135
- const manifestHash = createHash11("sha256").update(JSON.stringify({
4193
+ if (new Set(items.map((item) => item.threadId)).size !== 1) throw new Error("Prepared input manifest crosses threads");
4194
+ const hash = () => createHash11("sha256").update(JSON.stringify({
4136
4195
  accountId: this.value.accountId,
4137
4196
  messageIds: exact,
4138
- dispatchManifests: items.map((item) => item.dispatchManifest ?? null)
4197
+ dispatchManifests: exact.map((id2) => this.value.open[id2]?.dispatchManifest ?? null)
4139
4198
  })).digest("hex");
4199
+ const manifestHash = hash();
4140
4200
  return (...args) => {
4141
4201
  const runId = typeof args[0] === "string" ? args[0] : args[0]?.runId;
4142
4202
  if (typeof runId !== "string" || !runId || runId.length > 256) throw new Error("Prepared run callback has no valid runId");
4143
4203
  this.mutate(() => {
4144
- const currentHash = createHash11("sha256").update(JSON.stringify({
4145
- accountId: this.value.accountId,
4146
- messageIds: exact,
4147
- dispatchManifests: exact.map((id2) => this.value.items[id2]?.dispatchManifest ?? null)
4148
- })).digest("hex");
4204
+ const currentHash = hash();
4149
4205
  for (const [index, id2] of exact.entries()) {
4150
- const item = this.value.items[id2];
4151
- if (!item || item.invalidatedByRecall || this.isRecalled(item.message)) throw Error("Native prepared input was invalidated by a recall");
4206
+ const item = this.value.open[id2];
4207
+ if (!item) throw Error("Native prepared input is no longer in custody");
4208
+ if (item.invalidatedByRecall || this.recalledIdentity(item.threadId, item.serverId)) throw Error("Native prepared input was invalidated by a recall");
4152
4209
  if (item.revision !== revisions[index] || currentHash !== manifestHash) throw Error("Native prepared input source identity changed");
4153
4210
  if (item.runId && item.runId !== runId) throw new Error("Native prepared manifest was assigned to another run; operator review required");
4154
- Object.assign(item, { state: "handed_off", runId, manifestHash, readPending: readPolicy === "on_model_dispatch", handoffUnconfirmed: false });
4211
+ if (readPolicy === "on_model_dispatch") this.addRead(item);
4212
+ if (item.state === "awaiting_handoff") delete this.value.open[id2];
4213
+ else Object.assign(item, { state: "handed_off", runId, manifestHash, handoffUnconfirmed: false });
4155
4214
  }
4156
4215
  });
4157
4216
  return previous?.(...args);
4158
4217
  };
4159
4218
  }
4160
4219
  };
4220
+ function manifestReferences(manifest) {
4221
+ return [
4222
+ ...manifest.messageIds,
4223
+ ...(manifest.historyInputs ?? []).map((input) => input.id),
4224
+ ...manifest.assets.flatMap((asset) => asset.sourceMessageId ? [asset.sourceMessageId] : [])
4225
+ ];
4226
+ }
4227
+ function loadVersion2(parsed, held) {
4228
+ if (!parsed.open || typeof parsed.open !== "object" || Array.isArray(parsed.open) || !parsed.reads || typeof parsed.reads !== "object" || !parsed.boundaries || typeof parsed.boundaries !== "object") throw new Error("Native consumer identity or schema mismatch; state was preserved");
4229
+ const open2 = {};
4230
+ for (const [id2, item] of Object.entries(parsed.open)) {
4231
+ if (item?.id !== id2 || typeof item.threadId !== "string" || !item.threadId || !optionalServerId(item.serverId) || !OPEN_STATES.includes(item.state) || !decimal2(item.cursor) || typeof item.revision !== "string" || !item.revision || item.revision.length > 64 || typeof item.origin !== "string" || item.quoteServerId != null && !decimal2(item.quoteServerId) || item.inputServerIds != null && (!Array.isArray(item.inputServerIds) || item.inputServerIds.some((value) => !decimal2(value)))) throw new Error("Invalid native custody record; state was preserved");
4232
+ if (item.state === "dispatching" || item.state === "handed_off") {
4233
+ held.push(id2);
4234
+ continue;
4235
+ }
4236
+ if (item.state === "awaiting_handoff") continue;
4237
+ open2[id2] = item;
4238
+ }
4239
+ for (const [threadId2, read] of Object.entries(parsed.reads)) {
4240
+ if (!threadId2 || typeof read?.token !== "string" || !read.token || !Array.isArray(read.messages) || read.messages.some((message) => typeof message?.id !== "string" || !optionalServerId(message.serverId))) throw new Error("Invalid native read record; state was preserved");
4241
+ }
4242
+ for (const [threadId2, boundary] of Object.entries(parsed.boundaries)) {
4243
+ if (!threadId2 || !decimal2(boundary?.cursor) || boundary.messageId != null && typeof boundary.messageId !== "string" || boundary.createdAt != null && typeof boundary.createdAt !== "string") throw new Error("Invalid native group context record; state was preserved");
4244
+ }
4245
+ return { schemaVersion: 2, serverId: parsed.serverId, accountId: parsed.accountId, cursor: parsed.cursor, open: open2, reads: parsed.reads, boundaries: parsed.boundaries };
4246
+ }
4247
+ function migrateVersion1(parsed, held, skipped, now) {
4248
+ if (!parsed.items || typeof parsed.items !== "object" || Array.isArray(parsed.items)) throw new Error("Native consumer identity or schema mismatch; state was preserved");
4249
+ const items = [];
4250
+ for (const [id2, item] of Object.entries(parsed.items)) {
4251
+ const message = item?.message;
4252
+ if (message && message.accountId != null && message.accountId !== parsed.accountId) throw new Error("Native consumer identity or schema mismatch; state was preserved");
4253
+ if (message?.id !== id2 || typeof message.threadId !== "string" || !message.threadId || typeof item.state !== "string") continue;
4254
+ items.push([id2, { ...item, cursor: decimal2(item.cursor) ? item.cursor : void 0 }]);
4255
+ }
4256
+ const state = { schemaVersion: 2, serverId: parsed.serverId, accountId: parsed.accountId, cursor: parsed.cursor, open: {}, reads: {}, boundaries: {} };
4257
+ const serverId = (value) => decimal2(value) ? value : null;
4258
+ const time = (item) => item.message.createdAt ? Date.parse(item.message.createdAt) : Number.NaN;
4259
+ const order = (a, b) => {
4260
+ const cursors = BigInt(a.cursor ?? "0") - BigInt(b.cursor ?? "0");
4261
+ return cursors < 0n ? -1 : cursors > 0n ? 1 : (time(a) || 0) - (time(b) || 0);
4262
+ };
4263
+ const queued = items.map(([, item]) => item).filter((item) => item.state === "received" && item.origin === "live" && item.message.direction === "incoming" && !item.message.recall).sort(order);
4264
+ const recent = queued.filter((item) => {
4265
+ const sent = time(item);
4266
+ if (Number.isFinite(sent) && sent < now - NATIVE_CATCH_UP_WINDOW_MS) {
4267
+ skipped.old++;
4268
+ return false;
4269
+ }
4270
+ return true;
4271
+ });
4272
+ for (const item of recent.slice(-OPEN_LIMIT)) {
4273
+ const message = item.message, quoteServerId = serverId(message.quote?.serverId);
4274
+ state.open[message.id] = {
4275
+ id: message.id,
4276
+ threadId: message.threadId,
4277
+ serverId: serverId(message.serverId),
4278
+ ...quoteServerId ? { quoteServerId } : {},
4279
+ origin: "live",
4280
+ cursor: item.cursor ?? parsed.cursor,
4281
+ revision: typeof item.revision === "string" && item.revision && item.revision.length <= 64 ? item.revision : randomUUID5(),
4282
+ state: "received"
4283
+ };
4284
+ }
4285
+ for (const [id2, item] of items) {
4286
+ if (item.state === "dispatching" || item.state === "handed_off") held.push(id2);
4287
+ if (item.readPending === true) {
4288
+ const read = state.reads[item.message.threadId] ??= { token: randomUUID5(), messages: [] };
4289
+ read.messages = [...read.messages, { id: id2, serverId: serverId(item.message.serverId) }].slice(-READ_MESSAGE_LIMIT);
4290
+ }
4291
+ }
4292
+ for (const threadId2 of new Set(items.map(([, item]) => item.message.threadId).filter((thread3) => thread3.endsWith("@chatroom")))) {
4293
+ const inThread = items.map(([, item]) => item).filter((item) => item.message.threadId === threadId2).sort(order);
4294
+ const buffered = inThread.find((item) => item.groupContext === true && item.state === "ignored");
4295
+ const offered = inThread.filter((item) => ["dispatching", "handed_off", "completed", "needs_review"].includes(item.state) && (item.dispatchManifest || item.runId || item.state === "completed")).at(-1);
4296
+ const createdAt = (item) => typeof item.message.createdAt === "string" ? { createdAt: item.message.createdAt } : {};
4297
+ if (buffered) state.boundaries[threadId2] = { cursor: buffered.cursor && BigInt(buffered.cursor) > 0n ? (BigInt(buffered.cursor) - 1n).toString() : "0", ...createdAt(buffered) };
4298
+ else if (offered) state.boundaries[threadId2] = { cursor: offered.cursor ?? "0", messageId: offered.message.id, ...createdAt(offered) };
4299
+ }
4300
+ return state;
4301
+ }
4161
4302
 
4162
4303
  // src/native-history.ts
4163
4304
  import { buildHistoryContextFromEntries, buildInboundHistoryFromEntries, DEFAULT_GROUP_HISTORY_LIMIT } from "openclaw/plugin-sdk/reply-history";
@@ -4257,9 +4398,7 @@ function nativeWasMentioned(message) {
4257
4398
  return message.mentions?.state === "known" && (message.mentions.self === true || message.mentions.all === true);
4258
4399
  }
4259
4400
  async function projectNativeRead(client, accountId, state) {
4260
- const pending2 = state.items().filter((value) => value.readPending);
4261
- const threads = [...new Set(pending2.map((item) => item.message.threadId))];
4262
- for (const threadId2 of threads) {
4401
+ for (const { threadId: threadId2, token } of state.pendingReads()) {
4263
4402
  for (let attempt = 0; attempt < 2; attempt++) {
4264
4403
  let cursor;
4265
4404
  let thread3;
@@ -4274,10 +4413,8 @@ async function projectNativeRead(client, accountId, state) {
4274
4413
  }
4275
4414
  if (!thread3) break;
4276
4415
  try {
4277
- const receipt = await client.markRead(accountId, thread3.id, thread3.readStateVersion);
4278
- const notification = receipt?.phoneNotification?.state;
4279
- const phoneReadState = notification === "accepted" || notification === "rejected" || notification === "needs_review" ? notification : void 0;
4280
- for (const item of pending2.filter((item2) => item2.message.threadId === threadId2)) state.update(item.message.id, { readPending: false, phoneReadState }, item.revision);
4416
+ await client.markRead(accountId, thread3.id, thread3.readStateVersion);
4417
+ state.clearRead(threadId2, token);
4281
4418
  break;
4282
4419
  } catch (error) {
4283
4420
  if (error instanceof NativeApiError && error.status === 409 && attempt === 0) continue;
@@ -4288,115 +4425,198 @@ async function projectNativeRead(client, accountId, state) {
4288
4425
  }
4289
4426
  var NativeInputInvalidated = class extends Error {
4290
4427
  };
4291
- async function acceptNativeEvent(client, accountId, state, event) {
4428
+ function nativeTriggerEligible(message) {
4429
+ return message.direction === "incoming" && !!message.senderId && [1, 3, 34, 43, 47, 48, 49].includes(message.type) && !(message.type === 49 && message.appMessageType === 74) && !(message.type === 1 && !message.body) && !(message.type === 48 && (!message.location || !message.body));
4430
+ }
4431
+ async function resolveNativeAdmission(message, params) {
4432
+ const { account, cfg, core } = params;
4433
+ const isGroup = message.threadId.endsWith("@chatroom");
4434
+ const wasMentioned = nativeWasMentioned(message);
4435
+ const policy = resolveWeChatPolicyContext({ account, cfg, chatId: message.threadId });
4436
+ const allowTextCommands = core.channel.commands.shouldHandleTextCommands({ cfg, surface: "agent-wechat" });
4437
+ const commandBody = normalizeWeChatCommandBody(message.type === 1 ? message.body ?? "" : "", { isGroup, wasMentioned });
4438
+ const hasControlCommand = allowTextCommands && core.channel.commands.isControlCommandMessage(commandBody, cfg);
4439
+ const resolve = core.channel.inbound?.ingress?.resolveStable ?? resolveStableChannelMessageIngress;
4440
+ const readStoreAllowFrom = async () => core.channel.pairing.readAllowFromStore({ channel: "agent-wechat", accountId: account.accountId, env: process.env }).catch(() => []);
4441
+ const senderAdmission = (senderId) => resolveWeChatIngress({
4442
+ resolve,
4443
+ cfg,
4444
+ accountId: account.accountId,
4445
+ policy,
4446
+ isGroup,
4447
+ chatId: message.threadId,
4448
+ senderId,
4449
+ readStoreAllowFrom
4450
+ });
4451
+ const ingress = await resolveWeChatIngress({
4452
+ resolve,
4453
+ cfg,
4454
+ accountId: account.accountId,
4455
+ policy,
4456
+ isGroup,
4457
+ chatId: message.threadId,
4458
+ senderId: message.senderId ?? void 0,
4459
+ readStoreAllowFrom,
4460
+ command: { allowTextCommands, hasControlCommand },
4461
+ mention: { wasMentioned, allowTextCommands }
4462
+ });
4463
+ const unauthorizedDirectCommand = !isGroup && ingress.ingress.reasonCode === "control_command_unauthorized";
4464
+ return {
4465
+ isGroup,
4466
+ wasMentioned,
4467
+ policy,
4468
+ allowTextCommands,
4469
+ commandBody,
4470
+ hasControlCommand,
4471
+ senderAdmission,
4472
+ ingress,
4473
+ unauthorizedDirectCommand,
4474
+ admitted: ingress.ingress.admission === "dispatch" || unauthorizedDirectCommand
4475
+ };
4476
+ }
4477
+ async function nativeMayAnswer(message, params) {
4478
+ return nativeTriggerEligible(message) && (await resolveNativeAdmission(message, params)).admitted;
4479
+ }
4480
+ function withinWindow(time, now) {
4481
+ const at = time ? Date.parse(time) : Number.NaN;
4482
+ return !Number.isFinite(at) || at >= now - NATIVE_CATCH_UP_WINDOW_MS;
4483
+ }
4484
+ async function acceptNativeEvent(client, accountId, state, event, options = {}) {
4292
4485
  if (state.accountId !== accountId) throw Error("Native event crosses its custody account boundary");
4486
+ if (BigInt(event.cursor) <= BigInt(state.cursor)) return void 0;
4293
4487
  if (event.kind === "message.recalled") {
4294
4488
  const affected = state.acceptRecall(event.cursor, event.data);
4295
4489
  invalidateNativePreparedInputs(accountId, affected);
4296
4490
  return void 0;
4297
4491
  }
4298
- let message;
4299
- if (event.kind === "message.committed") {
4300
- if (typeof event.data.messageId !== "string") throw Error("Native committed message identity is missing; cursor retained");
4301
- message = await client.message(accountId, event.data.messageId);
4302
- if (message.id !== event.data.messageId || message.accountId !== accountId || message.threadId !== event.data.threadId) throw Error("Native committed message identity mismatch");
4492
+ if (event.kind !== "message.committed") {
4493
+ state.advance(event.cursor);
4494
+ return void 0;
4495
+ }
4496
+ if (typeof event.data.messageId !== "string") throw Error("Native committed message identity is missing; cursor retained");
4497
+ const origin = typeof event.data.origin === "string" ? event.data.origin : "unknown";
4498
+ if (origin !== "live" || event.data.direction != null && event.data.direction !== "incoming") {
4499
+ state.advance(event.cursor);
4500
+ return void 0;
4501
+ }
4502
+ const now = options.now ?? Date.now();
4503
+ if (!withinWindow(event.createdAt, now)) {
4504
+ state.skipped.old++;
4505
+ state.advance(event.cursor);
4506
+ return void 0;
4507
+ }
4508
+ const message = await client.message(accountId, event.data.messageId);
4509
+ if (message.id !== event.data.messageId || message.accountId !== accountId || message.threadId !== event.data.threadId) throw Error("Native committed message identity mismatch");
4510
+ if (message.direction !== "incoming" || options.answerable && !await options.answerable(message)) {
4511
+ state.advance(event.cursor);
4512
+ return message;
4513
+ }
4514
+ if (!withinWindow(message.createdAt, now)) {
4515
+ state.skipped.old++;
4516
+ state.advance(event.cursor);
4517
+ return message;
4303
4518
  }
4304
- const replaced = state.accept(event.cursor, message, typeof event.data.origin === "string" ? event.data.origin : "unknown");
4305
- if (replaced && message) invalidateNativePreparedInputs(accountId, [message.id]);
4519
+ const replaced = state.accept(event.cursor, message, origin);
4520
+ if (replaced) invalidateNativePreparedInputs(accountId, [message.id]);
4306
4521
  return message;
4307
4522
  }
4308
- async function recheckNativeInputs(client, state, messages) {
4309
- for (const message of messages) {
4310
- if (!state.isCurrent(message)) throw new NativeInputInvalidated();
4311
- const current = await client.message(message.accountId, message.id);
4312
- if (current.accountId !== message.accountId || current.threadId !== message.threadId || current.id !== message.id || current.serverId !== message.serverId) throw Error("Native input identity changed; delivery held for review");
4313
- const recall = nativeRecallInfo(current);
4314
- if (recall && current.serverId) {
4315
- const affected = state.acceptRecall(state.cursor, { ...recall, messageId: current.id, threadId: current.threadId, serverId: current.serverId });
4316
- invalidateNativePreparedInputs(message.accountId, [current.id, ...affected]);
4523
+ async function recheckNativeInput(client, state, message, available) {
4524
+ if (!available()) throw new NativeInputInvalidated();
4525
+ const current = await client.message(message.accountId, message.id);
4526
+ if (current.accountId !== message.accountId || current.threadId !== message.threadId || current.id !== message.id || current.serverId !== message.serverId) throw Error("Native input identity changed; delivery held for review");
4527
+ const recall = nativeRecallInfo(current);
4528
+ if (recall && current.serverId) {
4529
+ const affected = state.noteRecall({ ...recall, messageId: current.id, threadId: current.threadId, serverId: current.serverId });
4530
+ invalidateNativePreparedInputs(message.accountId, [current.id, ...affected]);
4531
+ throw new NativeInputInvalidated();
4532
+ }
4533
+ if (message.quote) {
4534
+ const quote = current.quote;
4535
+ if (quote?.state === "recalled") {
4536
+ const affected = state.noteRecall({ threadId: message.threadId, serverId: message.quote.serverId, observedAt: (/* @__PURE__ */ new Date()).toISOString() });
4537
+ invalidateNativePreparedInputs(message.accountId, affected);
4317
4538
  throw new NativeInputInvalidated();
4318
4539
  }
4319
- if (message.quote) {
4320
- const quote = current.quote;
4321
- if (quote?.state === "recalled") {
4322
- const affected = state.acceptRecall(state.cursor, {
4323
- threadId: message.threadId,
4324
- serverId: message.quote.serverId,
4325
- observedAt: (/* @__PURE__ */ new Date()).toISOString()
4326
- });
4327
- invalidateNativePreparedInputs(message.accountId, affected);
4328
- throw new NativeInputInvalidated();
4540
+ if (!quote || !sameEmbeddedQuote(message.quote, quote)) throw Error("Native embedded quote changed; delivery held for review");
4541
+ }
4542
+ if (message.type === 48 && (current.type !== 48 || current.body !== message.body || JSON.stringify(current.location) !== JSON.stringify(message.location))) {
4543
+ throw Error("Native location changed; delivery held for review");
4544
+ }
4545
+ if (!available()) throw new NativeInputInvalidated();
4546
+ }
4547
+ async function recheckNativeInputs(client, state, message, revision, history) {
4548
+ await recheckNativeInput(client, state, message, () => state.isCurrent(message, revision));
4549
+ for (const item of history) await recheckNativeInput(client, state, item, () => state.isAvailable(item));
4550
+ }
4551
+ function withoutRecalledQuote(state, message) {
4552
+ return message.quote && (message.quote.state === "recalled" || state.isRecalled({ threadId: message.threadId, serverId: message.quote.serverId })) ? { ...message, quote: void 0 } : message;
4553
+ }
4554
+ function nativeContextEligible(message) {
4555
+ return nativeTriggerEligible(message) && !nativeRecallInfo(message);
4556
+ }
4557
+ var HISTORY_PAGES = 5;
4558
+ async function readNativeGroupHistory(params) {
4559
+ const { client, state, message, limit } = params;
4560
+ const item = state.get(message.id), boundary = state.groupBoundary(message.threadId);
4561
+ if (!limit || !item || boundary && BigInt(item.cursor) <= BigInt(boundary.cursor)) return [];
4562
+ const since = boundary?.createdAt ? Date.parse(boundary.createdAt) : Number.NaN;
4563
+ const history = [];
4564
+ let found = false, cursor;
4565
+ for (let page = 0; page < HISTORY_PAGES; page++) {
4566
+ const result = await client.messages(message.accountId, message.threadId, { cursor, limit: 200 });
4567
+ for (const entry of result.items) {
4568
+ if (isNativeTombstone(entry)) continue;
4569
+ if (!found) {
4570
+ found = entry.id === message.id;
4571
+ continue;
4329
4572
  }
4330
- if (!quote || !sameEmbeddedQuote(message.quote, quote)) throw Error("Native embedded quote changed; delivery held for review");
4331
- }
4332
- if (message.type === 48 && (current.type !== 48 || current.body !== message.body || JSON.stringify(current.location) !== JSON.stringify(message.location))) {
4333
- throw Error("Native location changed; delivery held for review");
4573
+ if (entry.id === boundary?.messageId || entry.createdAt && Date.parse(entry.createdAt) < since) return history.reverse();
4574
+ if (!nativeContextEligible(entry) || state.isRecalled(entry) || state.get(entry.id) || params.isCommand(entry)) continue;
4575
+ history.push(withoutRecalledQuote(state, entry));
4576
+ if (history.length >= limit) return history.reverse();
4334
4577
  }
4335
- if (!state.isCurrent(message)) throw new NativeInputInvalidated();
4578
+ if (!result.nextCursor) break;
4579
+ cursor = result.nextCursor;
4336
4580
  }
4581
+ return history.reverse();
4337
4582
  }
4338
4583
  async function dispatchNativeMessage(params) {
4339
- const revision = params.state.get(params.message.id)?.revision;
4584
+ const revision = params.revision ?? params.state.get(params.message.id)?.revision;
4340
4585
  try {
4341
4586
  return await dispatchNativeMessageInput(params, revision);
4342
4587
  } catch (error) {
4343
4588
  const item = params.state.get(params.message.id);
4344
- if (params.state.isRecalled(params.message)) return "ignored";
4589
+ if (params.state.isRecalled(params.message)) {
4590
+ params.state.finish(params.message.id, revision);
4591
+ return "ignored";
4592
+ }
4345
4593
  if (error instanceof NativeInputInvalidated && item?.state === "received") return "pending";
4346
- if (item) params.state.update(params.message.id, { state: "needs_review" }, revision);
4594
+ params.state.finish(params.message.id, revision);
4347
4595
  return "needs_review";
4348
4596
  }
4349
4597
  }
4350
4598
  async function dispatchNativeMessageInput(params, revision) {
4351
- const { client, state, account, message, cfg, core } = params;
4599
+ const { client, state, account, cfg, core } = params;
4352
4600
  const readPolicy = account.native?.readPolicy ?? "on_inbound";
4353
- const custody = state.get(message.id);
4354
- if (state.isRecalled(message)) return "ignored";
4355
- if (!custody || custody.state !== "received" || !state.isCurrent(message, revision)) return "needs_review";
4601
+ const custody = state.get(params.message.id);
4602
+ if (state.isRecalled(params.message)) {
4603
+ state.finish(params.message.id, revision);
4604
+ return "ignored";
4605
+ }
4606
+ if (!custody || custody.state !== "received" || !state.isCurrent(params.message, revision)) return "needs_review";
4607
+ const message = withoutRecalledQuote(state, params.message);
4356
4608
  if (message.type === 49 && message.appMessageType === 74) {
4357
- state.update(message.id, { state: "ignored" }, revision);
4609
+ state.finish(message.id, revision);
4358
4610
  return "ignored";
4359
4611
  }
4360
- if (custody.origin !== "live" || message.direction !== "incoming" || ![1, 3, 34, 43, 47, 48, 49].includes(message.type) || message.type === 1 && !message.body || message.type === 48 && (!message.location || !message.body) || !message.senderId) {
4361
- state.update(message.id, { state: "ignored" }, revision);
4612
+ if (custody.origin !== "live" || !nativeTriggerEligible(message)) {
4613
+ state.finish(message.id, revision);
4362
4614
  return "ignored";
4363
4615
  }
4364
- const isGroup = message.threadId.endsWith("@chatroom");
4365
- const wasMentioned = nativeWasMentioned(message);
4366
- const policy = resolveWeChatPolicyContext({ account, cfg, chatId: message.threadId });
4367
- const allowTextCommands = core.channel.commands.shouldHandleTextCommands({ cfg, surface: "agent-wechat" });
4368
- const commandBody = normalizeWeChatCommandBody(message.type === 1 ? message.body ?? "" : "", { isGroup, wasMentioned });
4369
- const hasControlCommand = allowTextCommands && core.channel.commands.isControlCommandMessage(commandBody, cfg);
4370
- const resolve = core.channel.inbound?.ingress?.resolveStable ?? resolveStableChannelMessageIngress;
4371
- const senderAdmission = (senderId) => resolveWeChatIngress({
4372
- resolve,
4373
- cfg,
4374
- accountId: account.accountId,
4375
- policy,
4376
- isGroup,
4377
- chatId: message.threadId,
4378
- senderId,
4379
- readStoreAllowFrom: async () => core.channel.pairing.readAllowFromStore({ channel: "agent-wechat", accountId: account.accountId, env: process.env }).catch(() => [])
4380
- });
4381
- const ingress = await resolveWeChatIngress({
4382
- resolve,
4383
- cfg,
4384
- accountId: account.accountId,
4385
- policy,
4386
- isGroup,
4387
- chatId: message.threadId,
4388
- senderId: message.senderId,
4389
- readStoreAllowFrom: async () => core.channel.pairing.readAllowFromStore({ channel: "agent-wechat", accountId: account.accountId, env: process.env }).catch(() => []),
4390
- command: { allowTextCommands, hasControlCommand },
4391
- mention: { wasMentioned, allowTextCommands }
4392
- });
4393
- const unauthorizedDirectCommand = !isGroup && ingress.ingress.reasonCode === "control_command_unauthorized";
4394
- if (ingress.ingress.admission !== "dispatch" && !unauthorizedDirectCommand) {
4395
- if (isGroup && policy.requireMention && !wasMentioned && !hasControlCommand && (await senderAdmission(message.senderId)).ingress.admission === "dispatch") {
4396
- state.bufferGroupMessage(message.id, nativeGroupHistoryLimit(cfg), revision);
4397
- return "ignored";
4398
- }
4399
- state.update(message.id, { state: "ignored" }, revision);
4616
+ const admission = await resolveNativeAdmission(message, { account, cfg, core });
4617
+ const { isGroup, wasMentioned, policy, allowTextCommands, commandBody, hasControlCommand, senderAdmission, ingress } = admission;
4618
+ if (!admission.admitted) {
4619
+ state.finish(message.id, revision);
4400
4620
  return "ignored";
4401
4621
  }
4402
4622
  let preparedMedia;
@@ -4405,20 +4625,30 @@ async function dispatchNativeMessageInput(params, revision) {
4405
4625
  params.signal?.throwIfAborted();
4406
4626
  if (!state.isCurrent(message, revision)) throw new NativeInputInvalidated();
4407
4627
  };
4408
- const recheck = async (inputs) => {
4628
+ const recheck = async (history2) => {
4409
4629
  assertCurrent();
4410
- await recheckNativeInputs(client, state, inputs);
4630
+ await recheckNativeInputs(client, state, message, revision, history2);
4411
4631
  assertCurrent();
4412
4632
  };
4413
- await recheck([message]);
4633
+ await recheck([]);
4414
4634
  preparedMedia = await (params.prepareAttachment ?? prepareNativeAttachment)({ client, account, message, core, cfg, allowQuotedMessage, assertCurrent });
4415
4635
  if (preparedMedia.pending) return "pending";
4416
4636
  preparedMedia = await transcribeNativeAttachment(preparedMedia, core, cfg);
4417
- await recheck([message]);
4418
- const buffered = isGroup && !hasControlCommand ? state.groupHistory(message.threadId, message.id, nativeGroupHistoryLimit(cfg)) : [];
4637
+ await recheck([]);
4638
+ const contextual = isGroup && !hasControlCommand;
4639
+ const buffered = contextual ? await readNativeGroupHistory({
4640
+ client,
4641
+ state,
4642
+ message,
4643
+ limit: nativeGroupHistoryLimit(cfg),
4644
+ isCommand: (entry) => allowTextCommands && core.channel.commands.isControlCommandMessage(
4645
+ normalizeWeChatCommandBody(entry.type === 1 ? entry.body ?? "" : "", { isGroup, wasMentioned: nativeWasMentioned(entry) }),
4646
+ cfg
4647
+ )
4648
+ }) : [];
4419
4649
  const admitted = [];
4420
4650
  for (const item of buffered) {
4421
- if (item.message.senderId && (await senderAdmission(item.message.senderId)).ingress.admission === "dispatch") admitted.push(item.message);
4651
+ if (item.senderId && (await senderAdmission(item.senderId)).ingress.admission === "dispatch") admitted.push(item);
4422
4652
  }
4423
4653
  const history = await prepareNativeHistory(admitted, async (historical) => transcribeNativeAttachment(
4424
4654
  await (params.prepareAttachment ?? prepareNativeAttachment)({
@@ -4430,13 +4660,13 @@ async function dispatchNativeMessageInput(params, revision) {
4430
4660
  allowQuotedMessage,
4431
4661
  assertCurrent: () => {
4432
4662
  assertCurrent();
4433
- if (!state.isCurrent(historical)) throw new NativeInputInvalidated();
4663
+ if (!state.isAvailable(historical)) throw new NativeInputInvalidated();
4434
4664
  }
4435
4665
  }),
4436
4666
  core,
4437
4667
  cfg
4438
4668
  ));
4439
- await recheck([message, ...admitted]);
4669
+ await recheck(admitted);
4440
4670
  const context = buildNativeContext(history, message, preparedMedia);
4441
4671
  const inputBody = context.inputBody;
4442
4672
  const route = core.channel.routing.resolveAgentRoute({
@@ -4478,7 +4708,7 @@ async function dispatchNativeMessageInput(params, revision) {
4478
4708
  ...context.media.length ? { media: toInboundMediaFacts(context.media) } : {}
4479
4709
  });
4480
4710
  await core.channel.session.recordInboundSession({ storePath, sessionKey: route.sessionKey, ctx });
4481
- await recheck([message, ...admitted]);
4711
+ await recheck(admitted);
4482
4712
  const pipeline = (params.createPipeline ?? createChannelMessageReplyPipeline)({ cfg, agentId: route.agentId, channel: "agent-wechat", accountId: account.accountId });
4483
4713
  const { onModelSelected, ...prefixOptions } = pipeline;
4484
4714
  const dispatchManifest = nativeDispatchManifest({
@@ -4492,10 +4722,14 @@ async function dispatchNativeMessageInput(params, revision) {
4492
4722
  history: admitted
4493
4723
  });
4494
4724
  assertCurrent();
4495
- state.beginDispatch(message.id, dispatchManifest, buffered.map((item) => item.message.id));
4725
+ state.beginDispatch(message.id, dispatchManifest, {
4726
+ revision,
4727
+ boundary: contextual ? { createdAt: message.createdAt } : void 0,
4728
+ inputServerIds: [message.quote?.serverId, ...admitted.flatMap((item) => [item.serverId, item.quote?.serverId])].filter((id2) => !!id2)
4729
+ });
4496
4730
  const callback = readPolicy !== "on_inbound" && (message.type === 1 || message.type === 48 && !!message.location && !!message.body || message.type === 49 && [1, 17, 19, 87].includes(message.appMessageType ?? 0) && !!message.body || message.type === 49 && [3, 4, 5, 51].includes(message.appMessageType ?? 0) && !!message.link || preparedMedia.quote && [1, 49].includes(preparedMedia.quote.type ?? 0) && ["resolved", "embedded"].includes(preparedMedia.quote.state) || preparedMedia.attachment?.status === "ready" && preparedMedia.suppliedAssets?.length) ? state.preparedCallback([message.id], readPolicy) : void 0;
4497
4731
  if (callback) trackNativePreparedInput(dispatchManifest, callback);
4498
- const beforeSend = () => recheck([message, ...admitted]);
4732
+ const beforeSend = () => recheck(admitted);
4499
4733
  let failed = false;
4500
4734
  let delivery = 0;
4501
4735
  try {
@@ -4543,32 +4777,118 @@ async function dispatchNativeMessageInput(params, revision) {
4543
4777
  replyOptions: { runId: dispatchManifest.runId, onModelSelected, onPreparedAgentRunStart: callback }
4544
4778
  });
4545
4779
  params.signal?.throwIfAborted();
4546
- if (state.get(message.id)?.revision !== revision || state.get(message.id)?.dispatchManifest?.runId !== dispatchManifest.runId) return state.isRecalled(message) ? "ignored" : "needs_review";
4547
- if (state.get(message.id)?.invalidatedByRecall) return state.isRecalled(message) ? "ignored" : "needs_review";
4548
- const readPending = readPolicy === "on_inbound" && !failed && ingress.ingress.admission === "dispatch" ? true : state.get(message.id)?.readPending;
4549
- state.update(message.id, {
4550
- state: failed ? "needs_review" : "completed",
4551
- readPending,
4552
- handoffUnconfirmed: readPolicy === "on_model_dispatch" && !state.get(message.id)?.runId
4553
- }, revision);
4780
+ const settled = state.get(message.id);
4781
+ if (settled?.revision !== revision || settled?.dispatchManifest?.runId !== dispatchManifest.runId || settled.invalidatedByRecall) {
4782
+ state.finish(message.id, revision);
4783
+ return state.isRecalled(message) ? "ignored" : "needs_review";
4784
+ }
4785
+ state.complete(message.id, revision, {
4786
+ failed,
4787
+ requestRead: readPolicy === "on_inbound" && ingress.ingress.admission === "dispatch",
4788
+ awaitHandoff: readPolicy === "on_model_dispatch" && !settled.runId
4789
+ });
4554
4790
  return failed ? "needs_review" : "completed";
4555
4791
  } catch {
4556
- if (state.isRecalled(message)) return "ignored";
4557
- state.update(message.id, { state: "needs_review" }, revision);
4558
- return "needs_review";
4792
+ state.finish(message.id, revision);
4793
+ return state.isRecalled(message) ? "ignored" : "needs_review";
4559
4794
  }
4560
4795
  }
4561
- async function synchronizeNativeEvents(client, accountId, state) {
4562
- for (let index = 0; index < 100; index++) {
4563
- const page = await client.events(accountId, state.cursor, 200);
4564
- if (!page.items.length) return;
4565
- const before = state.cursor;
4566
- for (const event of page.items) await acceptNativeEvent(client, accountId, state, event);
4567
- if (state.cursor === before) throw Error("Native recovery event cursor did not advance");
4568
- await client.ack(accountId, "openclaw", state.cursor);
4569
- if (page.items.length < 200) return;
4796
+ var isExpiredCursor = (error) => error instanceof NativeApiError && error.code === "event_cursor_expired";
4797
+ async function resumeFromCatchUpWindow(client, accountId, state, options = {}) {
4798
+ const cutoff = (options.now ?? Date.now()) - NATIVE_CATCH_UP_WINDOW_MS;
4799
+ const reachesWindow = async (after) => {
4800
+ try {
4801
+ const next = (await client.events(accountId, after.toString(), 1)).items[0];
4802
+ return !next || !(Date.parse(next.createdAt) < cutoff);
4803
+ } catch (error) {
4804
+ if (isExpiredCursor(error)) return false;
4805
+ throw error;
4806
+ }
4807
+ };
4808
+ const before = state.cursor;
4809
+ let low = BigInt(before);
4810
+ if (await reachesWindow(low)) return void 0;
4811
+ let step = 1n, high = low + step;
4812
+ while (!await reachesWindow(high)) {
4813
+ if (step > 1n << 62n) throw Error("Native event log position could not be found");
4814
+ low = high;
4815
+ step *= 2n;
4816
+ high = low + step;
4817
+ }
4818
+ while (high - low > 1n) {
4819
+ const middle = (low + high) / 2n;
4820
+ if (await reachesWindow(middle)) high = middle;
4821
+ else low = middle;
4822
+ }
4823
+ state.advance(high.toString());
4824
+ state.commit();
4825
+ return state.cursor === before ? void 0 : state.cursor;
4826
+ }
4827
+ async function synchronizeNativeEvents(client, accountId, state, options = {}) {
4828
+ const resume = async () => {
4829
+ const from = state.cursor, to = await resumeFromCatchUpWindow(client, accountId, state, options);
4830
+ if (to) options.onResume?.(from, to);
4831
+ };
4832
+ const queued = [];
4833
+ const trim = () => {
4834
+ state.skipped.limit += state.dropQueued(queued.splice(0, Math.max(0, queued.length - NATIVE_CATCH_UP_LIMIT)));
4835
+ };
4836
+ try {
4837
+ if (options.includeQueued) {
4838
+ const unanswered = [];
4839
+ for (const item of state.items().filter((value) => value.state === "received").sort((a, b) => BigInt(a.cursor) < BigInt(b.cursor) ? -1 : BigInt(a.cursor) > BigInt(b.cursor) ? 1 : 0)) {
4840
+ const entry = { id: item.id, revision: item.revision };
4841
+ if (options.answerable) {
4842
+ let message;
4843
+ try {
4844
+ message = await client.message(accountId, item.id);
4845
+ } catch (error) {
4846
+ if (error instanceof NativeApiError && error.status === 404) {
4847
+ unanswered.push(entry);
4848
+ continue;
4849
+ }
4850
+ if (!(error instanceof NativeApiError)) throw error;
4851
+ }
4852
+ if (message && !await options.answerable(message)) {
4853
+ unanswered.push(entry);
4854
+ continue;
4855
+ }
4856
+ }
4857
+ queued.push(entry);
4858
+ }
4859
+ state.dropQueued(unanswered);
4860
+ }
4861
+ trim();
4862
+ if (state.cursor === "0") await resume();
4863
+ for (let index = 0; index < 100; index++) {
4864
+ let page;
4865
+ try {
4866
+ page = await client.events(accountId, state.cursor, 200);
4867
+ } catch (error) {
4868
+ if (!isExpiredCursor(error)) throw error;
4869
+ await resume();
4870
+ continue;
4871
+ }
4872
+ if (!page.items.length) {
4873
+ state.commit();
4874
+ return;
4875
+ }
4876
+ const before = state.cursor;
4877
+ for (const event of page.items) {
4878
+ const message = await acceptNativeEvent(client, accountId, state, event, options);
4879
+ const item = message && state.get(message.id);
4880
+ if (item?.cursor === event.cursor) queued.push({ id: item.id, revision: item.revision });
4881
+ }
4882
+ if (state.cursor === before) throw Error("Native recovery event cursor did not advance");
4883
+ trim();
4884
+ state.commit();
4885
+ await client.ack(accountId, "openclaw", state.cursor);
4886
+ if (page.items.length < 200) return;
4887
+ }
4888
+ throw Error("Native recovery backlog remains; no model input was dispatched");
4889
+ } finally {
4890
+ trim();
4570
4891
  }
4571
- throw Error("Native recovery backlog remains; no model input was dispatched");
4572
4892
  }
4573
4893
  function startNativeReadPump(task, failed, intervalMs = 5e3) {
4574
4894
  let active3 = false, stopped = false;
@@ -4595,8 +4915,26 @@ async function startNativeMonitor(opts) {
4595
4915
  if (typeof status.serverId !== "string") throw new Error("Native daemon identity is missing");
4596
4916
  const state = new NativeConsumerState(native.consumerStateDir, status.serverId, native.accountId);
4597
4917
  const core = getWeChatRuntime();
4918
+ const warn = (line) => {
4919
+ if (opts.log?.warn) opts.log.warn(line);
4920
+ else opts.log?.error?.(line);
4921
+ };
4922
+ if (state.heldOnOpen.length) warn(`${state.heldOnOpen.length} WeChat message(s) were not retried after restart: their model dispatch or reply could not be confirmed`);
4923
+ const reportSkipped = () => {
4924
+ const { old, limit, full } = state.skipped;
4925
+ state.skipped = { old: 0, limit: 0, full: 0 };
4926
+ if (old) opts.log?.info?.(`Skipped ${old} WeChat message(s) that arrived more than 24 hours ago`);
4927
+ if (limit) opts.log?.info?.(`Skipped ${limit} older missed WeChat message(s): catching up answers at most the newest ${NATIVE_CATCH_UP_LIMIT}`);
4928
+ if (full) warn(`${full} WeChat message(s) were not queued because the input queue is full`);
4929
+ };
4598
4930
  let backoff = 250;
4599
4931
  let readTask;
4932
+ const readFailures = /* @__PURE__ */ new Map();
4933
+ const answerable = (message) => {
4934
+ const cfg = core.config.current();
4935
+ return nativeMayAnswer(message, { account: resolveWeChatAccount(cfg, opts.account.accountId) ?? opts.account, cfg, core });
4936
+ };
4937
+ let startup = true;
4600
4938
  const flushRead = () => {
4601
4939
  if (native.readPolicy === "never") return Promise.resolve();
4602
4940
  return readTask ??= projectNativeRead(host2.client, native.accountId, state).finally(() => {
@@ -4608,22 +4946,45 @@ async function startNativeMonitor(opts) {
4608
4946
  const account = resolveWeChatAccount(cfg, opts.account.accountId) ?? opts.account;
4609
4947
  if (account.backend !== "native" || JSON.stringify(account.native) !== JSON.stringify(native)) throw new Error("Native service configuration changed; restart required before processing");
4610
4948
  for (const item of state.items().filter((value) => value.state === "received")) {
4949
+ if (state.get(item.id)?.revision !== item.revision || state.get(item.id)?.state !== "received") continue;
4950
+ let message;
4951
+ try {
4952
+ message = await host2.client.message(native.accountId, item.id);
4953
+ } catch (error) {
4954
+ if (!(error instanceof NativeApiError) && (error instanceof TypeError || error?.name === "TimeoutError" || error?.name === "AbortError")) throw error;
4955
+ const failures = (readFailures.get(item.id) ?? 0) + 1;
4956
+ readFailures.set(item.id, failures);
4957
+ if (error instanceof NativeApiError && error.status !== 404 && error.retryable && failures < 3) continue;
4958
+ readFailures.delete(item.id);
4959
+ state.finish(item.id, item.revision);
4960
+ if (!(error instanceof NativeApiError && error.status === 404)) warn(`WeChat message ${item.id} could not be read from the daemon and was not answered`);
4961
+ continue;
4962
+ }
4963
+ readFailures.delete(item.id);
4964
+ if (state.get(item.id)?.revision !== item.revision) continue;
4965
+ if (message.accountId !== native.accountId || message.threadId !== item.threadId || (message.serverId ?? null) !== item.serverId) {
4966
+ state.finish(item.id, item.revision);
4967
+ warn(`WeChat message ${item.id} changed before it was handled and was not answered`);
4968
+ continue;
4969
+ }
4970
+ if (message.createdAt && Date.parse(message.createdAt) < Date.now() - NATIVE_CATCH_UP_WINDOW_MS) {
4971
+ if (state.finish(item.id, item.revision)) state.skipped.old++;
4972
+ continue;
4973
+ }
4611
4974
  const outcome = await dispatchNativeMessage({
4612
4975
  client: host2.client,
4613
4976
  state,
4614
4977
  account,
4615
- message: item.message,
4978
+ message,
4616
4979
  cfg,
4617
4980
  core,
4981
+ revision: item.revision,
4618
4982
  signal: opts.abortSignal,
4619
4983
  onDelivered: () => opts.setStatus({ accountId: account.accountId, lastOutboundAt: Date.now() })
4620
4984
  });
4621
- if (outcome === "needs_review") {
4622
- const line = `WeChat message ${item.message.id} was not retried: its model dispatch or reply could not be confirmed`;
4623
- if (opts.log?.warn) opts.log.warn(line);
4624
- else opts.log?.error?.(line);
4625
- }
4985
+ if (outcome === "needs_review") warn(`WeChat message ${item.id} was not retried: its model dispatch or reply could not be confirmed`);
4626
4986
  }
4987
+ reportSkipped();
4627
4988
  try {
4628
4989
  await flushRead();
4629
4990
  } catch {
@@ -4649,7 +5010,7 @@ async function startNativeMonitor(opts) {
4649
5010
  do {
4650
5011
  processAgain = false;
4651
5012
  await process2();
4652
- } while (processAgain && !opts.abortSignal.aborted);
5013
+ } while (processAgain && intakeReady && !opts.abortSignal.aborted);
4653
5014
  })().catch(() => opts.log?.error?.("Native input processing was interrupted; durable custody was retained")).finally(() => {
4654
5015
  processing = void 0;
4655
5016
  });
@@ -4665,14 +5026,25 @@ async function startNativeMonitor(opts) {
4665
5026
  try {
4666
5027
  while (!opts.abortSignal.aborted) {
4667
5028
  try {
4668
- if (state.cursor !== "0") await host2.client.ack(native.accountId, "openclaw", state.cursor);
5029
+ if (state.cursor !== "0") {
5030
+ state.commit();
5031
+ await host2.client.ack(native.accountId, "openclaw", state.cursor);
5032
+ }
4669
5033
  intakeReady = false;
4670
- await synchronizeNativeEvents(host2.client, native.accountId, state);
5034
+ await synchronizeNativeEvents(host2.client, native.accountId, state, {
5035
+ answerable,
5036
+ includeQueued: startup,
5037
+ onResume: (from, to) => warn(`WeChat event position ${from === "0" ? "was new" : `${from} had expired`}; resumed at ${to}, the start of the last 24 hours`)
5038
+ });
5039
+ startup = false;
5040
+ reportSkipped();
4671
5041
  intakeReady = true;
4672
5042
  scheduleProcess();
4673
5043
  for await (const event of host2.client.watch(native.accountId, state.cursor, opts.abortSignal)) {
4674
- const message = await acceptNativeEvent(host2.client, native.accountId, state, event);
5044
+ const message = await acceptNativeEvent(host2.client, native.accountId, state, event, { answerable });
5045
+ reportSkipped();
4675
5046
  if (message?.direction === "incoming" && event.data.origin === "live" && !nativeRecallInfo(message)) opts.setStatus({ accountId: opts.account.accountId, lastInboundAt: Date.now() });
5047
+ state.commit();
4676
5048
  await host2.client.ack(native.accountId, "openclaw", state.cursor);
4677
5049
  scheduleProcess();
4678
5050
  backoff = 250;
@@ -4680,10 +5052,6 @@ async function startNativeMonitor(opts) {
4680
5052
  if (!opts.abortSignal.aborted) throw new Error("Native event stream closed");
4681
5053
  } catch (error) {
4682
5054
  if (opts.abortSignal.aborted) break;
4683
- if (error instanceof NativeApiError && error.code === "event_cursor_expired") {
4684
- opts.setStatus({ accountId: opts.account.accountId, connected: false, running: false, lastError: "event_cursor_expired" });
4685
- throw new Error("Native journal cursor expired; explicit snapshot/replay is required before resuming");
4686
- }
4687
5055
  opts.setStatus({ accountId: opts.account.accountId, connected: false, running: true });
4688
5056
  opts.log?.error?.("Native event stream interrupted; retained cursor/custody will resume without replaying sends");
4689
5057
  await new Promise((resolve) => {
@@ -6113,12 +6481,75 @@ function registerNativeStickerTools(api) {
6113
6481
 
6114
6482
  // src/native-contact-tool.ts
6115
6483
  var names4 = ["wechat_contacts", "wechat_contact_request"];
6484
+ var PER_PERSON_DM_SCOPES = /* @__PURE__ */ new Set(["per-peer", "per-channel-peer", "per-account-channel-peer"]);
6485
+ function isOwnerChatSession(entry, context, owner) {
6486
+ const sender = context.requesterSenderId;
6487
+ const route = entry?.delivery?.kind === "external" ? entry.delivery.context : void 0;
6488
+ if (!entry || !sender || entry.sessionId !== context.sessionId || entry.chatType !== "direct" || entry.spawnedBy !== void 0 || !route?.channel || route.threadId !== void 0 || route.channel === "agent-wechat" && (route.accountId ?? "default") !== owner.accountId || ![sender, `${route.channel}:${sender}`, ...route.channel === "agent-wechat" ? [`wechat:${sender}`] : []].includes(
6489
+ route.to ?? ""
6490
+ ))
6491
+ return false;
6492
+ try {
6493
+ const resolved = owner.routing?.resolveAgentRoute({
6494
+ cfg: owner.cfg,
6495
+ channel: route.channel,
6496
+ accountId: route.accountId,
6497
+ peer: { kind: "direct", id: sender }
6498
+ });
6499
+ return !!resolved && resolved.agentId === context.agentId && resolved.sessionKey === context.sessionKey && PER_PERSON_DM_SCOPES.has(resolved.dmScope ?? "");
6500
+ } catch {
6501
+ return false;
6502
+ }
6503
+ }
6116
6504
  function createNativeContactTools(context, dependencies = {}) {
6117
- const privateOwner = () => context.senderIsOwner === true && context.memoryAudience?.kind === "owner-private" && typeof context.assertMemoryAudienceCurrent === "function" && typeof context.assertInvocationCurrent === "function";
6118
- if (!privateOwner()) return [];
6119
6505
  const currentConfig = () => context.getRuntimeConfig?.() ?? context.runtimeConfig ?? context.config;
6506
+ const ownerAuthority = () => context.senderIsOwner === true && typeof context.assertInvocationCurrent === "function";
6507
+ const audienceOwner = () => context.memoryAudience?.kind === "owner-private" && typeof context.assertMemoryAudienceCurrent === "function";
6508
+ const noAudience = () => context.memoryAudience === void 0 && context.assertMemoryAudienceCurrent === void 0 && !!context.agentId && !!context.sessionKey && !!context.sessionId && !!context.requesterSenderId;
6120
6509
  const selected = resolveWeChatAccount(currentConfig());
6121
- if (!selected?.enabled || !selected.native || context.agentAccountId && context.agentAccountId !== selected.accountId || context.deliveryContext?.channel === "agent-wechat" && context.deliveryContext.accountId && context.deliveryContext.accountId !== selected.accountId)
6510
+ if (!selected?.enabled || !selected.native) return [];
6511
+ const sessionQuery = () => {
6512
+ const agentId = context.agentId;
6513
+ const cfg = currentConfig();
6514
+ return {
6515
+ agentId,
6516
+ storePath: dependencies.sessions.resolveStorePath(cfg?.session?.store, { agentId }),
6517
+ sessionKey: context.sessionKey,
6518
+ readConsistency: "latest"
6519
+ };
6520
+ };
6521
+ const ownerChat = (entry) => isOwnerChatSession(entry, context, {
6522
+ cfg: currentConfig(),
6523
+ accountId: selected.accountId,
6524
+ routing: dependencies.routing
6525
+ });
6526
+ const readOwnerChatNow = () => {
6527
+ try {
6528
+ return ownerChat(dependencies.sessions?.getSessionEntry?.(sessionQuery()));
6529
+ } catch {
6530
+ return false;
6531
+ }
6532
+ };
6533
+ const viaAudience = audienceOwner();
6534
+ if (!ownerAuthority() || !(viaAudience || noAudience() && readOwnerChatNow())) return [];
6535
+ const privateOwner = () => ownerAuthority() && (viaAudience ? audienceOwner() : noAudience());
6536
+ const ownerSessionCurrent = async (afterChange) => {
6537
+ if (viaAudience) return;
6538
+ const sessions = dependencies.sessions;
6539
+ let entry;
6540
+ try {
6541
+ entry = sessions?.getSessionEntryAsync ? await sessions.getSessionEntryAsync(sessionQuery()) : sessions?.getSessionEntry?.(sessionQuery());
6542
+ } catch {
6543
+ throw Error(
6544
+ afterChange ? "Could not reread the OpenClaw session before returning; a change may already have been made. Check it with status and the same idempotency key." : "Could not read the OpenClaw session to confirm the private owner chat"
6545
+ );
6546
+ }
6547
+ if (!ownerChat(entry))
6548
+ throw Error(
6549
+ afterChange ? "A private OpenClaw owner session is required to return this result; a change may already have been made. Check it with status and the same idempotency key." : "A private OpenClaw owner session is required"
6550
+ );
6551
+ };
6552
+ if (context.agentAccountId && context.agentAccountId !== selected.accountId || context.deliveryContext?.channel === "agent-wechat" && context.deliveryContext.accountId && context.deliveryContext.accountId !== selected.accountId)
6122
6553
  return [];
6123
6554
  const accountId = selected.native.accountId, configuration = nativeConfigurationKey(selected.native);
6124
6555
  const text4 = (description, maxLength = 8192) => ({
@@ -6226,15 +6657,19 @@ function createNativeContactTools(context, dependencies = {}) {
6226
6657
  signal?.throwIfAborted();
6227
6658
  if (!privateOwner()) throw Error("A private OpenClaw owner session is required");
6228
6659
  context.assertInvocationCurrent();
6229
- context.assertMemoryAudienceCurrent();
6660
+ context.assertMemoryAudienceCurrent?.();
6230
6661
  const current = resolveWeChatAccount(currentConfig());
6231
6662
  if (!current?.enabled || !current.native || current.accountId !== selected.accountId || current.native.accountId !== accountId || nativeConfigurationKey(current.native) !== configuration)
6232
6663
  throw Error("WeChat account configuration changed; start a new turn");
6233
6664
  return current.native;
6234
6665
  };
6666
+ guard2();
6667
+ await ownerSessionCurrent(false);
6235
6668
  const native = guard2();
6236
6669
  const { client } = await (dependencies.host ?? ensureNativeHost)(native);
6237
6670
  guard2();
6671
+ await ownerSessionCurrent(false);
6672
+ guard2();
6238
6673
  const id2 = args.id, key2 = args.idempotencyKey;
6239
6674
  let result;
6240
6675
  if (!index)
@@ -6317,6 +6752,8 @@ function createNativeContactTools(context, dependencies = {}) {
6317
6752
  }
6318
6753
  }
6319
6754
  guard2();
6755
+ await ownerSessionCurrent((required[action] ?? []).includes("idempotencyKey"));
6756
+ guard2();
6320
6757
  const details = { accountId, result };
6321
6758
  return { content: [{ type: "text", text: JSON.stringify(details) }], details };
6322
6759
  }
@@ -6324,7 +6761,13 @@ function createNativeContactTools(context, dependencies = {}) {
6324
6761
  }
6325
6762
  function registerNativeContactTools(api) {
6326
6763
  api.registerTool(
6327
- { contextVersion: 2, create: (context) => createNativeContactTools(context) },
6764
+ {
6765
+ contextVersion: 2,
6766
+ create: (context) => createNativeContactTools(context, {
6767
+ sessions: api.runtime?.agent?.session,
6768
+ routing: api.runtime?.channel?.routing
6769
+ })
6770
+ },
6328
6771
  { names: names4, optional: true }
6329
6772
  );
6330
6773
  }