@agent-wechat/agent-wechat 1.0.0-beta.9 → 1.0.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);
408
+ }
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);
349
417
  }
350
- groupMembers(accountId, roomId, options) {
351
- return this.request(`v1/accounts/${id(accountId)}/groups/${id(roomId)}/members${listQuery(options)}`);
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,20 @@ 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
+ /** Quote a locally stored text, image, voice, video, link, file or quoted reply in the same chat.
487
+ * Live acceptance and recipient rendering remain unverified; other source kinds are rejected.
488
+ */
489
+ sendText(accountId, threadId2, text3, idempotencyKey, quote) {
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
+ 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))
493
+ throw new Error("Invalid quote message identity");
494
+ const input = quote === void 0 ? { threadId: threadId2, text: text3 } : { kind: "text", threadId: threadId2, text: text3, quote };
495
+ return this.request(`v1/accounts/${id(accountId)}/sends`, { method: "POST", headers: { "Idempotency-Key": idempotencyKey }, body: JSON.stringify(input) });
418
496
  }
419
497
  send(accountId, sendId, signal) {
420
498
  return this.request(`v1/accounts/${id(accountId)}/sends/${id(sendId)}`, { signal });
@@ -432,20 +510,54 @@ var NativeWeChatClient = class {
432
510
  cancelSend(accountId, sendId) {
433
511
  return this.request(`v1/accounts/${id(accountId)}/sends/${id(sendId)}/cancel`, { method: "POST", body: "{}" });
434
512
  }
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))
513
+ /** A disk-backed Blob avoids holding the source in memory before staging. */
514
+ async upload(accountId, bytes, name3, contentType = "application/octet-stream", signal) {
515
+ const size = bytes instanceof Blob ? bytes.size : bytes.byteLength;
516
+ if (!size || size > NATIVE_MAX_SOURCE_BYTES || !name3 || name3.length > 255 || /[\r\n/\\]/.test(name3))
437
517
  throw new Error("Invalid bounded media upload");
518
+ 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
519
  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 });
520
+ form.set("file", part, name3);
521
+ const response = await this.response(`v1/accounts/${id(accountId)}/uploads`, { method: "POST", body: form, signal }, false, this.mediaTimeoutMs);
522
+ return JSON.parse(new TextDecoder().decode(await this.readBounded(response)));
441
523
  }
442
524
  sendMedia(accountId, input, key) {
443
525
  if (!key || /[\r\n]/.test(key))
444
526
  throw new Error("An idempotency key is required");
445
527
  return this.request(`v1/accounts/${id(accountId)}/sends`, { method: "POST", headers: { "Idempotency-Key": key }, body: JSON.stringify(input) });
446
528
  }
447
- mediaAssets(accountId, messageId) {
448
- return this.request(`v1/accounts/${id(accountId)}/messages/${id(messageId)}/media`);
529
+ mediaAssets(accountId, messageId, signal) {
530
+ return this.request(`v1/accounts/${id(accountId)}/messages/${id(messageId)}/media`, { signal });
531
+ }
532
+ async mediaAssetsBatch(accountId, messageIds, signal) {
533
+ if (!messageIds.length || messageIds.length > 40 || messageIds.some((id2) => !id2 || id2.length > 8192) || new Set(messageIds).size !== messageIds.length)
534
+ throw new Error("Invalid media lookup batch");
535
+ if (this.mediaBatchSupported) {
536
+ try {
537
+ const batch = await this.request(`v1/accounts/${id(accountId)}/media/lookup`, { method: "POST", body: JSON.stringify({ messageIds }), signal });
538
+ const expected = new Set(messageIds);
539
+ if (!Array.isArray(batch.items) || batch.items.length !== expected.size)
540
+ throw new Error("Invalid media lookup response");
541
+ for (const item of batch.items) {
542
+ 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))
543
+ throw new Error("Invalid media lookup identity");
544
+ }
545
+ return batch;
546
+ } catch (error) {
547
+ if (!(error instanceof NativeApiError) || ![404, 405].includes(error.status))
548
+ throw error;
549
+ this.mediaBatchSupported = false;
550
+ }
551
+ }
552
+ return { items: await Promise.all(messageIds.map(async (messageId) => {
553
+ try {
554
+ return { messageId, assets: (await this.mediaAssets(accountId, messageId, signal)).items, error: null };
555
+ } catch (error) {
556
+ if (!(error instanceof NativeApiError))
557
+ throw error;
558
+ return { messageId, assets: [], error: error.code };
559
+ }
560
+ })) };
449
561
  }
450
562
  transferMedia(accountId, input) {
451
563
  return this.request(`v1/accounts/${id(accountId)}/messages/${id(input.messageId)}/media-transfers`, { method: "POST", body: JSON.stringify(input) });
@@ -459,26 +571,94 @@ var NativeWeChatClient = class {
459
571
  cancelJob(accountId, jobId) {
460
572
  return this.request(`v1/accounts/${id(accountId)}/jobs/${id(jobId)}/cancel`, { method: "POST", body: "{}" });
461
573
  }
462
- retryJob(accountId, jobId) {
463
- return this.request(`v1/accounts/${id(accountId)}/jobs/${id(jobId)}/retry`, { method: "POST", body: "{}" });
574
+ retryJob(accountId, jobId, options = {}) {
575
+ if (!options || typeof options !== "object" || Array.isArray(options) || Object.keys(options).some((key) => key !== "reuseCompletedUpload"))
576
+ throw new Error("Invalid media retry options");
577
+ const reuse = options.reuseCompletedUpload;
578
+ if (reuse !== void 0 && typeof reuse !== "boolean")
579
+ throw new Error("Invalid media retry options");
580
+ 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
581
  }
465
582
  repairMediaWriteback(accountId, limit = 25) {
466
583
  if (!Number.isInteger(limit) || limit < 1 || limit > 100)
467
584
  throw new Error("Invalid media writeback limit");
468
585
  return this.request(`v1/accounts/${id(accountId)}/media-writeback/repair`, { method: "POST", body: JSON.stringify({ limit }) });
469
586
  }
470
- async mediaContent(accountId, assetId, options = {}) {
587
+ /** Consume the bounded stream once, or cancel it; this never starts a CDN transfer. */
588
+ async mediaContentStream(accountId, assetId, options = {}) {
471
589
  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))
590
+ 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
591
  throw new Error("Invalid bounded content request");
474
592
  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 } : {} });
593
+ const cancellation = new AbortController();
594
+ 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
595
  const length = response.headers.get("content-length");
477
596
  if (length && (!/^\d+$/.test(length) || Number(length) > max)) {
478
597
  await response.body?.cancel();
479
598
  throw new Error("Native media response exceeds its bound");
480
599
  }
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 };
600
+ if (!response.body && length && Number(length) > 0)
601
+ throw new Error("Native media response length mismatch");
602
+ let activeReader;
603
+ const iterate = async function* () {
604
+ cancellation.signal.throwIfAborted();
605
+ options.signal?.throwIfAborted();
606
+ const reader = response.body?.getReader();
607
+ if (!reader)
608
+ return;
609
+ activeReader = reader;
610
+ let size = 0;
611
+ try {
612
+ while (true) {
613
+ cancellation.signal.throwIfAborted();
614
+ options.signal?.throwIfAborted();
615
+ const { value, done } = await reader.read();
616
+ cancellation.signal.throwIfAborted();
617
+ options.signal?.throwIfAborted();
618
+ if (done)
619
+ break;
620
+ size += value.byteLength;
621
+ if (size > max)
622
+ throw new Error("Native media response exceeds its bound");
623
+ yield value;
624
+ }
625
+ if (length && size !== Number(length))
626
+ throw new Error("Native media response length mismatch");
627
+ } finally {
628
+ await reader.cancel().catch(() => {
629
+ });
630
+ reader.releaseLock();
631
+ activeReader = void 0;
632
+ }
633
+ };
634
+ let claimed = false;
635
+ const stream = { [Symbol.asyncIterator]() {
636
+ if (claimed)
637
+ throw new Error("Native media stream was already consumed");
638
+ claimed = true;
639
+ return iterate();
640
+ } };
641
+ return { stream, cancel: async () => {
642
+ cancellation.abort();
643
+ await (activeReader ? activeReader.cancel() : response.body?.cancel())?.catch(() => {
644
+ });
645
+ }, 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 };
646
+ }
647
+ async mediaContent(accountId, assetId, options = {}) {
648
+ const { stream, cancel: _cancel, ...metadata } = await this.mediaContentStream(accountId, assetId, options);
649
+ const chunks = [];
650
+ let size = 0;
651
+ for await (const chunk of stream) {
652
+ chunks.push(chunk);
653
+ size += chunk.byteLength;
654
+ }
655
+ const bytes = new Uint8Array(size);
656
+ let offset = 0;
657
+ for (const chunk of chunks) {
658
+ bytes.set(chunk, offset);
659
+ offset += chunk.byteLength;
660
+ }
661
+ return { ...metadata, bytes };
482
662
  }
483
663
  markRead(accountId, threadId2, expectedVersion) {
484
664
  if (typeof expectedVersion !== "string" || !expectedVersion || expectedVersion.length > 128)
@@ -488,12 +668,17 @@ var NativeWeChatClient = class {
488
668
  events(accountId, after = "0", limit = 100) {
489
669
  if (!Number.isInteger(limit) || limit < 1 || limit > 200)
490
670
  throw new Error("Invalid event page limit");
491
- return this.request(`v1/accounts/${id(accountId)}/events?after=${decimal(after)}&limit=${limit}`);
671
+ return this.request(`v1/accounts/${id(accountId)}/events?after=${decimal(after)}&limit=${limit}`).then((page) => {
672
+ for (const event of page.items)
673
+ if (event.kind === "message.recalled")
674
+ validateNativeRecallMetadata(event.data);
675
+ return page;
676
+ });
492
677
  }
493
678
  ack(accountId, consumerId, cursor) {
494
679
  return this.request(`v1/accounts/${id(accountId)}/consumers/${id(consumerId)}/ack`, { method: "POST", body: JSON.stringify({ cursor: decimal(cursor) }) });
495
680
  }
496
- async *watch(accountId, after = "0", signal) {
681
+ async *watch(accountId, after = "0", signal, options = {}) {
497
682
  const connection = new AbortController();
498
683
  const streamSignal = signal ? AbortSignal.any([signal, connection.signal]) : connection.signal;
499
684
  const bounded = async (work, milliseconds, reason) => {
@@ -535,6 +720,7 @@ var NativeWeChatClient = class {
535
720
  const { value, done } = await bounded(() => activeReader.read(), this.streamIdleTimeoutMs, "Native SSE idle timeout");
536
721
  if (done)
537
722
  break;
723
+ options.onActivity?.();
538
724
  buffer += decoder.decode(value, { stream: true });
539
725
  if (buffer.length > 1024 * 1024)
540
726
  throw new Error("Native SSE frame exceeds its bound");
@@ -552,6 +738,8 @@ var NativeWeChatClient = class {
552
738
  const event = payload;
553
739
  if (!event || typeof event.kind !== "string" || !event.data || typeof event.data !== "object")
554
740
  throw new Error("Invalid native event");
741
+ if (event.kind === "message.recalled")
742
+ validateNativeRecallMetadata(event.data);
555
743
  event.cursor = decimal(event.cursor ?? eventCursor);
556
744
  yield event;
557
745
  }
@@ -598,7 +786,7 @@ function requireNativeIdentity(value) {
598
786
  }
599
787
  }
600
788
  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]]));
789
+ 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
790
  }
603
791
  function nativeHostTarget(platform = process.platform, arch = process.arch) {
604
792
  const cpu = arch === "arm64" ? "aarch64" : "x86_64";
@@ -1034,15 +1222,21 @@ function resolveWeChatIngress(params) {
1034
1222
  });
1035
1223
  }
1036
1224
 
1225
+ // src/outbound-options.ts
1226
+ import { createHash as createHash6 } from "node:crypto";
1227
+
1037
1228
  // src/outbound-media.ts
1038
1229
  import { createHash as createHash5 } from "node:crypto";
1039
1230
  import { randomUUID as randomUUID2 } from "node:crypto";
1040
1231
 
1041
1232
  // src/native-media.ts
1042
1233
  import { createHash as createHash4, randomUUID } from "node:crypto";
1043
- import { open } from "node:fs/promises";
1044
- import { basename, extname } from "node:path";
1234
+ import { openAsBlob } from "node:fs";
1235
+ import { mkdtemp, open, rm } from "node:fs/promises";
1236
+ import { tmpdir } from "node:os";
1237
+ import { basename, extname, join as join2 } from "node:path";
1045
1238
  import { getImageMetadata, resizeToJpeg, IMAGE_REDUCE_QUALITY_STEPS } from "openclaw/plugin-sdk/media-runtime";
