@agent-wechat/agent-wechat 1.0.0-beta.9 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -114,13 +114,26 @@ import { delimiter, dirname, isAbsolute, join, toNamespacedPath } from "node:pat
114
114
  import { createConnection } from "node:net";
115
115
 
116
116
  // ../shared/dist/native.generated.js
117
- var NATIVE_MAX_SOURCE_BYTES = 26214383;
117
+ var NATIVE_MAX_SOURCE_BYTES = 536870912;
118
+ var NATIVE_MAX_ORDINARY_SOURCE_BYTES = 26214383;
119
+ var NATIVE_MAX_VIDEO_SOURCE_BYTES = 52428800;
118
120
 
119
121
  // ../shared/dist/native-client.js
120
122
  function isNativeTombstone(value) {
121
123
  const item = value;
122
124
  return item?.deleted === true && typeof item.id === "string" && typeof item.version === "string";
123
125
  }
126
+ function validateNativeRecallMetadata(value) {
127
+ if (!value || typeof value !== "object" || Array.isArray(value))
128
+ throw new Error("Invalid native recall metadata");
129
+ const recall = value;
130
+ if (recall.replacementText != null && (typeof recall.replacementText !== "string" || !recall.replacementText || recall.replacementText.length > 16384 || new TextEncoder().encode(recall.replacementText).length > 16384 || /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\ufffe\uffff]/.test(recall.replacementText)))
131
+ throw new Error("Invalid native recall metadata");
132
+ }
133
+ function validateMessageRecall(message) {
134
+ if (message.recall != null)
135
+ validateNativeRecallMetadata(message.recall);
136
+ }
124
137
  function listQuery(input) {
125
138
  const options = typeof input === "string" ? { cursor: input } : input;
126
139
  if (!options)
@@ -165,10 +178,12 @@ var decimal = (value) => {
165
178
  return value;
166
179
  };
167
180
  var NativeWeChatClient = class {
181
+ mediaBatchSupported = true;
168
182
  baseUrl;
169
183
  token;
170
184
  fetchImpl;
171
185
  timeoutMs;
186
+ mediaTimeoutMs;
172
187
  streamIdleTimeoutMs;
173
188
  constructor(options) {
174
189
  this.baseUrl = validateNativeBaseUrl(options.baseUrl);
@@ -178,18 +193,21 @@ var NativeWeChatClient = class {
178
193
  if (typeof options.token !== "string" || !options.token || /[\r\n]/.test(options.token))
179
194
  throw new Error("Native API bearer token is required");
180
195
  this.token = options.token;
181
- this.fetchImpl = options.fetch ?? fetch;
196
+ this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
182
197
  this.timeoutMs = options.timeoutMs ?? 3e4;
198
+ this.mediaTimeoutMs = options.mediaTimeoutMs ?? 60 * 6e4;
199
+ if (!Number.isInteger(this.mediaTimeoutMs) || this.mediaTimeoutMs < 1 || this.mediaTimeoutMs > 60 * 6e4)
200
+ throw new Error("Invalid native media timeout");
183
201
  this.streamIdleTimeoutMs = options.streamIdleTimeoutMs ?? 45e3;
184
202
  if (!Number.isInteger(this.streamIdleTimeoutMs) || this.streamIdleTimeoutMs < 1 || this.streamIdleTimeoutMs > 3e5)
185
203
  throw new Error("Invalid native stream idle timeout");
186
204
  }
187
- async response(path, init = {}, stream = false) {
205
+ async response(path, init = {}, stream = false, timeoutMs = this.timeoutMs) {
188
206
  const headers = new Headers(init.headers);
189
207
  headers.set("Authorization", `Bearer ${this.token}`);
190
208
  if (init.body != null && !(init.body instanceof FormData))
191
209
  headers.set("Content-Type", "application/json");
192
- const timeout = stream ? void 0 : AbortSignal.timeout(this.timeoutMs);
210
+ const timeout = stream ? void 0 : AbortSignal.timeout(timeoutMs);
193
211
  const signal = init.signal && timeout ? AbortSignal.any([init.signal, timeout]) : init.signal ?? timeout;
194
212
  const response = await this.fetchImpl(new URL(path, this.baseUrl), { ...init, headers, redirect: "error", signal });
195
213
  if (!response.ok) {
@@ -262,9 +280,22 @@ var NativeWeChatClient = class {
262
280
  throw new Error("Account ID or alias is required");
263
281
  return this.request("v1/accounts", { method: "POST", body: JSON.stringify(body) });
264
282
  }
283
+ removeAccount(accountId, confirmAccountId) {
284
+ if (accountId !== confirmAccountId)
285
+ throw new Error("Account confirmation does not match");
286
+ return this.request(`v1/accounts/${id(accountId)}`, { method: "DELETE", body: JSON.stringify({ confirmAccountId }) });
287
+ }
265
288
  updateAccount(accountId, options) {
266
289
  return this.request(`v1/accounts/${id(accountId)}`, { method: "PATCH", body: JSON.stringify(options) });
267
290
  }
291
+ accountSettings(accountId, signal) {
292
+ return this.request(`v1/accounts/${id(accountId)}/settings`, { signal });
293
+ }
294
+ updateAccountSettings(accountId, settings, signal) {
295
+ if (!Number.isSafeInteger(settings.autoDownloadMaxBytes) || settings.autoDownloadMaxBytes < 0 || settings.autoDownloadMaxBytes > NATIVE_MAX_SOURCE_BYTES)
296
+ throw new Error("Invalid automatic download limit");
297
+ return this.request(`v1/accounts/${id(accountId)}/settings`, { method: "PATCH", body: JSON.stringify(settings), signal });
298
+ }
268
299
  capabilities(accountId) {
269
300
  return this.request(`v1/accounts/${id(accountId)}/capabilities`);
270
301
  }
@@ -338,17 +369,62 @@ var NativeWeChatClient = class {
338
369
  groups(accountId, options) {
339
370
  return this.request(`v1/accounts/${id(accountId)}/groups${listQuery(options)}`);
340
371
  }
341
- thread(accountId, threadId2) {
342
- return this.request(`v1/accounts/${id(accountId)}/threads/${id(threadId2)}`);
372
+ thread(accountId, threadId2, signal) {
373
+ return this.request(`v1/accounts/${id(accountId)}/threads/${id(threadId2)}`, { signal });
343
374
  }
344
375
  contact(accountId, username) {
345
376
  return this.request(`v1/accounts/${id(accountId)}/contacts/${id(username)}`);
346
377
  }
347
- group(accountId, roomId) {
348
- return this.request(`v1/accounts/${id(accountId)}/groups/${id(roomId)}`);
378
+ group(accountId, roomId, signal) {
379
+ return this.request(`v1/accounts/${id(accountId)}/groups/${id(roomId)}`, { signal });
380
+ }
381
+ groupMembers(accountId, roomId, options, signal) {
382
+ return this.request(`v1/accounts/${id(accountId)}/groups/${id(roomId)}/members${listQuery(options)}`, { signal });
383
+ }
384
+ groupMember(accountId, roomId, username, signal) {
385
+ return this.request(`v1/accounts/${id(accountId)}/groups/${id(roomId)}/members/${id(username)}`, { signal });
386
+ }
387
+ async groupMutation(accountId, path, method, body, key, action, target, signal) {
388
+ if (typeof key !== "string" || !key || key.length > 200 || /[\u0000-\u001f\u007f]/.test(key))
389
+ throw new Error("A stable group idempotency key is required");
390
+ const operation = await this.request(`v1/accounts/${id(accountId)}/${path}`, { method, body: JSON.stringify(body), headers: { "Idempotency-Key": key }, signal });
391
+ const result = operation?.result;
392
+ if (!operation || operation.accountId !== accountId || operation.kind !== "group_mutation" || typeof operation.id !== "string" || !operation.id || !result || result.action !== action || result.targetId !== target)
393
+ throw new Error("Native group operation identity is invalid");
394
+ return operation;
395
+ }
396
+ /** A repeated key returns the same operation. Uncertain mutations must be inspected, never repeated with a new key. */
397
+ createGroup(accountId, input, key, signal) {
398
+ return this.groupMutation(accountId, "groups", "POST", input, key, "create", null, signal);
399
+ }
400
+ renameGroup(accountId, groupId, name3, key, signal) {
401
+ return this.groupMutation(accountId, `groups/${id(groupId)}`, "PATCH", { name: name3 }, key, "rename", groupId, signal);
402
+ }
403
+ leaveGroup(accountId, groupId, key, signal) {
404
+ return this.groupMutation(accountId, `groups/${id(groupId)}/leave`, "POST", {}, key, "leave", groupId, signal);
405
+ }
406
+ addGroupMembers(accountId, groupId, members, key, signal) {
407
+ return this.groupMutation(accountId, `groups/${id(groupId)}/members`, "POST", { members }, key, "add_members", groupId, signal);
349
408
  }
350
- groupMembers(accountId, roomId, options) {
351
- return this.request(`v1/accounts/${id(accountId)}/groups/${id(roomId)}/members${listQuery(options)}`);
409
+ removeGroupMembers(accountId, groupId, members, key, signal) {
410
+ return this.groupMutation(accountId, `groups/${id(groupId)}/members`, "DELETE", { members }, key, "remove_members", groupId, signal);
411
+ }
412
+ setMyGroupName(accountId, groupId, displayName, key, signal) {
413
+ return this.groupMutation(accountId, `groups/${id(groupId)}/my-name`, "PUT", { displayName }, key, "my_name", groupId, signal);
414
+ }
415
+ clearGroupAnnouncement(accountId, groupId, key, signal) {
416
+ return this.groupMutation(accountId, `groups/${id(groupId)}/announcement`, "DELETE", {}, key, "clear_announcement", groupId, signal);
417
+ }
418
+ setThreadMuted(accountId, threadId2, muted, key, signal) {
419
+ return this.groupMutation(accountId, `threads/${id(threadId2)}/notifications`, "PUT", { muted }, key, "mute", threadId2, signal);
420
+ }
421
+ setThreadPinned(accountId, threadId2, pinned, key, signal) {
422
+ if (typeof pinned !== "boolean")
423
+ throw new Error("Thread pinned state must be a boolean");
424
+ return this.groupMutation(accountId, `threads/${id(threadId2)}/pin`, "PUT", { pinned }, key, "pin", threadId2, signal);
425
+ }
426
+ groupMutationByKey(accountId, key, signal) {
427
+ return this.request(`v1/accounts/${id(accountId)}/group-mutations/by-idempotency-key?${new URLSearchParams({ key })}`, { signal });
352
428
  }
353
429
  refreshAvatar(accountId, username) {
354
430
  return this.request(`v1/accounts/${id(accountId)}/avatars/${id(username)}/refresh`, { method: "POST", body: "{}" });
@@ -377,13 +453,14 @@ var NativeWeChatClient = class {
377
453
  syncGroups(accountId) {
378
454
  return this.request(`v1/accounts/${id(accountId)}/group-sync`, { method: "POST", body: "{}" });
379
455
  }
380
- async messages(accountId, threadId2, options) {
381
- const result = await this.request(`v1/accounts/${id(accountId)}/threads/${id(threadId2)}/messages${listQuery(options)}`);
456
+ async messages(accountId, threadId2, options, signal) {
457
+ const result = await this.request(`v1/accounts/${id(accountId)}/threads/${id(threadId2)}/messages${listQuery(options)}`, { signal });
382
458
  for (const msg of result.items) {
383
459
  if (isNativeTombstone(msg))
384
460
  continue;
385
461
  if (typeof msg.id !== "string" || msg.accountId !== accountId || msg.threadId !== threadId2 || msg.serverId != null && (typeof msg.serverId !== "string" || !/^\d+$/.test(msg.serverId)))
386
462
  throw new Error("Invalid native message identity");
463
+ validateMessageRecall(msg);
387
464
  }
388
465
  return result;
389
466
  }
@@ -391,15 +468,9 @@ var NativeWeChatClient = class {
391
468
  const message = await this.request(`v1/accounts/${id(accountId)}/messages/${id(messageId)}`);
392
469
  if (message.id !== messageId || message.accountId !== accountId || message.serverId != null && (typeof message.serverId !== "string" || !/^\d+$/.test(message.serverId)))
393
470
  throw new Error("Invalid native message identity");
471
+ validateMessageRecall(message);
394
472
  return message;
395
473
  }
396
- /** Resolve only the stored original in this message's own conversation. */
397
- async quotedMessage(accountId, messageId) {
398
- const quote = await this.request(`v1/accounts/${id(accountId)}/messages/${id(messageId)}/quote`);
399
- if (quote.accountId !== accountId || quote.messageId !== messageId || typeof quote.threadId !== "string" || !["resolved", "embedded", "missing", "invalid", "unsupported", "ambiguous"].includes(quote.state) || (quote.state === "resolved" ? !quote.message || quote.message.accountId !== accountId || quote.message.threadId !== quote.threadId || quote.message.id === messageId : quote.message != null))
400
- throw new Error("Invalid native quote identity");
401
- return quote;
402
- }
403
474
  /** Account-wide local search, with the daemon's query-bound opaque cursor. */
404
475
  async searchMessages(accountId, options) {
405
476
  const result = await this.request(`v1/accounts/${id(accountId)}/messages${listQuery(options)}`);
@@ -408,13 +479,51 @@ var NativeWeChatClient = class {
408
479
  continue;
409
480
  if (typeof message.id !== "string" || message.accountId !== accountId || typeof message.threadId !== "string" || !message.threadId || message.serverId != null && (typeof message.serverId !== "string" || !/^\d+$/.test(message.serverId)))
410
481
  throw new Error("Invalid native archive message identity");
482
+ validateMessageRecall(message);
411
483
  }
412
484
  return result;
413
485
  }
414
- sendText(accountId, threadId2, text3, idempotencyKey) {
486
+ /** Send text with optional group mentions, or quote a locally stored message in the same chat.
487
+ * Quoted-reply live acceptance and recipient rendering remain unverified; unsupported targets are rejected.
488
+ */
489
+ sendText(accountId, threadId2, text3, idempotencyKey, quoteOrOptions) {
415
490
  if (!idempotencyKey || /[\r\n]/.test(idempotencyKey))
416
491
  throw new Error("An idempotency key is required");
417
- return this.request(`v1/accounts/${id(accountId)}/sends`, { method: "POST", headers: { "Idempotency-Key": idempotencyKey }, body: JSON.stringify({ threadId: threadId2, text: text3 }) });
492
+ const options = quoteOrOptions && typeof quoteOrOptions === "object" && "mentions" in quoteOrOptions ? quoteOrOptions : void 0;
493
+ const quote = options === void 0 ? quoteOrOptions : void 0;
494
+ if (options !== void 0) {
495
+ const mentions = options.mentions;
496
+ const ids = mentions?.userIds ?? [];
497
+ if (Object.keys(options).some((key) => key !== "mentions") || !threadId2.endsWith("@chatroom") || !mentions || typeof mentions !== "object" || Array.isArray(mentions) || Object.keys(mentions).some((key) => key !== "userIds" && key !== "all" && key !== "positions") || mentions.userIds !== void 0 && !Array.isArray(mentions.userIds) || mentions.all !== void 0 && typeof mentions.all !== "boolean" || !Array.isArray(ids) || ids.length > 128 || new Set(ids).size !== ids.length || mentions.all === true === ids.length > 0 || ids.some((id2) => typeof id2 !== "string" || !/^[A-Za-z0-9_@.-]{1,256}$/.test(id2) || id2 === "notify@all"))
498
+ throw new Error("Invalid text mentions");
499
+ const positions = mentions.positions ?? [];
500
+ if (mentions.positions !== void 0 && !Array.isArray(mentions.positions) || positions.length > 256)
501
+ throw new Error("Invalid text mentions");
502
+ if (positions.length) {
503
+ const boundary = (offset) => !(offset > 0 && offset < text3.length && text3.charCodeAt(offset - 1) >= 55296 && text3.charCodeAt(offset - 1) <= 56319 && text3.charCodeAt(offset) >= 56320 && text3.charCodeAt(offset) <= 57343);
504
+ const covered = /* @__PURE__ */ new Set();
505
+ const recipients = mentions.all === true ? 1 : ids.length;
506
+ let previous = 0;
507
+ if (!text3 || text3.includes("\0") || new TextEncoder().encode(text3).length > 65536)
508
+ throw new Error("Invalid text mentions");
509
+ for (const position of positions) {
510
+ if (!position || typeof position !== "object" || Array.isArray(position) || Object.keys(position).some((key) => !["start", "end", "index"].includes(key)) || !Number.isSafeInteger(position.start) || !Number.isSafeInteger(position.end) || !Number.isSafeInteger(position.index) || position.start < previous || position.start >= position.end || position.end > text3.length || position.index < 0 || position.index >= recipients || !boundary(position.start) || !boundary(position.end))
511
+ throw new Error("Invalid text mentions");
512
+ const span = text3.slice(position.start, position.end);
513
+ const label = span.slice(1, -1);
514
+ if (!span.startsWith("@") || !span.endsWith("\u2005") || !label.trim() || new TextEncoder().encode(label).length > 1024 || /[\u0000-\u001f\u007f-\u009f\u2005\ud800-\udfff]/u.test(label))
515
+ throw new Error("Invalid text mentions");
516
+ covered.add(position.index);
517
+ previous = position.end;
518
+ }
519
+ if (covered.size !== recipients)
520
+ throw new Error("Invalid text mentions");
521
+ }
522
+ }
523
+ if (quote !== void 0 && (!quote || typeof quote !== "object" || Array.isArray(quote) || Object.keys(quote).some((key) => key !== "messageId" && key !== "serverId") || typeof quote.messageId !== "string" || !quote.messageId || quote.messageId.length > 8192 || typeof quote.serverId !== "string" || !/^[1-9]\d{0,19}$/.test(quote.serverId) || BigInt(quote.serverId) > 18446744073709551615n))
524
+ throw new Error("Invalid quote message identity");
525
+ const input = options !== void 0 ? { kind: "text", threadId: threadId2, text: text3, mentions: options.mentions } : quote === void 0 ? { threadId: threadId2, text: text3 } : { kind: "text", threadId: threadId2, text: text3, quote };
526
+ return this.request(`v1/accounts/${id(accountId)}/sends`, { method: "POST", headers: { "Idempotency-Key": idempotencyKey }, body: JSON.stringify(input) });
418
527
  }
419
528
  send(accountId, sendId, signal) {
420
529
  return this.request(`v1/accounts/${id(accountId)}/sends/${id(sendId)}`, { signal });
@@ -432,20 +541,54 @@ var NativeWeChatClient = class {
432
541
  cancelSend(accountId, sendId) {
433
542
  return this.request(`v1/accounts/${id(accountId)}/sends/${id(sendId)}/cancel`, { method: "POST", body: "{}" });
434
543
  }
435
- async upload(accountId, bytes, name2, contentType = "application/octet-stream", signal) {
436
- if (!bytes.length || bytes.length > NATIVE_MAX_SOURCE_BYTES || !name2 || name2.length > 255 || /[\r\n/\\]/.test(name2))
544
+ /** A disk-backed Blob avoids holding the source in memory before staging. */
545
+ async upload(accountId, bytes, name3, contentType = "application/octet-stream", signal) {
546
+ const size = bytes instanceof Blob ? bytes.size : bytes.byteLength;
547
+ if (!size || size > NATIVE_MAX_SOURCE_BYTES || !name3 || name3.length > 255 || /[\r\n/\\]/.test(name3))
437
548
  throw new Error("Invalid bounded media upload");
549
+ const part = bytes instanceof Blob ? bytes.slice(0, bytes.size, contentType) : new Blob([bytes.buffer instanceof ArrayBuffer ? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength) : new Uint8Array(bytes)], { type: contentType });
438
550
  const form = new FormData();
439
- form.set("file", new Blob([new Uint8Array(bytes).buffer], { type: contentType }), name2);
440
- return this.request(`v1/accounts/${id(accountId)}/uploads`, { method: "POST", body: form, signal });
551
+ form.set("file", part, name3);
552
+ const response = await this.response(`v1/accounts/${id(accountId)}/uploads`, { method: "POST", body: form, signal }, false, this.mediaTimeoutMs);
553
+ return JSON.parse(new TextDecoder().decode(await this.readBounded(response)));
441
554
  }
442
555
  sendMedia(accountId, input, key) {
443
556
  if (!key || /[\r\n]/.test(key))
444
557
  throw new Error("An idempotency key is required");
445
558
  return this.request(`v1/accounts/${id(accountId)}/sends`, { method: "POST", headers: { "Idempotency-Key": key }, body: JSON.stringify(input) });
446
559
  }
447
- mediaAssets(accountId, messageId) {
448
- return this.request(`v1/accounts/${id(accountId)}/messages/${id(messageId)}/media`);
560
+ mediaAssets(accountId, messageId, signal) {
561
+ return this.request(`v1/accounts/${id(accountId)}/messages/${id(messageId)}/media`, { signal });
562
+ }
563
+ async mediaAssetsBatch(accountId, messageIds, signal) {
564
+ if (!messageIds.length || messageIds.length > 40 || messageIds.some((id2) => !id2 || id2.length > 8192) || new Set(messageIds).size !== messageIds.length)
565
+ throw new Error("Invalid media lookup batch");
566
+ if (this.mediaBatchSupported) {
567
+ try {
568
+ const batch = await this.request(`v1/accounts/${id(accountId)}/media/lookup`, { method: "POST", body: JSON.stringify({ messageIds }), signal });
569
+ const expected = new Set(messageIds);
570
+ if (!Array.isArray(batch.items) || batch.items.length !== expected.size)
571
+ throw new Error("Invalid media lookup response");
572
+ for (const item of batch.items) {
573
+ if (!expected.delete(item.messageId) || !Array.isArray(item.assets) || item.error !== null && typeof item.error !== "string" || item.assets.some((asset) => asset.accountId !== accountId || asset.messageId !== item.messageId))
574
+ throw new Error("Invalid media lookup identity");
575
+ }
576
+ return batch;
577
+ } catch (error) {
578
+ if (!(error instanceof NativeApiError) || ![404, 405].includes(error.status))
579
+ throw error;
580
+ this.mediaBatchSupported = false;
581
+ }
582
+ }
583
+ return { items: await Promise.all(messageIds.map(async (messageId) => {
584
+ try {
585
+ return { messageId, assets: (await this.mediaAssets(accountId, messageId, signal)).items, error: null };
586
+ } catch (error) {
587
+ if (!(error instanceof NativeApiError))
588
+ throw error;
589
+ return { messageId, assets: [], error: error.code };
590
+ }
591
+ })) };
449
592
  }
450
593
  transferMedia(accountId, input) {
451
594
  return this.request(`v1/accounts/${id(accountId)}/messages/${id(input.messageId)}/media-transfers`, { method: "POST", body: JSON.stringify(input) });
@@ -459,26 +602,94 @@ var NativeWeChatClient = class {
459
602
  cancelJob(accountId, jobId) {
460
603
  return this.request(`v1/accounts/${id(accountId)}/jobs/${id(jobId)}/cancel`, { method: "POST", body: "{}" });
461
604
  }
462
- retryJob(accountId, jobId) {
463
- return this.request(`v1/accounts/${id(accountId)}/jobs/${id(jobId)}/retry`, { method: "POST", body: "{}" });
605
+ retryJob(accountId, jobId, options = {}) {
606
+ if (!options || typeof options !== "object" || Array.isArray(options) || Object.keys(options).some((key) => key !== "reuseCompletedUpload"))
607
+ throw new Error("Invalid media retry options");
608
+ const reuse = options.reuseCompletedUpload;
609
+ if (reuse !== void 0 && typeof reuse !== "boolean")
610
+ throw new Error("Invalid media retry options");
611
+ return this.request(`v1/accounts/${id(accountId)}/jobs/${id(jobId)}/${reuse === true ? "retry-completed-upload" : "retry"}`, { method: "POST", body: JSON.stringify(reuse === void 0 ? {} : { reuseCompletedUpload: reuse }) });
464
612
  }
465
613
  repairMediaWriteback(accountId, limit = 25) {
466
614
  if (!Number.isInteger(limit) || limit < 1 || limit > 100)
467
615
  throw new Error("Invalid media writeback limit");
468
616
  return this.request(`v1/accounts/${id(accountId)}/media-writeback/repair`, { method: "POST", body: JSON.stringify({ limit }) });
469
617
  }
470
- async mediaContent(accountId, assetId, options = {}) {
618
+ /** Consume the bounded stream once, or cancel it; this never starts a CDN transfer. */
619
+ async mediaContentStream(accountId, assetId, options = {}) {
471
620
  const max = options.maxBytes ?? 128 * 1024 * 1024;
472
- if (!Number.isInteger(max) || max < 1 || max > 128 * 1024 * 1024 || options.range && !/^bytes=(?:\d+-\d*|-\d+)$/.test(options.range) || options.representation != null && !["original", "preview"].includes(options.representation))
621
+ if (!Number.isInteger(max) || max < 1 || max > Math.max(128 * 1024 * 1024, NATIVE_MAX_SOURCE_BYTES) || options.range && !/^bytes=(?:\d+-\d*|-\d+)$/.test(options.range) || options.representation != null && !["original", "preview"].includes(options.representation))
473
622
  throw new Error("Invalid bounded content request");
474
623
  const query = options.representation === "preview" ? "?representation=preview" : "";
475
- const response = await this.response(`v1/accounts/${id(accountId)}/media/${id(assetId)}/content${query}`, { signal: options.signal, headers: options.range ? { Range: options.range } : {} });
624
+ const cancellation = new AbortController();
625
+ const response = await this.response(`v1/accounts/${id(accountId)}/media/${id(assetId)}/content${query}`, { signal: options.signal ? AbortSignal.any([options.signal, cancellation.signal]) : cancellation.signal, headers: options.range ? { Range: options.range } : {} }, false, this.mediaTimeoutMs);
476
626
  const length = response.headers.get("content-length");
477
627
  if (length && (!/^\d+$/.test(length) || Number(length) > max)) {
478
628
  await response.body?.cancel();
479
629
  throw new Error("Native media response exceeds its bound");
480
630
  }
481
- return { bytes: await this.readBounded(response, max), contentType: response.headers.get("content-type") ?? "application/octet-stream", etag: response.headers.get("etag"), contentRange: response.headers.get("content-range"), sourceSha256: response.headers.get("x-source-sha256"), status: response.status };
631
+ if (!response.body && length && Number(length) > 0)
632
+ throw new Error("Native media response length mismatch");
633
+ let activeReader;
634
+ const iterate = async function* () {
635
+ cancellation.signal.throwIfAborted();
636
+ options.signal?.throwIfAborted();
637
+ const reader = response.body?.getReader();
638
+ if (!reader)
639
+ return;
640
+ activeReader = reader;
641
+ let size = 0;
642
+ try {
643
+ while (true) {
644
+ cancellation.signal.throwIfAborted();
645
+ options.signal?.throwIfAborted();
646
+ const { value, done } = await reader.read();
647
+ cancellation.signal.throwIfAborted();
648
+ options.signal?.throwIfAborted();
649
+ if (done)
650
+ break;
651
+ size += value.byteLength;
652
+ if (size > max)
653
+ throw new Error("Native media response exceeds its bound");
654
+ yield value;
655
+ }
656
+ if (length && size !== Number(length))
657
+ throw new Error("Native media response length mismatch");
658
+ } finally {
659
+ await reader.cancel().catch(() => {
660
+ });
661
+ reader.releaseLock();
662
+ activeReader = void 0;
663
+ }
664
+ };
665
+ let claimed = false;
666
+ const stream = { [Symbol.asyncIterator]() {
667
+ if (claimed)
668
+ throw new Error("Native media stream was already consumed");
669
+ claimed = true;
670
+ return iterate();
671
+ } };
672
+ return { stream, cancel: async () => {
673
+ cancellation.abort();
674
+ await (activeReader ? activeReader.cancel() : response.body?.cancel())?.catch(() => {
675
+ });
676
+ }, contentType: response.headers.get("content-type") ?? "application/octet-stream", etag: response.headers.get("etag"), contentRange: response.headers.get("content-range"), sourceSha256: response.headers.get("x-source-sha256"), status: response.status };
677
+ }
678
+ async mediaContent(accountId, assetId, options = {}) {
679
+ const { stream, cancel: _cancel, ...metadata } = await this.mediaContentStream(accountId, assetId, options);
680
+ const chunks = [];
681
+ let size = 0;
682
+ for await (const chunk of stream) {
683
+ chunks.push(chunk);
684
+ size += chunk.byteLength;
685
+ }
686
+ const bytes = new Uint8Array(size);
687
+ let offset = 0;
688
+ for (const chunk of chunks) {
689
+ bytes.set(chunk, offset);
690
+ offset += chunk.byteLength;
691
+ }
692
+ return { ...metadata, bytes };
482
693
  }
483
694
  markRead(accountId, threadId2, expectedVersion) {
484
695
  if (typeof expectedVersion !== "string" || !expectedVersion || expectedVersion.length > 128)
@@ -488,12 +699,17 @@ var NativeWeChatClient = class {
488
699
  events(accountId, after = "0", limit = 100) {
489
700
  if (!Number.isInteger(limit) || limit < 1 || limit > 200)
490
701
  throw new Error("Invalid event page limit");
491
- return this.request(`v1/accounts/${id(accountId)}/events?after=${decimal(after)}&limit=${limit}`);
702
+ return this.request(`v1/accounts/${id(accountId)}/events?after=${decimal(after)}&limit=${limit}`).then((page) => {
703
+ for (const event of page.items)
704
+ if (event.kind === "message.recalled")
705
+ validateNativeRecallMetadata(event.data);
706
+ return page;
707
+ });
492
708
  }
493
709
  ack(accountId, consumerId, cursor) {
494
710
  return this.request(`v1/accounts/${id(accountId)}/consumers/${id(consumerId)}/ack`, { method: "POST", body: JSON.stringify({ cursor: decimal(cursor) }) });
495
711
  }
496
- async *watch(accountId, after = "0", signal) {
712
+ async *watch(accountId, after = "0", signal, options = {}) {
497
713
  const connection = new AbortController();
498
714
  const streamSignal = signal ? AbortSignal.any([signal, connection.signal]) : connection.signal;
499
715
  const bounded = async (work, milliseconds, reason) => {
@@ -535,6 +751,7 @@ var NativeWeChatClient = class {
535
751
  const { value, done } = await bounded(() => activeReader.read(), this.streamIdleTimeoutMs, "Native SSE idle timeout");
536
752
  if (done)
537
753
  break;
754
+ options.onActivity?.();
538
755
  buffer += decoder.decode(value, { stream: true });
539
756
  if (buffer.length > 1024 * 1024)
540
757
  throw new Error("Native SSE frame exceeds its bound");
@@ -552,6 +769,8 @@ var NativeWeChatClient = class {
552
769
  const event = payload;
553
770
  if (!event || typeof event.kind !== "string" || !event.data || typeof event.data !== "object")
554
771
  throw new Error("Invalid native event");
772
+ if (event.kind === "message.recalled")
773
+ validateNativeRecallMetadata(event.data);
555
774
  event.cursor = decimal(event.cursor ?? eventCursor);
556
775
  yield event;
557
776
  }
@@ -598,7 +817,7 @@ function requireNativeIdentity(value) {
598
817
  }
599
818
  }
600
819
  function nativeChildEnvironment(token, environment = process.env) {
601
- return Object.fromEntries(["PATH", "HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "SystemRoot", "WINDIR", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "TMPDIR", "TMP", "TEMP", "LANG", "LC_ALL", "TZ", "SSL_CERT_FILE", "SSL_CERT_DIR"].filter((name2) => environment[name2] !== void 0 && environment[name2] !== token).map((name2) => [name2, environment[name2]]));
820
+ return Object.fromEntries(["PATH", "HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "SystemRoot", "WINDIR", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "TMPDIR", "TMP", "TEMP", "LANG", "LC_ALL", "TZ", "SSL_CERT_FILE", "SSL_CERT_DIR"].filter((name3) => environment[name3] !== void 0 && environment[name3] !== token).map((name3) => [name3, environment[name3]]));
602
821
  }
603
822
  function nativeHostTarget(platform = process.platform, arch = process.arch) {
604
823
  const cpu = arch === "arm64" ? "aarch64" : "x86_64";
@@ -913,8 +1132,8 @@ function normalizeWeChatCommandBody(raw, params) {
913
1132
  if (!prefix) {
914
1133
  return trimmed.slice(commandStart).trimStart();
915
1134
  }
916
- const hasHairSpace = rawPrefix.includes("\u2005") || trimmed[commandStart] === "\u2005";
917
- if (!hasHairSpace) {
1135
+ const hasMentionSeparator = rawPrefix.includes("\u2005") || trimmed[commandStart] === "\u2005";
1136
+ if (!hasMentionSeparator) {
918
1137
  return trimmed;
919
1138
  }
920
1139
  const mentionRegion = rawPrefix + (trimmed[commandStart] === "\u2005" ? "\u2005" : "");
@@ -1035,14 +1254,17 @@ function resolveWeChatIngress(params) {
1035
1254
  }
1036
1255
 
1037
1256
  // src/outbound-media.ts
1038
- import { createHash as createHash5 } from "node:crypto";
1039
- import { randomUUID as randomUUID2 } from "node:crypto";
1257
+ import { createHash as createHash6 } from "node:crypto";
1258
+ import { randomUUID as randomUUID3 } from "node:crypto";
1040
1259
 
1041
1260
  // src/native-media.ts
1042
1261
  import { createHash as createHash4, randomUUID } from "node:crypto";
1043
- import { open } from "node:fs/promises";
1044
- import { basename, extname } from "node:path";
1262
+ import { openAsBlob } from "node:fs";
1263
+ import { mkdtemp, open, rm } from "node:fs/promises";
1264
+ import { tmpdir } from "node:os";
1265
+ import { basename, extname, join as join2 } from "node:path";
1045
1266
  import { getImageMetadata, resizeToJpeg, IMAGE_REDUCE_QUALITY_STEPS } from "openclaw/plugin-sdk/media-runtime";
1267
+ import { saveMediaStream } from "openclaw/plugin-sdk/media-store";
1046
1268
 
1047
1269
  // src/attachment-store.ts
1048
1270
  import { createHash as createHash3 } from "node:crypto";
@@ -1062,6 +1284,12 @@ async function saveManagedAttachment(params) {
1062
1284
  }
1063
1285
  const buffer = Buffer.from(params.data, "base64");
1064
1286
  if (buffer.byteLength !== size) throw new Error("Attachment decoding length mismatch");
1287
+ return saveManagedAttachmentBytes({ ...params, bytes: buffer });
1288
+ }
1289
+ async function saveManagedAttachmentBytes(params) {
1290
+ const size = params.bytes.byteLength;
1291
+ if (size > params.maxBytes) throw new AttachmentTooLargeError(`Attachment exceeds configured ${params.maxBytes} byte limit`);
1292
+ const buffer = Buffer.from(params.bytes.buffer, params.bytes.byteOffset, size);
1065
1293
  const sha256 = createHash3("sha256").update(buffer).digest("hex");
1066
1294
  const saved = await params.saveMediaBuffer(
1067
1295
  buffer,
@@ -1072,31 +1300,59 @@ async function saveManagedAttachment(params) {
1072
1300
  );
1073
1301
  return { path: saved.path, size, sha256, filename: params.filename };
1074
1302
  }
1303
+ async function saveVerifiedManagedAttachmentStream(params) {
1304
+ if (!Number.isSafeInteger(params.expectedBytes) || params.expectedBytes < 1 || params.expectedBytes > params.maxBytes || !/^[a-f0-9]{64}$/.test(params.expectedSha256)) throw new Error("Native attachment integrity metadata is invalid");
1305
+ let size = 0, finished = false;
1306
+ const digest2 = createHash3("sha256");
1307
+ const stream = (async function* () {
1308
+ for await (const chunk of params.stream) {
1309
+ params.assertCurrent();
1310
+ size += chunk.byteLength;
1311
+ if (size > params.maxBytes || size > params.expectedBytes) throw new AttachmentTooLargeError("Native attachment stream exceeds its bound");
1312
+ digest2.update(chunk);
1313
+ yield chunk;
1314
+ }
1315
+ params.assertCurrent();
1316
+ if (size !== params.expectedBytes || digest2.digest("hex") !== params.expectedSha256) throw new Error("Native attachment integrity did not verify");
1317
+ finished = true;
1318
+ })();
1319
+ const saved = await params.saveMediaStream(
1320
+ stream,
1321
+ params.mime,
1322
+ "inbound",
1323
+ params.maxBytes,
1324
+ params.filename,
1325
+ void 0,
1326
+ { assertCommitAllowed: params.assertCurrent, durable: true }
1327
+ );
1328
+ if (!finished || saved.size != null && saved.size !== size) throw new Error("Native attachment stream was not fully saved");
1329
+ return { path: saved.path, size, sha256: params.expectedSha256, filename: params.filename };
1330
+ }
1075
1331
 
1076
1332
  // src/media-delivery.ts
1077
1333
  function appendReference(body, reference) {
1078
1334
  return body ? `${body}
1079
1335
  ${reference}` : reference;
1080
1336
  }
1081
- function safeDisplayName(name2) {
1082
- return name2.replace(/[\r\n\0]/g, " ").trim() || "attachment";
1337
+ function safeDisplayName(name3) {
1338
+ return name3.replace(/[\r\n\0]/g, " ").trim() || "attachment";
1083
1339
  }
1084
1340
  function renderAttachmentBody(originalBody, attachment, exposeNonVisualPath = true) {
1085
1341
  if (!attachment) return originalBody;
1086
- const name2 = safeDisplayName(attachment.filename);
1342
+ const name3 = safeDisplayName(attachment.filename);
1087
1343
  if (attachment.status !== "ready" || !attachment.path) {
1088
1344
  const label = attachment.kind === "file" ? "File" : attachment.kind === "image" ? "Image" : attachment.kind === "audio" ? "Voice message" : "Video";
1089
1345
  if (attachment.status === "pending") {
1090
- return appendReference(originalBody, `[${label} pending: ${name2}]`);
1346
+ return appendReference(originalBody, `[${label} pending: ${name3}]`);
1091
1347
  }
1092
1348
  if (attachment.status === "expired") {
1093
- return appendReference(originalBody, `[${label} expired: ${name2}; no cached copy available. Ask the sender to resend.]`);
1349
+ return appendReference(originalBody, `[${label} expired: ${name3}; no cached copy available. Ask the sender to resend.]`);
1094
1350
  }
1095
- return appendReference(originalBody, `[${label} unavailable: ${name2} (${attachment.status})]`);
1351
+ return appendReference(originalBody, `[${label} unavailable: ${name3} (${attachment.status})]`);
1096
1352
  }
1097
1353
  if (attachment.kind === "file") {
1098
- const prefix = originalBody.trim() === name2 ? "" : originalBody;
1099
- return appendReference(prefix, `[File: ${name2}]
1354
+ const prefix = originalBody.trim() === name3 ? "" : originalBody;
1355
+ return appendReference(prefix, `[File: ${name3}]
1100
1356
  [Local file: <${attachment.path}>]`);
1101
1357
  }
1102
1358
  if (exposeNonVisualPath) {
@@ -1115,6 +1371,24 @@ function renderAttachmentBody(originalBody, attachment, exposeNonVisualPath = tr
1115
1371
  return body;
1116
1372
  }
1117
1373
 
1374
+ // src/outbound-mentions.ts
1375
+ function parseWeChatTextMentions(value) {
1376
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw Error("Invalid WeChat mentions");
1377
+ const mentions = value;
1378
+ const ids = mentions.userIds;
1379
+ if (Object.keys(mentions).some((key) => key !== "userIds" && key !== "all") || mentions.all !== void 0 && mentions.all !== true || (mentions.all === true ? ids !== void 0 : !Array.isArray(ids) || !ids.length) || Array.isArray(ids) && (ids.length > 128 || new Set(ids).size !== ids.length || ids.some((id2) => typeof id2 !== "string" || !/^[A-Za-z0-9_@.-]{1,256}$/.test(id2) || id2 === "notify@all"))) throw Error("Invalid WeChat mentions");
1380
+ return mentions.all === true ? { all: true } : { userIds: [...ids] };
1381
+ }
1382
+ function validateWeChatMentionSend(mentions, input) {
1383
+ if (!mentions) return;
1384
+ parseWeChatTextMentions(mentions);
1385
+ if (!input.to.endsWith("@chatroom")) throw Error("WeChat mentions require a group conversation");
1386
+ if (typeof input.text !== "string" || !input.text.trim()) throw Error("WeChat mentions require a text message");
1387
+ if (input.mediaUrl || input.mediaUrls?.length || input.audioAsVoice || input.forceDocument || input.videoQuality != null || input.replyToId != null) {
1388
+ throw Error("WeChat mentions support group text only; do not combine with attachments, voice, document, video quality or quoted replies");
1389
+ }
1390
+ }
1391
+
1118
1392
  // src/native-send.ts
1119
1393
  async function nativeOutboundDelivery(client, accountId, threadId2, messageIds, source) {
1120
1394
  const receipts = [];
@@ -1147,32 +1421,91 @@ async function nativeOutboundDelivery(client, accountId, threadId2, messageIds,
1147
1421
  receiptState: "verified"
1148
1422
  } };
1149
1423
  }
1424
+ var NativeTextSendInspectionError = class extends Error {
1425
+ code = "native_text_send_inspection_required";
1426
+ retryable = false;
1427
+ accountId;
1428
+ threadId;
1429
+ idempotencyKey;
1430
+ state;
1431
+ sendId;
1432
+ constructor(accountId, threadId2, idempotencyKey, state, sendId) {
1433
+ super(`Native text send requires inspection (${state}); retain the original idempotency key and do not automatically resend`);
1434
+ this.name = "NativeTextSendInspectionError";
1435
+ this.accountId = accountId;
1436
+ this.threadId = threadId2;
1437
+ this.idempotencyKey = idempotencyKey;
1438
+ this.state = state;
1439
+ this.sendId = sendId;
1440
+ }
1441
+ };
1150
1442
  async function submitNativeText(client, accountId, threadId2, text3, key, options = {}) {
1151
- let intent = await client.sendText(accountId, threadId2, text3, key);
1443
+ const mentions = options.mentions === void 0 ? void 0 : parseWeChatTextMentions(options.mentions);
1444
+ validateWeChatMentionSend(mentions, { to: threadId2, text: text3, replyToId: options.quote?.messageId });
1445
+ const inspect = (value, sendId) => {
1446
+ const intent2 = value;
1447
+ if (!intent2 || typeof intent2 !== "object" || Array.isArray(intent2) || typeof intent2.id !== "string" || !intent2.id || intent2.accountId !== void 0 && intent2.accountId !== accountId || intent2.destination !== void 0 && intent2.destination !== threadId2 || intent2.kind !== void 0 || intent2.threadId !== void 0 || typeof intent2.state !== "string" || sendId !== void 0 && intent2.id !== sendId) throw new NativeTextSendInspectionError(accountId, threadId2, key, "receipt_identity_mismatch", sendId);
1448
+ return { ...intent2, accountId, destination: threadId2 };
1449
+ };
1450
+ let intent;
1451
+ try {
1452
+ intent = inspect(await client.sendText(accountId, threadId2, text3, key, options.quote ?? (mentions ? { mentions } : void 0)));
1453
+ } catch (error) {
1454
+ if (error instanceof NativeTextSendInspectionError || error instanceof NativeApiError && error.status < 500 && error.code !== "timeout") throw error;
1455
+ try {
1456
+ intent = inspect(await client.sendByKey(accountId, key));
1457
+ } catch (lookupError) {
1458
+ if (lookupError instanceof NativeTextSendInspectionError) throw lookupError;
1459
+ throw new NativeTextSendInspectionError(accountId, threadId2, key, "submission_unknown");
1460
+ }
1461
+ }
1152
1462
  const deadline = Date.now() + Math.max(1, Math.min(options.timeoutMs ?? 65e3, 65e3));
1153
- let delay = Math.max(1, Math.min(options.initialDelayMs ?? 250, 1e3));
1463
+ let delay2 = Math.max(1, Math.min(options.initialDelayMs ?? 250, 1e3));
1154
1464
  while (["queued", "submitting"].includes(intent.state) && Date.now() < deadline) {
1155
- await new Promise((resolve) => setTimeout(resolve, Math.min(delay, deadline - Date.now())));
1465
+ await new Promise((resolve) => setTimeout(resolve, Math.min(delay2, deadline - Date.now())));
1156
1466
  const remaining = deadline - Date.now();
1157
1467
  if (remaining <= 0) break;
1158
- intent = await client.send(accountId, intent.id, AbortSignal.timeout(remaining));
1159
- delay = Math.min(delay * 2, 1e3);
1468
+ try {
1469
+ intent = inspect(await client.send(accountId, intent.id, AbortSignal.timeout(remaining)), intent.id);
1470
+ } catch (error) {
1471
+ if (error instanceof NativeTextSendInspectionError) throw error;
1472
+ throw new NativeTextSendInspectionError(accountId, threadId2, key, "status_unavailable", intent.id);
1473
+ }
1474
+ delay2 = Math.min(delay2 * 2, 1e3);
1160
1475
  }
1161
- if (!["accepted", "sent", "server_accepted"].includes(intent.state)) throw new Error(`Native send ${intent.id} requires inspection (${intent.state}); do not automatically resend`);
1476
+ if (!["accepted", "sent", "server_accepted"].includes(intent.state)) throw new NativeTextSendInspectionError(accountId, threadId2, key, intent.state, intent.id);
1162
1477
  return intent;
1163
1478
  }
1164
1479
 
1165
1480
  // src/native-recall-state.ts
1166
1481
  function nativeRecallInfo(message) {
1482
+ if (message.recall) validateNativeRecallMetadata(message.recall);
1167
1483
  return message.recall;
1168
1484
  }
1169
1485
  function nativeRecallIdentity(threadId2, serverId) {
1170
1486
  return JSON.stringify([threadId2, serverId]);
1171
1487
  }
1172
1488
  function validateNativeRecall(value) {
1489
+ validateNativeRecallMetadata(value);
1173
1490
  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");
1174
1491
  }
1492
+ function mergeNativeRecall(prior, next) {
1493
+ validateNativeRecall(prior);
1494
+ validateNativeRecall(next);
1495
+ if (prior.threadId !== next.threadId || prior.serverId !== next.serverId) throw Error("Conflicting native recall identity; cursor retained");
1496
+ return {
1497
+ threadId: prior.threadId,
1498
+ serverId: prior.serverId,
1499
+ observedAt: prior.observedAt,
1500
+ ...prior.messageId ?? next.messageId ? { messageId: prior.messageId ?? next.messageId } : {},
1501
+ ...prior.recalledAt ?? next.recalledAt ? { recalledAt: prior.recalledAt ?? next.recalledAt } : {},
1502
+ ...(prior.replacementText ?? next.replacementText) != null ? { replacementText: prior.replacementText ?? next.replacementText } : {}
1503
+ };
1504
+ }
1175
1505
  function recalledNativeMessage(message, recall) {
1506
+ validateNativeRecall(recall);
1507
+ const previous = nativeRecallInfo(message);
1508
+ const replacementText = previous?.replacementText ?? recall.replacementText;
1176
1509
  return {
1177
1510
  ...message,
1178
1511
  type: 1e4,
@@ -1180,8 +1513,51 @@ function recalledNativeMessage(message, recall) {
1180
1513
  quote: void 0,
1181
1514
  link: void 0,
1182
1515
  media: [],
1516
+ senderId: message.senderId || null,
1517
+ direction: message.senderId ? message.direction : null,
1183
1518
  mentions: { state: "unknown", userIds: [], self: null, all: null, source: null },
1184
- recall: { observedAt: recall.observedAt, ...recall.recalledAt ? { recalledAt: recall.recalledAt } : {} }
1519
+ recall: {
1520
+ observedAt: previous?.observedAt ?? recall.observedAt,
1521
+ ...previous?.recalledAt ?? recall.recalledAt ? { recalledAt: previous?.recalledAt ?? recall.recalledAt } : {},
1522
+ ...replacementText != null ? { replacementText } : {}
1523
+ }
1524
+ };
1525
+ }
1526
+
1527
+ // src/native-quote.ts
1528
+ function sameEmbeddedQuote(stored, current) {
1529
+ if (stored.state === "unsupported" && current.state === "embedded")
1530
+ return ["serverId", "type", "appMessageType", "senderId", "direction"].every((field) => (stored[field] ?? null) === (current[field] ?? null));
1531
+ const compared = { ...current };
1532
+ for (const field of ["embeddedLink", "embeddedSticker"]) {
1533
+ if (!Object.hasOwn(stored, field)) delete compared[field];
1534
+ }
1535
+ return JSON.stringify(stored) === JSON.stringify(compared);
1536
+ }
1537
+ function renderEmbeddedQuote(message, permitted = true, imageBody) {
1538
+ const comment = (message.body ?? "").slice(0, 16384);
1539
+ const source = message.quote;
1540
+ const unavailable = (state2) => ({
1541
+ body: `${comment}${comment ? "\n\n" : ""}[Quoted message ${state2}]`,
1542
+ image: false,
1543
+ quote: { state: state2, type: source?.type, senderId: source?.senderId ?? void 0 }
1544
+ });
1545
+ if (!source) return unavailable("unavailable");
1546
+ if (!permitted) return unavailable("not permitted");
1547
+ const state = source.state ?? "missing";
1548
+ if (state === "recalled") return unavailable("recalled");
1549
+ if (!["embedded", "missing", "unsupported"].includes(state) || source.embeddedText != null && (typeof source.embeddedText !== "string" || source.embeddedText.length > 16384) || source.embeddedImage != null && typeof source.embeddedImage !== "boolean") return unavailable("invalid");
1550
+ const label = source.type === 1 || source.type === 49 && source.appMessageType === 1 ? "text" : source.type === 3 ? "image" : source.type === 34 ? "voice" : source.type === 43 ? "video" : source.type === 49 && source.appMessageType === 51 ? "Channels card" : source.type === 49 && source.appMessageType === 74 ? "file upload notice" : source.type === 49 && source.appMessageType === 87 ? "group announcement" : source.type === 49 && [3, 4, 5].includes(source.appMessageType ?? 0) ? "link" : source.type === 49 && source.appMessageType === 6 ? "file" : "message";
1551
+ const image = state === "embedded" && source.type === 3 && source.embeddedImage === true;
1552
+ if (state === "embedded" && !image && !source.embeddedText) return unavailable("invalid");
1553
+ const content = state === "missing" ? "" : image ? imageBody ?? "[Image metadata embedded in quote; image not retrieved]" : source.embeddedText ?? "";
1554
+ const status = state === "unsupported" ? `[${label} attachment unavailable from embedded quote]` : state === "missing" ? "[Embedded quote content unavailable]" : "";
1555
+ return {
1556
+ body: `${comment}${comment ? "\n\n" : ""}[Quoted ${label} from ${source.senderId ?? "unknown sender"}; embedded in reply]
1557
+ ${[content, status].filter(Boolean).join("\n")}
1558
+ [/Quoted message]`,
1559
+ image,
1560
+ quote: { state, type: source.type, senderId: source.senderId ?? void 0 }
1185
1561
  };
1186
1562
  }
1187
1563
 
@@ -1192,6 +1568,26 @@ function kind(type) {
1192
1568
  var terminalJobs = /* @__PURE__ */ new Set(["accepted", "completed", "succeeded", "available", "failed", "partial", "cancelled", "expired", "needs_review"]);
1193
1569
  var successfulSendJobs = /* @__PURE__ */ new Set(["accepted", "completed", "succeeded"]);
1194
1570
  var terminalIdentityErrors = /* @__PURE__ */ new Set(["media_identity_unavailable", "media_source_changed"]);
1571
+ var NativeMediaJobInspectionError = class extends Error {
1572
+ code = "native_media_job_inspection_required";
1573
+ retryable = false;
1574
+ jobId;
1575
+ accountId;
1576
+ threadId;
1577
+ idempotencyKey;
1578
+ state;
1579
+ reason;
1580
+ constructor(job, accountId, threadId2, key, reason) {
1581
+ super(`Native media job ${job.id} requires inspection (${job.state}); retain the original job and idempotency key and do not automatically resend`);
1582
+ this.name = "NativeMediaJobInspectionError";
1583
+ this.jobId = job.id;
1584
+ this.accountId = accountId;
1585
+ this.threadId = threadId2;
1586
+ this.idempotencyKey = key;
1587
+ this.state = job.state;
1588
+ this.reason = reason;
1589
+ }
1590
+ };
1195
1591
  function mediaSendResult(job) {
1196
1592
  return job.result && typeof job.result === "object" && !Array.isArray(job.result) ? job.result : {};
1197
1593
  }
@@ -1207,11 +1603,11 @@ function mediaSendReceiptIds(job, audioAsVoice) {
1207
1603
  async function waitNativeMediaSendReceipts(client, accountId, threadId2, initial, audioAsVoice, timeoutMs = 1e4) {
1208
1604
  if (initial.accountId !== accountId || initial.threadId !== threadId2 || initial.kind !== "send") throw Error("Native media receipt job identity mismatch; inspect the submitted job and do not resend");
1209
1605
  const deadline = Date.now() + Math.max(0, Math.min(timeoutMs, 1e4));
1210
- let job = initial, delay = 100;
1606
+ let job = initial, delay2 = 100;
1211
1607
  while (successfulSendJobs.has(job.state) && !mediaSendReceiptIds(job, audioAsVoice) && Date.now() < deadline) {
1212
1608
  const result = mediaSendResult(job);
1213
1609
  if (["unknown", "not_applicable"].includes(String(result.profileProjection)) || audioAsVoice && Array.isArray(result.chunks) && result.chunks.some((chunk) => !chunk || chunk.state !== "accepted")) break;
1214
- await new Promise((resolve) => setTimeout(resolve, Math.min(delay, Math.max(0, deadline - Date.now()))));
1610
+ await new Promise((resolve) => setTimeout(resolve, Math.min(delay2, Math.max(0, deadline - Date.now()))));
1215
1611
  const remaining = deadline - Date.now();
1216
1612
  if (remaining <= 0) break;
1217
1613
  let next;
@@ -1222,27 +1618,46 @@ async function waitNativeMediaSendReceipts(client, accountId, threadId2, initial
1222
1618
  }
1223
1619
  if (next.id !== initial.id || next.accountId !== accountId || next.threadId !== threadId2 || next.kind !== "send" || next.sourceId !== initial.sourceId || initial.serverMessageId != null && next.serverMessageId !== initial.serverMessageId) break;
1224
1620
  job = next;
1225
- delay = Math.min(delay * 2, 1e3);
1621
+ delay2 = Math.min(delay2 * 2, 1e3);
1226
1622
  }
1227
1623
  return job;
1228
1624
  }
1229
1625
  async function waitNativeMediaJob(client, accountId, initial, timeoutMs = 65e3, signal, assertCurrent) {
1626
+ return waitNativeMediaStatus(initial, timeoutMs, signal, assertCurrent, (job, pollSignal) => client.job(accountId, job.id, pollSignal));
1627
+ }
1628
+ async function waitNativeMediaStatus(initial, timeoutMs, signal, assertCurrent, readStatus) {
1230
1629
  const deadline = Date.now() + timeoutMs;
1231
1630
  let job = initial;
1232
- let delay = 250;
1631
+ let delay2 = 250;
1233
1632
  while (!terminalJobs.has(job.state) && Date.now() < deadline) {
1234
1633
  signal?.throwIfAborted();
1235
1634
  assertCurrent?.();
1236
- await new Promise((resolve) => setTimeout(resolve, Math.min(delay, Math.max(0, deadline - Date.now()))));
1635
+ await new Promise((resolve) => setTimeout(resolve, Math.min(delay2, Math.max(0, deadline - Date.now()))));
1237
1636
  const remaining = deadline - Date.now();
1238
1637
  if (remaining <= 0) break;
1239
1638
  signal?.throwIfAborted();
1240
1639
  assertCurrent?.();
1241
- job = await client.job(accountId, job.id, signal ? AbortSignal.any([signal, AbortSignal.timeout(remaining)]) : AbortSignal.timeout(remaining));
1242
- delay = Math.min(delay * 2, 1e3);
1640
+ const next = await readStatus(job, signal ? AbortSignal.any([signal, AbortSignal.timeout(remaining)]) : AbortSignal.timeout(remaining));
1641
+ if (!next) break;
1642
+ job = next;
1643
+ delay2 = Math.min(delay2 * 2, 1e3);
1243
1644
  }
1244
1645
  return job;
1245
1646
  }
1647
+ async function incomingMediaJobStatus(client, accountId, jobId, assetId, signal, assertCurrent) {
1648
+ let job;
1649
+ assertCurrent();
1650
+ try {
1651
+ job = await client.job(accountId, jobId, signal);
1652
+ } catch (error) {
1653
+ assertCurrent();
1654
+ if (error instanceof NativeApiError ? error.retryable && !terminalIdentityErrors.has(error.code) && error.code !== "message_recalled" : error instanceof TypeError || error instanceof DOMException && ["TimeoutError", "NetworkError", "AbortError"].includes(error.name)) return void 0;
1655
+ throw error;
1656
+ }
1657
+ assertCurrent();
1658
+ if (job.id !== jobId || job.accountId !== accountId || job.kind !== "download" || assetId != null && job.assetId != null && job.assetId !== assetId) throw Error("Native download job identity does not match its attachment");
1659
+ return job;
1660
+ }
1246
1661
  function select(assets, type, quality = "best") {
1247
1662
  const preferred = type === 34 ? ["normal"] : type === 43 ? ["normal", "original"] : ["original", "standard", "thumbnail", "encoded"];
1248
1663
  const rank = (asset) => {
@@ -1301,83 +1716,37 @@ ${prepared.body}`,
1301
1716
  };
1302
1717
  }
1303
1718
  async function prepareNativeQuote(params) {
1304
- const { client, account, message } = params;
1305
- const guard = () => {
1719
+ const { message } = params;
1720
+ const guard2 = () => {
1306
1721
  params.signal?.throwIfAborted();
1307
1722
  params.assertCurrent?.();
1308
1723
  };
1309
- guard();
1310
- const comment = (message.body ?? "").slice(0, 16384);
1311
- const unavailable = (state) => ({ body: `${comment}${comment ? "\n\n" : ""}[Quoted message ${state}; original lookup is confined to this chat]`, pending: false, retryable: state === "unavailable", quote: { state } });
1312
- await params.beforeMediaAccess?.();
1313
- guard();
1314
- let resolution;
1315
- try {
1316
- resolution = await client.quotedMessage(account.native.accountId, message.id);
1317
- } catch (error) {
1318
- guard();
1319
- if (!(error instanceof NativeApiError)) throw error;
1320
- if (error.code === "message_recalled") return { ...unavailable("recalled"), retryable: false, reason: "message_recalled" };
1321
- return terminalIdentityErrors.has(error.code) ? { ...unavailable("unavailable"), retryable: false, reason: error.code } : unavailable("unavailable");
1322
- }
1323
- guard();
1324
- if (resolution.accountId !== message.accountId || resolution.messageId !== message.id || resolution.threadId !== message.threadId) throw Error("Native quote identity does not match its message");
1325
- if (resolution.state === "recalled" || resolution.message && nativeRecallInfo(resolution.message)) return { ...unavailable("recalled"), retryable: false, reason: "message_recalled" };
1326
- if (!message.quote) return unavailable("invalid");
1327
- if (resolution.state === "embedded") {
1328
- if (resolution.message != null || (message.quote.type === 1 ? typeof resolution.embeddedText !== "string" || resolution.embeddedText.length > 16384 : message.quote.type !== 3 || resolution.embeddedImage !== true)) throw Error("Invalid embedded quote resolution");
1329
- const author = { senderId: resolution.senderId ?? null, direction: null };
1330
- if (params.allowQuotedMessage && !await params.allowQuotedMessage(author)) return unavailable("not permitted");
1331
- guard();
1332
- const quote2 = { state: "embedded", senderId: resolution.senderId ?? void 0, type: message.quote.type };
1333
- const prefix2 = `${comment}${comment ? "\n\n" : ""}[Quoted ${message.quote.type === 3 ? "image" : "text"} from ${resolution.senderId ?? "unknown sender"}; embedded in quote, original not stored]
1334
- `;
1335
- if (message.quote.type === 1) return { body: `${prefix2}${resolution.embeddedText}
1336
- [/Quoted message]`, pending: false, quote: quote2 };
1337
- const beforeMediaAccess2 = async () => {
1338
- await params.beforeMediaAccess?.();
1339
- guard();
1340
- if (params.allowQuotedMessage && !await params.allowQuotedMessage(author)) throw Error("Quoted message is no longer permitted");
1341
- guard();
1342
- };
1343
- const prepared2 = await prepareNativeAttachment({ ...params, message: { ...message, type: 3, appMessageType: void 0, quote: void 0 }, beforeMediaAccess: beforeMediaAccess2 });
1344
- return {
1345
- ...prepared2,
1346
- body: `${prefix2}${prepared2.body}
1347
- [/Quoted message]`,
1348
- pending: false,
1349
- quote: quote2,
1350
- ...prepared2.pending ? { attachment: { kind: "image", status: "pending", filename: "quoted-image" } } : {}
1351
- };
1352
- }
1353
- if (resolution.state !== "resolved") {
1354
- if (!["missing", "invalid", "unsupported", "ambiguous"].includes(resolution.state) || resolution.message != null) throw Error("Invalid native quote resolution");
1355
- return unavailable(resolution.state);
1356
- }
1357
- const original = resolution.message;
1358
- if (!original || original.accountId !== message.accountId || original.threadId !== message.threadId || original.id === message.id || original.serverId !== message.quote.serverId || original.type !== message.quote.type || ![1, 3].includes(original.type)) throw Error("Native quoted original crosses its message boundary");
1359
- if (params.allowQuotedMessage && !await params.allowQuotedMessage(original)) return unavailable("not permitted");
1360
- guard();
1361
- const quote = { state: "resolved", messageId: original.id, senderId: original.senderId ?? void 0, type: original.type };
1362
- const prefix = `${comment}${comment ? "\n\n" : ""}[Quoted ${original.type === 3 ? "image" : "text"} from ${original.senderId ?? "unknown sender"}; message ${original.id}]
1363
- `;
1364
- if (original.type === 1) return { body: `${prefix}${(original.body ?? "").slice(0, 16384)}
1365
- [/Quoted message]`, pending: false, quote };
1724
+ guard2();
1725
+ const author = { senderId: message.quote?.senderId ?? null, direction: message.quote?.direction ?? null };
1726
+ const permitted = !message.quote || !params.allowQuotedMessage || await params.allowQuotedMessage(author);
1727
+ guard2();
1728
+ const rendered = renderEmbeddedQuote(message, permitted);
1729
+ if (!rendered.image) return {
1730
+ body: rendered.body,
1731
+ quote: rendered.quote,
1732
+ pending: false,
1733
+ retryable: false,
1734
+ ...rendered.quote.state === "recalled" ? { reason: "message_recalled" } : {}
1735
+ };
1366
1736
  const beforeMediaAccess = async () => {
1367
1737
  await params.beforeMediaAccess?.();
1368
- guard();
1369
- if (params.allowQuotedMessage && !await params.allowQuotedMessage(original)) throw Error("Quoted message is no longer permitted");
1370
- guard();
1738
+ guard2();
1739
+ if (params.allowQuotedMessage && !await params.allowQuotedMessage(author)) throw Error("Quoted message is no longer permitted");
1740
+ guard2();
1371
1741
  };
1372
- const prepared = await prepareNativeAttachment({ ...params, message: original, beforeMediaAccess });
1742
+ const prepared = await prepareNativeAttachment({ ...params, message: { ...message, type: 3, appMessageType: void 0, quote: void 0, link: void 0 }, beforeMediaAccess });
1743
+ if (prepared.reason === "message_recalled" || terminalIdentityErrors.has(prepared.reason ?? "")) return prepared;
1373
1744
  return {
1374
1745
  ...prepared,
1375
- body: `${prefix}${prepared.body}
1376
- [/Quoted message]`,
1746
+ body: renderEmbeddedQuote(message, true, prepared.body).body,
1747
+ quote: rendered.quote,
1377
1748
  pending: false,
1378
- quote,
1379
- ...prepared.pending ? { attachment: { kind: "image", status: "pending", filename: "quoted-image" } } : {},
1380
- suppliedAssets: prepared.suppliedAssets?.map((asset) => ({ ...asset, sourceMessageId: original.id }))
1749
+ ...prepared.pending ? { attachment: { kind: "image", status: "pending", filename: "quoted-image" } } : {}
1381
1750
  };
1382
1751
  }
1383
1752
  async function prepareNativeAttachment(params) {
@@ -1402,28 +1771,32 @@ async function prepareNativeAttachment(params) {
1402
1771
  async function prepareNativeAttachmentInput(params) {
1403
1772
  const { client, account, message, core } = params;
1404
1773
  const attachmentKind = kind(message.type);
1405
- const guard = () => {
1774
+ const guard2 = () => {
1406
1775
  params.signal?.throwIfAborted();
1407
1776
  params.assertCurrent?.();
1408
1777
  };
1409
- guard();
1778
+ guard2();
1410
1779
  if (nativeRecallInfo(message)) return { body: "[Message recalled]", pending: false, retryable: false, reason: "message_recalled" };
1411
1780
  const authorize = async () => {
1412
- guard();
1781
+ guard2();
1413
1782
  await params.beforeMediaAccess?.();
1414
- guard();
1783
+ guard2();
1415
1784
  };
1416
1785
  if (message.type === 49 && message.appMessageType === 57) return prepareNativeQuote(params);
1786
+ if (message.type === 49 && [1, 74, 87].includes(message.appMessageType ?? 0)) return { body: message.body?.slice(0, 32768) || "[Shared text unavailable]", pending: false };
1417
1787
  if (message.type === 49 && message.appMessageType === 19) return { body: message.body?.slice(0, 65536) || "[Forwarded chat history unavailable]", pending: false };
1418
- if (message.type === 49 && [3, 4, 5].includes(message.appMessageType ?? 0) && message.link) return prepareNativeLink(params);
1788
+ if (message.type === 49 && [3, 4, 5, 51].includes(message.appMessageType ?? 0) && message.link) return prepareNativeLink(params);
1419
1789
  if (message.type === 49 && message.appMessageType != null && message.appMessageType !== 6) return { body: `[Unsupported WeChat app message subtype ${message.appMessageType}]`, pending: false, retryable: false };
1420
1790
  if (!attachmentKind) return { body: message.type === 1 ? message.body ?? "" : `[Unsupported WeChat message type ${message.type}]`, pending: false };
1421
1791
  const accountId = account.native.accountId;
1422
- const maxBytes = Math.min(account.mediaMaxMb * 1024 * 1024, 128 * 1024 * 1024);
1792
+ const maxBytes = Math.min(
1793
+ account.mediaMaxMb * 1024 * 1024,
1794
+ attachmentKind === "file" ? Math.max(NATIVE_MAX_SOURCE_BYTES, 128 * 1024 * 1024) : 128 * 1024 * 1024
1795
+ );
1423
1796
  const scopedAssets = async () => {
1424
1797
  await authorize();
1425
1798
  const items = (await client.mediaAssets(accountId, message.id)).items;
1426
- guard();
1799
+ guard2();
1427
1800
  if (items.some((asset2) => asset2.accountId !== accountId || asset2.messageId !== message.id)) throw Error("Native attachment identity does not match its message");
1428
1801
  return items;
1429
1802
  };
@@ -1445,9 +1818,9 @@ async function prepareNativeAttachmentInput(params) {
1445
1818
  let transferError;
1446
1819
  if (!asset && initialCandidate?.jobId && initialCandidate.state !== "recalled") {
1447
1820
  await authorize();
1448
- job = await client.job(accountId, initialCandidate.jobId, params.signal);
1449
- guard();
1450
- if (job.accountId !== accountId || job.kind !== "download" || job.assetId != null && job.assetId !== initialCandidate.id) throw Error("Native download job identity does not match its attachment");
1821
+ job = await incomingMediaJobStatus(client, accountId, initialCandidate.jobId, initialCandidate.id, params.signal, guard2);
1822
+ guard2();
1823
+ if (!job) return { body: `[${attachmentKind} pending: retrieval is unavailable]`, pending: true, jobId: initialCandidate.jobId, retryable: true };
1451
1824
  assets = await scopedAssets();
1452
1825
  asset = select(assets, message.type, quality);
1453
1826
  if (!asset && transferCandidate()?.state === "recalled") return { body: "[Message recalled]", pending: false, retryable: false, reason: "message_recalled" };
@@ -1457,11 +1830,17 @@ async function prepareNativeAttachmentInput(params) {
1457
1830
  await authorize();
1458
1831
  try {
1459
1832
  job = await client.transferMedia(accountId, { messageId: message.id, assetId: null, quality: transferQuality });
1460
- guard();
1461
- job = await waitNativeMediaJob(client, accountId, job, params.waitMs ?? 2e4, params.signal, guard);
1462
- guard();
1833
+ guard2();
1834
+ job = await waitNativeMediaStatus(
1835
+ job,
1836
+ params.waitMs ?? 2e4,
1837
+ params.signal,
1838
+ guard2,
1839
+ (known, pollSignal) => incomingMediaJobStatus(client, accountId, known.id, initialCandidate?.id, pollSignal, guard2)
1840
+ );
1841
+ guard2();
1463
1842
  } catch (error) {
1464
- guard();
1843
+ guard2();
1465
1844
  if (!(error instanceof NativeApiError) || terminalIdentityErrors.has(error.code)) throw error;
1466
1845
  if (error.retryable) return { body: `[${attachmentKind} pending: retrieval is unavailable]`, pending: true, jobId: job?.id, retryable: true };
1467
1846
  transferError = error;
@@ -1491,14 +1870,63 @@ async function prepareNativeAttachmentInput(params) {
1491
1870
  return { body: renderAttachmentBody("", attachment2), attachment: attachment2, pending: false };
1492
1871
  }
1493
1872
  await authorize();
1873
+ if (attachmentKind === "file" && asset.byteLength != null && asset.byteLength > 128 * 1024 * 1024) {
1874
+ const content2 = await client.mediaContentStream(accountId, asset.id, { maxBytes, signal: params.signal });
1875
+ const mime2 = content2.contentType.split(";", 1)[0].trim().toLowerCase();
1876
+ if (!/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/.test(mime2)) {
1877
+ await content2.cancel();
1878
+ throw Error("Native attachment MIME type is unsupported");
1879
+ }
1880
+ let saved2;
1881
+ try {
1882
+ saved2 = await saveVerifiedManagedAttachmentStream({
1883
+ stream: content2.stream,
1884
+ mime: mime2,
1885
+ filename,
1886
+ maxBytes,
1887
+ expectedBytes: asset.byteLength,
1888
+ expectedSha256: asset.sha256 ?? "",
1889
+ assertCurrent: guard2,
1890
+ saveMediaStream: params.saveMediaStream ?? saveMediaStream
1891
+ });
1892
+ } finally {
1893
+ await content2.cancel();
1894
+ }
1895
+ await authorize();
1896
+ const attachment2 = { kind: "file", filename, status: "ready", path: saved2.path, mime: mime2 };
1897
+ return {
1898
+ body: renderAttachmentBody("", attachment2),
1899
+ attachment: attachment2,
1900
+ mediaMime: mime2,
1901
+ pending: false,
1902
+ jobId: job?.id,
1903
+ retryable: false,
1904
+ variant: asset.actualVariant ?? asset.variant,
1905
+ suppliedAssets: [{
1906
+ id: asset.id,
1907
+ contextRole: "trigger",
1908
+ role: "file_reference",
1909
+ kind: "file",
1910
+ path: saved2.path,
1911
+ mime: mime2,
1912
+ sha256: saved2.sha256,
1913
+ byteLength: saved2.size,
1914
+ runtimeMedia: false,
1915
+ sourceSha256: saved2.sha256,
1916
+ sourceByteLength: saved2.size,
1917
+ sourceMime: mime2,
1918
+ sourcePath: saved2.path
1919
+ }]
1920
+ };
1921
+ }
1494
1922
  const content = await client.mediaContent(accountId, asset.id, { maxBytes, signal: params.signal });
1495
- guard();
1923
+ guard2();
1496
1924
  const mime = content.contentType.split(";", 1)[0].trim().toLowerCase();
1497
1925
  if (!/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/.test(mime)) throw Error("Native attachment MIME type is unsupported");
1498
1926
  const hash = createHash4("sha256").update(content.bytes).digest("hex");
1499
1927
  if (!asset.sha256 || hash !== asset.sha256 || asset.byteLength != null && asset.byteLength !== content.bytes.length) throw new Error("Native attachment integrity did not verify");
1500
1928
  await authorize();
1501
- const saved = await saveManagedAttachment({ data: Buffer.from(content.bytes).toString("base64"), mime, filename, maxBytes, saveMediaBuffer: core.channel.media.saveMediaBuffer });
1929
+ const saved = await saveManagedAttachmentBytes({ bytes: content.bytes, mime, filename, maxBytes, saveMediaBuffer: core.channel.media.saveMediaBuffer });
1502
1930
  const actual = asset.actualVariant ?? asset.variant;
1503
1931
  const attachment = {
1504
1932
  kind: attachmentKind,
@@ -1518,7 +1946,7 @@ async function prepareNativeAttachmentInput(params) {
1518
1946
  if (!preview || preview.sourceSha256 !== hash || !/^[a-f0-9]{64}$/.test(preview.sha256) || !Number.isInteger(preview.byteLength) || preview.byteLength <= 0 || preview.byteLength > 16 * 1024 * 1024 || !["image/jpeg", "image/png"].includes(preview.contentType)) throw Error("Native WXGF preview metadata did not verify");
1519
1947
  await authorize();
1520
1948
  const derived = await client.mediaContent(accountId, asset.id, { maxBytes: preview.byteLength, representation: "preview", signal: params.signal });
1521
- guard();
1949
+ guard2();
1522
1950
  const derivedMime = derived.contentType.split(";", 1)[0].trim().toLowerCase();
1523
1951
  if (derived.sourceSha256 !== hash || derivedMime !== preview.contentType || derived.bytes.length !== preview.byteLength || createHash4("sha256").update(derived.bytes).digest("hex") !== preview.sha256) throw Error("Native WXGF preview integrity did not verify");
1524
1952
  imageBytes = Buffer.from(derived.bytes);
@@ -1543,7 +1971,7 @@ async function prepareNativeAttachmentInput(params) {
1543
1971
  [Model image: prepared still preview; original retained separately]`;
1544
1972
  }
1545
1973
  }
1546
- guard();
1974
+ guard2();
1547
1975
  return {
1548
1976
  body,
1549
1977
  attachment,
@@ -1570,93 +1998,356 @@ async function prepareNativeAttachmentInput(params) {
1570
1998
  pending: false
1571
1999
  };
1572
2000
  }
1573
- async function sendNativeAttachment(client, account, threadId2, mediaUrl, audioAsVoice = false, key = randomUUID(), beforeSend) {
1574
- const max = Math.min(account.mediaMaxMb * 1024 * 1024, NATIVE_MAX_SOURCE_BYTES);
1575
- let bytes;
1576
- let filename;
1577
- let mime;
1578
- if (/^https?:/.test(mediaUrl)) {
1579
- const response = await fetch(mediaUrl, { redirect: "error", signal: AbortSignal.timeout(3e4) });
1580
- if (!response.ok) throw new Error(`Native outbound source unavailable (${response.status})`);
1581
- const length = response.headers.get("content-length");
1582
- if (length && (!/^\d+$/.test(length) || Number(length) > max)) {
1583
- await response.body?.cancel();
1584
- throw new Error("Native outbound source exceeds configured size");
1585
- }
1586
- const reader = response.body?.getReader();
1587
- if (!reader) throw new Error("Native outbound source has no bytes");
1588
- const chunks2 = [];
1589
- let size = 0;
1590
- try {
1591
- while (true) {
1592
- const { value, done } = await reader.read();
1593
- if (done) break;
1594
- size += value.length;
1595
- if (size > max) throw new Error("Native outbound source exceeds configured size");
1596
- chunks2.push(value);
2001
+ function validateNativeMediaSendOptions(options, audioAsVoice = false) {
2002
+ if (options.forceDocument != null && typeof options.forceDocument !== "boolean") throw new Error("Invalid WeChat document option");
2003
+ if (options.videoQuality != null && !["normal", "original"].includes(options.videoQuality)) throw new Error("Invalid WeChat video quality");
2004
+ if (options.forceDocument && (audioAsVoice || options.videoQuality != null)) throw new Error("Document sending cannot also request voice or video quality");
2005
+ }
2006
+ function outboundMediaKind(mime, audioAsVoice, options) {
2007
+ if (options.forceDocument) return "file";
2008
+ if (audioAsVoice && !mime.startsWith("audio/")) throw new Error("Voice sending requires an explicit audio attachment");
2009
+ const selected = audioAsVoice ? "voice" : mime.startsWith("image/") ? "image" : mime.startsWith("video/") ? "video" : "file";
2010
+ if (options.videoQuality != null && selected !== "video") throw new Error("Video quality requires a video attachment");
2011
+ return selected;
2012
+ }
2013
+ function outboundSourceLimit(account, selectedKind) {
2014
+ return Math.min(account.mediaMaxMb * 1024 * 1024, selectedKind === "file" ? NATIVE_MAX_SOURCE_BYTES : selectedKind === "video" ? NATIVE_MAX_VIDEO_SOURCE_BYTES : NATIVE_MAX_ORDINARY_SOURCE_BYTES);
2015
+ }
2016
+ async function sendNativeAttachment(client, account, threadId2, mediaUrl, audioAsVoice = false, key = randomUUID(), beforeSend, options = {}) {
2017
+ validateNativeMediaSendOptions(options, audioAsVoice);
2018
+ await beforeSend?.();
2019
+ let filename, mime, selectedKind, sourceBytes, source;
2020
+ let temporary;
2021
+ const accountId = account.native.accountId;
2022
+ try {
2023
+ let blob;
2024
+ if (/^https?:/.test(mediaUrl)) {
2025
+ const response = await fetch(mediaUrl, { redirect: "error", signal: AbortSignal.timeout(60 * 6e4) });
2026
+ if (!response.ok) throw new Error(`Native outbound source unavailable (${response.status})`);
2027
+ filename = basename(new URL(mediaUrl).pathname) || "attachment";
2028
+ mime = response.headers.get("content-type")?.split(";")[0].trim().toLowerCase() ?? "application/octet-stream";
2029
+ try {
2030
+ selectedKind = outboundMediaKind(mime, audioAsVoice, options);
2031
+ } catch (error) {
2032
+ await response.body?.cancel();
2033
+ throw error;
1597
2034
  }
1598
- } catch (error) {
1599
- await reader.cancel();
1600
- throw error;
1601
- } finally {
1602
- reader.releaseLock();
1603
- }
1604
- bytes = new Uint8Array(size);
1605
- let offset = 0;
1606
- for (const chunk of chunks2) {
1607
- bytes.set(chunk, offset);
1608
- offset += chunk.length;
1609
- }
1610
- filename = basename(new URL(mediaUrl).pathname) || "attachment";
1611
- mime = response.headers.get("content-type")?.split(";")[0] ?? "application/octet-stream";
1612
- } else {
1613
- const path = mediaUrl.startsWith("file:") ? new URL(mediaUrl) : mediaUrl;
1614
- const file = await open(path, "r");
1615
- try {
1616
- const stat = await file.stat();
1617
- if (!stat.isFile() || stat.size === 0 || stat.size > max) throw new Error("Native outbound source must be a bounded regular file");
1618
- const chunks2 = [];
1619
- let size = 0;
1620
- while (true) {
1621
- const chunk = Buffer.alloc(Math.min(65536, max + 1 - size));
1622
- const { bytesRead } = await file.read(chunk, 0, chunk.length, null);
1623
- if (!bytesRead) break;
1624
- size += bytesRead;
1625
- if (size > max) throw new Error("Native outbound source exceeds configured size");
1626
- chunks2.push(chunk.subarray(0, bytesRead));
2035
+ const max = outboundSourceLimit(account, selectedKind);
2036
+ const length = response.headers.get("content-length");
2037
+ if (length && (!/^\d+$/.test(length) || Number(length) > max)) {
2038
+ await response.body?.cancel();
2039
+ throw new Error("Native outbound source exceeds configured size");
1627
2040
  }
1628
- bytes = Buffer.concat(chunks2, size);
1629
- } finally {
1630
- await file.close();
2041
+ const reader = response.body?.getReader();
2042
+ if (!reader) throw new Error("Native outbound source has no bytes");
2043
+ let path, file, size = 0;
2044
+ try {
2045
+ temporary = await mkdtemp(join2(tmpdir(), "wechat-outbound-"));
2046
+ path = join2(temporary, "source");
2047
+ file = await open(path, "wx", 384);
2048
+ while (true) {
2049
+ const { value, done } = await reader.read();
2050
+ if (done) break;
2051
+ size += value.byteLength;
2052
+ if (size > max) throw new Error("Native outbound source exceeds configured size");
2053
+ await file.writeFile(value);
2054
+ }
2055
+ if (!size || length && size !== Number(length)) throw new Error("Native outbound source length mismatch");
2056
+ } finally {
2057
+ await reader.cancel().catch(() => {
2058
+ });
2059
+ reader.releaseLock();
2060
+ await file?.close();
2061
+ }
2062
+ blob = await openAsBlob(path, { type: mime });
2063
+ } else {
2064
+ const path = mediaUrl.startsWith("file:") ? new URL(mediaUrl) : mediaUrl;
2065
+ filename = basename(path instanceof URL ? path.pathname : path);
2066
+ const extension = extname(filename).toLowerCase();
2067
+ mime = [".png", ".jpg", ".jpeg", ".gif", ".webp"].includes(extension) ? `image/${extension === ".jpg" ? "jpeg" : extension.slice(1)}` : extension === ".mp4" ? "video/mp4" : [".wav", ".mp3", ".ogg", ".m4a", ".flac", ".aac"].includes(extension) ? `audio/${extension.slice(1)}` : "application/octet-stream";
2068
+ selectedKind = outboundMediaKind(mime, audioAsVoice, options);
2069
+ const max = outboundSourceLimit(account, selectedKind), file = await open(path, "r");
2070
+ let size;
2071
+ try {
2072
+ const stat = await file.stat();
2073
+ if (!stat.isFile() || !stat.size || stat.size > max) throw new Error("Native outbound source must be a bounded regular file");
2074
+ size = stat.size;
2075
+ } finally {
2076
+ await file.close();
2077
+ }
2078
+ blob = await openAsBlob(path, { type: mime });
2079
+ if (blob.size !== size) throw new Error("Native outbound source changed before staging");
1631
2080
  }
1632
- filename = basename(path instanceof URL ? path.pathname : path);
1633
- const extension = extname(filename).toLowerCase();
1634
- mime = [".png", ".jpg", ".jpeg", ".gif", ".webp"].includes(extension) ? `image/${extension === ".jpg" ? "jpeg" : extension.slice(1)}` : extension === ".mp4" ? "video/mp4" : [".wav", ".mp3", ".ogg", ".m4a", ".flac", ".aac"].includes(extension) ? `audio/${extension.slice(1)}` : "application/octet-stream";
2081
+ sourceBytes = blob.size;
2082
+ if (sourceBytes > outboundSourceLimit(account, selectedKind)) throw new Error("Native outbound source exceeds selected media kind size");
2083
+ await beforeSend?.();
2084
+ source = await client.upload(accountId, blob, filename, mime);
2085
+ } finally {
2086
+ if (temporary) await rm(temporary, { recursive: true, force: true });
1635
2087
  }
1636
- if (audioAsVoice && !mime.startsWith("audio/")) throw new Error("Voice sending requires an explicit audio attachment");
1637
- await beforeSend?.();
1638
- const accountId = account.native.accountId;
1639
- const source = await client.upload(accountId, bytes, filename, mime);
1640
- const input = { threadId: threadId2, kind: audioAsVoice ? "voice" : mime.startsWith("image/") ? "image" : mime.startsWith("video/") ? "video" : "file", sourceId: source.id, standardSourceId: null, thumbnailSourceId: null, playSeconds: null, durationMs: null };
2088
+ const input = {
2089
+ threadId: threadId2,
2090
+ kind: selectedKind,
2091
+ sourceId: source.id,
2092
+ standardSourceId: null,
2093
+ thumbnailSourceId: null,
2094
+ playSeconds: null,
2095
+ durationMs: null,
2096
+ ...selectedKind === "video" ? { videoQuality: options.videoQuality ?? "normal" } : {}
2097
+ };
1641
2098
  await beforeSend?.();
1642
- let job = await waitNativeMediaJob(client, accountId, await client.sendMedia(accountId, input, key), audioAsVoice ? 25 * 6e4 : 65e3);
2099
+ const waitMs = audioAsVoice ? 25 * 6e4 : selectedKind === "video" || selectedKind === "file" && sourceBytes > NATIVE_MAX_ORDINARY_SOURCE_BYTES ? 60 * 6e4 : 65e3;
2100
+ const submitted = await client.sendMedia(accountId, input, key);
2101
+ let job;
2102
+ try {
2103
+ job = await waitNativeMediaJob(client, accountId, submitted, waitMs);
2104
+ } catch {
2105
+ throw new NativeMediaJobInspectionError(submitted, accountId, threadId2, key, "status_unavailable");
2106
+ }
1643
2107
  if (successfulSendJobs.has(job.state)) job = await waitNativeMediaSendReceipts(client, accountId, threadId2, job, audioAsVoice);
1644
- if (!successfulSendJobs.has(job.state)) throw new Error(`Native media job ${job.id} requires inspection (${job.state}); retain completed items and do not automatically resend`);
2108
+ if (!successfulSendJobs.has(job.state)) throw new NativeMediaJobInspectionError(job, accountId, threadId2, key, "job_not_completed");
1645
2109
  const result = mediaSendResult(job);
1646
2110
  const chunks = Array.isArray(result.chunks) ? result.chunks.filter((chunk) => chunk && typeof chunk === "object") : [];
1647
2111
  const serverIds = audioAsVoice ? chunks.filter((chunk) => chunk.state === "accepted" && typeof chunk.serverMessageId === "string").map((chunk) => chunk.serverMessageId) : job.serverMessageId ? [job.serverMessageId] : void 0;
1648
2112
  return nativeOutboundDelivery(client, accountId, threadId2, mediaSendReceiptIds(job, audioAsVoice), { jobId: job.id, state: job.state, serverIds });
1649
2113
  }
1650
2114
 
2115
+ // src/native-prepared-boundary.ts
2116
+ import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
2117
+ import { basename as basename2, isAbsolute as isAbsolute2 } from "node:path";
2118
+ var pending = /* @__PURE__ */ new Map();
2119
+ var enabled = false;
2120
+ var digest = (value) => createHash5("sha256").update(value).digest("hex");
2121
+ function prune() {
2122
+ for (const [id2, item] of pending) if (item.expires < Date.now()) pending.delete(id2);
2123
+ }
2124
+ function nativeSourceMessageSid(message) {
2125
+ return `wechat-native:${message.accountId}:${message.id}:${digest(JSON.stringify([message.threadId, message.serverId ?? null]))}`;
2126
+ }
2127
+ function nativeDispatchManifest(params) {
2128
+ const history = params.history ?? [];
2129
+ if (history.length > 200 || history.some((message) => message.accountId !== params.message.accountId || message.threadId !== params.message.threadId || message.id === params.message.id)) throw Error("Invalid native history manifest");
2130
+ const assets = Object.freeze((params.assets ?? []).map((asset) => {
2131
+ if (typeof asset.id !== "string" || !asset.id || asset.id.length > 2048 || !/^[a-f0-9]{64}$/.test(asset.sha256) || !Number.isSafeInteger(asset.byteLength) || asset.byteLength < 1 || asset.byteLength > (asset.kind === "file" ? NATIVE_MAX_SOURCE_BYTES : 128 * 1024 * 1024) || typeof asset.path !== "string" || !isAbsolute2(asset.path) || asset.path.length > 4096 || typeof asset.mime !== "string" || asset.mime.length > 128 || !/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/.test(asset.mime) || !["image", "audio", "video", "file"].includes(asset.kind) || !["model_image", "file_reference"].includes(asset.role) || asset.role === "model_image" && (asset.kind !== "image" || !asset.mime.startsWith("image/") || !asset.runtimeMedia) || !["trigger", "history"].includes(asset.contextRole) || asset.sourceMessageId != null && (typeof asset.sourceMessageId !== "string" || !asset.sourceMessageId || asset.sourceMessageId.length > 8192 || ![params.message, ...history].some((message) => message.id === asset.messageId && message.type === 49 && message.appMessageType === 57 && message.quote?.type === 3)) || asset.contextRole === "history" && !history.some((message) => message.id === asset.messageId)) throw Error("Invalid native supplied asset manifest");
2132
+ return Object.freeze({ ...asset });
2133
+ }));
2134
+ const messageSid = nativeSourceMessageSid(params.message);
2135
+ const manifest = {
2136
+ schemaVersion: 2,
2137
+ runId: randomUUID2(),
2138
+ accountId: params.message.accountId,
2139
+ messageIds: Object.freeze([params.message.id]),
2140
+ messageSid,
2141
+ threadId: params.message.threadId,
2142
+ senderId: params.message.senderId ?? "",
2143
+ sessionKey: params.sessionKey,
2144
+ agentId: params.agentId,
2145
+ channelAccountId: params.channelAccountId,
2146
+ inputBodySha256: digest(params.inputBody),
2147
+ newInputs: Object.freeze([Object.freeze({
2148
+ id: params.message.id,
2149
+ version: params.message.version ?? "",
2150
+ contentSha256: digest(JSON.stringify([
2151
+ params.message.id,
2152
+ params.message.version,
2153
+ params.message.senderId,
2154
+ params.message.type,
2155
+ params.message.body,
2156
+ params.message.mentions,
2157
+ params.message.serverId,
2158
+ params.message.appMessageType,
2159
+ params.message.quote,
2160
+ params.message.link
2161
+ ])),
2162
+ role: "trigger"
2163
+ })]),
2164
+ ...history.length ? { historyInputs: Object.freeze(history.map((message) => Object.freeze({
2165
+ id: message.id,
2166
+ version: message.version ?? "",
2167
+ contentSha256: digest(JSON.stringify([message.id, message.version, message.senderId, message.type, message.body, message.mentions, message.serverId, message.appMessageType, message.quote, message.link])),
2168
+ role: "history"
2169
+ }))) } : {},
2170
+ assets,
2171
+ policySha256: digest(JSON.stringify(params.policy ?? null)),
2172
+ // Exact source-turn identity of OpenClaw 2026.10.2 through 2026.10.7. Requiring it in the later
2173
+ // snapshot prevents an identical older image/body from proving this input.
2174
+ hostSourceTurnId: `channel-user:v1:${digest(JSON.stringify(["agent-wechat", params.channelAccountId, `wechat:${params.message.threadId}`, messageSid]))}`
2175
+ };
2176
+ return Object.freeze({ ...manifest, manifestSha256: digest(JSON.stringify(manifest)) });
2177
+ }
2178
+ function trackNativePreparedInput(manifest, record) {
2179
+ prune();
2180
+ if (!enabled || pending.size >= 1024) return;
2181
+ pending.set(manifest.runId, { manifest, record, expires: Date.now() + 15 * 60 * 1e3 });
2182
+ }
2183
+ function invalidateNativePreparedInputs(accountId, messageIds) {
2184
+ const ids = new Set(messageIds);
2185
+ for (const [runId, item] of pending) {
2186
+ if (item.manifest.accountId === accountId && [
2187
+ ...item.manifest.messageIds,
2188
+ ...(item.manifest.historyInputs ?? []).map((input) => input.id),
2189
+ ...item.manifest.assets.flatMap((asset) => asset.sourceMessageId ? [asset.sourceMessageId] : [])
2190
+ ].some((id2) => ids.has(id2))) pending.delete(runId);
2191
+ }
2192
+ }
2193
+ function promptMatches(prompt, manifest) {
2194
+ if (typeof prompt !== "string" || Buffer.byteLength(prompt) > 1024 * 1024) return false;
2195
+ const text3 = prompt.replace(/^\[[^\]\r\n]{1,96}\] /, "");
2196
+ const candidates = [text3];
2197
+ const sender = `Conversation info: \u27E6openclaw:ctx\u27E7
2198
+ \`\`\`json
2199
+ ${JSON.stringify({ sender: { id: manifest.senderId } })}
2200
+ \`\`\`
2201
+
2202
+ `;
2203
+ if (manifest.threadId.endsWith("@chatroom") && text3.startsWith(sender)) candidates.push(text3.slice(sender.length));
2204
+ return candidates.some((text4) => normalizedPromptMatches(text4, manifest));
2205
+ }
2206
+ function normalizedPromptMatches(text3, manifest) {
2207
+ const runtimeAssets = manifest.assets.filter((asset) => asset.runtimeMedia);
2208
+ if (runtimeAssets.length) {
2209
+ if (runtimeAssets.length !== 1) return false;
2210
+ const asset = runtimeAssets[0];
2211
+ const header = /^\[media attached: ([^\r\n]+) \(([^)\r\n]+)\) \| (media:\/\/inbound\/[^\]\r\n]+)\]\n/.exec(text3);
2212
+ if (!header || !isAbsolute2(header[1]) || basename2(header[1]) !== `input-${basename2(asset.path)}` || header[2] !== asset.mime || header[3] !== `media://inbound/${basename2(asset.path)}`) return false;
2213
+ text3 = text3.slice(header[0].length);
2214
+ if (asset.kind === "video") text3 = text3.replace(/\n\n\[Video attachment not analyzed: video understanding is disabled\]$/, "");
2215
+ }
2216
+ return digest(text3) === manifest.inputBodySha256;
2217
+ }
2218
+ function currentMessageFacts(messages) {
2219
+ if (!Array.isArray(messages) || messages.length > 1e3) return [];
2220
+ const facts = [];
2221
+ for (const message of messages) {
2222
+ if (message?.role !== "custom" || message.customType !== "openclaw.runtime-context" || message.details?.source !== "openclaw-runtime-context" || message.details?.runtimeContextCarrier !== true) continue;
2223
+ const fragments = message.details?.fragments;
2224
+ if (!Array.isArray(fragments) || fragments.length > 64) return [];
2225
+ for (const fragment of fragments) {
2226
+ if (fragment?.kind !== "conversation-data" || typeof fragment.text !== "string" || fragment.text.length > 65536) continue;
2227
+ const match = /^Conversation info: ⟦openclaw:ctx⟧\n```json\n([^\n]+)\n```$/.exec(fragment.text);
2228
+ if (!match) continue;
2229
+ try {
2230
+ const value = JSON.parse(match[1]);
2231
+ if (typeof value.message_id === "string" && typeof value.chat_id === "string") facts.push({ messageId: value.message_id, chatId: value.chat_id });
2232
+ } catch {
2233
+ }
2234
+ }
2235
+ }
2236
+ return facts;
2237
+ }
2238
+ function matchingContext(ctx, manifest) {
2239
+ return ctx?.runId === manifest.runId && ctx?.sessionKey === manifest.sessionKey && ctx?.agentId === manifest.agentId;
2240
+ }
2241
+ function observeNativePreparedInput(event, ctx) {
2242
+ prune();
2243
+ const item = pending.get(event?.runId);
2244
+ if (!item) return;
2245
+ item.proof = void 0;
2246
+ item.started = false;
2247
+ const m = item.manifest;
2248
+ if (!matchingContext(ctx, m) || ctx?.channel !== "agent-wechat" || ctx?.accountId !== m.channelAccountId || ctx?.chatId !== (m.threadId.endsWith("@chatroom") ? m.threadId : `wechat:${m.threadId}`) || ctx?.sessionId !== event.sessionId || typeof event.sessionId !== "string" || !event.sessionId || typeof event.provider !== "string" || typeof event.model !== "string" || !promptMatches(event.prompt, m)) return;
2249
+ const facts = currentMessageFacts(event.historyMessages);
2250
+ if (facts.length !== 1 || facts[0].messageId !== m.messageSid || facts[0].chatId !== `wechat:${m.threadId}`) return;
2251
+ if (m.assets.length && event.imagesCount !== m.assets.filter((asset) => asset.role === "model_image").length) return;
2252
+ item.proof = { sessionId: event.sessionId, provider: event.provider, model: event.model };
2253
+ }
2254
+ function observeNativeModelCall(event, ctx) {
2255
+ prune();
2256
+ const item = pending.get(event?.runId);
2257
+ if (!item?.proof) return;
2258
+ const m = item.manifest, proof = item.proof;
2259
+ if (!matchingContext(ctx, m) || event.sessionKey !== m.sessionKey || event.sessionId !== proof.sessionId || ctx?.sessionId !== proof.sessionId || event.provider !== proof.provider || event.model !== proof.model || typeof event.callId !== "string" || !event.callId) return;
2260
+ item.started = true;
2261
+ if (!m.assets.length) {
2262
+ item.record(m.runId);
2263
+ pending.delete(m.runId);
2264
+ }
2265
+ }
2266
+ function observeNativeAgentEnd(event, ctx) {
2267
+ prune();
2268
+ const item = pending.get(event?.runId);
2269
+ if (!item?.proof || !item.started || !item.manifest.assets.length) return;
2270
+ const m = item.manifest, proof = item.proof;
2271
+ if (!matchingContext(ctx, m) || ctx?.sessionId !== proof.sessionId || ctx?.channel !== "agent-wechat" || ctx?.accountId !== m.channelAccountId || ctx?.chatId !== (m.threadId.endsWith("@chatroom") ? m.threadId : `wechat:${m.threadId}`) || ctx?.modelProviderId !== proof.provider || ctx?.modelId !== proof.model || !Array.isArray(event.messages) || event.messages.length > 1e3) return;
2272
+ const user = event.messages.findLast((message) => message?.role === "user");
2273
+ if (user?.idempotencyKey !== m.hostSourceTurnId) return;
2274
+ const blocks = typeof user.content === "string" ? [{ type: "text", text: user.content }] : user.content;
2275
+ if (!Array.isArray(blocks) || blocks.length > 32) return;
2276
+ if (blocks.some((block) => !["text", "image"].includes(block?.type) || block.type === "text" && typeof block.text !== "string")) return;
2277
+ const text3 = blocks.filter((block) => block?.type === "text").map((block) => block.text).join("\n");
2278
+ if (!promptMatches(text3, m)) return;
2279
+ const images = blocks.filter((block) => block?.type === "image");
2280
+ const expectedImages = m.assets.filter((asset) => asset.role === "model_image");
2281
+ if (images.length !== expectedImages.length) return;
2282
+ for (const [index, asset] of expectedImages.entries()) {
2283
+ const image = images[index];
2284
+ if (image.mimeType !== asset.mime || typeof image.data !== "string" || image.data.length > 8 * 1024 * 1024 || image.data.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(image.data)) return;
2285
+ const bytes = Buffer.from(image.data, "base64");
2286
+ if (bytes.length !== asset.byteLength || digest(bytes) !== asset.sha256) return;
2287
+ }
2288
+ if (m.assets.some((asset) => asset.role === "file_reference" && !text3.includes(asset.path))) return;
2289
+ item.record(m.runId);
2290
+ pending.delete(m.runId);
2291
+ }
2292
+ function registerNativePreparedBoundary(api) {
2293
+ const access2 = api.config?.plugins?.entries?.["agent-wechat"]?.hooks?.allowConversationAccess === true;
2294
+ enabled = access2;
2295
+ if (access2) {
2296
+ api.on("llm_input", observeNativePreparedInput);
2297
+ api.on("model_call_started", observeNativeModelCall);
2298
+ api.on("agent_end", observeNativeAgentEnd);
2299
+ }
2300
+ return () => {
2301
+ enabled = false;
2302
+ pending.clear();
2303
+ };
2304
+ }
2305
+
2306
+ // src/outbound-reply.ts
2307
+ function parseWeChatReplyTo(value) {
2308
+ if (value == null) return void 0;
2309
+ if (typeof value !== "string" || !value || value.length > 4096 || value === "." || value === ".." || /[\u0000-\u001f\u007f]/.test(value)) throw Error("Use an exact stored WeChat message ID for replyTo");
2310
+ return value;
2311
+ }
2312
+ function nativeReplyMessageId(replyToId, accountId) {
2313
+ if (!replyToId.startsWith("wechat-native:")) return replyToId;
2314
+ const prefix = `wechat-native:${accountId}:`;
2315
+ const end = replyToId.lastIndexOf(":");
2316
+ const id2 = replyToId.slice(prefix.length, end);
2317
+ if (!replyToId.startsWith(prefix) || !/^[a-f0-9]{64}$/.test(replyToId.slice(end + 1)) || !parseWeChatReplyTo(id2)) throw Error("WeChat reply target identity is invalid for this account");
2318
+ return id2;
2319
+ }
2320
+ function validateWeChatReplySend(replyToId, input) {
2321
+ if (parseWeChatReplyTo(replyToId) === void 0) return;
2322
+ if (input.mediaUrl || input.mediaUrls?.length || input.audioAsVoice || input.forceDocument || input.videoQuality != null) {
2323
+ throw Error("WeChat quoted replies support text only; send attachments separately");
2324
+ }
2325
+ if (typeof input.text !== "string" || !input.text.trim()) throw Error("WeChat quoted replies require message text");
2326
+ }
2327
+ function nativeReplyReference(message, accountId, threadId2, replyToId) {
2328
+ const messageId = nativeReplyMessageId(replyToId, accountId);
2329
+ if (message.id !== messageId || message.accountId !== accountId || message.threadId !== threadId2 || typeof message.serverId !== "string" || !/^[1-9]\d{0,19}$/.test(message.serverId) || BigInt(message.serverId) > 18446744073709551615n || replyToId.startsWith("wechat-native:") && nativeSourceMessageSid(message) !== replyToId) throw Error("WeChat reply target is unavailable or outside this conversation");
2330
+ return { messageId, serverId: message.serverId };
2331
+ }
2332
+
1651
2333
  // src/outbound-media.ts
1652
- async function sendWeChatMedia(cfg, to, text3, mediaUrl, audioAsVoice = false, idempotencyKey) {
2334
+ async function sendWeChatMedia(cfg, to, text3, mediaUrl, audioAsVoice = false, idempotencyKey, options = {}, beforeSend) {
2335
+ validateWeChatMentionSend(options.mentions, { to, text: text3, mediaUrl, audioAsVoice, ...options });
2336
+ const replyToId = parseWeChatReplyTo(options.replyToId);
2337
+ validateWeChatReplySend(replyToId, { text: text3, mediaUrl, audioAsVoice, ...options });
2338
+ validateNativeMediaSendOptions(options, audioAsVoice);
2339
+ if (!mediaUrl && (options.forceDocument || options.videoQuality != null)) throw new Error("WeChat media options require an attachment");
1653
2340
  const account = resolveWeChatAccount(cfg);
1654
2341
  if (!account?.native) throw new Error("No native daemon configured");
1655
2342
  const { client } = await ensureNativeHost(account.native);
1656
- const key = idempotencyKey ?? randomUUID2();
2343
+ const key = idempotencyKey ?? randomUUID3();
1657
2344
  if (!mediaUrl) {
1658
2345
  if (audioAsVoice) throw new Error("Voice sending requires an audio attachment");
1659
- const send = await submitNativeText(client, account.native.accountId, to, text3, key);
2346
+ const original = replyToId ? await client.message(account.native.accountId, nativeReplyMessageId(replyToId, account.native.accountId)) : void 0;
2347
+ const quote = replyToId && original ? nativeReplyReference(original, account.native.accountId, to, replyToId) : void 0;
2348
+ if (original?.recall) throw Error("The WeChat reply target has been recalled; choose another message");
2349
+ await beforeSend?.();
2350
+ const send = await submitNativeText(client, account.native.accountId, to, text3, key, { mentions: options.mentions, quote });
1660
2351
  return nativeOutboundDelivery(
1661
2352
  client,
1662
2353
  account.native.accountId,
@@ -1665,26 +2356,158 @@ async function sendWeChatMedia(cfg, to, text3, mediaUrl, audioAsVoice = false, i
1665
2356
  { sendId: send.id, state: send.state, serverIds: send.serverId ? [send.serverId] : void 0 }
1666
2357
  );
1667
2358
  }
1668
- const result = await sendNativeAttachment(client, account, to, mediaUrl, audioAsVoice, key);
1669
- if (text3) await submitNativeText(client, account.native.accountId, to, text3, createHash5("sha256").update(`${key}\0caption`).digest("hex"));
2359
+ const result = await sendNativeAttachment(client, account, to, mediaUrl, audioAsVoice, key, beforeSend, options);
2360
+ if (text3) {
2361
+ await beforeSend?.();
2362
+ await submitNativeText(client, account.native.accountId, to, text3, createHash6("sha256").update(`${key}\0caption`).digest("hex"));
2363
+ }
1670
2364
  return result;
1671
2365
  }
1672
2366
 
2367
+ // src/native-send-key.ts
2368
+ import { createHash as createHash7 } from "node:crypto";
2369
+ function nativeOutboundKey(queueId, partIndex = 0, attachmentIndex = 0) {
2370
+ return createHash7("sha256").update(JSON.stringify(["wechat-media", queueId, partIndex, attachmentIndex])).digest("hex");
2371
+ }
2372
+
2373
+ // src/outbound-options.ts
2374
+ function nativePayloadMediaOptions(payload) {
2375
+ const value = payload.channelData?.["agent-wechat"];
2376
+ if (value == null) return {};
2377
+ if (typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => key !== "videoQuality" && key !== "mentions")) throw Error("Invalid WeChat send options");
2378
+ const options = value;
2379
+ if (!Object.keys(options).length || options.videoQuality !== void 0 && !["normal", "original"].includes(options.videoQuality)) throw Error("Invalid WeChat media options");
2380
+ return {
2381
+ ...options.videoQuality !== void 0 ? { videoQuality: options.videoQuality } : {},
2382
+ ...options.mentions !== void 0 ? { mentions: parseWeChatTextMentions(options.mentions) } : {}
2383
+ };
2384
+ }
2385
+ var wechatMediaActions = {
2386
+ describeMessageTool: () => ({ actions: ["send"], schema: { actions: ["send"], visibility: "all-configured", properties: {
2387
+ replyTo: { type: "string", minLength: 1, maxLength: 4096, description: "Quote a stored WeChat message in this same chat. Use its exact id from wechat_history, wechat_search or wechat_message, or the current inbound message ID; not a server ID or send/job ID. Text replies only; cannot combine with attachments or mentions. The hub validates the original message." },
2388
+ channelData: { type: "object", description: "WeChat send options: mentions for ordinary group text, or videoQuality for one video attachment.", additionalProperties: true, properties: {
2389
+ "agent-wechat": { type: "object", additionalProperties: false, anyOf: [{ required: ["videoQuality"] }, { required: ["mentions"] }], properties: {
2390
+ videoQuality: { type: "string", enum: ["normal", "original"], description: "WeChat video mode: normal prepares playback; original also retains the unchanged source video. Cannot combine with forceDocument." },
2391
+ mentions: {
2392
+ type: "object",
2393
+ additionalProperties: false,
2394
+ description: "Mention exact members in an ordinary group text message. Get userIds from wechat_group_info, not display names. The hub adds visible @names and metadata. Use all=true only when the sender has permission. Cannot combine with DMs, media, voice, video quality or quoted replies.",
2395
+ properties: {
2396
+ userIds: { type: "array", minItems: 1, maxItems: 128, uniqueItems: true, items: { type: "string", minLength: 1, maxLength: 256, pattern: "^[A-Za-z0-9_@.-]+$" } },
2397
+ all: { type: "boolean", const: true }
2398
+ },
2399
+ oneOf: [{ required: ["userIds"], not: { required: ["all"] } }, { required: ["all"], not: { required: ["userIds"] } }]
2400
+ }
2401
+ } }
2402
+ } }
2403
+ } } }),
2404
+ prepareSendPayload: ({ ctx, to, payload, replyToId }) => {
2405
+ const options = nativePayloadMediaOptions(payload);
2406
+ const forceDocument = ctx.params.forceDocument ?? ctx.params.asDocument;
2407
+ validateWeChatMentionSend(options.mentions, { ...payload, ...options, to, forceDocument, replyToId: replyToId ?? payload.replyToId });
2408
+ const reply = parseWeChatReplyTo(replyToId ?? payload.replyToId);
2409
+ validateWeChatReplySend(reply, { ...payload, ...options, forceDocument });
2410
+ if (options.videoQuality == null && options.mentions == null && reply == null) return void 0;
2411
+ validateNativeMediaSendOptions({ ...options, forceDocument }, payload.audioAsVoice);
2412
+ return payload;
2413
+ }
2414
+ };
2415
+ var NativeMediaPayloadInspectionError = class extends Error {
2416
+ retryable = false;
2417
+ code = "native_media_payload_inspection_required";
2418
+ deliveries;
2419
+ pendingJob;
2420
+ constructor(deliveries, pendingJob) {
2421
+ super("WeChat attachment batch requires inspection; retain completed receipts and do not automatically resend");
2422
+ this.name = "NativeMediaPayloadInspectionError";
2423
+ this.deliveries = deliveries;
2424
+ this.pendingJob = pendingJob;
2425
+ }
2426
+ };
2427
+ function createWeChatMediaHandlers(send = sendWeChatMedia) {
2428
+ const key = (ctx, index = 0) => ctx.deliveryQueueId ? nativeOutboundKey(ctx.deliveryQueueId, ctx.deliveryPartIndex ?? 0, index) : void 0;
2429
+ const guard2 = (ctx) => async () => {
2430
+ ctx.signal?.throwIfAborted();
2431
+ await ctx.onPlatformSendDispatch?.();
2432
+ ctx.signal?.throwIfAborted();
2433
+ ctx.assertDirectAdapterHandoff?.();
2434
+ };
2435
+ const sendPayload = async (ctx) => {
2436
+ const replyToId = parseWeChatReplyTo(ctx.replyToId ?? ctx.payload.replyToId);
2437
+ const options = { ...nativePayloadMediaOptions(ctx.payload), forceDocument: ctx.forceDocument, ...replyToId && { replyToId } };
2438
+ const audioAsVoice = ctx.payload.audioAsVoice ?? ctx.audioAsVoice;
2439
+ validateWeChatMentionSend(options.mentions, {
2440
+ ...ctx.payload,
2441
+ ...options,
2442
+ to: ctx.to,
2443
+ text: ctx.payload.text ?? ctx.text,
2444
+ mediaUrl: ctx.payload.mediaUrl ?? ctx.mediaUrl,
2445
+ audioAsVoice,
2446
+ replyToId: ctx.replyToId ?? ctx.payload.replyToId
2447
+ });
2448
+ validateWeChatReplySend(replyToId, {
2449
+ ...ctx.payload,
2450
+ ...options,
2451
+ text: ctx.payload.text ?? ctx.text,
2452
+ mediaUrl: ctx.payload.mediaUrl ?? ctx.mediaUrl,
2453
+ audioAsVoice
2454
+ });
2455
+ validateNativeMediaSendOptions(options, audioAsVoice);
2456
+ const urls = [...new Set([...ctx.payload.mediaUrls ?? [], ctx.payload.mediaUrl ?? ctx.mediaUrl].filter((url2) => typeof url2 === "string" && !!url2))];
2457
+ if (urls.length > 16 || options.videoQuality != null && urls.length !== 1) throw Error("WeChat video quality requires one attachment per send");
2458
+ const deliveries = [];
2459
+ for (const [index, mediaUrl] of (urls.length ? urls : [void 0]).entries()) {
2460
+ let delivered;
2461
+ try {
2462
+ delivered = await send(ctx.cfg, ctx.to, index === 0 ? ctx.payload.text ?? ctx.text : "", mediaUrl, audioAsVoice, key(ctx, index), options, guard2(ctx));
2463
+ } catch (error) {
2464
+ if (!deliveries.length) throw error;
2465
+ throw new NativeMediaPayloadInspectionError(deliveries, error instanceof NativeMediaJobInspectionError ? { jobId: error.jobId, accountId: error.accountId, threadId: error.threadId, idempotencyKey: error.idempotencyKey } : void 0);
2466
+ }
2467
+ deliveries.push(delivered);
2468
+ if (urls.length > 1) {
2469
+ try {
2470
+ await ctx.onDeliveryResult?.({ channel: "agent-wechat", ...delivered });
2471
+ } catch {
2472
+ throw new NativeMediaPayloadInspectionError(deliveries);
2473
+ }
2474
+ }
2475
+ if (delivered.meta.outcome === "unknown") break;
2476
+ }
2477
+ const first = deliveries[0];
2478
+ return {
2479
+ channel: "agent-wechat",
2480
+ ...first,
2481
+ ...deliveries.length > 1 ? { meta: {
2482
+ ...first.meta,
2483
+ parts: deliveries,
2484
+ retryable: false,
2485
+ ...deliveries.some((part) => part.meta.outcome === "unknown") ? { outcome: "unknown", receiptState: "needs_review" } : {}
2486
+ } } : {}
2487
+ };
2488
+ };
2489
+ return {
2490
+ sendText: async (ctx) => sendPayload({ ...ctx, payload: ctx.payload ?? { text: ctx.text } }),
2491
+ sendMedia: async (ctx) => sendPayload({ ...ctx, payload: ctx.payload ?? { text: ctx.text, mediaUrl: ctx.mediaUrl } }),
2492
+ sendPayload
2493
+ };
2494
+ }
2495
+
1673
2496
  // src/native-monitor.ts
1674
- import { createHash as createHash8 } from "node:crypto";
2497
+ import { createHash as createHash9 } from "node:crypto";
1675
2498
  import { createChannelMessageReplyPipeline } from "openclaw/plugin-sdk/channel-outbound";
1676
2499
  import { resolveStableChannelMessageIngress } from "openclaw/plugin-sdk/channel-ingress-runtime";
1677
2500
 
1678
2501
  // src/native-consumer-state.ts
1679
- import { createHash as createHash6, randomUUID as randomUUID3 } from "node:crypto";
2502
+ import { createHash as createHash8, randomUUID as randomUUID4 } from "node:crypto";
1680
2503
  import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
1681
- import { dirname as dirname2, isAbsolute as isAbsolute2, join as join2 } from "node:path";
2504
+ import { dirname as dirname2, isAbsolute as isAbsolute3, join as join3 } from "node:path";
1682
2505
  var NativeConsumerState = class {
1683
2506
  file;
1684
2507
  value;
1685
2508
  constructor(directory, serverId, accountId) {
1686
- if (!isAbsolute2(directory) || !serverId || !accountId) throw new Error("Native consumer state requires absolute storage and bound server/account identities");
1687
- this.file = join2(directory, `${createHash6("sha256").update(`${serverId}\0${accountId}`).digest("hex")}.json`);
2509
+ if (!isAbsolute3(directory) || !serverId || !accountId) throw new Error("Native consumer state requires absolute storage and bound server/account identities");
2510
+ this.file = join3(directory, `${createHash8("sha256").update(`${serverId}\0${accountId}`).digest("hex")}.json`);
1688
2511
  this.value = { schemaVersion: 1, serverId, accountId, cursor: "0", items: {} };
1689
2512
  if (existsSync(this.file)) {
1690
2513
  const stat = lstatSync(this.file);
@@ -1693,9 +2516,10 @@ var NativeConsumerState = class {
1693
2516
  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");
1694
2517
  for (const [id2, item] of Object.entries(parsed.items)) {
1695
2518
  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");
2519
+ nativeRecallInfo(item.message);
1696
2520
  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");
1697
2521
  if (item.revision != null && (typeof item.revision !== "string" || !item.revision || item.revision.length > 64)) throw Error("Invalid native custody revision; state was preserved");
1698
- item.revision ??= randomUUID3();
2522
+ item.revision ??= randomUUID4();
1699
2523
  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");
1700
2524
  if (item.state === "dispatching") item.state = "needs_review";
1701
2525
  }
@@ -1734,7 +2558,7 @@ var NativeConsumerState = class {
1734
2558
  if (!stat.isDirectory() || stat.isSymbolicLink() || stat.mode & 63) throw new Error("Native consumer directory must be private (0700)");
1735
2559
  const bytes = JSON.stringify(this.value);
1736
2560
  if (Buffer.byteLength(bytes) > 16 * 1024 * 1024) throw new Error("Native custody state is full; intake paused without advancing acknowledgement");
1737
- const temporary = `${this.file}.${randomUUID3()}.tmp`;
2561
+ const temporary = `${this.file}.${randomUUID4()}.tmp`;
1738
2562
  let fd;
1739
2563
  try {
1740
2564
  fd = openSync(temporary, "wx", 384);
@@ -1797,7 +2621,7 @@ var NativeConsumerState = class {
1797
2621
  item.readPending = false;
1798
2622
  }
1799
2623
  }
1800
- this.value.items[message.id] = { message, revision: randomUUID3(), origin, state: nativeRecallInfo(message) ? "ignored" : "received", cursor };
2624
+ this.value.items[message.id] = { message, revision: randomUUID4(), origin, state: nativeRecallInfo(message) ? "ignored" : "received", cursor };
1801
2625
  }
1802
2626
  this.value.cursor = cursor;
1803
2627
  });
@@ -1822,13 +2646,8 @@ var NativeConsumerState = class {
1822
2646
  }
1823
2647
  const key = nativeRecallIdentity(recall.threadId, recall.serverId);
1824
2648
  this.value.recalls ??= {};
1825
- this.value.recalls[key] ??= {
1826
- threadId: recall.threadId,
1827
- serverId: recall.serverId,
1828
- observedAt: recall.observedAt,
1829
- ...recall.messageId ? { messageId: recall.messageId } : {},
1830
- ...recall.recalledAt ? { recalledAt: recall.recalledAt } : {}
1831
- };
2649
+ const remembered = mergeNativeRecall(this.value.recalls[key] ?? recall, recall);
2650
+ this.value.recalls[key] = remembered;
1832
2651
  const affected = /* @__PURE__ */ new Set();
1833
2652
  for (const item of this.items()) {
1834
2653
  if (item.message.threadId !== recall.threadId) continue;
@@ -1836,7 +2655,7 @@ var NativeConsumerState = class {
1836
2655
  const quote = item.message.quote?.serverId === recall.serverId;
1837
2656
  if (!target && !quote) continue;
1838
2657
  affected.add(item.message.id);
1839
- item.message = target ? recalledNativeMessage(item.message, recall) : { ...item.message, quote: void 0 };
2658
+ item.message = target ? recalledNativeMessage(item.message, remembered) : { ...item.message, quote: void 0 };
1840
2659
  if (target) item.groupContext = false;
1841
2660
  item.readPending = false;
1842
2661
  if (["dispatching", "handed_off"].includes(item.state)) item.state = "needs_review";
@@ -1907,7 +2726,7 @@ var NativeConsumerState = class {
1907
2726
  });
1908
2727
  const revisions = items.map((item) => item.revision);
1909
2728
  if (new Set(items.map((item) => item.message.threadId)).size !== 1) throw new Error("Prepared input manifest crosses threads");
1910
- const manifestHash = createHash6("sha256").update(JSON.stringify({
2729
+ const manifestHash = createHash8("sha256").update(JSON.stringify({
1911
2730
  accountId: this.value.accountId,
1912
2731
  messageIds: exact,
1913
2732
  dispatchManifests: items.map((item) => item.dispatchManifest ?? null)
@@ -1916,7 +2735,7 @@ var NativeConsumerState = class {
1916
2735
  const runId = typeof args[0] === "string" ? args[0] : args[0]?.runId;
1917
2736
  if (typeof runId !== "string" || !runId || runId.length > 256) throw new Error("Prepared run callback has no valid runId");
1918
2737
  this.mutate(() => {
1919
- const currentHash = createHash6("sha256").update(JSON.stringify({
2738
+ const currentHash = createHash8("sha256").update(JSON.stringify({
1920
2739
  accountId: this.value.accountId,
1921
2740
  messageIds: exact,
1922
2741
  dispatchManifests: exact.map((id2) => this.value.items[id2]?.dispatchManifest ?? null)
@@ -1934,197 +2753,6 @@ var NativeConsumerState = class {
1934
2753
  }
1935
2754
  };
1936
2755
 
1937
- // src/native-prepared-boundary.ts
1938
- import { createHash as createHash7, randomUUID as randomUUID4 } from "node:crypto";
1939
- import { basename as basename2, isAbsolute as isAbsolute3 } from "node:path";
1940
- var pending = /* @__PURE__ */ new Map();
1941
- var enabled = false;
1942
- var digest = (value) => createHash7("sha256").update(value).digest("hex");
1943
- function prune() {
1944
- for (const [id2, item] of pending) if (item.expires < Date.now()) pending.delete(id2);
1945
- }
1946
- function nativeSourceMessageSid(message) {
1947
- return `wechat-native:${message.accountId}:${message.id}:${digest(JSON.stringify([message.threadId, message.serverId ?? null]))}`;
1948
- }
1949
- function nativeDispatchManifest(params) {
1950
- const history = params.history ?? [];
1951
- if (history.length > 200 || history.some((message) => message.accountId !== params.message.accountId || message.threadId !== params.message.threadId || message.id === params.message.id)) throw Error("Invalid native history manifest");
1952
- const assets = Object.freeze((params.assets ?? []).map((asset) => {
1953
- if (typeof asset.id !== "string" || !asset.id || asset.id.length > 2048 || !/^[a-f0-9]{64}$/.test(asset.sha256) || !Number.isSafeInteger(asset.byteLength) || asset.byteLength < 1 || asset.byteLength > 128 * 1024 * 1024 || typeof asset.path !== "string" || !isAbsolute3(asset.path) || asset.path.length > 4096 || typeof asset.mime !== "string" || asset.mime.length > 128 || !/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/.test(asset.mime) || !["image", "audio", "video", "file"].includes(asset.kind) || !["model_image", "file_reference"].includes(asset.role) || asset.role === "model_image" && (asset.kind !== "image" || !asset.mime.startsWith("image/") || !asset.runtimeMedia) || !["trigger", "history"].includes(asset.contextRole) || asset.sourceMessageId != null && (typeof asset.sourceMessageId !== "string" || !asset.sourceMessageId || asset.sourceMessageId.length > 8192 || ![params.message, ...history].some((message) => message.id === asset.messageId && message.type === 49 && message.appMessageType === 57 && message.quote?.type === 3)) || asset.contextRole === "history" && !history.some((message) => message.id === asset.messageId)) throw Error("Invalid native supplied asset manifest");
1954
- return Object.freeze({ ...asset });
1955
- }));
1956
- const messageSid = nativeSourceMessageSid(params.message);
1957
- const manifest = {
1958
- schemaVersion: 2,
1959
- runId: randomUUID4(),
1960
- accountId: params.message.accountId,
1961
- messageIds: Object.freeze([params.message.id]),
1962
- messageSid,
1963
- threadId: params.message.threadId,
1964
- senderId: params.message.senderId ?? "",
1965
- sessionKey: params.sessionKey,
1966
- agentId: params.agentId,
1967
- channelAccountId: params.channelAccountId,
1968
- inputBodySha256: digest(params.inputBody),
1969
- newInputs: Object.freeze([Object.freeze({
1970
- id: params.message.id,
1971
- version: params.message.version ?? "",
1972
- contentSha256: digest(JSON.stringify([
1973
- params.message.id,
1974
- params.message.version,
1975
- params.message.senderId,
1976
- params.message.type,
1977
- params.message.body,
1978
- params.message.mentions,
1979
- params.message.serverId,
1980
- params.message.appMessageType,
1981
- params.message.quote,
1982
- params.message.link
1983
- ])),
1984
- role: "trigger"
1985
- })]),
1986
- ...history.length ? { historyInputs: Object.freeze(history.map((message) => Object.freeze({
1987
- id: message.id,
1988
- version: message.version ?? "",
1989
- contentSha256: digest(JSON.stringify([message.id, message.version, message.senderId, message.type, message.body, message.mentions, message.serverId, message.appMessageType, message.quote, message.link])),
1990
- role: "history"
1991
- }))) } : {},
1992
- assets,
1993
- policySha256: digest(JSON.stringify(params.policy ?? null)),
1994
- // Exact released 2026.10.2 source-turn identity. Requiring it in the later
1995
- // snapshot prevents an identical older image/body from proving this input.
1996
- hostSourceTurnId: `channel-user:v1:${digest(JSON.stringify(["agent-wechat", params.channelAccountId, `wechat:${params.message.threadId}`, messageSid]))}`
1997
- };
1998
- return Object.freeze({ ...manifest, manifestSha256: digest(JSON.stringify(manifest)) });
1999
- }
2000
- function trackNativePreparedInput(manifest, record) {
2001
- prune();
2002
- if (!enabled || pending.size >= 1024) return;
2003
- pending.set(manifest.runId, { manifest, record, expires: Date.now() + 15 * 60 * 1e3 });
2004
- }
2005
- function invalidateNativePreparedInputs(accountId, messageIds) {
2006
- const ids = new Set(messageIds);
2007
- for (const [runId, item] of pending) {
2008
- if (item.manifest.accountId === accountId && [
2009
- ...item.manifest.messageIds,
2010
- ...(item.manifest.historyInputs ?? []).map((input) => input.id),
2011
- ...item.manifest.assets.flatMap((asset) => asset.sourceMessageId ? [asset.sourceMessageId] : [])
2012
- ].some((id2) => ids.has(id2))) pending.delete(runId);
2013
- }
2014
- }
2015
- function promptMatches(prompt, manifest) {
2016
- if (typeof prompt !== "string" || Buffer.byteLength(prompt) > 1024 * 1024) return false;
2017
- const text3 = prompt.replace(/^\[[^\]\r\n]{1,96}\] /, "");
2018
- const candidates = [text3];
2019
- const sender = `Conversation info: \u27E6openclaw:ctx\u27E7
2020
- \`\`\`json
2021
- ${JSON.stringify({ sender: { id: manifest.senderId } })}
2022
- \`\`\`
2023
-
2024
- `;
2025
- if (manifest.threadId.endsWith("@chatroom") && text3.startsWith(sender)) candidates.push(text3.slice(sender.length));
2026
- return candidates.some((text4) => normalizedPromptMatches(text4, manifest));
2027
- }
2028
- function normalizedPromptMatches(text3, manifest) {
2029
- const runtimeAssets = manifest.assets.filter((asset) => asset.runtimeMedia);
2030
- if (runtimeAssets.length) {
2031
- if (runtimeAssets.length !== 1) return false;
2032
- const asset = runtimeAssets[0];
2033
- const header = /^\[media attached: ([^\r\n]+) \(([^)\r\n]+)\) \| (media:\/\/inbound\/[^\]\r\n]+)\]\n/.exec(text3);
2034
- if (!header || !isAbsolute3(header[1]) || basename2(header[1]) !== `input-${basename2(asset.path)}` || header[2] !== asset.mime || header[3] !== `media://inbound/${basename2(asset.path)}`) return false;
2035
- text3 = text3.slice(header[0].length);
2036
- if (asset.kind === "video") text3 = text3.replace(/\n\n\[Video attachment not analyzed: video understanding is disabled\]$/, "");
2037
- }
2038
- return digest(text3) === manifest.inputBodySha256;
2039
- }
2040
- function currentMessageFacts(messages) {
2041
- if (!Array.isArray(messages) || messages.length > 1e3) return [];
2042
- const facts = [];
2043
- for (const message of messages) {
2044
- if (message?.role !== "custom" || message.customType !== "openclaw.runtime-context" || message.details?.source !== "openclaw-runtime-context" || message.details?.runtimeContextCarrier !== true) continue;
2045
- const fragments = message.details?.fragments;
2046
- if (!Array.isArray(fragments) || fragments.length > 64) return [];
2047
- for (const fragment of fragments) {
2048
- if (fragment?.kind !== "conversation-data" || typeof fragment.text !== "string" || fragment.text.length > 65536) continue;
2049
- const match = /^Conversation info: ⟦openclaw:ctx⟧\n```json\n([^\n]+)\n```$/.exec(fragment.text);
2050
- if (!match) continue;
2051
- try {
2052
- const value = JSON.parse(match[1]);
2053
- if (typeof value.message_id === "string" && typeof value.chat_id === "string") facts.push({ messageId: value.message_id, chatId: value.chat_id });
2054
- } catch {
2055
- }
2056
- }
2057
- }
2058
- return facts;
2059
- }
2060
- function matchingContext(ctx, manifest) {
2061
- return ctx?.runId === manifest.runId && ctx?.sessionKey === manifest.sessionKey && ctx?.agentId === manifest.agentId;
2062
- }
2063
- function observeNativePreparedInput(event, ctx) {
2064
- prune();
2065
- const item = pending.get(event?.runId);
2066
- if (!item) return;
2067
- item.proof = void 0;
2068
- item.started = false;
2069
- const m = item.manifest;
2070
- if (!matchingContext(ctx, m) || ctx?.channel !== "agent-wechat" || ctx?.accountId !== m.channelAccountId || ctx?.chatId !== (m.threadId.endsWith("@chatroom") ? m.threadId : `wechat:${m.threadId}`) || ctx?.sessionId !== event.sessionId || typeof event.sessionId !== "string" || !event.sessionId || typeof event.provider !== "string" || typeof event.model !== "string" || !promptMatches(event.prompt, m)) return;
2071
- const facts = currentMessageFacts(event.historyMessages);
2072
- if (facts.length !== 1 || facts[0].messageId !== m.messageSid || facts[0].chatId !== `wechat:${m.threadId}`) return;
2073
- if (m.assets.length && event.imagesCount !== m.assets.filter((asset) => asset.role === "model_image").length) return;
2074
- item.proof = { sessionId: event.sessionId, provider: event.provider, model: event.model };
2075
- }
2076
- function observeNativeModelCall(event, ctx) {
2077
- prune();
2078
- const item = pending.get(event?.runId);
2079
- if (!item?.proof) return;
2080
- const m = item.manifest, proof = item.proof;
2081
- if (!matchingContext(ctx, m) || event.sessionKey !== m.sessionKey || event.sessionId !== proof.sessionId || ctx?.sessionId !== proof.sessionId || event.provider !== proof.provider || event.model !== proof.model || typeof event.callId !== "string" || !event.callId) return;
2082
- item.started = true;
2083
- if (!m.assets.length) {
2084
- item.record(m.runId);
2085
- pending.delete(m.runId);
2086
- }
2087
- }
2088
- function observeNativeAgentEnd(event, ctx) {
2089
- prune();
2090
- const item = pending.get(event?.runId);
2091
- if (!item?.proof || !item.started || !item.manifest.assets.length) return;
2092
- const m = item.manifest, proof = item.proof;
2093
- if (!matchingContext(ctx, m) || ctx?.sessionId !== proof.sessionId || ctx?.channel !== "agent-wechat" || ctx?.accountId !== m.channelAccountId || ctx?.chatId !== (m.threadId.endsWith("@chatroom") ? m.threadId : `wechat:${m.threadId}`) || ctx?.modelProviderId !== proof.provider || ctx?.modelId !== proof.model || !Array.isArray(event.messages) || event.messages.length > 1e3) return;
2094
- const user = event.messages.findLast((message) => message?.role === "user");
2095
- if (user?.idempotencyKey !== m.hostSourceTurnId) return;
2096
- const blocks = typeof user.content === "string" ? [{ type: "text", text: user.content }] : user.content;
2097
- if (!Array.isArray(blocks) || blocks.length > 32) return;
2098
- if (blocks.some((block) => !["text", "image"].includes(block?.type) || block.type === "text" && typeof block.text !== "string")) return;
2099
- const text3 = blocks.filter((block) => block?.type === "text").map((block) => block.text).join("\n");
2100
- if (!promptMatches(text3, m)) return;
2101
- const images = blocks.filter((block) => block?.type === "image");
2102
- const expectedImages = m.assets.filter((asset) => asset.role === "model_image");
2103
- if (images.length !== expectedImages.length) return;
2104
- for (const [index, asset] of expectedImages.entries()) {
2105
- const image = images[index];
2106
- if (image.mimeType !== asset.mime || typeof image.data !== "string" || image.data.length > 8 * 1024 * 1024 || image.data.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(image.data)) return;
2107
- const bytes = Buffer.from(image.data, "base64");
2108
- if (bytes.length !== asset.byteLength || digest(bytes) !== asset.sha256) return;
2109
- }
2110
- if (m.assets.some((asset) => asset.role === "file_reference" && !text3.includes(asset.path))) return;
2111
- item.record(m.runId);
2112
- pending.delete(m.runId);
2113
- }
2114
- function registerNativePreparedBoundary(api) {
2115
- const access2 = api.config?.plugins?.entries?.["agent-wechat"]?.hooks?.allowConversationAccess === true;
2116
- enabled = access2;
2117
- if (access2) {
2118
- api.on("llm_input", observeNativePreparedInput);
2119
- api.on("model_call_started", observeNativeModelCall);
2120
- api.on("agent_end", observeNativeAgentEnd);
2121
- }
2122
- return () => {
2123
- enabled = false;
2124
- pending.clear();
2125
- };
2126
- }
2127
-
2128
2756
  // src/native-history.ts
2129
2757
  import { buildHistoryContextFromEntries, buildInboundHistoryFromEntries, DEFAULT_GROUP_HISTORY_LIMIT } from "openclaw/plugin-sdk/reply-history";
2130
2758
  function nativeGroupHistoryLimit(cfg) {
@@ -2214,7 +2842,7 @@ function buildNativeContext(history, message, prepared) {
2214
2842
 
2215
2843
  // src/native-monitor.ts
2216
2844
  function nativeWasMentioned(message) {
2217
- return message.mentions?.state === "known" && message.mentions.self === true;
2845
+ return message.mentions?.state === "known" && (message.mentions.self === true || message.mentions.all === true);
2218
2846
  }
2219
2847
  async function projectNativeRead(client, accountId, state) {
2220
2848
  const pending2 = state.items().filter((value) => value.readPending);
@@ -2277,17 +2905,17 @@ async function recheckNativeInputs(client, state, messages) {
2277
2905
  throw new NativeInputInvalidated();
2278
2906
  }
2279
2907
  if (message.quote) {
2280
- const quote = await client.quotedMessage(message.accountId, message.id);
2281
- if (quote.accountId !== message.accountId || quote.threadId !== message.threadId || quote.messageId !== message.id) throw Error("Native quote identity changed");
2282
- if (quote.state === "recalled" || quote.message && nativeRecallInfo(quote.message)) {
2908
+ const quote = current.quote;
2909
+ if (quote?.state === "recalled") {
2283
2910
  const affected = state.acceptRecall(state.cursor, {
2284
2911
  threadId: message.threadId,
2285
2912
  serverId: message.quote.serverId,
2286
- observedAt: quote.message && nativeRecallInfo(quote.message)?.observedAt || (/* @__PURE__ */ new Date()).toISOString()
2913
+ observedAt: (/* @__PURE__ */ new Date()).toISOString()
2287
2914
  });
2288
2915
  invalidateNativePreparedInputs(message.accountId, affected);
2289
2916
  throw new NativeInputInvalidated();
2290
2917
  }
2918
+ if (!quote || !sameEmbeddedQuote(message.quote, quote)) throw Error("Native embedded quote changed; delivery held for review");
2291
2919
  }
2292
2920
  if (!state.isCurrent(message)) throw new NativeInputInvalidated();
2293
2921
  }
@@ -2310,6 +2938,10 @@ async function dispatchNativeMessageInput(params, revision) {
2310
2938
  const custody = state.get(message.id);
2311
2939
  if (state.isRecalled(message)) return "ignored";
2312
2940
  if (!custody || custody.state !== "received" || !state.isCurrent(message, revision)) return "needs_review";
2941
+ if (message.type === 49 && message.appMessageType === 74) {
2942
+ state.update(message.id, { state: "ignored" }, revision);
2943
+ return "ignored";
2944
+ }
2313
2945
  if (custody.origin !== "live" || message.direction !== "incoming" || ![1, 3, 34, 43, 47, 49].includes(message.type) || message.type === 1 && !message.body || !message.senderId) {
2314
2946
  state.update(message.id, { state: "ignored" }, revision);
2315
2947
  return "ignored";
@@ -2444,7 +3076,7 @@ async function dispatchNativeMessageInput(params, revision) {
2444
3076
  });
2445
3077
  assertCurrent();
2446
3078
  state.beginDispatch(message.id, dispatchManifest, buffered.map((item) => item.message.id));
2447
- const callback = readPolicy !== "on_inbound" && (message.type === 1 || message.type === 49 && message.appMessageType === 19 && !!message.body || message.type === 49 && [3, 4, 5].includes(message.appMessageType ?? 0) && !!message.link || preparedMedia.quote?.type === 1 && ["resolved", "embedded"].includes(preparedMedia.quote.state) || preparedMedia.attachment?.status === "ready" && preparedMedia.suppliedAssets?.length) ? state.preparedCallback([message.id], readPolicy) : void 0;
3079
+ const callback = readPolicy !== "on_inbound" && (message.type === 1 || message.type === 49 && [1, 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;
2448
3080
  if (callback) trackNativePreparedInput(dispatchManifest, callback);
2449
3081
  const beforeSend = () => recheck([message, ...admitted]);
2450
3082
  let failed = false;
@@ -2459,17 +3091,19 @@ async function dispatchNativeMessageInput(params, revision) {
2459
3091
  params.signal?.throwIfAborted();
2460
3092
  if (state.get(message.id)?.invalidatedByRecall) return;
2461
3093
  await beforeSend();
3094
+ const options = nativePayloadMediaOptions(payload);
3095
+ validateWeChatMentionSend(options.mentions, { ...payload, ...options, to: message.threadId });
2462
3096
  const urls = payload.mediaUrls?.length ? payload.mediaUrls : payload.mediaUrl ? [payload.mediaUrl] : [];
2463
3097
  if (urls.length > 16) throw new Error("Native reply media count exceeds its bound");
2464
3098
  if (payload.audioAsVoice && !urls.length) throw new Error("Native voice reply requires an audio attachment");
2465
3099
  for (const url2 of urls) {
2466
- const key = createHash8("sha256").update(`${dispatchManifest.messageSid}\0${delivery++}`).digest("hex");
3100
+ const key = createHash9("sha256").update(`${dispatchManifest.messageSid}\0${delivery++}`).digest("hex");
2467
3101
  await sendNativeAttachment(client, account, message.threadId, url2, payload.audioAsVoice === true, key, beforeSend);
2468
3102
  }
2469
3103
  if (payload.text) {
2470
3104
  await beforeSend();
2471
- const key = createHash8("sha256").update(`${dispatchManifest.messageSid}\0${delivery++}`).digest("hex");
2472
- await submitNativeText(client, account.native.accountId, message.threadId, payload.text, key);
3105
+ const key = createHash9("sha256").update(`${dispatchManifest.messageSid}\0${delivery++}`).digest("hex");
3106
+ await submitNativeText(client, account.native.accountId, message.threadId, payload.text, key, { mentions: options.mentions });
2473
3107
  }
2474
3108
  if (urls.length || payload.text) params.onDelivered?.();
2475
3109
  },
@@ -2644,104 +3278,199 @@ async function startNativeMonitor(opts) {
2644
3278
 
2645
3279
  // src/native-login.ts
2646
3280
  import { randomUUID as randomUUID5 } from "node:crypto";
3281
+ import { setTimeout as delay } from "node:timers/promises";
2647
3282
  var operations = /* @__PURE__ */ new Map();
2648
3283
  var terminal = /* @__PURE__ */ new Set(["succeeded", "failed", "cancelled", "expired", "rejected", "needs_login"]);
2649
- async function nativeLoginStart(account, options = {}) {
3284
+ function guard(access2) {
3285
+ access2.signal?.throwIfAborted();
3286
+ access2.assertCurrent?.();
3287
+ }
3288
+ function validateOperation(operation, accountId, operationId) {
3289
+ if (operation.accountId !== accountId || operation.kind !== "login" || operationId && operation.id !== operationId) throw Error("Native login operation identity does not match its account");
3290
+ }
3291
+ async function nativeLoginStart(account, options = {}, access2 = {}) {
3292
+ guard(access2);
2650
3293
  const native = account.native;
2651
- const { client } = await ensureNativeHost(native);
3294
+ const { client } = await (access2.host ?? ensureNativeHost)(native);
3295
+ guard(access2);
3296
+ const configurationKey = nativeConfigurationKey(native);
2652
3297
  const existing = operations.get(account.accountId);
2653
- if (existing && existing.accountId === native.accountId && !options.force) {
2654
- existing.operation = await client.operation(native.accountId, existing.operation.id);
2655
- if (!terminal.has(existing.operation.state)) return nativeLoginWait(account.accountId, Math.min(options.timeoutMs ?? 3e4, 3e4), true);
2656
- }
3298
+ if (existing && existing.configurationKey === configurationKey) {
3299
+ const refreshed = await client.operation(native.accountId, existing.operation.id);
3300
+ guard(access2);
3301
+ validateOperation(refreshed, native.accountId, existing.operation.id);
3302
+ existing.operation = refreshed;
3303
+ existing.client = client;
3304
+ if (!terminal.has(existing.operation.state)) return nativeLoginWait(account, Math.min(options.timeoutMs ?? 3e4, 3e4), true, access2);
3305
+ }
3306
+ guard(access2);
2657
3307
  const operation = await client.login(native.accountId, {
2658
3308
  allowQr: true,
2659
3309
  forceQr: options.force === true,
2660
3310
  timeoutSeconds: Math.max(10, Math.min(900, Math.ceil((options.timeoutMs ?? 3e5) / 1e3))),
2661
3311
  computerName: "agent-wechat"
2662
- });
2663
- operations.set(account.accountId, { client, accountId: native.accountId, operation });
2664
- return nativeLoginWait(account.accountId, Math.min(options.timeoutMs ?? 3e4, 3e4), true);
3312
+ }, randomUUID5());
3313
+ validateOperation(operation, native.accountId);
3314
+ operations.set(account.accountId, { client, accountId: native.accountId, configurationKey, operation });
3315
+ guard(access2);
3316
+ return nativeLoginWait(account, Math.min(options.timeoutMs ?? 3e4, 3e4), true, access2);
2665
3317
  }
2666
- async function nativeLoginWait(accountId, timeoutMs = 3e4, stopAtQr = false) {
2667
- const active2 = operations.get(accountId);
2668
- if (!active2) return { connected: false, message: "No native login operation; start login first" };
3318
+ async function nativeLoginWait(account, timeoutMs = 3e4, stopAtQr = false, access2 = {}) {
3319
+ guard(access2);
3320
+ const active2 = operations.get(account.accountId);
3321
+ if (!active2 || active2.configurationKey !== nativeConfigurationKey(account.native)) return { connected: false, state: "idle", message: "No native login operation; start login first" };
2669
3322
  const deadline = Date.now() + Math.max(1e3, Math.min(timeoutMs, 3e5));
2670
3323
  while (Date.now() < deadline) {
2671
- active2.operation = await active2.client.operation(active2.accountId, active2.operation.id);
3324
+ guard(access2);
3325
+ const refreshed = await active2.client.operation(active2.accountId, active2.operation.id);
3326
+ guard(access2);
3327
+ validateOperation(refreshed, active2.accountId, active2.operation.id);
3328
+ active2.operation = refreshed;
2672
3329
  const state = active2.operation.state;
2673
- if (state === "succeeded") return { connected: true, message: "Native login succeeded" };
2674
- if (terminal.has(state)) return { connected: false, message: `Native login ${state}` };
3330
+ const result = { connected: state === "succeeded", state, operationId: active2.operation.id };
3331
+ if (state === "succeeded") return { ...result, message: "Native login succeeded" };
3332
+ if (terminal.has(state)) return { ...result, message: `Native login ${state}` };
3333
+ if (stopAtQr && state === "awaiting_approval") return { ...result, message: "Approve native login on your phone" };
2675
3334
  if (stopAtQr && active2.operation.result?.qrAvailable === true) {
2676
3335
  const generation = active2.operation.result?.qrGeneration;
2677
3336
  const png = await active2.client.qr(active2.accountId, active2.operation.id, typeof generation === "number" ? generation : void 0);
2678
- return { connected: false, qrDataUrl: `data:image/png;base64,${Buffer.from(png).toString("base64")}`, message: "Scan the white-background native QR and approve login" };
3337
+ guard(access2);
3338
+ return { ...result, qrDataUrl: `data:image/png;base64,${Buffer.from(png).toString("base64")}`, message: "Scan the white-background native QR and approve login" };
2679
3339
  }
2680
- if (stopAtQr && state === "awaiting_approval") return { connected: false, message: "Approve native login on your phone" };
2681
- await new Promise((resolve) => setTimeout(resolve, 500));
3340
+ await delay(Math.min(500, Math.max(0, deadline - Date.now())), void 0, { signal: access2.signal });
2682
3341
  }
2683
- return { connected: false, message: "Native login remains pending; wait on the same operation rather than starting a replacement" };
2684
- }
2685
- async function sendNativeText(account, threadId2, text3, key = randomUUID5()) {
2686
- const native = account.native;
2687
- const { client } = await ensureNativeHost(native);
2688
- const send = await submitNativeText(client, native.accountId, threadId2, text3, key);
2689
- return nativeOutboundDelivery(
2690
- client,
2691
- native.accountId,
2692
- threadId2,
2693
- send.localMessageId ? [send.localMessageId] : [],
2694
- { sendId: send.id, state: send.state, serverIds: send.serverId ? [send.serverId] : void 0 }
2695
- );
3342
+ guard(access2);
3343
+ return { connected: false, state: active2.operation.state, operationId: active2.operation.id, message: "Native login remains pending; wait on the same operation rather than starting a replacement" };
2696
3344
  }
2697
- function createNativeLoginTool(account) {
3345
+ function createNativeLoginTool(account, dependencies = {}) {
3346
+ const actions = ["status", "start", "wait", "disconnect", "logout", "forget"];
3347
+ const configurationKey = nativeConfigurationKey(account.native);
2698
3348
  return {
2699
3349
  label: "WeChat Login",
2700
3350
  name: "wechat_login",
2701
- description: "Inspect/start native login, disconnect retaining trust, or request durable logout. Logout commits local inhibition and reports its native server outcome separately; it does not promise saved-device revocation. Explicitly confirmed forget removes local authentication while retaining history. A QR is returned as an image when available.",
2702
- parameters: { type: "object", properties: { action: { type: "string", enum: ["status", "start", "disconnect", "logout", "forget"] }, force: { type: "boolean" }, confirm: { type: "boolean" } }, required: ["action"] },
2703
- execute: async (_id, params) => {
3351
+ catalogMode: "direct-only",
3352
+ description: "Check WeChat status, start or resume native login, or wait for the same login operation. Show the returned QR image to the user to scan and approve on their phone; do not generate a replacement QR. Repeated start reuses an active operation. For a new operation, force uses QR instead of saved trust. timeoutMs bounds the wait. Disconnect retains saved trust. Logout reports its durable native outcome; it does not promise saved-device revocation. Forget requires confirm=true and removes local authentication while retaining history.",
3353
+ parameters: { type: "object", additionalProperties: false, properties: {
3354
+ action: { type: "string", enum: actions },
3355
+ force: { type: "boolean", description: "With start, use QR instead of saved trust for a new login. An active login is still reused." },
3356
+ timeoutMs: { type: "integer", minimum: 1e3, maximum: 3e5, description: "Wait bound in milliseconds; defaults to 30000. Start returns as soon as a QR is available." },
3357
+ confirm: { type: "boolean", description: "Required true for forget." }
3358
+ }, required: ["action"] },
3359
+ execute: async (_id, params, signal) => {
3360
+ if (!params || typeof params !== "object" || Array.isArray(params)) throw Error("Expected login arguments");
2704
3361
  const args = params;
2705
- const native = account.native;
2706
- const { client } = await ensureNativeHost(native);
2707
- if (args.action === "start") {
2708
- const result2 = await nativeLoginStart(account, { force: args.force });
3362
+ if (Object.keys(args).some((key) => !["action", "force", "timeoutMs", "confirm"].includes(key)) || !actions.includes(args.action) || args.force !== void 0 && typeof args.force !== "boolean" || args.confirm !== void 0 && typeof args.confirm !== "boolean" || args.timeoutMs !== void 0 && (!Number.isSafeInteger(args.timeoutMs) || args.timeoutMs < 1e3 || args.timeoutMs > 3e5)) throw Error("Invalid native login arguments");
3363
+ if (args.action === "forget" && args.confirm !== true) throw Error("Forgetting native credentials requires confirm=true");
3364
+ const access2 = { host: dependencies.host, signal, assertCurrent: () => {
3365
+ dependencies.context?.assertInvocationCurrent?.();
3366
+ if (!dependencies.context) return;
3367
+ const context = dependencies.context;
3368
+ const config = context.getRuntimeConfig?.() ?? context.runtimeConfig ?? context.config;
3369
+ const current = config && resolveWeChatAccount(config);
3370
+ if (!current?.enabled || !current.native || nativeConfigurationKey(current.native) !== configurationKey) throw Error("Native login configuration changed; invoke the tool again");
3371
+ } };
3372
+ guard(access2);
3373
+ if (args.action === "start" || args.action === "wait") {
3374
+ const result2 = args.action === "start" ? await nativeLoginStart(account, { force: args.force, timeoutMs: args.timeoutMs }, access2) : await nativeLoginWait(account, args.timeoutMs, false, access2);
2709
3375
  const content = [{ type: "text", text: result2.message }];
2710
3376
  if (result2.qrDataUrl) content.push({ type: "image", data: result2.qrDataUrl.split(",")[1], mimeType: "image/png" });
2711
- return { content, details: { connected: result2.connected } };
3377
+ return { content, details: { connected: result2.connected, state: result2.state, operationId: result2.operationId } };
2712
3378
  }
3379
+ const native = account.native;
3380
+ const { client } = await (access2.host ?? ensureNativeHost)(native);
3381
+ guard(access2);
2713
3382
  const result = args.action === "status" ? await client.account(native.accountId) : args.action === "disconnect" ? await client.disconnect(native.accountId) : args.action === "logout" ? await client.logout(native.accountId, randomUUID5()) : args.action === "forget" && args.confirm === true ? await client.forgetCredentials(native.accountId, randomUUID5(), true) : (() => {
2714
3383
  throw new Error("Unknown native login action");
2715
3384
  })();
3385
+ if (args.action !== "status") operations.delete(account.accountId);
3386
+ guard(access2);
2716
3387
  return { content: [{ type: "text", text: JSON.stringify(result) }], details: result };
2717
3388
  }
2718
3389
  };
2719
3390
  }
3391
+ function registerNativeLoginTool(api) {
3392
+ api.registerTool({ contextVersion: 2, create: (context) => {
3393
+ const config = context.getRuntimeConfig?.() ?? context.runtimeConfig ?? context.config;
3394
+ const account = config && resolveWeChatAccount(config);
3395
+ return account?.enabled && account.native ? [createNativeLoginTool(account, { context })] : [];
3396
+ } }, { names: ["wechat_login"] });
3397
+ }
2720
3398
 
2721
- // src/channel.ts
2722
- async function sendWeChatText(cfg, to, text3) {
2723
- const account = resolveWeChatAccount(cfg);
2724
- if (!account?.serverUrl) throw new Error("No native daemon configured");
2725
- return sendNativeText(account, to, text3);
3399
+ // src/native-outbound-recovery.ts
3400
+ import { createMessageReceiptFromOutboundResults } from "openclaw/plugin-sdk/channel-outbound";
3401
+ function createWeChatDurableFinal(host2 = ensureNativeHost) {
3402
+ return {
3403
+ capabilities: { text: true, media: true, payload: true, replyTo: true, messageSendingHooks: true, reconcileUnknownSend: true },
3404
+ automaticUnknownSendReconciliation: true,
3405
+ reconcileUnknownSendKinds: { text: true, payload: true },
3406
+ reconcileUnknownSend: async (ctx) => {
3407
+ const unresolved = {
3408
+ status: "unresolved",
3409
+ retryable: false,
3410
+ error: "Inspect the original WeChat send receipt; do not send again with a new key."
3411
+ };
3412
+ try {
3413
+ if (ctx.channel !== "agent-wechat" || !ctx.queueId || ctx.payloads.length !== 1) return unresolved;
3414
+ const payload = ctx.payloads[0];
3415
+ const options = nativePayloadMediaOptions(payload);
3416
+ const replyToId = parseWeChatReplyTo(ctx.effectiveReplyToId ?? ctx.replyToId ?? payload.replyToId);
3417
+ if (payload.mediaUrl || payload.mediaUrls?.length || payload.audioAsVoice || payload.videoAsNote || payload.location || payload.presentation || payload.interactive || options.videoQuality != null || typeof payload.text !== "string" || !payload.text.trim()) return unresolved;
3418
+ validateWeChatMentionSend(options.mentions, { ...payload, to: ctx.to, replyToId });
3419
+ validateWeChatReplySend(replyToId, payload);
3420
+ const account = resolveWeChatAccount(ctx.cfg);
3421
+ if (!account?.enabled || !account.native || ctx.accountId && ctx.accountId !== account.accountId) return unresolved;
3422
+ const configurationKey = nativeConfigurationKey(account.native);
3423
+ const current = () => {
3424
+ const selected = resolveWeChatAccount(ctx.cfg);
3425
+ return selected?.enabled && selected.native && nativeConfigurationKey(selected.native) === configurationKey;
3426
+ };
3427
+ const { client } = await host2(account.native);
3428
+ if (!current()) return unresolved;
3429
+ const intent = await client.sendByKey(account.native.accountId, nativeOutboundKey(ctx.queueId));
3430
+ if (!current() || !("destination" in intent) || intent.accountId !== account.native.accountId || intent.destination !== ctx.to || !["accepted", "sent", "server_accepted"].includes(intent.state) || !intent.localMessageId || !intent.serverId) return unresolved;
3431
+ if (!options.mentions) {
3432
+ const message = await client.message(account.native.accountId, intent.localMessageId);
3433
+ if (!current() || message.body !== payload.text) return unresolved;
3434
+ if (replyToId) {
3435
+ const original = await client.message(account.native.accountId, nativeReplyMessageId(replyToId, account.native.accountId));
3436
+ const quote = nativeReplyReference(original, account.native.accountId, ctx.to, replyToId);
3437
+ if (!current() || message.type !== 49 || message.appMessageType !== 57 || message.quote?.serverId !== quote.serverId) return unresolved;
3438
+ } else if (message.type !== 1 || message.quote) return unresolved;
3439
+ }
3440
+ const delivery = await nativeOutboundDelivery(
3441
+ client,
3442
+ account.native.accountId,
3443
+ ctx.to,
3444
+ [intent.localMessageId],
3445
+ { sendId: intent.id, state: intent.state, serverIds: [intent.serverId] }
3446
+ );
3447
+ if (!current() || delivery.meta.outcome !== "sent" || !delivery.messageId) return unresolved;
3448
+ const receipt = createMessageReceiptFromOutboundResults({
3449
+ results: [{ channel: "agent-wechat", ...delivery }],
3450
+ kind: "text",
3451
+ threadId: ctx.threadId == null ? void 0 : String(ctx.threadId)
3452
+ });
3453
+ return { status: "sent", receipt, messageId: delivery.messageId };
3454
+ } catch {
3455
+ return unresolved;
3456
+ }
3457
+ }
3458
+ };
2726
3459
  }
3460
+
3461
+ // src/channel.ts
3462
+ var mediaHandlers = createWeChatMediaHandlers();
2727
3463
  var wechatMessageAdapter = createChannelMessageAdapterFromOutbound({
2728
3464
  id: "agent-wechat",
2729
3465
  capabilities: {
2730
3466
  text: true,
2731
3467
  media: true,
3468
+ replyTo: true,
2732
3469
  messageSendingHooks: true
2733
3470
  },
2734
- outbound: {
2735
- sendText: async ({ cfg, to, text: text3 }) => ({
2736
- channel: "agent-wechat",
2737
- ...await sendWeChatText(cfg, to, text3)
2738
- }),
2739
- sendMedia: async ({ cfg, to, text: text3, mediaUrl, audioAsVoice }) => ({
2740
- channel: "agent-wechat",
2741
- ...await sendWeChatMedia(cfg, to, text3, mediaUrl, audioAsVoice)
2742
- })
2743
- }
3471
+ outbound: mediaHandlers
2744
3472
  });
3473
+ wechatMessageAdapter.durableFinal = createWeChatDurableFinal();
2745
3474
  var meta = {
2746
3475
  id: "agent-wechat",
2747
3476
  label: "WeChat",
@@ -2763,6 +3492,7 @@ var wechatPlugin = {
2763
3492
  tts: { voice: { synthesisTarget: "voice-note", transcodesAudio: true } }
2764
3493
  },
2765
3494
  reload: { configPrefixes: ["channels.agent-wechat"] },
3495
+ actions: wechatMediaActions,
2766
3496
  configSchema: {
2767
3497
  uiHints: { "native.token": { sensitive: true } },
2768
3498
  schema: {
@@ -2880,14 +3610,7 @@ var wechatPlugin = {
2880
3610
  // ---- Outbound adapter for OpenClaw hosts using the outbound hook ----
2881
3611
  outbound: {
2882
3612
  deliveryMode: "direct",
2883
- sendText: async ({ cfg, to, text: text3 }) => ({
2884
- channel: "agent-wechat",
2885
- ...await sendWeChatText(cfg, to, text3)
2886
- }),
2887
- sendMedia: async ({ cfg, to, text: text3, mediaUrl, audioAsVoice }) => ({
2888
- channel: "agent-wechat",
2889
- ...await sendWeChatMedia(cfg, to, text3, mediaUrl, audioAsVoice)
2890
- })
3613
+ ...mediaHandlers
2891
3614
  },
2892
3615
  message: wechatMessageAdapter,
2893
3616
  gateway: {
@@ -2917,7 +3640,7 @@ var wechatPlugin = {
2917
3640
  loginWithQrWait: async ({ accountId, timeoutMs }) => {
2918
3641
  const account = resolveWeChatAccount(getWeChatRuntime().config.current(), accountId ?? void 0);
2919
3642
  if (!account?.native) return { connected: false, message: "No native daemon configured" };
2920
- return nativeLoginWait(account.accountId, timeoutMs);
3643
+ return nativeLoginWait(account, timeoutMs);
2921
3644
  }
2922
3645
  },
2923
3646
  auth: {
@@ -2943,10 +3666,6 @@ var wechatPlugin = {
2943
3666
  linked: runtime2?.linked ?? false
2944
3667
  })
2945
3668
  },
2946
- agentTools: (({ cfg }) => {
2947
- const account = resolveWeChatAccount(cfg);
2948
- return account?.native ? [createNativeLoginTool(account)] : [];
2949
- }),
2950
3669
  directory: {
2951
3670
  self: async ({ cfg }) => {
2952
3671
  const account = resolveWeChatAccount(cfg);
@@ -3054,7 +3773,7 @@ function createNativeFacade(config, dependencies = {}) {
3054
3773
  fail(res, 403, "facade_account_forbidden");
3055
3774
  return true;
3056
3775
  }
3057
- if (!["GET", "HEAD", "POST", "PATCH", "DELETE"].includes(req.method ?? "")) {
3776
+ if (!["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"].includes(req.method ?? "")) {
3058
3777
  fail(res, 405, "method_not_allowed");
3059
3778
  return true;
3060
3779
  }
@@ -3067,19 +3786,23 @@ function createNativeFacade(config, dependencies = {}) {
3067
3786
  try {
3068
3787
  const host2 = dependencies.endpoint ? void 0 : await ensureNativeHost(config);
3069
3788
  const headers = new Headers();
3070
- for (const name2 of ["content-type", "accept", "range", "if-none-match", "if-range", "last-event-id", "idempotency-key"]) {
3071
- const value = req.headers[name2];
3072
- if (typeof value === "string") headers.set(name2, value);
3789
+ for (const name3 of ["content-type", "accept", "range", "if-none-match", "if-range", "last-event-id", "idempotency-key"]) {
3790
+ const value = req.headers[name3];
3791
+ if (typeof value === "string") headers.set(name3, value);
3073
3792
  }
3793
+ const upload = pieces.length === 4 && pieces[3] === "uploads" && req.method === "POST";
3794
+ const mediaContent = pieces.length === 6 && pieces[3] === "media" && pieces[5] === "content" && parsed.searchParams.get("representation") !== "preview";
3795
+ const requestLimit = upload ? NATIVE_MAX_SOURCE_BYTES + 64 * 1024 : MAX_BODY;
3796
+ const responseLimit = mediaContent ? Math.max(MAX_BODY, NATIVE_MAX_SOURCE_BYTES) : MAX_BODY;
3074
3797
  const length = req.headers["content-length"];
3075
- if (length && (!/^\d+$/.test(length) || Number(length) > MAX_BODY)) {
3798
+ if (length && (!/^\d+$/.test(length) || Number(length) > requestLimit)) {
3076
3799
  fail(res, 413, "payload_too_large");
3077
3800
  return true;
3078
3801
  }
3079
3802
  let size = 0;
3080
3803
  const body = ["GET", "HEAD"].includes(req.method ?? "") ? void 0 : Readable.toWeb(req).pipeThrough(new NodeTransformStream({ transform(chunk, controller) {
3081
3804
  size += chunk.byteLength;
3082
- if (size > MAX_BODY) {
3805
+ if (size > requestLimit) {
3083
3806
  tooLarge = true;
3084
3807
  throw new Error("payload_too_large");
3085
3808
  }
@@ -3092,10 +3815,16 @@ function createNativeFacade(config, dependencies = {}) {
3092
3815
  headers.set("Authorization", `Bearer ${dependencies.token}`);
3093
3816
  response = await (dependencies.fetch ?? fetch)(new URL(relative, dependencies.endpoint), init);
3094
3817
  }
3818
+ const responseLength = response.headers.get("content-length");
3819
+ if (responseLength && (!/^\d+$/.test(responseLength) || Number(responseLength) > responseLimit)) {
3820
+ await response.body?.cancel();
3821
+ fail(res, 502, "native_facade_unavailable");
3822
+ return true;
3823
+ }
3095
3824
  res.statusCode = response.status;
3096
- for (const name2 of ["content-type", "content-length", "content-range", "accept-ranges", "etag", "cache-control", "content-disposition", "x-content-type-options"]) {
3097
- const value = response.headers.get(name2);
3098
- if (value) res.setHeader(name2, value);
3825
+ for (const name3 of ["content-type", "content-length", "content-range", "accept-ranges", "etag", "cache-control", "content-disposition", "x-content-type-options"]) {
3826
+ const value = response.headers.get(name3);
3827
+ if (value) res.setHeader(name3, value);
3099
3828
  }
3100
3829
  res.setHeader("x-content-type-options", "nosniff");
3101
3830
  const reader = response.body?.getReader();
@@ -3110,7 +3839,7 @@ function createNativeFacade(config, dependencies = {}) {
3110
3839
  const { value, done } = await reader.read();
3111
3840
  if (done) break;
3112
3841
  emitted += value.length;
3113
- if (!sse && emitted > MAX_BODY) throw new Error("upstream_response_too_large");
3842
+ if (!sse && emitted > responseLimit) throw new Error("upstream_response_too_large");
3114
3843
  if (!res.write(value)) await drain(res, abort.signal);
3115
3844
  }
3116
3845
  } finally {
@@ -3154,14 +3883,14 @@ function object(value) {
3154
3883
  if (!value || typeof value !== "object" || Array.isArray(value)) throw Error("Expected tool arguments");
3155
3884
  return value;
3156
3885
  }
3157
- function string(value, name2, max = 4096) {
3158
- if (typeof value !== "string" || !value.trim() || value.length > max || /[\u0000-\u001f\u007f]/.test(value)) throw Error(`Invalid ${name2}`);
3886
+ function string(value, name3, max = 4096) {
3887
+ if (typeof value !== "string" || !value.trim() || value.length > max || /[\u0000-\u001f\u007f]/.test(value)) throw Error(`Invalid ${name3}`);
3159
3888
  return value.trim();
3160
3889
  }
3161
3890
  function threadId(value) {
3162
3891
  return string(string(value, "thread ID").replace(/^(?:agent-)?wechat:(?:group:)?/i, ""), "thread ID");
3163
3892
  }
3164
- function messageResult(message, retrievalTool = "wechat_media") {
3893
+ function messageResult(message, retrievalTool = "wechat_media", quotePermitted = false) {
3165
3894
  if (nativeRecallInfo(message)) return {
3166
3895
  id: message.id,
3167
3896
  threadId: message.threadId,
@@ -3176,8 +3905,15 @@ function messageResult(message, retrievalTool = "wechat_media") {
3176
3905
  const isForward = message.type === 49 && message.appMessageType === 19;
3177
3906
  const isLink = message.type === 49 && [3, 4, 5].includes(message.appMessageType ?? 0) && !!message.link;
3178
3907
  const kind2 = isQuote ? "quote" : isForward ? "forwarded_history" : isLink ? "link_preview" : message.type === 3 ? "image" : message.type === 47 ? "sticker" : message.type === 34 ? "voice" : message.type === 43 ? "video" : message.type === 49 && (message.appMessageType == null || message.appMessageType === 6) ? "file" : "unsupported";
3179
- const body = message.type === 1 || isForward || isLink ? message.body ?? "" : isQuote ? `${message.body ?? ""}
3180
- [Quoted original not retrieved; use ${retrievalTool} with this message ID]` : `[WeChat ${kind2} message; attachment content has not been retrieved by this tool]`;
3908
+ const body = message.type === 1 || isForward || isLink ? message.body ?? "" : isQuote ? renderEmbeddedQuote(message, quotePermitted).body : `[WeChat ${kind2} message; attachment content has not been retrieved by this tool]`;
3909
+ const quote = message.quote && {
3910
+ serverId: message.quote.serverId,
3911
+ type: message.quote.type,
3912
+ state: quotePermitted ? message.quote.state : "not permitted",
3913
+ senderId: message.quote.senderId,
3914
+ appMessageType: message.quote.appMessageType,
3915
+ embeddedImage: quotePermitted ? message.quote.embeddedImage : void 0
3916
+ };
3181
3917
  return {
3182
3918
  id: message.id,
3183
3919
  threadId: message.threadId,
@@ -3186,7 +3922,7 @@ function messageResult(message, retrievalTool = "wechat_media") {
3186
3922
  direction: message.direction,
3187
3923
  type: message.type,
3188
3924
  appMessageType: message.appMessageType,
3189
- quote: message.quote,
3925
+ quote,
3190
3926
  link: isLink ? message.link : void 0,
3191
3927
  createdAt: message.createdAt,
3192
3928
  body: body.slice(0, 4e3),
@@ -3227,9 +3963,9 @@ function createLookupTools(context, dependencies, archive) {
3227
3963
  if (!currentThread) return [];
3228
3964
  }
3229
3965
  const selectedId = selected.native.accountId;
3230
- const tool = (name2, action, description, properties, required = []) => ({
3231
- name: name2,
3232
- label: name2.replaceAll("_", " "),
3966
+ const tool = (name3, action, description, properties, required = []) => ({
3967
+ name: name3,
3968
+ label: name3.replaceAll("_", " "),
3233
3969
  description,
3234
3970
  // The pinned host's tool_call wrapper JSON-serializes image blocks. Its
3235
3971
  // public direct-only surface preserves actual image content for vision.
@@ -3237,7 +3973,7 @@ function createLookupTools(context, dependencies, archive) {
3237
3973
  parameters: { type: "object", additionalProperties: false, properties, required },
3238
3974
  execute: async (_callId, input, signal) => {
3239
3975
  const args = object(input);
3240
- const guard = () => {
3976
+ const guard2 = () => {
3241
3977
  signal?.throwIfAborted();
3242
3978
  context.assertInvocationCurrent?.();
3243
3979
  const cfg2 = currentConfig();
@@ -3245,7 +3981,7 @@ function createLookupTools(context, dependencies, archive) {
3245
3981
  if (!account2?.enabled || !account2.native || account2.native.accountId !== selectedId || account2.accountId !== selected.accountId || nativeConfigurationKey(account2.native) !== configurationKey) throw Error("WeChat account configuration changed; start a new turn");
3246
3982
  return { cfg: cfg2, account: account2, native: account2.native };
3247
3983
  };
3248
- const { cfg, account, native } = guard();
3984
+ const { cfg, account, native } = guard2();
3249
3985
  if (Object.keys(args).some((key) => !Object.hasOwn(properties, key))) throw Error(archive ? "Unknown archive lookup argument" : "Unknown lookup argument; WeChat history is restricted to the current conversation");
3250
3986
  const limit = args.limit ?? 20;
3251
3987
  if (!Number.isInteger(limit) || limit < 1 || limit > 50) throw Error("limit must be 1\u201350");
@@ -3262,7 +3998,7 @@ function createLookupTools(context, dependencies, archive) {
3262
3998
  const core = dependencies.core ?? getWeChatRuntime();
3263
3999
  const allowed = async (sender) => {
3264
4000
  if (archive) return true;
3265
- const { cfg: cfg2, account: account2 } = guard();
4001
+ const { cfg: cfg2, account: account2 } = guard2();
3266
4002
  const result2 = await resolveWeChatIngress({
3267
4003
  resolve: core.channel.inbound?.ingress?.resolveStable ?? resolveStableChannelMessageIngress2,
3268
4004
  cfg: cfg2,
@@ -3276,10 +4012,15 @@ function createLookupTools(context, dependencies, archive) {
3276
4012
  return result2.ingress.admission === "dispatch";
3277
4013
  };
3278
4014
  if (!await allowed(requesterSenderId)) throw Error("WeChat conversation access is no longer allowed");
3279
- guard();
4015
+ guard2();
3280
4016
  const { client } = await (dependencies.host ?? ensureNativeHost)(native);
3281
- guard();
4017
+ guard2();
3282
4018
  const accountId = native.accountId;
4019
+ const visibleMessage = async (message) => messageResult(
4020
+ message,
4021
+ archive ? "wechat_archive_media" : "wechat_media",
4022
+ !message.quote || archive || message.quote.direction === "outgoing" || !!message.quote.senderId && await allowed(message.quote.senderId)
4023
+ );
3283
4024
  let result;
3284
4025
  if (action === "threads") {
3285
4026
  const page = await client.threads(accountId, { limit, cursor, ...query ? { query } : {} });
@@ -3292,21 +4033,20 @@ function createLookupTools(context, dependencies, archive) {
3292
4033
  result = { ...page, items, scope: "local_profile", note: "Locally stored threads; coverage may be partial. This lookup does not mark threads read." };
3293
4034
  } else if (action === "message" || action === "media") {
3294
4035
  const message = await client.message(accountId, messageId);
3295
- guard();
4036
+ guard2();
3296
4037
  if (!await allowed(requesterSenderId)) throw Error("WeChat conversation access is no longer allowed");
3297
4038
  if (message.id !== messageId || message.accountId !== accountId || !archive && message.threadId !== conversation || message.direction !== "outgoing" && !await allowed(message.senderId ?? void 0)) throw Error("Message is outside the permitted conversation or sender policy");
3298
- result = messageResult(message, archive ? "wechat_archive_media" : "wechat_media");
4039
+ if (action === "message") result = await visibleMessage(message);
3299
4040
  if (action === "media") {
3300
4041
  const checkRecall = async () => {
3301
- guard();
4042
+ guard2();
3302
4043
  const latest = await client.message(accountId, messageId);
3303
- guard();
4044
+ guard2();
3304
4045
  if (latest.id !== message.id || latest.accountId !== accountId || latest.threadId !== message.threadId || latest.serverId !== message.serverId) throw Error("Native media message identity changed");
3305
4046
  if (nativeRecallInfo(latest)) throw new NativeApiError(410, "message_recalled", false);
3306
4047
  if (message.quote) {
3307
- const quote = await client.quotedMessage(accountId, message.id);
3308
- guard();
3309
- if (quote.state === "recalled" || quote.message && nativeRecallInfo(quote.message)) throw new NativeApiError(410, "message_recalled", false);
4048
+ if (latest.quote?.state === "recalled") throw new NativeApiError(410, "message_recalled", false);
4049
+ if (!latest.quote || JSON.stringify(latest.quote) !== JSON.stringify(message.quote)) throw new NativeApiError(409, "media_source_changed", false);
3310
4050
  }
3311
4051
  };
3312
4052
  let prepared;
@@ -3321,7 +4061,7 @@ function createLookupTools(context, dependencies, archive) {
3321
4061
  download: args.download !== false,
3322
4062
  waitMs: 2e3,
3323
4063
  signal,
3324
- assertCurrent: guard,
4064
+ assertCurrent: guard2,
3325
4065
  allowQuotedMessage: async (original) => original.direction === "outgoing" || await allowed(original.senderId ?? void 0),
3326
4066
  beforeMediaAccess: async () => {
3327
4067
  if (!await allowed(requesterSenderId) || message.direction !== "outgoing" && !await allowed(message.senderId ?? void 0)) throw Error("WeChat conversation access is no longer allowed");
@@ -3329,7 +4069,7 @@ function createLookupTools(context, dependencies, archive) {
3329
4069
  }
3330
4070
  });
3331
4071
  } catch (error) {
3332
- guard();
4072
+ guard2();
3333
4073
  if (!(error instanceof NativeApiError)) throw error;
3334
4074
  const details2 = {
3335
4075
  messageId: message.id,
@@ -3340,7 +4080,7 @@ function createLookupTools(context, dependencies, archive) {
3340
4080
  };
3341
4081
  return { content: [{ type: "text", text: JSON.stringify(details2) }], details: details2 };
3342
4082
  }
3343
- guard();
4083
+ guard2();
3344
4084
  if (!await allowed(requesterSenderId) || message.direction !== "outgoing" && !await allowed(message.senderId ?? void 0)) throw Error("WeChat conversation access is no longer allowed");
3345
4085
  const details = {
3346
4086
  messageId: message.id,
@@ -3357,7 +4097,7 @@ function createLookupTools(context, dependencies, archive) {
3357
4097
  };
3358
4098
  const image = prepared.suppliedAssets?.find((asset) => asset.role === "model_image");
3359
4099
  const output = image ? await imageResultFromFile({ label: "WeChat attachment", path: image.path, extraText: JSON.stringify(details), details }) : { content: [{ type: "text", text: JSON.stringify(details) }], details };
3360
- guard();
4100
+ guard2();
3361
4101
  try {
3362
4102
  await checkRecall();
3363
4103
  } catch (error) {
@@ -3374,7 +4114,7 @@ function createLookupTools(context, dependencies, archive) {
3374
4114
  for (const message of page.items) {
3375
4115
  if (isNativeTombstone(message)) continue;
3376
4116
  if (conversation && message.threadId !== conversation || message.accountId !== accountId) throw Error("WeChat history response crosses a conversation boundary");
3377
- if (message.direction === "outgoing" || await allowed(message.senderId ?? void 0)) items.push(messageResult(message, archive ? "wechat_archive_media" : "wechat_media"));
4117
+ if (message.direction === "outgoing" || await allowed(message.senderId ?? void 0)) items.push(await visibleMessage(message));
3378
4118
  }
3379
4119
  result = {
3380
4120
  ...page,
@@ -3384,7 +4124,7 @@ function createLookupTools(context, dependencies, archive) {
3384
4124
  note: archive ? "Account-wide local history may be partial. These reads do not mark threads read or download attachments." : "Local history may be partial. A filtered page can be empty with a nextCursor. These reads do not mark a conversation read or download attachments."
3385
4125
  };
3386
4126
  }
3387
- guard();
4127
+ guard2();
3388
4128
  return { content: [{ type: "text", text: JSON.stringify(result) }], details: result };
3389
4129
  }
3390
4130
  });
@@ -3399,13 +4139,13 @@ function createLookupTools(context, dependencies, archive) {
3399
4139
  tool(archiveNames[1], "search", "Search locally stored messages across every thread in the configured WeChat account, including other senders. Optional threadId narrows the search. Follow nextCursor with the same query and thread selection; no remote backfill or read marking.", { query: querySchema, threadId: messageIdSchema, ...pageSchema }, ["query"]),
3400
4140
  tool(archiveNames[2], "history", "Read the locally stored history of any thread in the configured WeChat account, newest first, without sender filtering or read marking. Use wechat_archive_threads to find thread IDs.", { threadId: messageIdSchema, ...pageSchema }, ["threadId"]),
3401
4141
  tool(archiveNames[3], "message", "Look up a stored message in any thread of the configured WeChat account by its exact opaque message ID. Use wechat_archive_media to retrieve its attachment.", { messageId: messageIdSchema }, ["messageId"]),
3402
- tool(archiveNames[4], "media", "Retrieve an attachment or quoted text/image from any thread in the configured WeChat account by its message ID. Use the parent quote message ID for quotes. Returns verified managed file paths and an image preview for vision. Cached bytes first; missing media requests a bounded server-owned download unless download=false. Preserve pending/expired/unavailable results and never automatically retry retryable=false. No sends or read marking.", mediaSchema, ["messageId"])
4142
+ tool(archiveNames[4], "media", "Retrieve an attachment or quoted text/image/link from any thread in the configured WeChat account by its message ID. Use the parent quote message ID for quotes. Returns verified managed file paths and an image preview for vision. Cached bytes first; missing media requests a bounded server-owned download unless download=false. Preserve pending/expired/unavailable results and never automatically retry retryable=false. No sends or read marking.", mediaSchema, ["messageId"])
3403
4143
  ];
3404
4144
  return [
3405
4145
  tool(names[0], "history", "Read the current WeChat conversation's locally stored messages, newest first, beyond the recent inbound buffer. Follow nextCursor for older history; no remote history backfill or read marking.", { ...pageSchema }),
3406
4146
  tool(names[1], "search", "Search the current WeChat conversation's locally stored message text by case-insensitive substring, beyond buffered messages. Follow nextCursor with the same query in this conversation.", { query: querySchema, ...pageSchema }, ["query"]),
3407
4147
  tool(names[2], "message", "Look up a stored message by its exact opaque message ID in the current WeChat conversation. Media is described without downloading it; use wechat_media to retrieve its attachment. Long text is bounded.", { messageId: messageIdSchema }, ["messageId"]),
3408
- tool(names[3], "media", "Retrieve a message attachment or quoted text/image from the current WeChat conversation. Use the parent quote message ID for quotes. Returns a verified local file path and an image preview for vision when applicable. Uses cached bytes first; download defaults to true and requests a bounded server-owned transfer if missing. Pending results may be checked again; never automatically retry confirmed expiry or retryable=false. Does not send messages or mark the thread read.", mediaSchema, ["messageId"])
4148
+ tool(names[3], "media", "Retrieve a message attachment or quoted text/image/link from the current WeChat conversation. Use the parent quote message ID for quotes. Returns a verified local file path and an image preview for vision when applicable. Uses cached bytes first; download defaults to true and requests a bounded server-owned transfer if missing. Pending results may be checked again; never automatically retry confirmed expiry or retryable=false. Does not send messages or mark the thread read.", mediaSchema, ["messageId"])
3409
4149
  ];
3410
4150
  }
3411
4151
  function registerNativeHistoryTools(api) {
@@ -3471,7 +4211,7 @@ function createNativeShareTools(context, dependencies = {}) {
3471
4211
  ...args.description !== void 0 ? { description: args.description === "" ? "" : text(args.description, "description", 16384, true) } : {},
3472
4212
  ...args.thumbnailUrl !== void 0 ? { thumbnailUrl: url(args.thumbnailUrl, "thumbnail URL") } : {}
3473
4213
  };
3474
- const guard = () => {
4214
+ const guard2 = () => {
3475
4215
  signal?.throwIfAborted();
3476
4216
  context.assertInvocationCurrent?.();
3477
4217
  const cfg = currentConfig(), account = resolveWeChatAccount(cfg);
@@ -3480,7 +4220,7 @@ function createNativeShareTools(context, dependencies = {}) {
3480
4220
  };
3481
4221
  const core = dependencies.core ?? getWeChatRuntime();
3482
4222
  const authorize = async () => {
3483
- const { cfg, account } = guard();
4223
+ const { cfg, account } = guard2();
3484
4224
  const result = await resolveWeChatIngress({
3485
4225
  resolve: core.channel.inbound?.ingress?.resolveStable ?? resolveStableChannelMessageIngress3,
3486
4226
  cfg,
@@ -3491,11 +4231,11 @@ function createNativeShareTools(context, dependencies = {}) {
3491
4231
  senderId: requester,
3492
4232
  readStoreAllowFrom: async () => core.channel.pairing.readAllowFromStore({ channel: "agent-wechat", accountId: account.accountId, env: process.env }).catch(() => [])
3493
4233
  });
3494
- guard();
4234
+ guard2();
3495
4235
  if (result.ingress.admission !== "dispatch") throw Error("WeChat conversation access is no longer allowed");
3496
4236
  };
3497
4237
  await authorize();
3498
- const { native } = guard();
4238
+ const { native } = guard2();
3499
4239
  const { client } = await (dependencies.host ?? ensureNativeHost)(native);
3500
4240
  await authorize();
3501
4241
  let intent;
@@ -3530,7 +4270,7 @@ function registerNativeShareTools(api) {
3530
4270
  }
3531
4271
 
3532
4272
  // src/native-recall-tools.ts
3533
- import { createHash as createHash9 } from "node:crypto";
4273
+ import { createHash as createHash10 } from "node:crypto";
3534
4274
  import { resolveStableChannelMessageIngress as resolveStableChannelMessageIngress4 } from "openclaw/plugin-sdk/channel-ingress-runtime";
3535
4275
  var names2 = ["wechat_recall"];
3536
4276
  function text2(value, label) {
@@ -3541,7 +4281,7 @@ function thread2(value) {
3541
4281
  return text2(text2(value, "conversation").replace(/^(?:agent-)?wechat:(?:group:)?/i, ""), "conversation");
3542
4282
  }
3543
4283
  function nativeRecallKey(accountId, threadId2, messageId, serverId) {
3544
- return `openclaw-recall-${createHash9("sha256").update(JSON.stringify([accountId, threadId2, messageId, serverId])).digest("hex")}`;
4284
+ return `openclaw-recall-${createHash10("sha256").update(JSON.stringify([accountId, threadId2, messageId, serverId])).digest("hex")}`;
3545
4285
  }
3546
4286
  function createNativeRecallTools(context, dependencies = {}) {
3547
4287
  const currentConfig = () => context.getRuntimeConfig?.() ?? context.runtimeConfig ?? context.config;
@@ -3573,7 +4313,7 @@ function createNativeRecallTools(context, dependencies = {}) {
3573
4313
  const messageId = text2(input.messageId, "message ID");
3574
4314
  const serverId = text2(input.serverId, "server ID");
3575
4315
  if (!/^[1-9]\d{0,19}$/.test(serverId) || BigInt(serverId) > 18446744073709551615n) throw Error("Invalid exact server message ID");
3576
- const guard = () => {
4316
+ const guard2 = () => {
3577
4317
  signal?.throwIfAborted();
3578
4318
  context.assertInvocationCurrent?.();
3579
4319
  const cfg = currentConfig(), account = resolveWeChatAccount(cfg);
@@ -3581,7 +4321,7 @@ function createNativeRecallTools(context, dependencies = {}) {
3581
4321
  return { cfg, account, native: account.native };
3582
4322
  };
3583
4323
  const allowed = async () => {
3584
- const { cfg, account } = guard();
4324
+ const { cfg, account } = guard2();
3585
4325
  const core = dependencies.core ?? getWeChatRuntime();
3586
4326
  const ingress = await resolveWeChatIngress({
3587
4327
  resolve: core.channel.inbound?.ingress?.resolveStable ?? resolveStableChannelMessageIngress4,
@@ -3593,20 +4333,20 @@ function createNativeRecallTools(context, dependencies = {}) {
3593
4333
  senderId: requester,
3594
4334
  readStoreAllowFrom: async () => core.channel.pairing.readAllowFromStore({ channel: "agent-wechat", accountId: account.accountId, env: process.env }).catch(() => [])
3595
4335
  });
3596
- guard();
4336
+ guard2();
3597
4337
  if (ingress.ingress.admission !== "dispatch") throw Error("WeChat conversation access is no longer allowed");
3598
4338
  };
3599
4339
  await allowed();
3600
- const { native } = guard();
4340
+ const { native } = guard2();
3601
4341
  const { client } = await (dependencies.host ?? ensureNativeHost)(native);
3602
- guard();
4342
+ guard2();
3603
4343
  const message = await client.message(accountId, messageId);
3604
- guard();
4344
+ guard2();
3605
4345
  const retainedRecall = !!nativeRecallInfo(message);
3606
4346
  if (message.id !== messageId || message.accountId !== accountId || message.threadId !== conversation || message.direction !== "outgoing" && !retainedRecall) throw Error("Recall target is outside this conversation or was not sent by this account");
3607
4347
  if (message.serverId !== serverId) throw Error("The exact server identity does not match this receipt; the local message identity may have been reused");
3608
4348
  await allowed();
3609
- guard();
4349
+ guard2();
3610
4350
  const key = nativeRecallKey(accountId, conversation, messageId, serverId);
3611
4351
  let operation;
3612
4352
  let operationId;
@@ -3636,13 +4376,13 @@ function createNativeRecallTools(context, dependencies = {}) {
3636
4376
  const deadline = Date.now() + Math.max(0, Math.min(dependencies.waitMs ?? 2e3, 1e4));
3637
4377
  while (["queued", "running", "submitting"].includes(operation.state) && Date.now() < deadline) {
3638
4378
  await new Promise((resolve) => setTimeout(resolve, Math.min(250, deadline - Date.now())));
3639
- guard();
4379
+ guard2();
3640
4380
  const remaining = Math.max(1, deadline - Date.now());
3641
4381
  const next = await client.operation(accountId, operation.id, signal ? AbortSignal.any([signal, AbortSignal.timeout(remaining)]) : AbortSignal.timeout(remaining));
3642
4382
  checkOperation(next);
3643
4383
  operation = next;
3644
4384
  }
3645
- guard();
4385
+ guard2();
3646
4386
  } catch (error) {
3647
4387
  const reason = error instanceof NativeApiError ? error.code : "recall_result_unavailable";
3648
4388
  return result("needs_review", { reason, note: "Inspect the existing operation or repeat only this same message with the same idempotency key. No automatic second submission was made." });
@@ -3664,6 +4404,55 @@ function registerNativeRecallTools(api) {
3664
4404
  api.registerTool({ contextVersion: 2, create: (context) => createNativeRecallTools(context) }, { names: names2 });
3665
4405
  }
3666
4406
 
4407
+ // src/native-group-tool.ts
4408
+ var name2 = "wechat_group_info";
4409
+ function createNativeGroupTools(context, dependencies = {}) {
4410
+ if (context.senderIsOwner !== true || typeof context.assertInvocationCurrent !== "function") return [];
4411
+ const currentConfig = () => context.getRuntimeConfig?.() ?? context.runtimeConfig ?? context.config;
4412
+ const selected = resolveWeChatAccount(currentConfig());
4413
+ if (!selected?.enabled || !selected.native || context.agentAccountId && context.agentAccountId !== selected.accountId || context.deliveryContext?.channel === "agent-wechat" && context.deliveryContext.accountId && context.deliveryContext.accountId !== selected.accountId) return [];
4414
+ const accountId = selected.native.accountId;
4415
+ const configurationKey = nativeConfigurationKey(selected.native);
4416
+ return [{
4417
+ name: name2,
4418
+ label: "WeChat Group Info",
4419
+ description: "Read cached group information and one page of members for the configured WeChat account. Available only to the trusted OpenClaw owner. Does not create groups, invite people or change settings. Cached member absence does not prove non-membership.",
4420
+ parameters: { type: "object", additionalProperties: false, properties: {
4421
+ groupId: { type: "string", minLength: 10, maxLength: 256, description: "Exact ordinary group username ending in @chatroom." },
4422
+ limit: { type: "integer", minimum: 1, maximum: 100 },
4423
+ cursor: { type: "string", maxLength: 8192 },
4424
+ username: { type: "string", minLength: 1, maxLength: 256, description: "Optionally inspect one exact member instead of listing a page." }
4425
+ }, required: ["groupId"] },
4426
+ execute: async (_callId, input, signal) => {
4427
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((k) => !["groupId", "limit", "cursor", "username"].includes(k))) throw Error("Invalid group info request");
4428
+ const args = input;
4429
+ const identity = (value) => typeof value === "string" && value.length > 0 && value.length <= 256 && !/[\s\u0000-\u001f\u007f]/u.test(value);
4430
+ if (!identity(args.groupId) || !args.groupId.endsWith("@chatroom") || args.groupId.length <= 9 || args.limit != null && (!Number.isInteger(args.limit) || Number(args.limit) < 1 || Number(args.limit) > 100) || args.cursor != null && (typeof args.cursor !== "string" || args.cursor.length > 8192) || args.username != null && !identity(args.username) || args.username != null && (args.limit != null || args.cursor != null)) throw Error("Invalid group info selectors");
4431
+ const guard2 = () => {
4432
+ signal?.throwIfAborted();
4433
+ if (context.senderIsOwner !== true) throw Error("OpenClaw owner authorization is required");
4434
+ context.assertInvocationCurrent();
4435
+ const account = resolveWeChatAccount(currentConfig());
4436
+ if (!account?.enabled || !account.native || account.accountId !== selected.accountId || account.native.accountId !== accountId || nativeConfigurationKey(account.native) !== configurationKey) throw Error("WeChat account configuration changed; start a new turn");
4437
+ return account.native;
4438
+ };
4439
+ const native = guard2();
4440
+ const { client } = await (dependencies.host ?? ensureNativeHost)(native);
4441
+ guard2();
4442
+ const group = await client.group(accountId, args.groupId, signal);
4443
+ guard2();
4444
+ if (group.id !== args.groupId || group.roomId !== args.groupId) throw Error("Group identity is invalid");
4445
+ const members = typeof args.username === "string" ? await client.groupMember(accountId, args.groupId, args.username, signal) : await client.groupMembers(accountId, args.groupId, { limit: args.limit == null ? 50 : Number(args.limit), cursor: args.cursor }, signal);
4446
+ guard2();
4447
+ const details = { accountId, group, members, source: "cached", membershipAbsence: "unconfirmed" };
4448
+ return { content: [{ type: "text", text: JSON.stringify(details) }], details };
4449
+ }
4450
+ }];
4451
+ }
4452
+ function registerNativeGroupTools(api) {
4453
+ api.registerTool({ contextVersion: 2, create: (context) => createNativeGroupTools(context) }, { names: [name2] });
4454
+ }
4455
+
3667
4456
  // index.ts
3668
4457
  var plugin = {
3669
4458
  id: "agent-wechat",
@@ -3677,6 +4466,8 @@ var plugin = {
3677
4466
  registerNativeHistoryTools(api);
3678
4467
  registerNativeShareTools(api);
3679
4468
  registerNativeRecallTools(api);
4469
+ registerNativeGroupTools(api);
4470
+ registerNativeLoginTool(api);
3680
4471
  const stopFacade = selected?.native ? registerNativeFacade(api, selected.native) : () => {
3681
4472
  };
3682
4473
  const stopPreparedBoundary = selected?.native?.readPolicy && selected.native.readPolicy !== "on_inbound" ? registerNativePreparedBoundary(api) : () => {