@agent-wechat/agent-wechat 2.7.0 → 2.8.0

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