1239
+ import { saveMediaStream } from "openclaw/plugin-sdk/media-store";
1046
1240
 
1047
1241
  // src/attachment-store.ts
1048
1242
  import { createHash as createHash3 } from "node:crypto";
@@ -1062,6 +1256,12 @@ async function saveManagedAttachment(params) {
1062
1256
  }
1063
1257
  const buffer = Buffer.from(params.data, "base64");
1064
1258
  if (buffer.byteLength !== size) throw new Error("Attachment decoding length mismatch");
1259
+ return saveManagedAttachmentBytes({ ...params, bytes: buffer });
1260
+ }
1261
+ async function saveManagedAttachmentBytes(params) {
1262
+ const size = params.bytes.byteLength;
1263
+ if (size > params.maxBytes) throw new AttachmentTooLargeError(`Attachment exceeds configured ${params.maxBytes} byte limit`);
1264
+ const buffer = Buffer.from(params.bytes.buffer, params.bytes.byteOffset, size);
1065
1265
  const sha256 = createHash3("sha256").update(buffer).digest("hex");
1066
1266
  const saved = await params.saveMediaBuffer(
1067
1267
  buffer,
@@ -1072,31 +1272,59 @@ async function saveManagedAttachment(params) {
1072
1272
  );
1073
1273
  return { path: saved.path, size, sha256, filename: params.filename };
1074
1274
  }
1275
+ async function saveVerifiedManagedAttachmentStream(params) {
1276
+ 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");
1277
+ let size = 0, finished = false;
1278
+ const digest2 = createHash3("sha256");
1279
+ const stream = (async function* () {
1280
+ for await (const chunk of params.stream) {
1281
+ params.assertCurrent();
1282
+ size += chunk.byteLength;
1283
+ if (size > params.maxBytes || size > params.expectedBytes) throw new AttachmentTooLargeError("Native attachment stream exceeds its bound");
1284
+ digest2.update(chunk);
1285
+ yield chunk;
1286
+ }
1287
+ params.assertCurrent();
1288
+ if (size !== params.expectedBytes || digest2.digest("hex") !== params.expectedSha256) throw new Error("Native attachment integrity did not verify");
1289
+ finished = true;
1290
+ })();
1291
+ const saved = await params.saveMediaStream(
1292
+ stream,
1293
+ params.mime,
1294
+ "inbound",
1295
+ params.maxBytes,
1296
+ params.filename,
1297
+ void 0,
1298
+ { assertCommitAllowed: params.assertCurrent, durable: true }
1299
+ );
1300
+ if (!finished || saved.size != null && saved.size !== size) throw new Error("Native attachment stream was not fully saved");
1301
+ return { path: saved.path, size, sha256: params.expectedSha256, filename: params.filename };
1302
+ }
1075
1303
 
1076
1304
  // src/media-delivery.ts
1077
1305
  function appendReference(body, reference) {
1078
1306
  return body ? `${body}
1079
1307
  ${reference}` : reference;
1080
1308
  }
1081
- function safeDisplayName(name2) {
1082
- return name2.replace(/[\r\n\0]/g, " ").trim() || "attachment";
1309
+ function safeDisplayName(name3) {
1310
+ return name3.replace(/[\r\n\0]/g, " ").trim() || "attachment";
1083
1311
  }
1084
1312
  function renderAttachmentBody(originalBody, attachment, exposeNonVisualPath = true) {
1085
1313
  if (!attachment) return originalBody;
1086
- const name2 = safeDisplayName(attachment.filename);
1314
+ const name3 = safeDisplayName(attachment.filename);
1087
1315
  if (attachment.status !== "ready" || !attachment.path) {
1088
1316
  const label = attachment.kind === "file" ? "File" : attachment.kind === "image" ? "Image" : attachment.kind === "audio" ? "Voice message" : "Video";
1089
1317
  if (attachment.status === "pending") {
1090
- return appendReference(originalBody, `[${label} pending: ${name2}]`);
1318
+ return appendReference(originalBody, `[${label} pending: ${name3}]`);
1091
1319
  }
1092
1320
  if (attachment.status === "expired") {
1093
- return appendReference(originalBody, `[${label} expired: ${name2}; no cached copy available. Ask the sender to resend.]`);
1321
+ return appendReference(originalBody, `[${label} expired: ${name3}; no cached copy available. Ask the sender to resend.]`);
1094
1322
  }
1095
- return appendReference(originalBody, `[${label} unavailable: ${name2} (${attachment.status})]`);
1323
+ return appendReference(originalBody, `[${label} unavailable: ${name3} (${attachment.status})]`);
1096
1324
  }
1097
1325
  if (attachment.kind === "file") {
1098
- const prefix = originalBody.trim() === name2 ? "" : originalBody;
1099
- return appendReference(prefix, `[File: ${name2}]
1326
+ const prefix = originalBody.trim() === name3 ? "" : originalBody;
1327
+ return appendReference(prefix, `[File: ${name3}]
1100
1328
  [Local file: <${attachment.path}>]`);
1101
1329
  }
1102
1330
  if (exposeNonVisualPath) {
@@ -1150,13 +1378,13 @@ async function nativeOutboundDelivery(client, accountId, threadId2, messageIds,
1150
1378
  async function submitNativeText(client, accountId, threadId2, text3, key, options = {}) {
1151
1379
  let intent = await client.sendText(accountId, threadId2, text3, key);
1152
1380
  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));
1381
+ let delay2 = Math.max(1, Math.min(options.initialDelayMs ?? 250, 1e3));
1154
1382
  while (["queued", "submitting"].includes(intent.state) && Date.now() < deadline) {
1155
- await new Promise((resolve) => setTimeout(resolve, Math.min(delay, deadline - Date.now())));
1383
+ await new Promise((resolve) => setTimeout(resolve, Math.min(delay2, deadline - Date.now())));
1156
1384
  const remaining = deadline - Date.now();
1157
1385
  if (remaining <= 0) break;
1158
1386
  intent = await client.send(accountId, intent.id, AbortSignal.timeout(remaining));
1159
- delay = Math.min(delay * 2, 1e3);
1387
+ delay2 = Math.min(delay2 * 2, 1e3);
1160
1388
  }
1161
1389
  if (!["accepted", "sent", "server_accepted"].includes(intent.state)) throw new Error(`Native send ${intent.id} requires inspection (${intent.state}); do not automatically resend`);
1162
1390
  return intent;
@@ -1164,15 +1392,33 @@ async function submitNativeText(client, accountId, threadId2, text3, key, option
1164
1392
 
1165
1393
  // src/native-recall-state.ts
1166
1394
  function nativeRecallInfo(message) {
1395
+ if (message.recall) validateNativeRecallMetadata(message.recall);
1167
1396
  return message.recall;
1168
1397
  }
1169
1398
  function nativeRecallIdentity(threadId2, serverId) {
1170
1399
  return JSON.stringify([threadId2, serverId]);
1171
1400
  }
1172
1401
  function validateNativeRecall(value) {
1402
+ validateNativeRecallMetadata(value);
1173
1403
  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
1404
  }
1405
+ function mergeNativeRecall(prior, next) {
1406
+ validateNativeRecall(prior);
1407
+ validateNativeRecall(next);
1408
+ if (prior.threadId !== next.threadId || prior.serverId !== next.serverId) throw Error("Conflicting native recall identity; cursor retained");
1409
+ return {
1410
+ threadId: prior.threadId,
1411
+ serverId: prior.serverId,
1412
+ observedAt: prior.observedAt,
1413
+ ...prior.messageId ?? next.messageId ? { messageId: prior.messageId ?? next.messageId } : {},
1414
+ ...prior.recalledAt ?? next.recalledAt ? { recalledAt: prior.recalledAt ?? next.recalledAt } : {},
1415
+ ...(prior.replacementText ?? next.replacementText) != null ? { replacementText: prior.replacementText ?? next.replacementText } : {}
1416
+ };
1417
+ }
1175
1418
  function recalledNativeMessage(message, recall) {
1419
+ validateNativeRecall(recall);
1420
+ const previous = nativeRecallInfo(message);
1421
+ const replacementText = previous?.replacementText ?? recall.replacementText;
1176
1422
  return {
1177
1423
  ...message,
1178
1424
  type: 1e4,
@@ -1180,8 +1426,51 @@ function recalledNativeMessage(message, recall) {
1180
1426
  quote: void 0,
1181
1427
  link: void 0,
1182
1428
  media: [],
1429
+ senderId: message.senderId || null,
1430
+ direction: message.senderId ? message.direction : null,
1183
1431
  mentions: { state: "unknown", userIds: [], self: null, all: null, source: null },
1184
- recall: { observedAt: recall.observedAt, ...recall.recalledAt ? { recalledAt: recall.recalledAt } : {} }
1432
+ recall: {
1433
+ observedAt: previous?.observedAt ?? recall.observedAt,
1434
+ ...previous?.recalledAt ?? recall.recalledAt ? { recalledAt: previous?.recalledAt ?? recall.recalledAt } : {},
1435
+ ...replacementText != null ? { replacementText } : {}
1436
+ }
1437
+ };
1438
+ }
1439
+
1440
+ // src/native-quote.ts
1441
+ function sameEmbeddedQuote(stored, current) {
1442
+ if (stored.state === "unsupported" && current.state === "embedded")
1443
+ return ["serverId", "type", "appMessageType", "senderId", "direction"].every((field) => (stored[field] ?? null) === (current[field] ?? null));
1444
+ const compared = { ...current };
1445
+ for (const field of ["embeddedLink", "embeddedSticker"]) {
1446
+ if (!Object.hasOwn(stored, field)) delete compared[field];
1447
+ }
1448
+ return JSON.stringify(stored) === JSON.stringify(compared);
1449
+ }
1450
+ function renderEmbeddedQuote(message, permitted = true, imageBody) {
1451
+ const comment = (message.body ?? "").slice(0, 16384);
1452
+ const source = message.quote;
1453
+ const unavailable = (state2) => ({
1454
+ body: `${comment}${comment ? "\n\n" : ""}[Quoted message ${state2}]`,
1455
+ image: false,
1456
+ quote: { state: state2, type: source?.type, senderId: source?.senderId ?? void 0 }
1457
+ });
1458
+ if (!source) return unavailable("unavailable");
1459
+ if (!permitted) return unavailable("not permitted");
1460
+ const state = source.state ?? "missing";
1461
+ if (state === "recalled") return unavailable("recalled");
1462
+ 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");
1463
+ const label = source.type === 1 ? "text" : source.type === 3 ? "image" : source.type === 34 ? "voice" : source.type === 43 ? "video" : source.type === 49 && source.appMessageType === 5 ? "link" : source.type === 49 && source.appMessageType === 6 ? "file" : "message";
1464
+ const image = state === "embedded" && source.type === 3 && source.embeddedImage === true;
1465
+ if (state === "embedded" && !image && !source.embeddedText) return unavailable("invalid");
1466
+ const content = state === "missing" ? "" : image ? imageBody ?? "[Image metadata embedded in quote; image not retrieved]" : source.embeddedText ?? "";
1467
+ const status = state === "unsupported" ? `[${label} attachment unavailable from embedded quote]` : state === "missing" ? "[Embedded quote content unavailable]" : "";
1468
+ return {
1469
+ body: `${comment}${comment ? "\n\n" : ""}[Quoted ${label} from ${source.senderId ?? "unknown sender"}; embedded in reply]
1470
+ ${[content, status].filter(Boolean).join("\n")}
1471
+ [/Quoted message]`,
1472
+ image,
1473
+ quote: { state, type: source.type, senderId: source.senderId ?? void 0 }
1185
1474
  };
1186
1475
  }
1187
1476
 
@@ -1192,6 +1481,26 @@ function kind(type) {
1192
1481
  var terminalJobs = /* @__PURE__ */ new Set(["accepted", "completed", "succeeded", "available", "failed", "partial", "cancelled", "expired", "needs_review"]);
1193
1482
  var successfulSendJobs = /* @__PURE__ */ new Set(["accepted", "completed", "succeeded"]);
1194
1483
  var terminalIdentityErrors = /* @__PURE__ */ new Set(["media_identity_unavailable", "media_source_changed"]);
1484
+ var NativeMediaJobInspectionError = class extends Error {
1485
+ code = "native_media_job_inspection_required";
1486
+ retryable = false;
1487
+ jobId;
1488
+ accountId;
1489
+ threadId;
1490
+ idempotencyKey;
1491
+ state;
1492
+ reason;
1493
+ constructor(job, accountId, threadId2, key, reason) {
1494
+ super(`Native media job ${job.id} requires inspection (${job.state}); retain the original job and idempotency key and do not automatically resend`);
1495
+ this.name = "NativeMediaJobInspectionError";
1496
+ this.jobId = job.id;
1497
+ this.accountId = accountId;
1498
+ this.threadId = threadId2;
1499
+ this.idempotencyKey = key;
1500
+ this.state = job.state;
1501
+ this.reason = reason;
1502
+ }
1503
+ };
1195
1504
  function mediaSendResult(job) {
1196
1505
  return job.result && typeof job.result === "object" && !Array.isArray(job.result) ? job.result : {};
1197
1506
  }
@@ -1207,11 +1516,11 @@ function mediaSendReceiptIds(job, audioAsVoice) {
1207
1516
  async function waitNativeMediaSendReceipts(client, accountId, threadId2, initial, audioAsVoice, timeoutMs = 1e4) {
1208
1517
  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
1518
  const deadline = Date.now() + Math.max(0, Math.min(timeoutMs, 1e4));
1210
- let job = initial, delay = 100;
1519
+ let job = initial, delay2 = 100;
1211
1520
  while (successfulSendJobs.has(job.state) && !mediaSendReceiptIds(job, audioAsVoice) && Date.now() < deadline) {
1212
1521
  const result = mediaSendResult(job);
1213
1522
  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()))));
1523
+ await new Promise((resolve) => setTimeout(resolve, Math.min(delay2, Math.max(0, deadline - Date.now()))));
1215
1524
  const remaining = deadline - Date.now();
1216
1525
  if (remaining <= 0) break;
1217
1526
  let next;
@@ -1222,27 +1531,46 @@ async function waitNativeMediaSendReceipts(client, accountId, threadId2, initial
1222
1531
  }
1223
1532
  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
1533
  job = next;
1225
- delay = Math.min(delay * 2, 1e3);
1534
+ delay2 = Math.min(delay2 * 2, 1e3);
1226
1535
  }
1227
1536
  return job;
1228
1537
  }
1229
1538
  async function waitNativeMediaJob(client, accountId, initial, timeoutMs = 65e3, signal, assertCurrent) {
1539
+ return waitNativeMediaStatus(initial, timeoutMs, signal, assertCurrent, (job, pollSignal) => client.job(accountId, job.id, pollSignal));
1540
+ }
1541
+ async function waitNativeMediaStatus(initial, timeoutMs, signal, assertCurrent, readStatus) {
1230
1542
  const deadline = Date.now() + timeoutMs;
1231
1543
  let job = initial;
1232
- let delay = 250;
1544
+ let delay2 = 250;
1233
1545
  while (!terminalJobs.has(job.state) && Date.now() < deadline) {
1234
1546
  signal?.throwIfAborted();
1235
1547
  assertCurrent?.();
1236
- await new Promise((resolve) => setTimeout(resolve, Math.min(delay, Math.max(0, deadline - Date.now()))));
1548
+ await new Promise((resolve) => setTimeout(resolve, Math.min(delay2, Math.max(0, deadline - Date.now()))));
1237
1549
  const remaining = deadline - Date.now();
1238
1550
  if (remaining <= 0) break;
1239
1551
  signal?.throwIfAborted();
1240
1552
  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);
1553
+ const next = await readStatus(job, signal ? AbortSignal.any([signal, AbortSignal.timeout(remaining)]) : AbortSignal.timeout(remaining));
1554
+ if (!next) break;
1555
+ job = next;
1556
+ delay2 = Math.min(delay2 * 2, 1e3);
1243
1557
  }
1244
1558
  return job;
1245
1559
  }
1560
+ async function incomingMediaJobStatus(client, accountId, jobId, assetId, signal, assertCurrent) {
1561
+ let job;
1562
+ assertCurrent();
1563
+ try {
1564
+ job = await client.job(accountId, jobId, signal);
1565
+ } catch (error) {
1566
+ assertCurrent();
1567
+ 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;
1568
+ throw error;
1569
+ }
1570
+ assertCurrent();
1571
+ 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");
1572
+ return job;
1573
+ }
1246
1574
  function select(assets, type, quality = "best") {
1247
1575
  const preferred = type === 34 ? ["normal"] : type === 43 ? ["normal", "original"] : ["original", "standard", "thumbnail", "encoded"];
1248
1576
  const rank = (asset) => {
@@ -1301,83 +1629,37 @@ ${prepared.body}`,
1301
1629
  };
1302
1630
  }
1303
1631
  async function prepareNativeQuote(params) {
1304
- const { client, account, message } = params;
1305
- const guard = () => {
1632
+ const { message } = params;
1633
+ const guard2 = () => {
1306
1634
  params.signal?.throwIfAborted();
1307
1635
  params.assertCurrent?.();
1308
1636
  };
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 };
1637
+ guard2();
1638
+ const author = { senderId: message.quote?.senderId ?? null, direction: message.quote?.direction ?? null };
1639
+ const permitted = !message.quote || !params.allowQuotedMessage || await params.allowQuotedMessage(author);
1640
+ guard2();
1641
+ const rendered = renderEmbeddedQuote(message, permitted);
1642
+ if (!rendered.image) return {
1643
+ body: rendered.body,
1644
+ quote: rendered.quote,
1645
+ pending: false,
1646
+ retryable: false,
1647
+ ...rendered.quote.state === "recalled" ? { reason: "message_recalled" } : {}
1648
+ };
1366
1649
  const beforeMediaAccess = async () => {
1367
1650
  await params.beforeMediaAccess?.();
1368
- guard();
1369
- if (params.allowQuotedMessage && !await params.allowQuotedMessage(original)) throw Error("Quoted message is no longer permitted");
1370
- guard();
1651
+ guard2();
1652
+ if (params.allowQuotedMessage && !await params.allowQuotedMessage(author)) throw Error("Quoted message is no longer permitted");
1653
+ guard2();
1371
1654
  };
1372
- const prepared = await prepareNativeAttachment({ ...params, message: original, beforeMediaAccess });
1655
+ const prepared = await prepareNativeAttachment({ ...params, message: { ...message, type: 3, appMessageType: void 0, quote: void 0, link: void 0 }, beforeMediaAccess });
1656
+ if (prepared.reason === "message_recalled" || terminalIdentityErrors.has(prepared.reason ?? "")) return prepared;
1373
1657
  return {
1374
1658
  ...prepared,
1375
- body: `${prefix}${prepared.body}
1376
- [/Quoted message]`,
1659
+ body: renderEmbeddedQuote(message, true, prepared.body).body,
1660
+ quote: rendered.quote,
1377
1661
  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 }))
1662
+ ...prepared.pending ? { attachment: { kind: "image", status: "pending", filename: "quoted-image" } } : {}
1381
1663
  };
1382
1664
  }
1383
1665
  async function prepareNativeAttachment(params) {
@@ -1402,16 +1684,16 @@ async function prepareNativeAttachment(params) {
1402
1684
  async function prepareNativeAttachmentInput(params) {
1403
1685
  const { client, account, message, core } = params;
1404
1686
  const attachmentKind = kind(message.type);
1405
- const guard = () => {
1687
+ const guard2 = () => {
1406
1688
  params.signal?.throwIfAborted();
1407
1689
  params.assertCurrent?.();
1408
1690
  };
1409
- guard();
1691
+ guard2();
1410
1692
  if (nativeRecallInfo(message)) return { body: "[Message recalled]", pending: false, retryable: false, reason: "message_recalled" };
1411
1693
  const authorize = async () => {
1412
- guard();
1694
+ guard2();
1413
1695
  await params.beforeMediaAccess?.();
1414
- guard();
1696
+ guard2();
1415
1697
  };
1416
1698
  if (message.type === 49 && message.appMessageType === 57) return prepareNativeQuote(params);
1417
1699
  if (message.type === 49 && message.appMessageType === 19) return { body: message.body?.slice(0, 65536) || "[Forwarded chat history unavailable]", pending: false };
@@ -1419,11 +1701,14 @@ async function prepareNativeAttachmentInput(params) {
1419
1701
  if (message.type === 49 && message.appMessageType != null && message.appMessageType !== 6) return { body: `[Unsupported WeChat app message subtype ${message.appMessageType}]`, pending: false, retryable: false };
1420
1702
  if (!attachmentKind) return { body: message.type === 1 ? message.body ?? "" : `[Unsupported WeChat message type ${message.type}]`, pending: false };
1421
1703
  const accountId = account.native.accountId;
1422
- const maxBytes = Math.min(account.mediaMaxMb * 1024 * 1024, 128 * 1024 * 1024);
1704
+ const maxBytes = Math.min(
1705
+ account.mediaMaxMb * 1024 * 1024,
1706
+ attachmentKind === "file" ? Math.max(NATIVE_MAX_SOURCE_BYTES, 128 * 1024 * 1024) : 128 * 1024 * 1024
1707
+ );
1423
1708
  const scopedAssets = async () => {
1424
1709
  await authorize();
1425
1710
  const items = (await client.mediaAssets(accountId, message.id)).items;
1426
- guard();
1711
+ guard2();
1427
1712
  if (items.some((asset2) => asset2.accountId !== accountId || asset2.messageId !== message.id)) throw Error("Native attachment identity does not match its message");
1428
1713
  return items;
1429
1714
  };
@@ -1445,9 +1730,9 @@ async function prepareNativeAttachmentInput(params) {
1445
1730
  let transferError;
1446
1731
  if (!asset && initialCandidate?.jobId && initialCandidate.state !== "recalled") {
1447
1732
  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");
1733
+ job = await incomingMediaJobStatus(client, accountId, initialCandidate.jobId, initialCandidate.id, params.signal, guard2);
1734
+ guard2();
1735
+ if (!job) return { body: `[${attachmentKind} pending: retrieval is unavailable]`, pending: true, jobId: initialCandidate.jobId, retryable: true };
1451
1736
  assets = await scopedAssets();
1452
1737
  asset = select(assets, message.type, quality);
1453
1738
  if (!asset && transferCandidate()?.state === "recalled") return { body: "[Message recalled]", pending: false, retryable: false, reason: "message_recalled" };
@@ -1457,11 +1742,17 @@ async function prepareNativeAttachmentInput(params) {
1457
1742
  await authorize();
1458
1743
  try {
1459
1744
  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();
1745
+ guard2();
1746
+ job = await waitNativeMediaStatus(
1747
+ job,
1748
+ params.waitMs ?? 2e4,
1749
+ params.signal,
1750
+ guard2,
1751
+ (known, pollSignal) => incomingMediaJobStatus(client, accountId, known.id, initialCandidate?.id, pollSignal, guard2)
1752
+ );
1753
+ guard2();
1463
1754
  } catch (error) {
1464
- guard();
1755
+ guard2();
1465
1756
  if (!(error instanceof NativeApiError) || terminalIdentityErrors.has(error.code)) throw error;
1466
1757
  if (error.retryable) return { body: `[${attachmentKind} pending: retrieval is unavailable]`, pending: true, jobId: job?.id, retryable: true };
1467
1758
  transferError = error;
@@ -1491,14 +1782,63 @@ async function prepareNativeAttachmentInput(params) {
1491
1782
  return { body: renderAttachmentBody("", attachment2), attachment: attachment2, pending: false };
1492
1783
  }
1493
1784
  await authorize();
1785
+ if (attachmentKind === "file" && asset.byteLength != null && asset.byteLength > 128 * 1024 * 1024) {
1786
+ const content2 = await client.mediaContentStream(accountId, asset.id, { maxBytes, signal: params.signal });
1787
+ const mime2 = content2.contentType.split(";", 1)[0].trim().toLowerCase();
1788
+ if (!/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/.test(mime2)) {
1789
+ await content2.cancel();
1790
+ throw Error("Native attachment MIME type is unsupported");
1791
+ }
1792
+ let saved2;
1793
+ try {
1794
+ saved2 = await saveVerifiedManagedAttachmentStream({
1795
+ stream: content2.stream,
1796
+ mime: mime2,
1797
+ filename,
1798
+ maxBytes,
1799
+ expectedBytes: asset.byteLength,
1800
+ expectedSha256: asset.sha256 ?? "",
1801
+ assertCurrent: guard2,
1802
+ saveMediaStream: params.saveMediaStream ?? saveMediaStream
1803
+ });
1804
+ } finally {
1805
+ await content2.cancel();
1806
+ }
1807
+ await authorize();
1808
+ const attachment2 = { kind: "file", filename, status: "ready", path: saved2.path, mime: mime2 };
1809
+ return {
1810
+ body: renderAttachmentBody("", attachment2),
1811
+ attachment: attachment2,
1812
+ mediaMime: mime2,
1813
+ pending: false,
1814
+ jobId: job?.id,
1815
+ retryable: false,
1816
+ variant: asset.actualVariant ?? asset.variant,
1817
+ suppliedAssets: [{
1818
+ id: asset.id,
1819
+ contextRole: "trigger",
1820
+ role: "file_reference",
1821
+ kind: "file",
1822
+ path: saved2.path,
1823
+ mime: mime2,
1824
+ sha256: saved2.sha256,
1825
+ byteLength: saved2.size,
1826
+ runtimeMedia: false,
1827
+ sourceSha256: saved2.sha256,
1828
+ sourceByteLength: saved2.size,
1829
+ sourceMime: mime2,
1830
+ sourcePath: saved2.path
1831
+ }]
1832
+ };
1833
+ }
1494
1834
  const content = await client.mediaContent(accountId, asset.id, { maxBytes, signal: params.signal });
1495
- guard();
1835
+ guard2();
1496
1836
  const mime = content.contentType.split(";", 1)[0].trim().toLowerCase();
1497
1837
  if (!/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/.test(mime)) throw Error("Native attachment MIME type is unsupported");
1498
1838
  const hash = createHash4("sha256").update(content.bytes).digest("hex");
1499
1839
  if (!asset.sha256 || hash !== asset.sha256 || asset.byteLength != null && asset.byteLength !== content.bytes.length) throw new Error("Native attachment integrity did not verify");
1500
1840
  await authorize();
1501
- const saved = await saveManagedAttachment({ data: Buffer.from(content.bytes).toString("base64"), mime, filename, maxBytes, saveMediaBuffer: core.channel.media.saveMediaBuffer });
1841
+ const saved = await saveManagedAttachmentBytes({ bytes: content.bytes, mime, filename, maxBytes, saveMediaBuffer: core.channel.media.saveMediaBuffer });
1502
1842
  const actual = asset.actualVariant ?? asset.variant;
1503
1843
  const attachment = {
1504
1844
  kind: attachmentKind,
@@ -1518,7 +1858,7 @@ async function prepareNativeAttachmentInput(params) {
1518
1858
  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
1859
  await authorize();
1520
1860
  const derived = await client.mediaContent(accountId, asset.id, { maxBytes: preview.byteLength, representation: "preview", signal: params.signal });
1521
- guard();
1861
+ guard2();
1522
1862
  const derivedMime = derived.contentType.split(";", 1)[0].trim().toLowerCase();
1523
1863
  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
1864
  imageBytes = Buffer.from(derived.bytes);
@@ -1543,7 +1883,7 @@ async function prepareNativeAttachmentInput(params) {
1543
1883
  [Model image: prepared still preview; original retained separately]`;
1544
1884
  }
1545
1885
  }
1546
- guard();
1886
+ guard2();
1547
1887
  return {
1548
1888
  body,
1549
1889
  attachment,
@@ -1570,78 +1910,114 @@ async function prepareNativeAttachmentInput(params) {
1570
1910
  pending: false
1571
1911
  };
1572
1912
  }
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);
1913
+ function validateNativeMediaSendOptions(options, audioAsVoice = false) {
1914
+ if (options.forceDocument != null && typeof options.forceDocument !== "boolean") throw new Error("Invalid WeChat document option");
1915
+ if (options.videoQuality != null && !["normal", "original"].includes(options.videoQuality)) throw new Error("Invalid WeChat video quality");
1916
+ if (options.forceDocument && (audioAsVoice || options.videoQuality != null)) throw new Error("Document sending cannot also request voice or video quality");
1917
+ }
1918
+ function outboundMediaKind(mime, audioAsVoice, options) {
1919
+ if (options.forceDocument) return "file";
1920
+ if (audioAsVoice && !mime.startsWith("audio/")) throw new Error("Voice sending requires an explicit audio attachment");
1921
+ const selected = audioAsVoice ? "voice" : mime.startsWith("image/") ? "image" : mime.startsWith("video/") ? "video" : "file";
1922
+ if (options.videoQuality != null && selected !== "video") throw new Error("Video quality requires a video attachment");
1923
+ return selected;
1924
+ }
1925
+ function outboundSourceLimit(account, selectedKind) {
1926
+ 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);
1927
+ }
1928
+ async function sendNativeAttachment(client, account, threadId2, mediaUrl, audioAsVoice = false, key = randomUUID(), beforeSend, options = {}) {
1929
+ validateNativeMediaSendOptions(options, audioAsVoice);
1930
+ await beforeSend?.();
1931
+ let filename, mime, selectedKind, sourceBytes, source;
1932
+ let temporary;
1933
+ const accountId = account.native.accountId;
1934
+ try {
1935
+ let blob;
1936
+ if (/^https?:/.test(mediaUrl)) {
1937
+ const response = await fetch(mediaUrl, { redirect: "error", signal: AbortSignal.timeout(60 * 6e4) });
1938
+ if (!response.ok) throw new Error(`Native outbound source unavailable (${response.status})`);
1939
+ filename = basename(new URL(mediaUrl).pathname) || "attachment";
1940
+ mime = response.headers.get("content-type")?.split(";")[0].trim().toLowerCase() ?? "application/octet-stream";
1941
+ try {
1942
+ selectedKind = outboundMediaKind(mime, audioAsVoice, options);
1943
+ } catch (error) {
1944
+ await response.body?.cancel();
1945
+ throw error;
1597
1946
  }
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));
1947
+ const max = outboundSourceLimit(account, selectedKind);
1948
+ const length = response.headers.get("content-length");
1949
+ if (length && (!/^\d+$/.test(length) || Number(length) > max)) {
1950
+ await response.body?.cancel();
1951
+ throw new Error("Native outbound source exceeds configured size");
1627
1952
  }
1628
- bytes = Buffer.concat(chunks2, size);
1629
- } finally {
1630
- await file.close();
1953
+ const reader = response.body?.getReader();
1954
+ if (!reader) throw new Error("Native outbound source has no bytes");
1955
+ let path, file, size = 0;
1956
+ try {
1957
+ temporary = await mkdtemp(join2(tmpdir(), "wechat-outbound-"));
1958
+ path = join2(temporary, "source");
1959
+ file = await open(path, "wx", 384);
1960
+ while (true) {
1961
+ const { value, done } = await reader.read();
1962
+ if (done) break;
1963
+ size += value.byteLength;
1964
+ if (size > max) throw new Error("Native outbound source exceeds configured size");
1965
+ await file.writeFile(value);
1966
+ }
1967
+ if (!size || length && size !== Number(length)) throw new Error("Native outbound source length mismatch");
1968
+ } finally {
1969
+ await reader.cancel().catch(() => {
1970
+ });
1971
+ reader.releaseLock();
1972
+ await file?.close();
1973
+ }
1974
+ blob = await openAsBlob(path, { type: mime });
1975
+ } else {
1976
+ const path = mediaUrl.startsWith("file:") ? new URL(mediaUrl) : mediaUrl;
1977
+ filename = basename(path instanceof URL ? path.pathname : path);
1978
+ const extension = extname(filename).toLowerCase();
1979
+ 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";
1980
+ selectedKind = outboundMediaKind(mime, audioAsVoice, options);
1981
+ const max = outboundSourceLimit(account, selectedKind), file = await open(path, "r");
1982
+ let size;
1983
+ try {
1984
+ const stat = await file.stat();
1985
+ if (!stat.isFile() || !stat.size || stat.size > max) throw new Error("Native outbound source must be a bounded regular file");
1986
+ size = stat.size;
1987
+ } finally {
1988
+ await file.close();
1989
+ }
1990
+ blob = await openAsBlob(path, { type: mime });
1991
+ if (blob.size !== size) throw new Error("Native outbound source changed before staging");
1631
1992
  }
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";
1993
+ sourceBytes = blob.size;
1994
+ if (sourceBytes > outboundSourceLimit(account, selectedKind)) throw new Error("Native outbound source exceeds selected media kind size");
1995
+ await beforeSend?.();
1996
+ source = await client.upload(accountId, blob, filename, mime);
1997
+ } finally {
1998
+ if (temporary) await rm(temporary, { recursive: true, force: true });
1635
1999
  }
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 };
2000
+ const input = {
2001
+ threadId: threadId2,
2002
+ kind: selectedKind,
2003
+ sourceId: source.id,
2004
+ standardSourceId: null,
2005
+ thumbnailSourceId: null,
2006
+ playSeconds: null,
2007
+ durationMs: null,
2008
+ ...selectedKind === "video" ? { videoQuality: options.videoQuality ?? "normal" } : {}
2009
+ };
1641
2010
  await beforeSend?.();
1642
- let job = await waitNativeMediaJob(client, accountId, await client.sendMedia(accountId, input, key), audioAsVoice ? 25 * 6e4 : 65e3);
2011
+ const waitMs = audioAsVoice ? 25 * 6e4 : selectedKind === "video" || selectedKind === "file" && sourceBytes > NATIVE_MAX_ORDINARY_SOURCE_BYTES ? 60 * 6e4 : 65e3;
2012
+ const submitted = await client.sendMedia(accountId, input, key);
2013
+ let job;
2014
+ try {
2015
+ job = await waitNativeMediaJob(client, accountId, submitted, waitMs);
2016
+ } catch {
2017
+ throw new NativeMediaJobInspectionError(submitted, accountId, threadId2, key, "status_unavailable");
2018
+ }
1643
2019
  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`);
2020
+ if (!successfulSendJobs.has(job.state)) throw new NativeMediaJobInspectionError(job, accountId, threadId2, key, "job_not_completed");
1645
2021
  const result = mediaSendResult(job);
1646
2022
  const chunks = Array.isArray(result.chunks) ? result.chunks.filter((chunk) => chunk && typeof chunk === "object") : [];
1647
2023
  const serverIds = audioAsVoice ? chunks.filter((chunk) => chunk.state === "accepted" && typeof chunk.serverMessageId === "string").map((chunk) => chunk.serverMessageId) : job.serverMessageId ? [job.serverMessageId] : void 0;
@@ -1649,13 +2025,16 @@ async function sendNativeAttachment(client, account, threadId2, mediaUrl, audioA
1649
2025
  }
1650
2026
 
1651
2027
  // src/outbound-media.ts
1652
- async function sendWeChatMedia(cfg, to, text3, mediaUrl, audioAsVoice = false, idempotencyKey) {
2028
+ async function sendWeChatMedia(cfg, to, text3, mediaUrl, audioAsVoice = false, idempotencyKey, options = {}, beforeSend) {
2029
+ validateNativeMediaSendOptions(options, audioAsVoice);
2030
+ if (!mediaUrl && (options.forceDocument || options.videoQuality != null)) throw new Error("WeChat media options require an attachment");
1653
2031
  const account = resolveWeChatAccount(cfg);
1654
2032
  if (!account?.native) throw new Error("No native daemon configured");
1655
2033
  const { client } = await ensureNativeHost(account.native);
1656
2034
  const key = idempotencyKey ?? randomUUID2();
1657
2035
  if (!mediaUrl) {
1658
2036
  if (audioAsVoice) throw new Error("Voice sending requires an audio attachment");
2037
+ await beforeSend?.();
1659
2038
  const send = await submitNativeText(client, account.native.accountId, to, text3, key);
1660
2039
  return nativeOutboundDelivery(
1661
2040
  client,
@@ -1665,26 +2044,116 @@ async function sendWeChatMedia(cfg, to, text3, mediaUrl, audioAsVoice = false, i
1665
2044
  { sendId: send.id, state: send.state, serverIds: send.serverId ? [send.serverId] : void 0 }
1666
2045
  );
1667
2046
  }
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"));
2047
+ const result = await sendNativeAttachment(client, account, to, mediaUrl, audioAsVoice, key, beforeSend, options);
2048
+ if (text3) {
2049
+ await beforeSend?.();
2050
+ await submitNativeText(client, account.native.accountId, to, text3, createHash5("sha256").update(`${key}\0caption`).digest("hex"));
2051
+ }
1670
2052
  return result;
1671
2053
  }
1672
2054
 
2055
+ // src/outbound-options.ts
2056
+ function nativePayloadMediaOptions(payload) {
2057
+ const value = payload.channelData?.["agent-wechat"];
2058
+ if (value == null) return {};
2059
+ if (typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => key !== "videoQuality") || !["normal", "original"].includes(value.videoQuality)) throw Error("Invalid WeChat media options");
2060
+ return { videoQuality: value.videoQuality };
2061
+ }
2062
+ var wechatMediaActions = {
2063
+ describeMessageTool: () => ({ actions: ["send"], schema: { actions: ["send"], visibility: "all-configured", properties: {
2064
+ channelData: { type: "object", description: "WeChat per-send media options. Use agent-wechat.videoQuality for a single video attachment.", additionalProperties: true, properties: {
2065
+ "agent-wechat": { type: "object", additionalProperties: false, required: ["videoQuality"], properties: {
2066
+ videoQuality: { type: "string", enum: ["normal", "original"], description: "WeChat video mode: normal prepares playback; original also retains the unchanged source video. Cannot combine with forceDocument." }
2067
+ } }
2068
+ } }
2069
+ } } }),
2070
+ prepareSendPayload: ({ ctx, payload }) => {
2071
+ const options = nativePayloadMediaOptions(payload);
2072
+ if (options.videoQuality == null) return void 0;
2073
+ validateNativeMediaSendOptions({ ...options, forceDocument: ctx.params.forceDocument ?? ctx.params.asDocument }, payload.audioAsVoice);
2074
+ return payload;
2075
+ }
2076
+ };
2077
+ var NativeMediaPayloadInspectionError = class extends Error {
2078
+ retryable = false;
2079
+ code = "native_media_payload_inspection_required";
2080
+ deliveries;
2081
+ pendingJob;
2082
+ constructor(deliveries, pendingJob) {
2083
+ super("WeChat attachment batch requires inspection; retain completed receipts and do not automatically resend");
2084
+ this.name = "NativeMediaPayloadInspectionError";
2085
+ this.deliveries = deliveries;
2086
+ this.pendingJob = pendingJob;
2087
+ }
2088
+ };
2089
+ function createWeChatMediaHandlers(send = sendWeChatMedia) {
2090
+ const key = (ctx, index = 0) => ctx.deliveryQueueId ? createHash6("sha256").update(JSON.stringify(["wechat-media", ctx.deliveryQueueId, ctx.deliveryPartIndex ?? 0, index])).digest("hex") : void 0;
2091
+ const guard2 = (ctx) => async () => {
2092
+ ctx.signal?.throwIfAborted();
2093
+ await ctx.onPlatformSendDispatch?.();
2094
+ ctx.signal?.throwIfAborted();
2095
+ ctx.assertDirectAdapterHandoff?.();
2096
+ };
2097
+ return {
2098
+ sendMedia: async (ctx) => ({
2099
+ channel: "agent-wechat",
2100
+ ...await send(ctx.cfg, ctx.to, ctx.text, ctx.mediaUrl, ctx.audioAsVoice, key(ctx), { forceDocument: ctx.forceDocument }, guard2(ctx))
2101
+ }),
2102
+ sendPayload: async (ctx) => {
2103
+ const options = { ...nativePayloadMediaOptions(ctx.payload), forceDocument: ctx.forceDocument };
2104
+ const audioAsVoice = ctx.payload.audioAsVoice ?? ctx.audioAsVoice;
2105
+ validateNativeMediaSendOptions(options, audioAsVoice);
2106
+ const urls = [...new Set([...ctx.payload.mediaUrls ?? [], ctx.payload.mediaUrl ?? ctx.mediaUrl].filter((url2) => typeof url2 === "string" && !!url2))];
2107
+ if (urls.length > 16 || options.videoQuality != null && urls.length !== 1) throw Error("WeChat video quality requires one attachment per send");
2108
+ const deliveries = [];
2109
+ for (const [index, mediaUrl] of (urls.length ? urls : [void 0]).entries()) {
2110
+ let delivered;
2111
+ try {
2112
+ delivered = await send(ctx.cfg, ctx.to, index === 0 ? ctx.payload.text ?? ctx.text : "", mediaUrl, audioAsVoice, key(ctx, index), options, guard2(ctx));
2113
+ } catch (error) {
2114
+ if (!deliveries.length) throw error;
2115
+ throw new NativeMediaPayloadInspectionError(deliveries, error instanceof NativeMediaJobInspectionError ? { jobId: error.jobId, accountId: error.accountId, threadId: error.threadId, idempotencyKey: error.idempotencyKey } : void 0);
2116
+ }
2117
+ deliveries.push(delivered);
2118
+ if (urls.length > 1) {
2119
+ try {
2120
+ await ctx.onDeliveryResult?.({ channel: "agent-wechat", ...delivered });
2121
+ } catch {
2122
+ throw new NativeMediaPayloadInspectionError(deliveries);
2123
+ }
2124
+ }
2125
+ if (delivered.meta.outcome === "unknown") break;
2126
+ }
2127
+ const first = deliveries[0];
2128
+ return {
2129
+ channel: "agent-wechat",
2130
+ ...first,
2131
+ ...deliveries.length > 1 ? { meta: {
2132
+ ...first.meta,
2133
+ parts: deliveries,
2134
+ retryable: false,
2135
+ ...deliveries.some((part) => part.meta.outcome === "unknown") ? { outcome: "unknown", receiptState: "needs_review" } : {}
2136
+ } } : {}
2137
+ };
2138
+ }
2139
+ };
2140
+ }
2141
+
1673
2142
  // src/native-monitor.ts
1674
- import { createHash as createHash8 } from "node:crypto";
2143
+ import { createHash as createHash9 } from "node:crypto";
1675
2144
  import { createChannelMessageReplyPipeline } from "openclaw/plugin-sdk/channel-outbound";
1676
2145
  import { resolveStableChannelMessageIngress } from "openclaw/plugin-sdk/channel-ingress-runtime";
1677
2146
 
1678
2147
  // src/native-consumer-state.ts
1679
- import { createHash as createHash6, randomUUID as randomUUID3 } from "node:crypto";
2148
+ import { createHash as createHash7, randomUUID as randomUUID3 } from "node:crypto";
1680
2149
  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";
2150
+ import { dirname as dirname2, isAbsolute as isAbsolute2, join as join3 } from "node:path";
1682
2151
  var NativeConsumerState = class {
1683
2152
  file;
1684
2153
  value;
1685
2154
  constructor(directory, serverId, accountId) {
1686
2155
  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`);
2156
+ this.file = join3(directory, `${createHash7("sha256").update(`${serverId}\0${accountId}`).digest("hex")}.json`);
1688
2157
  this.value = { schemaVersion: 1, serverId, accountId, cursor: "0", items: {} };
1689
2158
  if (existsSync(this.file)) {
1690
2159
  const stat = lstatSync(this.file);
@@ -1693,6 +2162,7 @@ var NativeConsumerState = class {
1693
2162
  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
2163
  for (const [id2, item] of Object.entries(parsed.items)) {
1695
2164
  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");
2165
+ nativeRecallInfo(item.message);
1696
2166
  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
2167
  if (item.revision != null && (typeof item.revision !== "string" || !item.revision || item.revision.length > 64)) throw Error("Invalid native custody revision; state was preserved");
1698
2168
  item.revision ??= randomUUID3();
@@ -1822,13 +2292,8 @@ var NativeConsumerState = class {
1822
2292
  }
1823
2293
  const key = nativeRecallIdentity(recall.threadId, recall.serverId);
1824
2294
  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
- };
2295
+ const remembered = mergeNativeRecall(this.value.recalls[key] ?? recall, recall);
2296
+ this.value.recalls[key] = remembered;
1832
2297
  const affected = /* @__PURE__ */ new Set();
1833
2298
  for (const item of this.items()) {
1834
2299
  if (item.message.threadId !== recall.threadId) continue;
@@ -1836,7 +2301,7 @@ var NativeConsumerState = class {
1836
2301
  const quote = item.message.quote?.serverId === recall.serverId;
1837
2302
  if (!target && !quote) continue;
1838
2303
  affected.add(item.message.id);
1839
- item.message = target ? recalledNativeMessage(item.message, recall) : { ...item.message, quote: void 0 };
2304
+ item.message = target ? recalledNativeMessage(item.message, remembered) : { ...item.message, quote: void 0 };
1840
2305
  if (target) item.groupContext = false;
1841
2306
  item.readPending = false;
1842
2307
  if (["dispatching", "handed_off"].includes(item.state)) item.state = "needs_review";
@@ -1907,7 +2372,7 @@ var NativeConsumerState = class {
1907
2372
  });
1908
2373
  const revisions = items.map((item) => item.revision);
1909
2374
  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({
2375
+ const manifestHash = createHash7("sha256").update(JSON.stringify({
1911
2376
  accountId: this.value.accountId,
1912
2377
  messageIds: exact,
1913
2378
  dispatchManifests: items.map((item) => item.dispatchManifest ?? null)
@@ -1916,7 +2381,7 @@ var NativeConsumerState = class {
1916
2381
  const runId = typeof args[0] === "string" ? args[0] : args[0]?.runId;
1917
2382
  if (typeof runId !== "string" || !runId || runId.length > 256) throw new Error("Prepared run callback has no valid runId");
1918
2383
  this.mutate(() => {
1919
- const currentHash = createHash6("sha256").update(JSON.stringify({
2384
+ const currentHash = createHash7("sha256").update(JSON.stringify({
1920
2385
  accountId: this.value.accountId,
1921
2386
  messageIds: exact,
1922
2387
  dispatchManifests: exact.map((id2) => this.value.items[id2]?.dispatchManifest ?? null)
@@ -1935,11 +2400,11 @@ var NativeConsumerState = class {
1935
2400
  };
1936
2401
 
1937
2402
  // src/native-prepared-boundary.ts
1938
- import { createHash as createHash7, randomUUID as randomUUID4 } from "node:crypto";
2403
+ import { createHash as createHash8, randomUUID as randomUUID4 } from "node:crypto";
1939
2404
  import { basename as basename2, isAbsolute as isAbsolute3 } from "node:path";
1940
2405
  var pending = /* @__PURE__ */ new Map();
1941
2406
  var enabled = false;
1942
- var digest = (value) => createHash7("sha256").update(value).digest("hex");
2407
+ var digest = (value) => createHash8("sha256").update(value).digest("hex");
1943
2408
  function prune() {
1944
2409
  for (const [id2, item] of pending) if (item.expires < Date.now()) pending.delete(id2);
1945
2410
  }
@@ -1950,7 +2415,7 @@ function nativeDispatchManifest(params) {
1950
2415
  const history = params.history ?? [];
1951
2416
  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
2417
  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");
2418
+ 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" || !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
2419
  return Object.freeze({ ...asset });
1955
2420
  }));
1956
2421
  const messageSid = nativeSourceMessageSid(params.message);
@@ -1991,7 +2456,7 @@ function nativeDispatchManifest(params) {
1991
2456
  }))) } : {},
1992
2457
  assets,
1993
2458
  policySha256: digest(JSON.stringify(params.policy ?? null)),
1994
- // Exact released 2026.10.2 source-turn identity. Requiring it in the later
2459
+ // Exact source-turn identity of OpenClaw 2026.10.2 through 2026.10.7. Requiring it in the later
1995
2460
  // snapshot prevents an identical older image/body from proving this input.
1996
2461
  hostSourceTurnId: `channel-user:v1:${digest(JSON.stringify(["agent-wechat", params.channelAccountId, `wechat:${params.message.threadId}`, messageSid]))}`
1997
2462
  };
@@ -2277,17 +2742,17 @@ async function recheckNativeInputs(client, state, messages) {
2277
2742
  throw new NativeInputInvalidated();
2278
2743
  }
2279
2744
  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)) {
2745
+ const quote = current.quote;
2746
+ if (quote?.state === "recalled") {
2283
2747
  const affected = state.acceptRecall(state.cursor, {
2284
2748
  threadId: message.threadId,
2285
2749
  serverId: message.quote.serverId,
2286
- observedAt: quote.message && nativeRecallInfo(quote.message)?.observedAt || (/* @__PURE__ */ new Date()).toISOString()
2750
+ observedAt: (/* @__PURE__ */ new Date()).toISOString()
2287
2751
  });
2288
2752
  invalidateNativePreparedInputs(message.accountId, affected);
2289
2753
  throw new NativeInputInvalidated();
2290
2754
  }
2755
+ if (!quote || !sameEmbeddedQuote(message.quote, quote)) throw Error("Native embedded quote changed; delivery held for review");
2291
2756
  }
2292
2757
  if (!state.isCurrent(message)) throw new NativeInputInvalidated();
2293
2758
  }
@@ -2444,7 +2909,7 @@ async function dispatchNativeMessageInput(params, revision) {
2444
2909
  });
2445
2910
  assertCurrent();
2446
2911
  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;
2912
+ 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 && [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
2913
  if (callback) trackNativePreparedInput(dispatchManifest, callback);
2449
2914
  const beforeSend = () => recheck([message, ...admitted]);
2450
2915
  let failed = false;
@@ -2463,12 +2928,12 @@ async function dispatchNativeMessageInput(params, revision) {
2463
2928
  if (urls.length > 16) throw new Error("Native reply media count exceeds its bound");
2464
2929
  if (payload.audioAsVoice && !urls.length) throw new Error("Native voice reply requires an audio attachment");
2465
2930
  for (const url2 of urls) {
2466
- const key = createHash8("sha256").update(`${dispatchManifest.messageSid}\0${delivery++}`).digest("hex");
2931
+ const key = createHash9("sha256").update(`${dispatchManifest.messageSid}\0${delivery++}`).digest("hex");
2467
2932
  await sendNativeAttachment(client, account, message.threadId, url2, payload.audioAsVoice === true, key, beforeSend);
2468
2933
  }
2469
2934
  if (payload.text) {
2470
2935
  await beforeSend();
2471
- const key = createHash8("sha256").update(`${dispatchManifest.messageSid}\0${delivery++}`).digest("hex");
2936
+ const key = createHash9("sha256").update(`${dispatchManifest.messageSid}\0${delivery++}`).digest("hex");
2472
2937
  await submitNativeText(client, account.native.accountId, message.threadId, payload.text, key);
2473
2938
  }
2474
2939
  if (urls.length || payload.text) params.onDelivered?.();
@@ -2644,43 +3109,69 @@ async function startNativeMonitor(opts) {
2644
3109
 
2645
3110
  // src/native-login.ts
2646
3111
  import { randomUUID as randomUUID5 } from "node:crypto";
3112
+ import { setTimeout as delay } from "node:timers/promises";
2647
3113
  var operations = /* @__PURE__ */ new Map();
2648
3114
  var terminal = /* @__PURE__ */ new Set(["succeeded", "failed", "cancelled", "expired", "rejected", "needs_login"]);
2649
- async function nativeLoginStart(account, options = {}) {
3115
+ function guard(access2) {
3116
+ access2.signal?.throwIfAborted();
3117
+ access2.assertCurrent?.();
3118
+ }
3119
+ function validateOperation(operation, accountId, operationId) {
3120
+ if (operation.accountId !== accountId || operation.kind !== "login" || operationId && operation.id !== operationId) throw Error("Native login operation identity does not match its account");
3121
+ }
3122
+ async function nativeLoginStart(account, options = {}, access2 = {}) {
3123
+ guard(access2);
2650
3124
  const native = account.native;
2651
- const { client } = await ensureNativeHost(native);
3125
+ const { client } = await (access2.host ?? ensureNativeHost)(native);
3126
+ guard(access2);
3127
+ const configurationKey = nativeConfigurationKey(native);
2652
3128
  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
- }
3129
+ if (existing && existing.configurationKey === configurationKey) {
3130
+ const refreshed = await client.operation(native.accountId, existing.operation.id);
3131
+ guard(access2);
3132
+ validateOperation(refreshed, native.accountId, existing.operation.id);
3133
+ existing.operation = refreshed;
3134
+ existing.client = client;
3135
+ if (!terminal.has(existing.operation.state)) return nativeLoginWait(account, Math.min(options.timeoutMs ?? 3e4, 3e4), true, access2);
3136
+ }
3137
+ guard(access2);
2657
3138
  const operation = await client.login(native.accountId, {
2658
3139
  allowQr: true,
2659
3140
  forceQr: options.force === true,
2660
3141
  timeoutSeconds: Math.max(10, Math.min(900, Math.ceil((options.timeoutMs ?? 3e5) / 1e3))),
2661
3142
  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);
3143
+ }, randomUUID5());
3144
+ validateOperation(operation, native.accountId);
3145
+ operations.set(account.accountId, { client, accountId: native.accountId, configurationKey, operation });
3146
+ guard(access2);
3147
+ return nativeLoginWait(account, Math.min(options.timeoutMs ?? 3e4, 3e4), true, access2);
2665
3148
  }
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" };
3149
+ async function nativeLoginWait(account, timeoutMs = 3e4, stopAtQr = false, access2 = {}) {
3150
+ guard(access2);
3151
+ const active2 = operations.get(account.accountId);
3152
+ if (!active2 || active2.configurationKey !== nativeConfigurationKey(account.native)) return { connected: false, state: "idle", message: "No native login operation; start login first" };
2669
3153
  const deadline = Date.now() + Math.max(1e3, Math.min(timeoutMs, 3e5));
2670
3154
  while (Date.now() < deadline) {
2671
- active2.operation = await active2.client.operation(active2.accountId, active2.operation.id);
3155
+ guard(access2);
3156
+ const refreshed = await active2.client.operation(active2.accountId, active2.operation.id);
3157
+ guard(access2);
3158
+ validateOperation(refreshed, active2.accountId, active2.operation.id);
3159
+ active2.operation = refreshed;
2672
3160
  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}` };
3161
+ const result = { connected: state === "succeeded", state, operationId: active2.operation.id };
3162
+ if (state === "succeeded") return { ...result, message: "Native login succeeded" };
3163
+ if (terminal.has(state)) return { ...result, message: `Native login ${state}` };
3164
+ if (stopAtQr && state === "awaiting_approval") return { ...result, message: "Approve native login on your phone" };
2675
3165
  if (stopAtQr && active2.operation.result?.qrAvailable === true) {
2676
3166
  const generation = active2.operation.result?.qrGeneration;
2677
3167
  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" };
3168
+ guard(access2);
3169
+ return { ...result, qrDataUrl: `data:image/png;base64,${Buffer.from(png).toString("base64")}`, message: "Scan the white-background native QR and approve login" };
2679
3170
  }
2680
- if (stopAtQr && state === "awaiting_approval") return { connected: false, message: "Approve native login on your phone" };
2681
- await new Promise((resolve) => setTimeout(resolve, 500));
3171
+ await delay(Math.min(500, Math.max(0, deadline - Date.now())), void 0, { signal: access2.signal });
2682
3172
  }
2683
- return { connected: false, message: "Native login remains pending; wait on the same operation rather than starting a replacement" };
3173
+ guard(access2);
3174
+ 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" };
2684
3175
  }
2685
3176
  async function sendNativeText(account, threadId2, text3, key = randomUUID5()) {
2686
3177
  const native = account.native;
@@ -2694,29 +3185,59 @@ async function sendNativeText(account, threadId2, text3, key = randomUUID5()) {
2694
3185
  { sendId: send.id, state: send.state, serverIds: send.serverId ? [send.serverId] : void 0 }
2695
3186
  );
2696
3187
  }
2697
- function createNativeLoginTool(account) {
3188
+ function createNativeLoginTool(account, dependencies = {}) {
3189
+ const actions = ["status", "start", "wait", "disconnect", "logout", "forget"];
3190
+ const configurationKey = nativeConfigurationKey(account.native);
2698
3191
  return {
2699
3192
  label: "WeChat Login",
2700
3193
  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) => {
3194
+ catalogMode: "direct-only",
3195
+ 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.",
3196
+ parameters: { type: "object", additionalProperties: false, properties: {
3197
+ action: { type: "string", enum: actions },
3198
+ force: { type: "boolean", description: "With start, use QR instead of saved trust for a new login. An active login is still reused." },
3199
+ timeoutMs: { type: "integer", minimum: 1e3, maximum: 3e5, description: "Wait bound in milliseconds; defaults to 30000. Start returns as soon as a QR is available." },
3200
+ confirm: { type: "boolean", description: "Required true for forget." }
3201
+ }, required: ["action"] },
3202
+ execute: async (_id, params, signal) => {
3203
+ if (!params || typeof params !== "object" || Array.isArray(params)) throw Error("Expected login arguments");
2704
3204
  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 });
3205
+ 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");
3206
+ if (args.action === "forget" && args.confirm !== true) throw Error("Forgetting native credentials requires confirm=true");
3207
+ const access2 = { host: dependencies.host, signal, assertCurrent: () => {
3208
+ dependencies.context?.assertInvocationCurrent?.();
3209
+ if (!dependencies.context) return;
3210
+ const context = dependencies.context;
3211
+ const config = context.getRuntimeConfig?.() ?? context.runtimeConfig ?? context.config;
3212
+ const current = config && resolveWeChatAccount(config);
3213
+ if (!current?.enabled || !current.native || nativeConfigurationKey(current.native) !== configurationKey) throw Error("Native login configuration changed; invoke the tool again");
3214
+ } };
3215
+ guard(access2);
3216
+ if (args.action === "start" || args.action === "wait") {
3217
+ const result2 = args.action === "start" ? await nativeLoginStart(account, { force: args.force, timeoutMs: args.timeoutMs }, access2) : await nativeLoginWait(account, args.timeoutMs, false, access2);
2709
3218
  const content = [{ type: "text", text: result2.message }];
2710
3219
  if (result2.qrDataUrl) content.push({ type: "image", data: result2.qrDataUrl.split(",")[1], mimeType: "image/png" });
2711
- return { content, details: { connected: result2.connected } };
3220
+ return { content, details: { connected: result2.connected, state: result2.state, operationId: result2.operationId } };
2712
3221
  }
3222
+ const native = account.native;
3223
+ const { client } = await (access2.host ?? ensureNativeHost)(native);
3224
+ guard(access2);
2713
3225
  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
3226
  throw new Error("Unknown native login action");
2715
3227
  })();
3228
+ if (args.action !== "status") operations.delete(account.accountId);
3229
+ guard(access2);
2716
3230
  return { content: [{ type: "text", text: JSON.stringify(result) }], details: result };
2717
3231
  }
2718
3232
  };
2719
3233
  }
3234
+ function registerNativeLoginTool(api) {
3235
+ api.registerTool({ contextVersion: 2, create: (context) => {
3236
+ const config = context.getRuntimeConfig?.() ?? context.runtimeConfig ?? context.config;
3237
+ const account = config && resolveWeChatAccount(config);
3238
+ return account?.enabled && account.native ? [createNativeLoginTool(account, { context })] : [];
3239
+ } }, { names: ["wechat_login"] });
3240
+ }
2720
3241
 
2721
3242
  // src/channel.ts
2722
3243
  async function sendWeChatText(cfg, to, text3) {
@@ -2724,6 +3245,7 @@ async function sendWeChatText(cfg, to, text3) {
2724
3245
  if (!account?.serverUrl) throw new Error("No native daemon configured");
2725
3246
  return sendNativeText(account, to, text3);
2726
3247
  }
3248
+ var mediaHandlers = createWeChatMediaHandlers();
2727
3249
  var wechatMessageAdapter = createChannelMessageAdapterFromOutbound({
2728
3250
  id: "agent-wechat",
2729
3251
  capabilities: {
@@ -2736,10 +3258,7 @@ var wechatMessageAdapter = createChannelMessageAdapterFromOutbound({
2736
3258
  channel: "agent-wechat",
2737
3259
  ...await sendWeChatText(cfg, to, text3)
2738
3260
  }),
2739
- sendMedia: async ({ cfg, to, text: text3, mediaUrl, audioAsVoice }) => ({
2740
- channel: "agent-wechat",
2741
- ...await sendWeChatMedia(cfg, to, text3, mediaUrl, audioAsVoice)
2742
- })
3261
+ ...mediaHandlers
2743
3262
  }
2744
3263
  });
2745
3264
  var meta = {
@@ -2763,6 +3282,7 @@ var wechatPlugin = {
2763
3282
  tts: { voice: { synthesisTarget: "voice-note", transcodesAudio: true } }
2764
3283
  },
2765
3284
  reload: { configPrefixes: ["channels.agent-wechat"] },
3285
+ actions: wechatMediaActions,
2766
3286
  configSchema: {
2767
3287
  uiHints: { "native.token": { sensitive: true } },
2768
3288
  schema: {
@@ -2884,10 +3404,7 @@ var wechatPlugin = {
2884
3404
  channel: "agent-wechat",
2885
3405
  ...await sendWeChatText(cfg, to, text3)
2886
3406
  }),
2887
- sendMedia: async ({ cfg, to, text: text3, mediaUrl, audioAsVoice }) => ({
2888
- channel: "agent-wechat",
2889
- ...await sendWeChatMedia(cfg, to, text3, mediaUrl, audioAsVoice)
2890
- })
3407
+ ...mediaHandlers
2891
3408
  },
2892
3409
  message: wechatMessageAdapter,
2893
3410
  gateway: {
@@ -2917,7 +3434,7 @@ var wechatPlugin = {
2917
3434
  loginWithQrWait: async ({ accountId, timeoutMs }) => {
2918
3435
  const account = resolveWeChatAccount(getWeChatRuntime().config.current(), accountId ?? void 0);
2919
3436
  if (!account?.native) return { connected: false, message: "No native daemon configured" };
2920
- return nativeLoginWait(account.accountId, timeoutMs);
3437
+ return nativeLoginWait(account, timeoutMs);
2921
3438
  }
2922
3439
  },
2923
3440
  auth: {
@@ -2943,10 +3460,6 @@ var wechatPlugin = {
2943
3460
  linked: runtime2?.linked ?? false
2944
3461
  })
2945
3462
  },
2946
- agentTools: (({ cfg }) => {
2947
- const account = resolveWeChatAccount(cfg);
2948
- return account?.native ? [createNativeLoginTool(account)] : [];
2949
- }),
2950
3463
  directory: {
2951
3464
  self: async ({ cfg }) => {
2952
3465
  const account = resolveWeChatAccount(cfg);
@@ -3054,7 +3567,7 @@ function createNativeFacade(config, dependencies = {}) {
3054
3567
  fail(res, 403, "facade_account_forbidden");
3055
3568
  return true;
3056
3569
  }
3057
- if (!["GET", "HEAD", "POST", "PATCH", "DELETE"].includes(req.method ?? "")) {
3570
+ if (!["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"].includes(req.method ?? "")) {
3058
3571
  fail(res, 405, "method_not_allowed");
3059
3572
  return true;
3060
3573
  }
@@ -3067,19 +3580,23 @@ function createNativeFacade(config, dependencies = {}) {
3067
3580
  try {
3068
3581
  const host2 = dependencies.endpoint ? void 0 : await ensureNativeHost(config);
3069
3582
  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);
3583
+ for (const name3 of ["content-type", "accept", "range", "if-none-match", "if-range", "last-event-id", "idempotency-key"]) {
3584
+ const value = req.headers[name3];
3585
+ if (typeof value === "string") headers.set(name3, value);
3073
3586
  }
3587
+ const upload = pieces.length === 4 && pieces[3] === "uploads" && req.method === "POST";
3588
+ const mediaContent = pieces.length === 6 && pieces[3] === "media" && pieces[5] === "content" && parsed.searchParams.get("representation") !== "preview";
3589
+ const requestLimit = upload ? NATIVE_MAX_SOURCE_BYTES + 64 * 1024 : MAX_BODY;
3590
+ const responseLimit = mediaContent ? Math.max(MAX_BODY, NATIVE_MAX_SOURCE_BYTES) : MAX_BODY;
3074
3591
  const length = req.headers["content-length"];
3075
- if (length && (!/^\d+$/.test(length) || Number(length) > MAX_BODY)) {
3592
+ if (length && (!/^\d+$/.test(length) || Number(length) > requestLimit)) {
3076
3593
  fail(res, 413, "payload_too_large");
3077
3594
  return true;
3078
3595
  }
3079
3596
  let size = 0;
3080
3597
  const body = ["GET", "HEAD"].includes(req.method ?? "") ? void 0 : Readable.toWeb(req).pipeThrough(new NodeTransformStream({ transform(chunk, controller) {
3081
3598
  size += chunk.byteLength;
3082
- if (size > MAX_BODY) {
3599
+ if (size > requestLimit) {
3083
3600
  tooLarge = true;
3084
3601
  throw new Error("payload_too_large");
3085
3602
  }
@@ -3092,10 +3609,16 @@ function createNativeFacade(config, dependencies = {}) {
3092
3609
  headers.set("Authorization", `Bearer ${dependencies.token}`);
3093
3610
  response = await (dependencies.fetch ?? fetch)(new URL(relative, dependencies.endpoint), init);
3094
3611
  }
3612
+ const responseLength = response.headers.get("content-length");
3613
+ if (responseLength && (!/^\d+$/.test(responseLength) || Number(responseLength) > responseLimit)) {
3614
+ await response.body?.cancel();
3615
+ fail(res, 502, "native_facade_unavailable");
3616
+ return true;
3617
+ }
3095
3618
  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);
3619
+ for (const name3 of ["content-type", "content-length", "content-range", "accept-ranges", "etag", "cache-control", "content-disposition", "x-content-type-options"]) {
3620
+ const value = response.headers.get(name3);
3621
+ if (value) res.setHeader(name3, value);
3099
3622
  }
3100
3623
  res.setHeader("x-content-type-options", "nosniff");
3101
3624
  const reader = response.body?.getReader();
@@ -3110,7 +3633,7 @@ function createNativeFacade(config, dependencies = {}) {
3110
3633
  const { value, done } = await reader.read();
3111
3634
  if (done) break;
3112
3635
  emitted += value.length;
3113
- if (!sse && emitted > MAX_BODY) throw new Error("upstream_response_too_large");
3636
+ if (!sse && emitted > responseLimit) throw new Error("upstream_response_too_large");
3114
3637
  if (!res.write(value)) await drain(res, abort.signal);
3115
3638
  }
3116
3639
  } finally {
@@ -3154,14 +3677,14 @@ function object(value) {
3154
3677
  if (!value || typeof value !== "object" || Array.isArray(value)) throw Error("Expected tool arguments");
3155
3678
  return value;
3156
3679
  }
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}`);
3680
+ function string(value, name3, max = 4096) {
3681
+ if (typeof value !== "string" || !value.trim() || value.length > max || /[\u0000-\u001f\u007f]/.test(value)) throw Error(`Invalid ${name3}`);
3159
3682
  return value.trim();
3160
3683
  }
3161
3684
  function threadId(value) {
3162
3685
  return string(string(value, "thread ID").replace(/^(?:agent-)?wechat:(?:group:)?/i, ""), "thread ID");
3163
3686
  }
3164
- function messageResult(message, retrievalTool = "wechat_media") {
3687
+ function messageResult(message, retrievalTool = "wechat_media", quotePermitted = false) {
3165
3688
  if (nativeRecallInfo(message)) return {
3166
3689
  id: message.id,
3167
3690
  threadId: message.threadId,
@@ -3176,8 +3699,15 @@ function messageResult(message, retrievalTool = "wechat_media") {
3176
3699
  const isForward = message.type === 49 && message.appMessageType === 19;
3177
3700
  const isLink = message.type === 49 && [3, 4, 5].includes(message.appMessageType ?? 0) && !!message.link;
3178
3701
  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]`;
3702
+ 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]`;
3703
+ const quote = message.quote && {
3704
+ serverId: message.quote.serverId,
3705
+ type: message.quote.type,
3706
+ state: quotePermitted ? message.quote.state : "not permitted",
3707
+ senderId: message.quote.senderId,
3708
+ appMessageType: message.quote.appMessageType,
3709
+ embeddedImage: quotePermitted ? message.quote.embeddedImage : void 0
3710
+ };
3181
3711
  return {
3182
3712
  id: message.id,
3183
3713
  threadId: message.threadId,
@@ -3186,7 +3716,7 @@ function messageResult(message, retrievalTool = "wechat_media") {
3186
3716
  direction: message.direction,
3187
3717
  type: message.type,
3188
3718
  appMessageType: message.appMessageType,
3189
- quote: message.quote,
3719
+ quote,
3190
3720
  link: isLink ? message.link : void 0,
3191
3721
  createdAt: message.createdAt,
3192
3722
  body: body.slice(0, 4e3),
@@ -3227,9 +3757,9 @@ function createLookupTools(context, dependencies, archive) {
3227
3757
  if (!currentThread) return [];
3228
3758
  }
3229
3759
  const selectedId = selected.native.accountId;
3230
- const tool = (name2, action, description, properties, required = []) => ({
3231
- name: name2,
3232
- label: name2.replaceAll("_", " "),
3760
+ const tool = (name3, action, description, properties, required = []) => ({
3761
+ name: name3,
3762
+ label: name3.replaceAll("_", " "),
3233
3763
  description,
3234
3764
  // The pinned host's tool_call wrapper JSON-serializes image blocks. Its
3235
3765
  // public direct-only surface preserves actual image content for vision.
@@ -3237,7 +3767,7 @@ function createLookupTools(context, dependencies, archive) {
3237
3767
  parameters: { type: "object", additionalProperties: false, properties, required },
3238
3768
  execute: async (_callId, input, signal) => {
3239
3769
  const args = object(input);
3240
- const guard = () => {
3770
+ const guard2 = () => {
3241
3771
  signal?.throwIfAborted();
3242
3772
  context.assertInvocationCurrent?.();
3243
3773
  const cfg2 = currentConfig();
@@ -3245,7 +3775,7 @@ function createLookupTools(context, dependencies, archive) {
3245
3775
  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
3776
  return { cfg: cfg2, account: account2, native: account2.native };
3247
3777
  };
3248
- const { cfg, account, native } = guard();
3778
+ const { cfg, account, native } = guard2();
3249
3779
  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
3780
  const limit = args.limit ?? 20;
3251
3781
  if (!Number.isInteger(limit) || limit < 1 || limit > 50) throw Error("limit must be 1\u201350");
@@ -3262,7 +3792,7 @@ function createLookupTools(context, dependencies, archive) {
3262
3792
  const core = dependencies.core ?? getWeChatRuntime();
3263
3793
  const allowed = async (sender) => {
3264
3794
  if (archive) return true;
3265
- const { cfg: cfg2, account: account2 } = guard();
3795
+ const { cfg: cfg2, account: account2 } = guard2();
3266
3796
  const result2 = await resolveWeChatIngress({
3267
3797
  resolve: core.channel.inbound?.ingress?.resolveStable ?? resolveStableChannelMessageIngress2,
3268
3798
  cfg: cfg2,
@@ -3276,10 +3806,15 @@ function createLookupTools(context, dependencies, archive) {
3276
3806
  return result2.ingress.admission === "dispatch";
3277
3807
  };
3278
3808
  if (!await allowed(requesterSenderId)) throw Error("WeChat conversation access is no longer allowed");
3279
- guard();
3809
+ guard2();
3280
3810
  const { client } = await (dependencies.host ?? ensureNativeHost)(native);
3281
- guard();
3811
+ guard2();
3282
3812
  const accountId = native.accountId;
3813
+ const visibleMessage = async (message) => messageResult(
3814
+ message,
3815
+ archive ? "wechat_archive_media" : "wechat_media",
3816
+ !message.quote || archive || message.quote.direction === "outgoing" || !!message.quote.senderId && await allowed(message.quote.senderId)
3817
+ );
3283
3818
  let result;
3284
3819
  if (action === "threads") {
3285
3820
  const page = await client.threads(accountId, { limit, cursor, ...query ? { query } : {} });
@@ -3292,21 +3827,20 @@ function createLookupTools(context, dependencies, archive) {
3292
3827
  result = { ...page, items, scope: "local_profile", note: "Locally stored threads; coverage may be partial. This lookup does not mark threads read." };
3293
3828
  } else if (action === "message" || action === "media") {
3294
3829
  const message = await client.message(accountId, messageId);
3295
- guard();
3830
+ guard2();
3296
3831
  if (!await allowed(requesterSenderId)) throw Error("WeChat conversation access is no longer allowed");
3297
3832
  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");
3833
+ if (action === "message") result = await visibleMessage(message);
3299
3834
  if (action === "media") {
3300
3835
  const checkRecall = async () => {
3301
- guard();
3836
+ guard2();
3302
3837
  const latest = await client.message(accountId, messageId);
3303
- guard();
3838
+ guard2();
3304
3839
  if (latest.id !== message.id || latest.accountId !== accountId || latest.threadId !== message.threadId || latest.serverId !== message.serverId) throw Error("Native media message identity changed");
3305
3840
  if (nativeRecallInfo(latest)) throw new NativeApiError(410, "message_recalled", false);
3306
3841
  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);
3842
+ if (latest.quote?.state === "recalled") throw new NativeApiError(410, "message_recalled", false);
3843
+ if (!latest.quote || JSON.stringify(latest.quote) !== JSON.stringify(message.quote)) throw new NativeApiError(409, "media_source_changed", false);
3310
3844
  }
3311
3845
  };
3312
3846
  let prepared;
@@ -3321,7 +3855,7 @@ function createLookupTools(context, dependencies, archive) {
3321
3855
  download: args.download !== false,
3322
3856
  waitMs: 2e3,
3323
3857
  signal,
3324
- assertCurrent: guard,
3858
+ assertCurrent: guard2,
3325
3859
  allowQuotedMessage: async (original) => original.direction === "outgoing" || await allowed(original.senderId ?? void 0),
3326
3860
  beforeMediaAccess: async () => {
3327
3861
  if (!await allowed(requesterSenderId) || message.direction !== "outgoing" && !await allowed(message.senderId ?? void 0)) throw Error("WeChat conversation access is no longer allowed");
@@ -3329,7 +3863,7 @@ function createLookupTools(context, dependencies, archive) {
3329
3863
  }
3330
3864
  });
3331
3865
  } catch (error) {
3332
- guard();
3866
+ guard2();
3333
3867
  if (!(error instanceof NativeApiError)) throw error;
3334
3868
  const details2 = {
3335
3869
  messageId: message.id,
@@ -3340,7 +3874,7 @@ function createLookupTools(context, dependencies, archive) {
3340
3874
  };
3341
3875
  return { content: [{ type: "text", text: JSON.stringify(details2) }], details: details2 };
3342
3876
  }
3343
- guard();
3877
+ guard2();
3344
3878
  if (!await allowed(requesterSenderId) || message.direction !== "outgoing" && !await allowed(message.senderId ?? void 0)) throw Error("WeChat conversation access is no longer allowed");
3345
3879
  const details = {
3346
3880
  messageId: message.id,
@@ -3357,7 +3891,7 @@ function createLookupTools(context, dependencies, archive) {
3357
3891
  };
3358
3892
  const image = prepared.suppliedAssets?.find((asset) => asset.role === "model_image");
3359
3893
  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();
3894
+ guard2();
3361
3895
  try {
3362
3896
  await checkRecall();
3363
3897
  } catch (error) {
@@ -3374,7 +3908,7 @@ function createLookupTools(context, dependencies, archive) {
3374
3908
  for (const message of page.items) {
3375
3909
  if (isNativeTombstone(message)) continue;
3376
3910
  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"));
3911
+ if (message.direction === "outgoing" || await allowed(message.senderId ?? void 0)) items.push(await visibleMessage(message));
3378
3912
  }
3379
3913
  result = {
3380
3914
  ...page,
@@ -3384,7 +3918,7 @@ function createLookupTools(context, dependencies, archive) {
3384
3918
  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
3919
  };
3386
3920
  }
3387
- guard();
3921
+ guard2();
3388
3922
  return { content: [{ type: "text", text: JSON.stringify(result) }], details: result };
3389
3923
  }
3390
3924
  });
@@ -3399,13 +3933,13 @@ function createLookupTools(context, dependencies, archive) {
3399
3933
  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
3934
  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
3935
  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"])
3936
+ 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
3937
  ];
3404
3938
  return [
3405
3939
  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
3940
  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
3941
  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"])
3942
+ 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
3943
  ];
3410
3944
  }
3411
3945
  function registerNativeHistoryTools(api) {
@@ -3471,7 +4005,7 @@ function createNativeShareTools(context, dependencies = {}) {
3471
4005
  ...args.description !== void 0 ? { description: args.description === "" ? "" : text(args.description, "description", 16384, true) } : {},
3472
4006
  ...args.thumbnailUrl !== void 0 ? { thumbnailUrl: url(args.thumbnailUrl, "thumbnail URL") } : {}
3473
4007
  };
3474
- const guard = () => {
4008
+ const guard2 = () => {
3475
4009
  signal?.throwIfAborted();
3476
4010
  context.assertInvocationCurrent?.();
3477
4011
  const cfg = currentConfig(), account = resolveWeChatAccount(cfg);
@@ -3480,7 +4014,7 @@ function createNativeShareTools(context, dependencies = {}) {
3480
4014
  };
3481
4015
  const core = dependencies.core ?? getWeChatRuntime();
3482
4016
  const authorize = async () => {
3483
- const { cfg, account } = guard();
4017
+ const { cfg, account } = guard2();
3484
4018
  const result = await resolveWeChatIngress({
3485
4019
  resolve: core.channel.inbound?.ingress?.resolveStable ?? resolveStableChannelMessageIngress3,
3486
4020
  cfg,
@@ -3491,11 +4025,11 @@ function createNativeShareTools(context, dependencies = {}) {
3491
4025
  senderId: requester,
3492
4026
  readStoreAllowFrom: async () => core.channel.pairing.readAllowFromStore({ channel: "agent-wechat", accountId: account.accountId, env: process.env }).catch(() => [])
3493
4027
  });
3494
- guard();
4028
+ guard2();
3495
4029
  if (result.ingress.admission !== "dispatch") throw Error("WeChat conversation access is no longer allowed");
3496
4030
  };
3497
4031
  await authorize();
3498
- const { native } = guard();
4032
+ const { native } = guard2();
3499
4033
  const { client } = await (dependencies.host ?? ensureNativeHost)(native);
3500
4034
  await authorize();
3501
4035
  let intent;
@@ -3530,7 +4064,7 @@ function registerNativeShareTools(api) {
3530
4064
  }
3531
4065
 
3532
4066
  // src/native-recall-tools.ts
3533
- import { createHash as createHash9 } from "node:crypto";
4067
+ import { createHash as createHash10 } from "node:crypto";
3534
4068
  import { resolveStableChannelMessageIngress as resolveStableChannelMessageIngress4 } from "openclaw/plugin-sdk/channel-ingress-runtime";
3535
4069
  var names2 = ["wechat_recall"];
3536
4070
  function text2(value, label) {
@@ -3541,7 +4075,7 @@ function thread2(value) {
3541
4075
  return text2(text2(value, "conversation").replace(/^(?:agent-)?wechat:(?:group:)?/i, ""), "conversation");
3542
4076
  }
3543
4077
  function nativeRecallKey(accountId, threadId2, messageId, serverId) {
3544
- return `openclaw-recall-${createHash9("sha256").update(JSON.stringify([accountId, threadId2, messageId, serverId])).digest("hex")}`;
4078
+ return `openclaw-recall-${createHash10("sha256").update(JSON.stringify([accountId, threadId2, messageId, serverId])).digest("hex")}`;
3545
4079
  }
3546
4080
  function createNativeRecallTools(context, dependencies = {}) {
3547
4081
  const currentConfig = () => context.getRuntimeConfig?.() ?? context.runtimeConfig ?? context.config;
@@ -3573,7 +4107,7 @@ function createNativeRecallTools(context, dependencies = {}) {
3573
4107
  const messageId = text2(input.messageId, "message ID");
3574
4108
  const serverId = text2(input.serverId, "server ID");
3575
4109
  if (!/^[1-9]\d{0,19}$/.test(serverId) || BigInt(serverId) > 18446744073709551615n) throw Error("Invalid exact server message ID");
3576
- const guard = () => {
4110
+ const guard2 = () => {
3577
4111
  signal?.throwIfAborted();
3578
4112
  context.assertInvocationCurrent?.();
3579
4113
  const cfg = currentConfig(), account = resolveWeChatAccount(cfg);
@@ -3581,7 +4115,7 @@ function createNativeRecallTools(context, dependencies = {}) {
3581
4115
  return { cfg, account, native: account.native };
3582
4116
  };
3583
4117
  const allowed = async () => {
3584
- const { cfg, account } = guard();
4118
+ const { cfg, account } = guard2();
3585
4119
  const core = dependencies.core ?? getWeChatRuntime();
3586
4120
  const ingress = await resolveWeChatIngress({
3587
4121
  resolve: core.channel.inbound?.ingress?.resolveStable ?? resolveStableChannelMessageIngress4,
@@ -3593,20 +4127,20 @@ function createNativeRecallTools(context, dependencies = {}) {
3593
4127
  senderId: requester,
3594
4128
  readStoreAllowFrom: async () => core.channel.pairing.readAllowFromStore({ channel: "agent-wechat", accountId: account.accountId, env: process.env }).catch(() => [])
3595
4129
  });
3596
- guard();
4130
+ guard2();
3597
4131
  if (ingress.ingress.admission !== "dispatch") throw Error("WeChat conversation access is no longer allowed");
3598
4132
  };
3599
4133
  await allowed();
3600
- const { native } = guard();
4134
+ const { native } = guard2();
3601
4135
  const { client } = await (dependencies.host ?? ensureNativeHost)(native);
3602
- guard();
4136
+ guard2();
3603
4137
  const message = await client.message(accountId, messageId);
3604
- guard();
4138
+ guard2();
3605
4139
  const retainedRecall = !!nativeRecallInfo(message);
3606
4140
  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
4141
  if (message.serverId !== serverId) throw Error("The exact server identity does not match this receipt; the local message identity may have been reused");
3608
4142
  await allowed();
3609
- guard();
4143
+ guard2();
3610
4144
  const key = nativeRecallKey(accountId, conversation, messageId, serverId);
3611
4145
  let operation;
3612
4146
  let operationId;
@@ -3636,13 +4170,13 @@ function createNativeRecallTools(context, dependencies = {}) {
3636
4170
  const deadline = Date.now() + Math.max(0, Math.min(dependencies.waitMs ?? 2e3, 1e4));
3637
4171
  while (["queued", "running", "submitting"].includes(operation.state) && Date.now() < deadline) {
3638
4172
  await new Promise((resolve) => setTimeout(resolve, Math.min(250, deadline - Date.now())));
3639
- guard();
4173
+ guard2();
3640
4174
  const remaining = Math.max(1, deadline - Date.now());
3641
4175
  const next = await client.operation(accountId, operation.id, signal ? AbortSignal.any([signal, AbortSignal.timeout(remaining)]) : AbortSignal.timeout(remaining));
3642
4176
  checkOperation(next);
3643
4177
  operation = next;
3644
4178
  }
3645
- guard();
4179
+ guard2();
3646
4180
  } catch (error) {
3647
4181
  const reason = error instanceof NativeApiError ? error.code : "recall_result_unavailable";
3648
4182
  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 +4198,55 @@ function registerNativeRecallTools(api) {
3664
4198
  api.registerTool({ contextVersion: 2, create: (context) => createNativeRecallTools(context) }, { names: names2 });
3665
4199
  }
3666
4200
 
4201
+ // src/native-group-tool.ts
4202
+ var name2 = "wechat_group_info";
4203
+ function createNativeGroupTools(context, dependencies = {}) {
4204
+ if (context.senderIsOwner !== true || typeof context.assertInvocationCurrent !== "function") return [];
4205
+ const currentConfig = () => context.getRuntimeConfig?.() ?? context.runtimeConfig ?? context.config;
4206
+ const selected = resolveWeChatAccount(currentConfig());
4207
+ 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 [];
4208
+ const accountId = selected.native.accountId;
4209
+ const configurationKey = nativeConfigurationKey(selected.native);
4210
+ return [{
4211
+ name: name2,
4212
+ label: "WeChat Group Info",
4213
+ 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.",
4214
+ parameters: { type: "object", additionalProperties: false, properties: {
4215
+ groupId: { type: "string", minLength: 10, maxLength: 256, description: "Exact ordinary group username ending in @chatroom." },
4216
+ limit: { type: "integer", minimum: 1, maximum: 100 },
4217
+ cursor: { type: "string", maxLength: 8192 },
4218
+ username: { type: "string", minLength: 1, maxLength: 256, description: "Optionally inspect one exact member instead of listing a page." }
4219
+ }, required: ["groupId"] },
4220
+ execute: async (_callId, input, signal) => {
4221
+ 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");
4222
+ const args = input;
4223
+ const identity = (value) => typeof value === "string" && value.length > 0 && value.length <= 256 && !/[\s\u0000-\u001f\u007f]/u.test(value);
4224
+ 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");
4225
+ const guard2 = () => {
4226
+ signal?.throwIfAborted();
4227
+ if (context.senderIsOwner !== true) throw Error("OpenClaw owner authorization is required");
4228
+ context.assertInvocationCurrent();
4229
+ const account = resolveWeChatAccount(currentConfig());
4230
+ 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");
4231
+ return account.native;
4232
+ };
4233
+ const native = guard2();
4234
+ const { client } = await (dependencies.host ?? ensureNativeHost)(native);
4235
+ guard2();
4236
+ const group = await client.group(accountId, args.groupId, signal);
4237
+ guard2();
4238
+ if (group.id !== args.groupId || group.roomId !== args.groupId) throw Error("Group identity is invalid");
4239
+ 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);
4240
+ guard2();
4241
+ const details = { accountId, group, members, source: "cached", membershipAbsence: "unconfirmed" };
4242
+ return { content: [{ type: "text", text: JSON.stringify(details) }], details };
4243
+ }
4244
+ }];
4245
+ }
4246
+ function registerNativeGroupTools(api) {
4247
+ api.registerTool({ contextVersion: 2, create: (context) => createNativeGroupTools(context) }, { names: [name2] });
4248
+ }
4249
+
3667
4250
  // index.ts
3668
4251
  var plugin = {
3669
4252
  id: "agent-wechat",
@@ -3677,6 +4260,8 @@ var plugin = {
3677
4260
  registerNativeHistoryTools(api);
3678
4261
  registerNativeShareTools(api);
3679
4262
  registerNativeRecallTools(api);
4263
+ registerNativeGroupTools(api);
4264
+ registerNativeLoginTool(api);
3680
4265
  const stopFacade = selected?.native ? registerNativeFacade(api, selected.native) : () => {
3681
4266
  };
3682
4267
  const stopPreparedBoundary = selected?.native?.readPolicy && selected.native.readPolicy !== "on_inbound" ? registerNativePreparedBoundary(api) : () => {