@agent-wechat/agent-wechat 1.0.0-beta.8 → 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
@@ -110,17 +110,30 @@ import { constants } from "node:fs";
110
110
  import { access, lstat, readFile, realpath } from "node:fs/promises";
111
111
  import { spawn, execFile } from "node:child_process";
112
112
  import { promisify } from "node:util";
113
- import { delimiter, dirname, isAbsolute, join } from "node:path";
113
+ import { delimiter, dirname, isAbsolute, join, toNamespacedPath } from "node:path";
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)
@@ -146,13 +159,13 @@ var NativeApiError = class extends Error {
146
159
  }
147
160
  };
148
161
  function validateNativeBaseUrl(input) {
149
- const url = new URL(input);
150
- const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname.toLowerCase());
151
- if (url.username || url.password || url.search || url.hash || !["http:", "https:"].includes(url.protocol) || url.protocol === "http:" && !loopback)
162
+ const url2 = new URL(input);
163
+ const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url2.hostname.toLowerCase());
164
+ if (url2.username || url2.password || url2.search || url2.hash || !["http:", "https:"].includes(url2.protocol) || url2.protocol === "http:" && !loopback)
152
165
  throw new Error("Native API requires verified HTTPS or a loopback HTTP endpoint, without embedded credentials");
153
- if (!url.pathname.endsWith("/"))
154
- url.pathname += "/";
155
- return url;
166
+ if (!url2.pathname.endsWith("/"))
167
+ url2.pathname += "/";
168
+ return url2;
156
169
  }
157
170
  var id = (value) => {
158
171
  if (typeof value !== "string" || !value || value === "." || value === ".." || value.length > 4096 || /[\u0000-\u001f\u007f]/.test(value))
@@ -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
  }
@@ -283,8 +314,24 @@ var NativeWeChatClient = class {
283
314
  throw new Error("Invalid login idempotency key");
284
315
  return this.request(`v1/accounts/${id(accountId)}/auth/login`, { method: "POST", headers: key ? { "Idempotency-Key": key } : void 0, body: JSON.stringify(options) });
285
316
  }
286
- operation(accountId, operationId) {
287
- return this.request(`v1/accounts/${id(accountId)}/operations/${id(operationId)}`);
317
+ operation(accountId, operationId, signal) {
318
+ return this.request(`v1/accounts/${id(accountId)}/operations/${id(operationId)}`, { signal });
319
+ }
320
+ /** Submit once with a stable key; inspect the returned operation after uncertainty. */
321
+ async recallMessage(accountId, messageId, serverId, idempotencyKey, signal) {
322
+ if (typeof serverId !== "string" || !/^[1-9]\d{0,19}$/.test(serverId) || BigInt(serverId) > 18446744073709551615n)
323
+ throw new Error("Invalid exact recall server ID");
324
+ if (typeof idempotencyKey !== "string" || !idempotencyKey || idempotencyKey.length > 200 || /[\r\n]/.test(idempotencyKey))
325
+ throw new Error("Invalid recall idempotency key");
326
+ const operation = await this.request(`v1/accounts/${id(accountId)}/messages/${id(messageId)}/recall`, {
327
+ method: "POST",
328
+ headers: { "Idempotency-Key": idempotencyKey },
329
+ body: JSON.stringify({ serverId }),
330
+ signal
331
+ });
332
+ if (!operation || operation.accountId !== accountId || operation.kind !== "message_recall" || typeof operation.id !== "string" || !operation.id || typeof operation.state !== "string")
333
+ throw new Error("Native recall operation identity is invalid");
334
+ return operation;
288
335
  }
289
336
  cancelOperation(accountId, operationId) {
290
337
  return this.request(`v1/accounts/${id(accountId)}/operations/${id(operationId)}`, { method: "DELETE" });
@@ -322,17 +369,62 @@ var NativeWeChatClient = class {
322
369
  groups(accountId, options) {
323
370
  return this.request(`v1/accounts/${id(accountId)}/groups${listQuery(options)}`);
324
371
  }
325
- thread(accountId, threadId2) {
326
- 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 });
327
374
  }
328
375
  contact(accountId, username) {
329
376
  return this.request(`v1/accounts/${id(accountId)}/contacts/${id(username)}`);
330
377
  }
331
- group(accountId, roomId) {
332
- 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);
333
411
  }
334
- groupMembers(accountId, roomId, options) {
335
- return this.request(`v1/accounts/${id(accountId)}/groups/${id(roomId)}/members${listQuery(options)}`);
412
+ setMyGroupName(accountId, groupId, displayName, key, signal) {
413
+ return this.groupMutation(accountId, `groups/${id(groupId)}/my-name`, "PUT", { displayName }, key, "my_name", groupId, signal);
414
+ }
415
+ clearGroupAnnouncement(accountId, groupId, key, signal) {
416
+ return this.groupMutation(accountId, `groups/${id(groupId)}/announcement`, "DELETE", {}, key, "clear_announcement", groupId, signal);
417
+ }
418
+ setThreadMuted(accountId, threadId2, muted, key, signal) {
419
+ return this.groupMutation(accountId, `threads/${id(threadId2)}/notifications`, "PUT", { muted }, key, "mute", threadId2, signal);
420
+ }
421
+ setThreadPinned(accountId, threadId2, pinned, key, signal) {
422
+ if (typeof pinned !== "boolean")
423
+ throw new Error("Thread pinned state must be a boolean");
424
+ return this.groupMutation(accountId, `threads/${id(threadId2)}/pin`, "PUT", { pinned }, key, "pin", threadId2, signal);
425
+ }
426
+ groupMutationByKey(accountId, key, signal) {
427
+ return this.request(`v1/accounts/${id(accountId)}/group-mutations/by-idempotency-key?${new URLSearchParams({ key })}`, { signal });
336
428
  }
337
429
  refreshAvatar(accountId, username) {
338
430
  return this.request(`v1/accounts/${id(accountId)}/avatars/${id(username)}/refresh`, { method: "POST", body: "{}" });
@@ -361,13 +453,14 @@ var NativeWeChatClient = class {
361
453
  syncGroups(accountId) {
362
454
  return this.request(`v1/accounts/${id(accountId)}/group-sync`, { method: "POST", body: "{}" });
363
455
  }
364
- async messages(accountId, threadId2, options) {
365
- 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 });
366
458
  for (const msg of result.items) {
367
459
  if (isNativeTombstone(msg))
368
460
  continue;
369
461
  if (typeof msg.id !== "string" || msg.accountId !== accountId || msg.threadId !== threadId2 || msg.serverId != null && (typeof msg.serverId !== "string" || !/^\d+$/.test(msg.serverId)))
370
462
  throw new Error("Invalid native message identity");
463
+ validateMessageRecall(msg);
371
464
  }
372
465
  return result;
373
466
  }
@@ -375,15 +468,9 @@ var NativeWeChatClient = class {
375
468
  const message = await this.request(`v1/accounts/${id(accountId)}/messages/${id(messageId)}`);
376
469
  if (message.id !== messageId || message.accountId !== accountId || message.serverId != null && (typeof message.serverId !== "string" || !/^\d+$/.test(message.serverId)))
377
470
  throw new Error("Invalid native message identity");
471
+ validateMessageRecall(message);
378
472
  return message;
379
473
  }
380
- /** Resolve only the stored original in this message's own conversation. */
381
- async quotedMessage(accountId, messageId) {
382
- const quote = await this.request(`v1/accounts/${id(accountId)}/messages/${id(messageId)}/quote`);
383
- 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))
384
- throw new Error("Invalid native quote identity");
385
- return quote;
386
- }
387
474
  /** Account-wide local search, with the daemon's query-bound opaque cursor. */
388
475
  async searchMessages(accountId, options) {
389
476
  const result = await this.request(`v1/accounts/${id(accountId)}/messages${listQuery(options)}`);
@@ -392,17 +479,29 @@ var NativeWeChatClient = class {
392
479
  continue;
393
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)))
394
481
  throw new Error("Invalid native archive message identity");
482
+ validateMessageRecall(message);
395
483
  }
396
484
  return result;
397
485
  }
398
- sendText(accountId, threadId2, text, 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) {
399
490
  if (!idempotencyKey || /[\r\n]/.test(idempotencyKey))
400
491
  throw new Error("An idempotency key is required");
401
- return this.request(`v1/accounts/${id(accountId)}/sends`, { method: "POST", headers: { "Idempotency-Key": idempotencyKey }, body: JSON.stringify({ threadId: threadId2, text }) });
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) });
402
496
  }
403
497
  send(accountId, sendId, signal) {
404
498
  return this.request(`v1/accounts/${id(accountId)}/sends/${id(sendId)}`, { signal });
405
499
  }
500
+ sendShare(accountId, input, key, signal) {
501
+ if (!key || key.length > 200 || /[\u0000-\u001f\u007f]/.test(key))
502
+ throw new Error("An idempotency key is required");
503
+ return this.request(`v1/accounts/${id(accountId)}/sends`, { method: "POST", headers: { "Idempotency-Key": key }, body: JSON.stringify(input), signal });
504
+ }
406
505
  sendByKey(accountId, key) {
407
506
  if (!key || key.length > 200)
408
507
  throw new Error("Invalid idempotency key");
@@ -411,20 +510,54 @@ var NativeWeChatClient = class {
411
510
  cancelSend(accountId, sendId) {
412
511
  return this.request(`v1/accounts/${id(accountId)}/sends/${id(sendId)}/cancel`, { method: "POST", body: "{}" });
413
512
  }
414
- async upload(accountId, bytes, name, contentType = "application/octet-stream", signal) {
415
- if (!bytes.length || bytes.length > NATIVE_MAX_SOURCE_BYTES || !name || name.length > 255 || /[\r\n/\\]/.test(name))
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))
416
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 });
417
519
  const form = new FormData();
418
- form.set("file", new Blob([new Uint8Array(bytes).buffer], { type: contentType }), name);
419
- 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)));
420
523
  }
421
524
  sendMedia(accountId, input, key) {
422
525
  if (!key || /[\r\n]/.test(key))
423
526
  throw new Error("An idempotency key is required");
424
527
  return this.request(`v1/accounts/${id(accountId)}/sends`, { method: "POST", headers: { "Idempotency-Key": key }, body: JSON.stringify(input) });
425
528
  }
426
- mediaAssets(accountId, messageId) {
427
- 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
+ })) };
428
561
  }
429
562
  transferMedia(accountId, input) {
430
563
  return this.request(`v1/accounts/${id(accountId)}/messages/${id(input.messageId)}/media-transfers`, { method: "POST", body: JSON.stringify(input) });
@@ -438,26 +571,94 @@ var NativeWeChatClient = class {
438
571
  cancelJob(accountId, jobId) {
439
572
  return this.request(`v1/accounts/${id(accountId)}/jobs/${id(jobId)}/cancel`, { method: "POST", body: "{}" });
440
573
  }
441
- retryJob(accountId, jobId) {
442
- 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 }) });
443
581
  }
444
582
  repairMediaWriteback(accountId, limit = 25) {
445
583
  if (!Number.isInteger(limit) || limit < 1 || limit > 100)
446
584
  throw new Error("Invalid media writeback limit");
447
585
  return this.request(`v1/accounts/${id(accountId)}/media-writeback/repair`, { method: "POST", body: JSON.stringify({ limit }) });
448
586
  }
449
- 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 = {}) {
450
589
  const max = options.maxBytes ?? 128 * 1024 * 1024;
451
- 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))
452
591
  throw new Error("Invalid bounded content request");
453
592
  const query = options.representation === "preview" ? "?representation=preview" : "";
454
- 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);
455
595
  const length = response.headers.get("content-length");
456
596
  if (length && (!/^\d+$/.test(length) || Number(length) > max)) {
457
597
  await response.body?.cancel();
458
598
  throw new Error("Native media response exceeds its bound");
459
599
  }
460
- 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 };
461
662
  }
462
663
  markRead(accountId, threadId2, expectedVersion) {
463
664
  if (typeof expectedVersion !== "string" || !expectedVersion || expectedVersion.length > 128)
@@ -467,12 +668,17 @@ var NativeWeChatClient = class {
467
668
  events(accountId, after = "0", limit = 100) {
468
669
  if (!Number.isInteger(limit) || limit < 1 || limit > 200)
469
670
  throw new Error("Invalid event page limit");
470
- 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
+ });
471
677
  }
472
678
  ack(accountId, consumerId, cursor) {
473
679
  return this.request(`v1/accounts/${id(accountId)}/consumers/${id(consumerId)}/ack`, { method: "POST", body: JSON.stringify({ cursor: decimal(cursor) }) });
474
680
  }
475
- async *watch(accountId, after = "0", signal) {
681
+ async *watch(accountId, after = "0", signal, options = {}) {
476
682
  const connection = new AbortController();
477
683
  const streamSignal = signal ? AbortSignal.any([signal, connection.signal]) : connection.signal;
478
684
  const bounded = async (work, milliseconds, reason) => {
@@ -514,6 +720,7 @@ var NativeWeChatClient = class {
514
720
  const { value, done } = await bounded(() => activeReader.read(), this.streamIdleTimeoutMs, "Native SSE idle timeout");
515
721
  if (done)
516
722
  break;
723
+ options.onActivity?.();
517
724
  buffer += decoder.decode(value, { stream: true });
518
725
  if (buffer.length > 1024 * 1024)
519
726
  throw new Error("Native SSE frame exceeds its bound");
@@ -531,6 +738,8 @@ var NativeWeChatClient = class {
531
738
  const event = payload;
532
739
  if (!event || typeof event.kind !== "string" || !event.data || typeof event.data !== "object")
533
740
  throw new Error("Invalid native event");
741
+ if (event.kind === "message.recalled")
742
+ validateNativeRecallMetadata(event.data);
534
743
  event.cursor = decimal(event.cursor ?? eventCursor);
535
744
  yield event;
536
745
  }
@@ -577,11 +786,22 @@ function requireNativeIdentity(value) {
577
786
  }
578
787
  }
579
788
  function nativeChildEnvironment(token, environment = process.env) {
580
- return Object.fromEntries(["PATH", "HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "TMPDIR", "TMP", "TEMP", "LANG", "LC_ALL", "TZ", "SSL_CERT_FILE", "SSL_CERT_DIR"].filter((name) => environment[name] !== void 0 && environment[name] !== token).map((name) => [name, environment[name]]));
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]]));
581
790
  }
582
791
  function nativeHostTarget(platform = process.platform, arch = process.arch) {
583
- if (platform !== "linux" || !["x64", "arm64"].includes(arch)) throw new Error("native_binary_incompatible: managed hosting requires Linux x64 or ARM64; use external mode for remote daemons");
584
- return { arch, rustTarget: arch === "arm64" ? "aarch64-unknown-linux-gnu" : "x86_64-unknown-linux-gnu" };
792
+ const cpu = arch === "arm64" ? "aarch64" : "x86_64";
793
+ const suffix = { linux: "unknown-linux-gnu", darwin: "apple-darwin", win32: "pc-windows-msvc" }[platform];
794
+ if (!suffix || !["x64", "arm64"].includes(arch) || platform === "darwin" && arch !== "arm64") throw new Error("native_binary_incompatible: unsupported host platform; use external mode for remote daemons");
795
+ return { platform, arch, rustTarget: `${cpu}-${suffix}`, key: `${platform}-${arch}${platform === "linux" ? "-gnu" : ""}`, executable: platform === "win32" ? "wx.exe" : "wx" };
796
+ }
797
+ function nativeExecutableFormat(bytes, platform = process.platform) {
798
+ if (platform === "linux") return bytes.subarray(0, 4).equals(Buffer.from([127, 69, 76, 70]));
799
+ if (platform === "darwin") return bytes.subarray(0, 4).equals(Buffer.from([207, 250, 237, 254]));
800
+ if (platform === "win32" && bytes.length >= 64 && bytes[0] === 77 && bytes[1] === 90) {
801
+ const offset = bytes.readUInt32LE(60);
802
+ return offset >= 64 && offset <= bytes.length - 4 && bytes.subarray(offset, offset + 4).equals(Buffer.from([80, 69, 0, 0]));
803
+ }
804
+ return false;
585
805
  }
586
806
  async function resolveNativeExecutable(explicit, path = process.env.PATH ?? "", environment = nativeChildEnvironment("")) {
587
807
  const target = nativeHostTarget();
@@ -590,40 +810,48 @@ async function resolveNativeExecutable(explicit, path = process.env.PATH ?? "",
590
810
  if (!candidate) {
591
811
  for (const directory of path.split(delimiter).filter(isAbsolute)) {
592
812
  try {
593
- await access(join(directory, "wx"), constants.X_OK);
594
- candidate = join(directory, "wx");
813
+ await access(join(directory, target.executable), constants.X_OK);
814
+ candidate = join(directory, target.executable);
595
815
  break;
596
816
  } catch {
597
817
  }
818
+ if (process.platform === "win32") {
819
+ const payload = join(directory, "node_modules", "@agent-wechat", "cli", "scripts", "native-launcher.mjs");
820
+ try {
821
+ await access(payload);
822
+ candidate = payload;
823
+ break;
824
+ } catch {
825
+ }
826
+ }
598
827
  }
599
828
  }
600
829
  if (!candidate) throw new Error("native_binary_missing: install native wx separately or configure its absolute path");
601
830
  candidate = await realpath(candidate);
602
- if (candidate.endsWith("/scripts/native-launcher.mjs")) {
831
+ if (candidate.replaceAll("\\", "/").endsWith("/scripts/native-launcher.mjs")) {
603
832
  const root = dirname(dirname(candidate));
604
833
  const pkg = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
605
834
  if (pkg.name !== "@agent-wechat/cli" || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(pkg.version)) throw new Error("Unsupported native CLI launcher");
606
835
  const manifest = JSON.parse(await readFile(join(root, "native-release.json"), "utf8"));
607
- const asset = manifest.assets?.find((value) => value.rustTarget === target.rustTarget && value.platform === "linux" && value.arch === target.arch && value.libc === "gnu");
836
+ const asset = manifest.assets?.find((value) => value.rustTarget === target.rustTarget && value.platform === target.platform && value.arch === target.arch && (target.platform !== "linux" || value.libc === "gnu"));
608
837
  if (manifest.version !== pkg.version || !asset || !/^[a-f0-9]{64}$/.test(asset.sha256)) throw new Error("Native CLI manifest is incompatible");
609
- candidate = await realpath(join(root, "native", pkg.version, `linux-${target.arch}-gnu`, "wx"));
838
+ candidate = await realpath(join(root, "native", pkg.version, target.key, target.executable));
610
839
  const bytes = await readFile(candidate);
611
840
  if (bytes.length !== asset.bytes || createHash2("sha256").update(bytes).digest("hex") !== asset.sha256) throw new Error("Installed native executable checksum mismatch");
612
841
  }
613
842
  const stat = await lstat(candidate);
614
843
  if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("Native executable must be a regular file");
615
844
  await access(candidate, constants.X_OK);
616
- const magic = (await readFile(candidate)).subarray(0, 4);
617
- if (!magic.equals(Buffer.from([127, 69, 76, 70]))) throw new Error("native_binary_required: configure the actual native ELF executable, not an unverified process wrapper");
845
+ if (!nativeExecutableFormat(await readFile(candidate))) throw new Error("native_binary_required: configure the actual native executable for this OS");
618
846
  const { stdout } = await exec(candidate, ["--json", "version"], { env: environment, timeout: 5e3, maxBuffer: 65536 });
619
847
  const version = JSON.parse(stdout);
620
848
  requireNativeIdentity(version);
621
849
  if (version.target !== target.rustTarget) throw new Error("native_binary_incompatible: executable architecture differs from this host");
622
850
  return candidate;
623
851
  }
624
- async function portOccupied(url) {
852
+ async function portOccupied(url2) {
625
853
  return new Promise((resolve, reject) => {
626
- const socket = createConnection({ host: url.hostname.replace(/^\[|\]$/g, ""), port: Number(url.port || (url.protocol === "https:" ? 443 : 80)) });
854
+ const socket = createConnection({ host: url2.hostname.replace(/^\[|\]$/g, ""), port: Number(url2.port || (url2.protocol === "https:" ? 443 : 80)) });
627
855
  socket.setTimeout(1e3);
628
856
  socket.once("connect", () => {
629
857
  socket.destroy();
@@ -640,7 +868,7 @@ async function portOccupied(url) {
640
868
  });
641
869
  });
642
870
  }
643
- async function stopOwnedChild(child) {
871
+ async function stopOwnedChild(child, graceful) {
644
872
  if (!child.pid || child.exitCode !== null || child.signalCode !== null) return;
645
873
  await new Promise((resolve) => {
646
874
  const kill = setTimeout(() => {
@@ -650,7 +878,10 @@ async function stopOwnedChild(child) {
650
878
  clearTimeout(kill);
651
879
  resolve();
652
880
  });
653
- child.kill("SIGTERM");
881
+ if (graceful) void graceful().catch(() => {
882
+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGTERM");
883
+ });
884
+ else child.kill("SIGTERM");
654
885
  });
655
886
  }
656
887
  async function startNativeHost(config) {
@@ -665,11 +896,11 @@ async function startNativeHost(config) {
665
896
  });
666
897
  }
667
898
  if (config.mode !== "managed" || config.endpoint || !config.dataDir || !isAbsolute(config.dataDir) || config.serverConfig && !isAbsolute(config.serverConfig)) throw new Error("Managed native mode requires absolute dataDir/config paths and no remote endpoint");
668
- const url = validateNativeBaseUrl(`http://${config.listen ?? "127.0.0.1:6174"}`);
669
- if (await portOccupied(url)) throw new Error("native_owner_conflict: configured port is already owned; use external mode for an independently operated daemon");
899
+ const url2 = validateNativeBaseUrl(`http://${config.listen ?? "127.0.0.1:6174"}`);
900
+ if (await portOccupied(url2)) throw new Error("native_owner_conflict: configured port is already owned; use external mode for an independently operated daemon");
670
901
  const executable = await resolveNativeExecutable(config.executable, void 0, nativeChildEnvironment(token));
671
- const client = new NativeWeChatClient({ baseUrl: url.href, token, timeoutMs: 1e3 });
672
- const args = ["serve", "--data-dir", config.dataDir, "--token-stdin", "--listen", url.host];
902
+ const client = new NativeWeChatClient({ baseUrl: url2.href, token, timeoutMs: 1e3 });
903
+ const args = ["serve", "--data-dir", config.dataDir, "--token-stdin", "--listen", url2.host];
673
904
  if (config.serverConfig) args.push("--server-config", config.serverConfig);
674
905
  const child = spawn(executable, args, { env: nativeChildEnvironment(token), stdio: ["pipe", "ignore", "pipe"], shell: false });
675
906
  child.stderr?.on("data", () => {
@@ -692,10 +923,21 @@ async function startNativeHost(config) {
692
923
  if (exited) throw new Error("Native owned child exited before readiness");
693
924
  try {
694
925
  const status = await client.status();
695
- const dataDir = await realpath(config.dataDir);
926
+ const canonical = await realpath(config.dataDir);
927
+ const dataDir = process.platform === "win32" ? toNamespacedPath(canonical) : canonical;
696
928
  if (exited || status.version.backend !== "native" || status.version.apiVersion !== 1 || status.pid !== child.pid || status.dataDir !== dataDir || typeof status.serverId !== "string" || typeof status.ownershipGeneration !== "string") throw new Error("native_owner_conflict: readiness identity does not match the owned process/store");
697
929
  requireNativeIdentity(status.version);
698
- return host(new NativeWeChatClient({ baseUrl: url.href, token }), token, () => stopOwnedChild(child));
930
+ return host(new NativeWeChatClient({ baseUrl: url2.href, token }), token, () => stopOwnedChild(child, async () => {
931
+ const response = await fetch(new URL("v1/daemon/shutdown", url2), {
932
+ method: "POST",
933
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
934
+ body: JSON.stringify({ pid: status.pid, serverId: status.serverId, ownershipGeneration: status.ownershipGeneration }),
935
+ redirect: "error",
936
+ signal: AbortSignal.timeout(3e3)
937
+ });
938
+ if (!response.ok) throw new Error("Owned daemon refused graceful shutdown");
939
+ await response.body?.cancel();
940
+ }));
699
941
  } catch (error) {
700
942
  if (String(error).includes("native_owner_conflict")) throw error;
701
943
  await new Promise((resolve) => setTimeout(resolve, 100));
@@ -980,15 +1222,21 @@ function resolveWeChatIngress(params) {
980
1222
  });
981
1223
  }
982
1224
 
1225
+ // src/outbound-options.ts
1226
+ import { createHash as createHash6 } from "node:crypto";
1227
+
983
1228
  // src/outbound-media.ts
984
1229
  import { createHash as createHash5 } from "node:crypto";
985
1230
  import { randomUUID as randomUUID2 } from "node:crypto";
986
1231
 
987
1232
  // src/native-media.ts
988
1233
  import { createHash as createHash4, randomUUID } from "node:crypto";
989
- import { open } from "node:fs/promises";
990
- 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";
991
1238
  import { getImageMetadata, resizeToJpeg, IMAGE_REDUCE_QUALITY_STEPS } from "openclaw/plugin-sdk/media-runtime";
1239
+ import { saveMediaStream } from "openclaw/plugin-sdk/media-store";
992
1240
 
993
1241
  // src/attachment-store.ts
994
1242
  import { createHash as createHash3 } from "node:crypto";
@@ -1008,6 +1256,12 @@ async function saveManagedAttachment(params) {
1008
1256
  }
1009
1257
  const buffer = Buffer.from(params.data, "base64");
1010
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);
1011
1265
  const sha256 = createHash3("sha256").update(buffer).digest("hex");
1012
1266
  const saved = await params.saveMediaBuffer(
1013
1267
  buffer,
@@ -1018,31 +1272,59 @@ async function saveManagedAttachment(params) {
1018
1272
  );
1019
1273
  return { path: saved.path, size, sha256, filename: params.filename };
1020
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
+ }
1021
1303
 
1022
1304
  // src/media-delivery.ts
1023
1305
  function appendReference(body, reference) {
1024
1306
  return body ? `${body}
1025
1307
  ${reference}` : reference;
1026
1308
  }
1027
- function safeDisplayName(name) {
1028
- return name.replace(/[\r\n\0]/g, " ").trim() || "attachment";
1309
+ function safeDisplayName(name3) {
1310
+ return name3.replace(/[\r\n\0]/g, " ").trim() || "attachment";
1029
1311
  }
1030
1312
  function renderAttachmentBody(originalBody, attachment, exposeNonVisualPath = true) {
1031
1313
  if (!attachment) return originalBody;
1032
- const name = safeDisplayName(attachment.filename);
1314
+ const name3 = safeDisplayName(attachment.filename);
1033
1315
  if (attachment.status !== "ready" || !attachment.path) {
1034
1316
  const label = attachment.kind === "file" ? "File" : attachment.kind === "image" ? "Image" : attachment.kind === "audio" ? "Voice message" : "Video";
1035
1317
  if (attachment.status === "pending") {
1036
- return appendReference(originalBody, `[${label} pending: ${name}]`);
1318
+ return appendReference(originalBody, `[${label} pending: ${name3}]`);
1037
1319
  }
1038
1320
  if (attachment.status === "expired") {
1039
- return appendReference(originalBody, `[${label} expired: ${name}; 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.]`);
1040
1322
  }
1041
- return appendReference(originalBody, `[${label} unavailable: ${name} (${attachment.status})]`);
1323
+ return appendReference(originalBody, `[${label} unavailable: ${name3} (${attachment.status})]`);
1042
1324
  }
1043
1325
  if (attachment.kind === "file") {
1044
- const prefix = originalBody.trim() === name ? "" : originalBody;
1045
- return appendReference(prefix, `[File: ${name}]
1326
+ const prefix = originalBody.trim() === name3 ? "" : originalBody;
1327
+ return appendReference(prefix, `[File: ${name3}]
1046
1328
  [Local file: <${attachment.path}>]`);
1047
1329
  }
1048
1330
  if (exposeNonVisualPath) {
@@ -1061,28 +1343,234 @@ function renderAttachmentBody(originalBody, attachment, exposeNonVisualPath = tr
1061
1343
  return body;
1062
1344
  }
1063
1345
 
1346
+ // src/native-send.ts
1347
+ async function nativeOutboundDelivery(client, accountId, threadId2, messageIds, source) {
1348
+ const receipts = [];
1349
+ try {
1350
+ if (!Array.isArray(messageIds) || !messageIds.length || messageIds.length > 256 || messageIds.some((id2) => typeof id2 !== "string" || !id2 || id2.length > 4096) || new Set(messageIds).size !== messageIds.length) throw Error("Message receipts unavailable");
1351
+ for (const [index, messageId] of messageIds.entries()) {
1352
+ const message = await client.message(accountId, messageId);
1353
+ if (message.id !== messageId || message.accountId !== accountId || message.threadId !== threadId2 || message.direction !== "outgoing" || typeof message.serverId !== "string" || !/^[1-9]\d{0,19}$/.test(message.serverId) || BigInt(message.serverId) > 18446744073709551615n || source.serverIds?.[index] != null && source.serverIds[index] !== message.serverId) throw Error("Message receipt identity mismatch");
1354
+ receipts.push({ messageId, serverId: message.serverId, accountId, threadId: threadId2 });
1355
+ }
1356
+ } catch {
1357
+ return { messageId: "", meta: {
1358
+ accountId,
1359
+ threadId: threadId2,
1360
+ ...source,
1361
+ messageIds: receipts,
1362
+ outcome: "unknown",
1363
+ receiptState: "needs_review",
1364
+ retryable: false,
1365
+ note: "Send submitted. Inspect the durable send/job and retained receipts; do not resend automatically."
1366
+ } };
1367
+ }
1368
+ return { messageId: receipts[0].messageId, meta: {
1369
+ accountId,
1370
+ threadId: threadId2,
1371
+ serverId: receipts[0].serverId,
1372
+ outcome: "sent",
1373
+ ...source,
1374
+ messageIds: receipts,
1375
+ receiptState: "verified"
1376
+ } };
1377
+ }
1378
+ async function submitNativeText(client, accountId, threadId2, text3, key, options = {}) {
1379
+ let intent = await client.sendText(accountId, threadId2, text3, key);
1380
+ const deadline = Date.now() + Math.max(1, Math.min(options.timeoutMs ?? 65e3, 65e3));
1381
+ let delay2 = Math.max(1, Math.min(options.initialDelayMs ?? 250, 1e3));
1382
+ while (["queued", "submitting"].includes(intent.state) && Date.now() < deadline) {
1383
+ await new Promise((resolve) => setTimeout(resolve, Math.min(delay2, deadline - Date.now())));
1384
+ const remaining = deadline - Date.now();
1385
+ if (remaining <= 0) break;
1386
+ intent = await client.send(accountId, intent.id, AbortSignal.timeout(remaining));
1387
+ delay2 = Math.min(delay2 * 2, 1e3);
1388
+ }
1389
+ if (!["accepted", "sent", "server_accepted"].includes(intent.state)) throw new Error(`Native send ${intent.id} requires inspection (${intent.state}); do not automatically resend`);
1390
+ return intent;
1391
+ }
1392
+
1393
+ // src/native-recall-state.ts
1394
+ function nativeRecallInfo(message) {
1395
+ if (message.recall) validateNativeRecallMetadata(message.recall);
1396
+ return message.recall;
1397
+ }
1398
+ function nativeRecallIdentity(threadId2, serverId) {
1399
+ return JSON.stringify([threadId2, serverId]);
1400
+ }
1401
+ function validateNativeRecall(value) {
1402
+ validateNativeRecallMetadata(value);
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");
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
+ }
1418
+ function recalledNativeMessage(message, recall) {
1419
+ validateNativeRecall(recall);
1420
+ const previous = nativeRecallInfo(message);
1421
+ const replacementText = previous?.replacementText ?? recall.replacementText;
1422
+ return {
1423
+ ...message,
1424
+ type: 1e4,
1425
+ body: "[Message recalled]",
1426
+ quote: void 0,
1427
+ link: void 0,
1428
+ media: [],
1429
+ senderId: message.senderId || null,
1430
+ direction: message.senderId ? message.direction : null,
1431
+ mentions: { state: "unknown", userIds: [], self: null, all: null, source: null },
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 }
1474
+ };
1475
+ }
1476
+
1064
1477
  // src/native-media.ts
1065
1478
  function kind(type) {
1066
1479
  return type === 3 || type === 47 ? "image" : type === 34 ? "audio" : type === 43 ? "video" : type === 49 ? "file" : void 0;
1067
1480
  }
1068
- var terminalJobs = /* @__PURE__ */ new Set(["accepted", "completed", "succeeded", "available", "failed", "cancelled", "expired", "needs_review"]);
1481
+ var terminalJobs = /* @__PURE__ */ new Set(["accepted", "completed", "succeeded", "available", "failed", "partial", "cancelled", "expired", "needs_review"]);
1482
+ var successfulSendJobs = /* @__PURE__ */ new Set(["accepted", "completed", "succeeded"]);
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
+ };
1504
+ function mediaSendResult(job) {
1505
+ return job.result && typeof job.result === "object" && !Array.isArray(job.result) ? job.result : {};
1506
+ }
1507
+ function mediaSendReceiptIds(job, audioAsVoice) {
1508
+ const result = mediaSendResult(job), ids = result.messageIds;
1509
+ if (!successfulSendJobs.has(job.state) || result.profileProjection === "unknown" || !Array.isArray(ids) || !ids.length || ids.length > 256 || ids.some((id2) => typeof id2 !== "string" || !id2 || id2.length > 4096) || new Set(ids).size !== ids.length) return void 0;
1510
+ if (audioAsVoice) {
1511
+ const chunks = result.chunks;
1512
+ if (!Array.isArray(chunks) || !chunks.length || chunks.length !== ids.length || chunks.some((chunk) => !chunk || chunk.state !== "accepted" || typeof chunk.serverMessageId !== "string")) return void 0;
1513
+ } else if (ids.length !== 1) return void 0;
1514
+ return ids;
1515
+ }
1516
+ async function waitNativeMediaSendReceipts(client, accountId, threadId2, initial, audioAsVoice, timeoutMs = 1e4) {
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");
1518
+ const deadline = Date.now() + Math.max(0, Math.min(timeoutMs, 1e4));
1519
+ let job = initial, delay2 = 100;
1520
+ while (successfulSendJobs.has(job.state) && !mediaSendReceiptIds(job, audioAsVoice) && Date.now() < deadline) {
1521
+ const result = mediaSendResult(job);
1522
+ if (["unknown", "not_applicable"].includes(String(result.profileProjection)) || audioAsVoice && Array.isArray(result.chunks) && result.chunks.some((chunk) => !chunk || chunk.state !== "accepted")) break;
1523
+ await new Promise((resolve) => setTimeout(resolve, Math.min(delay2, Math.max(0, deadline - Date.now()))));
1524
+ const remaining = deadline - Date.now();
1525
+ if (remaining <= 0) break;
1526
+ let next;
1527
+ try {
1528
+ next = await client.job(accountId, initial.id, AbortSignal.timeout(remaining));
1529
+ } catch {
1530
+ break;
1531
+ }
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;
1533
+ job = next;
1534
+ delay2 = Math.min(delay2 * 2, 1e3);
1535
+ }
1536
+ return job;
1537
+ }
1069
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) {
1070
1542
  const deadline = Date.now() + timeoutMs;
1071
1543
  let job = initial;
1072
- let delay = 250;
1544
+ let delay2 = 250;
1073
1545
  while (!terminalJobs.has(job.state) && Date.now() < deadline) {
1074
1546
  signal?.throwIfAborted();
1075
1547
  assertCurrent?.();
1076
- 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()))));
1077
1549
  const remaining = deadline - Date.now();
1078
1550
  if (remaining <= 0) break;
1079
1551
  signal?.throwIfAborted();
1080
1552
  assertCurrent?.();
1081
- job = await client.job(accountId, job.id, signal ? AbortSignal.any([signal, AbortSignal.timeout(remaining)]) : AbortSignal.timeout(remaining));
1082
- 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);
1083
1557
  }
1084
1558
  return job;
1085
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
+ }
1086
1574
  function select(assets, type, quality = "best") {
1087
1575
  const preferred = type === 34 ? ["normal"] : type === 43 ? ["normal", "original"] : ["original", "standard", "thumbnail", "encoded"];
1088
1576
  const rank = (asset) => {
@@ -1103,107 +1591,124 @@ async function prepareImageRepresentation(bytes, mime, cfg) {
1103
1591
  }
1104
1592
  throw Error("Native model image representation exceeds its bound");
1105
1593
  }
1106
- async function prepareNativeQuote(params) {
1107
- const { client, account, message } = params;
1108
- const guard = () => {
1109
- params.signal?.throwIfAborted();
1110
- params.assertCurrent?.();
1111
- };
1112
- guard();
1113
- const comment = (message.body ?? "").slice(0, 16384);
1114
- 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 } });
1115
- if (!message.quote) return unavailable("invalid");
1116
- await params.beforeMediaAccess?.();
1117
- guard();
1118
- let resolution;
1594
+ async function prepareNativeLink(params) {
1595
+ const { message } = params;
1596
+ const link = message.link;
1597
+ const body = [`[Link]${link.title ? ` ${link.title}` : ""}`, link.description, link.url].filter(Boolean).join("\n").slice(0, 65536);
1598
+ const unavailable = (status, reason) => ({
1599
+ body: `${body}
1600
+ [Link preview ${status}]`,
1601
+ pending: false,
1602
+ retryable: false,
1603
+ reason,
1604
+ attachment: { kind: "image", status, filename: "link-preview" }
1605
+ });
1606
+ if (params.quality && !["best", "thumbnail"].includes(params.quality)) return unavailable("unsupported", "unsupported_media_variant");
1607
+ let prepared;
1119
1608
  try {
1120
- resolution = await client.quotedMessage(account.native.accountId, message.id);
1609
+ prepared = await prepareNativeAttachment({
1610
+ ...params,
1611
+ quality: "thumbnail",
1612
+ message: { ...message, type: 3, appMessageType: void 0, quote: void 0, link: void 0 }
1613
+ });
1121
1614
  } catch (error) {
1122
- guard();
1615
+ params.signal?.throwIfAborted();
1616
+ params.assertCurrent?.();
1123
1617
  if (!(error instanceof NativeApiError)) throw error;
1124
- return unavailable("unavailable");
1125
- }
1126
- guard();
1127
- if (resolution.accountId !== message.accountId || resolution.messageId !== message.id || resolution.threadId !== message.threadId) throw Error("Native quote identity does not match its message");
1128
- if (resolution.state === "embedded") {
1129
- 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");
1130
- const author = { senderId: resolution.senderId ?? null, direction: null };
1131
- if (params.allowQuotedMessage && !await params.allowQuotedMessage(author)) return unavailable("not permitted");
1132
- guard();
1133
- const quote2 = { state: "embedded", senderId: resolution.senderId ?? void 0, type: message.quote.type };
1134
- const prefix2 = `${comment}${comment ? "\n\n" : ""}[Quoted ${message.quote.type === 3 ? "image" : "text"} from ${resolution.senderId ?? "unknown sender"}; embedded in quote, original not stored]
1135
- `;
1136
- if (message.quote.type === 1) return { body: `${prefix2}${resolution.embeddedText}
1137
- [/Quoted message]`, pending: false, quote: quote2 };
1138
- const beforeMediaAccess2 = async () => {
1139
- await params.beforeMediaAccess?.();
1140
- guard();
1141
- if (params.allowQuotedMessage && !await params.allowQuotedMessage(author)) throw Error("Quoted message is no longer permitted");
1142
- guard();
1143
- };
1144
- const prepared2 = await prepareNativeAttachment({ ...params, message: { ...message, type: 3, appMessageType: void 0, quote: void 0 }, beforeMediaAccess: beforeMediaAccess2 });
1145
- return {
1146
- ...prepared2,
1147
- body: `${prefix2}${prepared2.body}
1148
- [/Quoted message]`,
1149
- pending: false,
1150
- quote: quote2,
1151
- ...prepared2.pending ? { attachment: { kind: "image", status: "pending", filename: "quoted-image" } } : {}
1152
- };
1618
+ if (terminalIdentityErrors.has(error.code) || error.code === "message_recalled") throw error;
1619
+ return { ...unavailable("unavailable", error.code), retryable: error.retryable };
1153
1620
  }
1154
- if (resolution.state !== "resolved") {
1155
- if (!["missing", "invalid", "unsupported", "ambiguous"].includes(resolution.state) || resolution.message != null) throw Error("Invalid native quote resolution");
1156
- return unavailable(resolution.state);
1157
- }
1158
- const original = resolution.message;
1159
- 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");
1160
- if (params.allowQuotedMessage && !await params.allowQuotedMessage(original)) return unavailable("not permitted");
1161
- guard();
1162
- const quote = { state: "resolved", messageId: original.id, senderId: original.senderId ?? void 0, type: original.type };
1163
- const prefix = `${comment}${comment ? "\n\n" : ""}[Quoted ${original.type === 3 ? "image" : "text"} from ${original.senderId ?? "unknown sender"}; message ${original.id}]
1164
- `;
1165
- if (original.type === 1) return { body: `${prefix}${(original.body ?? "").slice(0, 16384)}
1166
- [/Quoted message]`, pending: false, quote };
1621
+ if (prepared.reason === "message_recalled" || terminalIdentityErrors.has(prepared.reason ?? "")) return prepared;
1622
+ return {
1623
+ ...prepared,
1624
+ body: `${body}
1625
+ [Link preview]
1626
+ ${prepared.body}`,
1627
+ pending: false,
1628
+ ...prepared.pending ? { attachment: { kind: "image", status: "pending", filename: "link-preview" } } : {}
1629
+ };
1630
+ }
1631
+ async function prepareNativeQuote(params) {
1632
+ const { message } = params;
1633
+ const guard2 = () => {
1634
+ params.signal?.throwIfAborted();
1635
+ params.assertCurrent?.();
1636
+ };
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
+ };
1167
1649
  const beforeMediaAccess = async () => {
1168
1650
  await params.beforeMediaAccess?.();
1169
- guard();
1170
- if (params.allowQuotedMessage && !await params.allowQuotedMessage(original)) throw Error("Quoted message is no longer permitted");
1171
- guard();
1651
+ guard2();
1652
+ if (params.allowQuotedMessage && !await params.allowQuotedMessage(author)) throw Error("Quoted message is no longer permitted");
1653
+ guard2();
1172
1654
  };
1173
- 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;
1174
1657
  return {
1175
1658
  ...prepared,
1176
- body: `${prefix}${prepared.body}
1177
- [/Quoted message]`,
1659
+ body: renderEmbeddedQuote(message, true, prepared.body).body,
1660
+ quote: rendered.quote,
1178
1661
  pending: false,
1179
- quote,
1180
- ...prepared.pending ? { attachment: { kind: "image", status: "pending", filename: "quoted-image" } } : {},
1181
- suppliedAssets: prepared.suppliedAssets?.map((asset) => ({ ...asset, sourceMessageId: original.id }))
1662
+ ...prepared.pending ? { attachment: { kind: "image", status: "pending", filename: "quoted-image" } } : {}
1182
1663
  };
1183
1664
  }
1184
1665
  async function prepareNativeAttachment(params) {
1666
+ try {
1667
+ return await prepareNativeAttachmentInput(params);
1668
+ } catch (error) {
1669
+ params.signal?.throwIfAborted();
1670
+ params.assertCurrent?.();
1671
+ if (!(error instanceof NativeApiError) || !terminalIdentityErrors.has(error.code)) throw error;
1672
+ if (params.message.type === 49 && params.message.appMessageType === 57) return {
1673
+ body: `${(params.message.body ?? "").slice(0, 16384)}
1674
+ [Quoted message unavailable: stored source identity could not be verified]`,
1675
+ quote: { state: "unavailable" },
1676
+ pending: false,
1677
+ retryable: false,
1678
+ reason: error.code
1679
+ };
1680
+ const attachment = { kind: kind(params.message.type) ?? "file", filename: "attachment", status: "unavailable" };
1681
+ return { body: renderAttachmentBody("", attachment), attachment, pending: false, retryable: false, reason: error.code };
1682
+ }
1683
+ }
1684
+ async function prepareNativeAttachmentInput(params) {
1185
1685
  const { client, account, message, core } = params;
1186
1686
  const attachmentKind = kind(message.type);
1187
- const guard = () => {
1687
+ const guard2 = () => {
1188
1688
  params.signal?.throwIfAborted();
1189
1689
  params.assertCurrent?.();
1190
1690
  };
1191
- guard();
1691
+ guard2();
1692
+ if (nativeRecallInfo(message)) return { body: "[Message recalled]", pending: false, retryable: false, reason: "message_recalled" };
1192
1693
  const authorize = async () => {
1193
- guard();
1694
+ guard2();
1194
1695
  await params.beforeMediaAccess?.();
1195
- guard();
1696
+ guard2();
1196
1697
  };
1197
1698
  if (message.type === 49 && message.appMessageType === 57) return prepareNativeQuote(params);
1198
1699
  if (message.type === 49 && message.appMessageType === 19) return { body: message.body?.slice(0, 65536) || "[Forwarded chat history unavailable]", pending: false };
1700
+ if (message.type === 49 && [3, 4, 5].includes(message.appMessageType ?? 0) && message.link) return prepareNativeLink(params);
1199
1701
  if (message.type === 49 && message.appMessageType != null && message.appMessageType !== 6) return { body: `[Unsupported WeChat app message subtype ${message.appMessageType}]`, pending: false, retryable: false };
1200
1702
  if (!attachmentKind) return { body: message.type === 1 ? message.body ?? "" : `[Unsupported WeChat message type ${message.type}]`, pending: false };
1201
1703
  const accountId = account.native.accountId;
1202
- 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
+ );
1203
1708
  const scopedAssets = async () => {
1204
1709
  await authorize();
1205
1710
  const items = (await client.mediaAssets(accountId, message.id)).items;
1206
- guard();
1711
+ guard2();
1207
1712
  if (items.some((asset2) => asset2.accountId !== accountId || asset2.messageId !== message.id)) throw Error("Native attachment identity does not match its message");
1208
1713
  return items;
1209
1714
  };
@@ -1223,34 +1728,44 @@ async function prepareNativeAttachment(params) {
1223
1728
  }
1224
1729
  let job;
1225
1730
  let transferError;
1226
- if (!asset && initialCandidate?.jobId) {
1731
+ if (!asset && initialCandidate?.jobId && initialCandidate.state !== "recalled") {
1227
1732
  await authorize();
1228
- job = await client.job(accountId, initialCandidate.jobId, params.signal);
1229
- guard();
1230
- 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 };
1231
1736
  assets = await scopedAssets();
1232
1737
  asset = select(assets, message.type, quality);
1738
+ if (!asset && transferCandidate()?.state === "recalled") return { body: "[Message recalled]", pending: false, retryable: false, reason: "message_recalled" };
1233
1739
  if (!asset && ["queued", "running"].includes(job.state)) return { body: `[${attachmentKind} pending]`, pending: true, jobId: job.id, retryable: true };
1234
1740
  }
1235
- if (!asset && !job && params.download !== false && !["expired", "unsupported"].includes(transferCandidate()?.state ?? "")) {
1741
+ if (!asset && !job && params.download !== false && !["expired", "unsupported", "recalled"].includes(transferCandidate()?.state ?? "")) {
1742
+ await authorize();
1236
1743
  try {
1237
- await authorize();
1238
1744
  job = await client.transferMedia(accountId, { messageId: message.id, assetId: null, quality: transferQuality });
1239
- guard();
1240
- job = await waitNativeMediaJob(client, accountId, job, params.waitMs ?? 2e4, params.signal, guard);
1241
- 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();
1242
1754
  } catch (error) {
1243
- guard();
1244
- if (!(error instanceof NativeApiError) || error.retryable) return { body: `[${attachmentKind} pending: retrieval is unavailable]`, pending: true, jobId: job?.id, retryable: true };
1755
+ guard2();
1756
+ if (!(error instanceof NativeApiError) || terminalIdentityErrors.has(error.code)) throw error;
1757
+ if (error.retryable) return { body: `[${attachmentKind} pending: retrieval is unavailable]`, pending: true, jobId: job?.id, retryable: true };
1245
1758
  transferError = error;
1246
1759
  }
1247
1760
  assets = await scopedAssets();
1248
1761
  asset = select(assets, message.type, quality);
1762
+ if (!asset && transferCandidate()?.state === "recalled") return { body: "[Message recalled]", pending: false, retryable: false, reason: "message_recalled" };
1249
1763
  if (!asset && job && ["queued", "running"].includes(job.state)) return { body: `[${attachmentKind} pending]`, pending: true, jobId: job.id, retryable: true };
1250
1764
  }
1251
1765
  const candidate = transferCandidate();
1252
1766
  const filename = basename(asset?.filename ?? candidate?.filename ?? `message-${createHash4("sha256").update(message.id).digest("hex").slice(0, 12)}.bin`).replace(/[\r\n\0]/g, "_");
1253
1767
  if (!asset) {
1768
+ if (candidate?.state === "recalled" || transferError?.code === "message_recalled") return { body: "[Message recalled]", pending: false, retryable: false, reason: "message_recalled" };
1254
1769
  const state = candidate?.state === "expired" ? "expired" : candidate?.state === "unsupported" ? "unsupported" : "unavailable";
1255
1770
  const attachment2 = { kind: attachmentKind, filename, status: state, expiresAt: candidate?.expiresAt ?? void 0 };
1256
1771
  return {
@@ -1267,14 +1782,63 @@ async function prepareNativeAttachment(params) {
1267
1782
  return { body: renderAttachmentBody("", attachment2), attachment: attachment2, pending: false };
1268
1783
  }
1269
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
+ }
1270
1834
  const content = await client.mediaContent(accountId, asset.id, { maxBytes, signal: params.signal });
1271
- guard();
1835
+ guard2();
1272
1836
  const mime = content.contentType.split(";", 1)[0].trim().toLowerCase();
1273
1837
  if (!/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/.test(mime)) throw Error("Native attachment MIME type is unsupported");
1274
1838
  const hash = createHash4("sha256").update(content.bytes).digest("hex");
1275
1839
  if (!asset.sha256 || hash !== asset.sha256 || asset.byteLength != null && asset.byteLength !== content.bytes.length) throw new Error("Native attachment integrity did not verify");
1276
1840
  await authorize();
1277
- 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 });
1278
1842
  const actual = asset.actualVariant ?? asset.variant;
1279
1843
  const attachment = {
1280
1844
  kind: attachmentKind,
@@ -1294,7 +1858,7 @@ async function prepareNativeAttachment(params) {
1294
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");
1295
1859
  await authorize();
1296
1860
  const derived = await client.mediaContent(accountId, asset.id, { maxBytes: preview.byteLength, representation: "preview", signal: params.signal });
1297
- guard();
1861
+ guard2();
1298
1862
  const derivedMime = derived.contentType.split(";", 1)[0].trim().toLowerCase();
1299
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");
1300
1864
  imageBytes = Buffer.from(derived.bytes);
@@ -1319,7 +1883,7 @@ async function prepareNativeAttachment(params) {
1319
1883
  [Model image: prepared still preview; original retained separately]`;
1320
1884
  }
1321
1885
  }
1322
- guard();
1886
+ guard2();
1323
1887
  return {
1324
1888
  body,
1325
1889
  attachment,
@@ -1346,125 +1910,250 @@ async function prepareNativeAttachment(params) {
1346
1910
  pending: false
1347
1911
  };
1348
1912
  }
1349
- async function sendNativeAttachment(client, account, threadId2, mediaUrl, audioAsVoice = false, key = randomUUID()) {
1350
- const max = Math.min(account.mediaMaxMb * 1024 * 1024, NATIVE_MAX_SOURCE_BYTES);
1351
- let bytes;
1352
- let filename;
1353
- let mime;
1354
- if (/^https?:/.test(mediaUrl)) {
1355
- const response = await fetch(mediaUrl, { redirect: "error", signal: AbortSignal.timeout(3e4) });
1356
- if (!response.ok) throw new Error(`Native outbound source unavailable (${response.status})`);
1357
- const length = response.headers.get("content-length");
1358
- if (length && (!/^\d+$/.test(length) || Number(length) > max)) {
1359
- await response.body?.cancel();
1360
- throw new Error("Native outbound source exceeds configured size");
1361
- }
1362
- const reader = response.body?.getReader();
1363
- if (!reader) throw new Error("Native outbound source has no bytes");
1364
- const chunks = [];
1365
- let size = 0;
1366
- try {
1367
- while (true) {
1368
- const { value, done } = await reader.read();
1369
- if (done) break;
1370
- size += value.length;
1371
- if (size > max) throw new Error("Native outbound source exceeds configured size");
1372
- chunks.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;
1373
1946
  }
1374
- } catch (error) {
1375
- await reader.cancel();
1376
- throw error;
1377
- } finally {
1378
- reader.releaseLock();
1379
- }
1380
- bytes = new Uint8Array(size);
1381
- let offset = 0;
1382
- for (const chunk of chunks) {
1383
- bytes.set(chunk, offset);
1384
- offset += chunk.length;
1385
- }
1386
- filename = basename(new URL(mediaUrl).pathname) || "attachment";
1387
- mime = response.headers.get("content-type")?.split(";")[0] ?? "application/octet-stream";
1388
- } else {
1389
- const path = mediaUrl.startsWith("file:") ? new URL(mediaUrl) : mediaUrl;
1390
- const file = await open(path, "r");
1391
- try {
1392
- const stat = await file.stat();
1393
- if (!stat.isFile() || stat.size === 0 || stat.size > max) throw new Error("Native outbound source must be a bounded regular file");
1394
- const chunks = [];
1395
- let size = 0;
1396
- while (true) {
1397
- const chunk = Buffer.alloc(Math.min(65536, max + 1 - size));
1398
- const { bytesRead } = await file.read(chunk, 0, chunk.length, null);
1399
- if (!bytesRead) break;
1400
- size += bytesRead;
1401
- if (size > max) throw new Error("Native outbound source exceeds configured size");
1402
- chunks.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");
1403
1952
  }
1404
- bytes = Buffer.concat(chunks, size);
1405
- } finally {
1406
- 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");
1407
1992
  }
1408
- filename = basename(path instanceof URL ? path.pathname : path);
1409
- const extension = extname(filename).toLowerCase();
1410
- 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";
1411
- }
1412
- if (audioAsVoice && !mime.startsWith("audio/")) throw new Error("Voice sending requires an explicit audio attachment");
1413
- const accountId = account.native.accountId;
1414
- const source = await client.upload(accountId, bytes, filename, mime);
1415
- 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 };
1416
- const job = await waitNativeMediaJob(client, accountId, await client.sendMedia(accountId, input, key), audioAsVoice ? 25 * 6e4 : 65e3);
1417
- if (!["accepted", "completed", "succeeded"].includes(job.state)) throw new Error(`Native media job ${job.id} requires inspection (${job.state}); retain completed items and do not automatically resend`);
1418
- return `agent-wechat-native:${accountId}:${job.id}`;
1419
- }
1420
-
1421
- // src/native-send.ts
1422
- async function submitNativeText(client, accountId, threadId2, text, key, options = {}) {
1423
- let intent = await client.sendText(accountId, threadId2, text, key);
1424
- const deadline = Date.now() + Math.max(1, Math.min(options.timeoutMs ?? 65e3, 65e3));
1425
- let delay = Math.max(1, Math.min(options.initialDelayMs ?? 250, 1e3));
1426
- while (["queued", "submitting"].includes(intent.state) && Date.now() < deadline) {
1427
- await new Promise((resolve) => setTimeout(resolve, Math.min(delay, deadline - Date.now())));
1428
- const remaining = deadline - Date.now();
1429
- if (remaining <= 0) break;
1430
- intent = await client.send(accountId, intent.id, AbortSignal.timeout(remaining));
1431
- delay = Math.min(delay * 2, 1e3);
1432
- }
1433
- if (!["accepted", "sent", "server_accepted"].includes(intent.state)) throw new Error(`Native send ${intent.id} requires inspection (${intent.state}); do not automatically resend`);
1434
- return intent;
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 });
1999
+ }
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
+ };
2010
+ await beforeSend?.();
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
+ }
2019
+ if (successfulSendJobs.has(job.state)) job = await waitNativeMediaSendReceipts(client, accountId, threadId2, job, audioAsVoice);
2020
+ if (!successfulSendJobs.has(job.state)) throw new NativeMediaJobInspectionError(job, accountId, threadId2, key, "job_not_completed");
2021
+ const result = mediaSendResult(job);
2022
+ const chunks = Array.isArray(result.chunks) ? result.chunks.filter((chunk) => chunk && typeof chunk === "object") : [];
2023
+ const serverIds = audioAsVoice ? chunks.filter((chunk) => chunk.state === "accepted" && typeof chunk.serverMessageId === "string").map((chunk) => chunk.serverMessageId) : job.serverMessageId ? [job.serverMessageId] : void 0;
2024
+ return nativeOutboundDelivery(client, accountId, threadId2, mediaSendReceiptIds(job, audioAsVoice), { jobId: job.id, state: job.state, serverIds });
1435
2025
  }
1436
2026
 
1437
2027
  // src/outbound-media.ts
1438
- async function sendWeChatMedia(cfg, to, text, 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");
1439
2031
  const account = resolveWeChatAccount(cfg);
1440
2032
  if (!account?.native) throw new Error("No native daemon configured");
1441
2033
  const { client } = await ensureNativeHost(account.native);
1442
2034
  const key = idempotencyKey ?? randomUUID2();
1443
2035
  if (!mediaUrl) {
1444
2036
  if (audioAsVoice) throw new Error("Voice sending requires an audio attachment");
1445
- const send = await submitNativeText(client, account.native.accountId, to, text, key);
1446
- return `agent-wechat-native:${account.native.accountId}:${send.id}`;
2037
+ await beforeSend?.();
2038
+ const send = await submitNativeText(client, account.native.accountId, to, text3, key);
2039
+ return nativeOutboundDelivery(
2040
+ client,
2041
+ account.native.accountId,
2042
+ to,
2043
+ send.localMessageId ? [send.localMessageId] : [],
2044
+ { sendId: send.id, state: send.state, serverIds: send.serverId ? [send.serverId] : void 0 }
2045
+ );
2046
+ }
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"));
1447
2051
  }
1448
- const result = await sendNativeAttachment(client, account, to, mediaUrl, audioAsVoice, key);
1449
- if (text) await submitNativeText(client, account.native.accountId, to, text, createHash5("sha256").update(`${key}\0caption`).digest("hex"));
1450
2052
  return result;
1451
2053
  }
1452
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
+
1453
2142
  // src/native-monitor.ts
1454
- import { createHash as createHash8 } from "node:crypto";
2143
+ import { createHash as createHash9 } from "node:crypto";
1455
2144
  import { createChannelMessageReplyPipeline } from "openclaw/plugin-sdk/channel-outbound";
1456
2145
  import { resolveStableChannelMessageIngress } from "openclaw/plugin-sdk/channel-ingress-runtime";
1457
2146
 
1458
2147
  // src/native-consumer-state.ts
1459
- import { createHash as createHash6, randomUUID as randomUUID3 } from "node:crypto";
2148
+ import { createHash as createHash7, randomUUID as randomUUID3 } from "node:crypto";
1460
2149
  import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
1461
- 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";
1462
2151
  var NativeConsumerState = class {
1463
2152
  file;
1464
2153
  value;
1465
2154
  constructor(directory, serverId, accountId) {
1466
2155
  if (!isAbsolute2(directory) || !serverId || !accountId) throw new Error("Native consumer state requires absolute storage and bound server/account identities");
1467
- 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`);
1468
2157
  this.value = { schemaVersion: 1, serverId, accountId, cursor: "0", items: {} };
1469
2158
  if (existsSync(this.file)) {
1470
2159
  const stat = lstatSync(this.file);
@@ -1473,10 +2162,18 @@ var NativeConsumerState = class {
1473
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");
1474
2163
  for (const [id2, item] of Object.entries(parsed.items)) {
1475
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);
1476
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");
2167
+ if (item.revision != null && (typeof item.revision !== "string" || !item.revision || item.revision.length > 64)) throw Error("Invalid native custody revision; state was preserved");
2168
+ item.revision ??= randomUUID3();
1477
2169
  if (item.groupContext && (!item.cursor || item.origin !== "live" || item.state !== "ignored" || item.message.direction !== "incoming" || !item.message.threadId.endsWith("@chatroom"))) throw new Error("Invalid native buffered group context; state was preserved");
1478
2170
  if (item.state === "dispatching") item.state = "needs_review";
1479
2171
  }
2172
+ if (parsed.recalls != null && (!parsed.recalls || typeof parsed.recalls !== "object" || Array.isArray(parsed.recalls))) throw Error("Invalid native recall state; state was preserved");
2173
+ for (const [key, recall] of Object.entries(parsed.recalls ?? {})) {
2174
+ validateNativeRecall(recall);
2175
+ if (key !== nativeRecallIdentity(recall.threadId, recall.serverId)) throw Error("Invalid native recall identity; state was preserved");
2176
+ }
1480
2177
  this.value = parsed;
1481
2178
  this.persist();
1482
2179
  }
@@ -1484,12 +2181,22 @@ var NativeConsumerState = class {
1484
2181
  get cursor() {
1485
2182
  return this.value.cursor;
1486
2183
  }
2184
+ get accountId() {
2185
+ return this.value.accountId;
2186
+ }
1487
2187
  items() {
1488
2188
  return Object.values(this.value.items);
1489
2189
  }
1490
2190
  get(messageId) {
1491
2191
  return this.value.items[messageId];
1492
2192
  }
2193
+ isRecalled(message) {
2194
+ return !!nativeRecallInfo(message) || !!(message.serverId && this.value.recalls?.[nativeRecallIdentity(message.threadId, message.serverId)]);
2195
+ }
2196
+ isCurrent(message, revision) {
2197
+ const current = this.get(message.id);
2198
+ return !!current && (revision === void 0 || current.revision === revision) && !this.isRecalled(message) && JSON.stringify(current.message) === JSON.stringify(message);
2199
+ }
1493
2200
  persist() {
1494
2201
  const directory = dirname2(this.file);
1495
2202
  mkdirSync(directory, { recursive: true, mode: 448 });
@@ -1533,42 +2240,124 @@ var NativeConsumerState = class {
1533
2240
  accept(cursor, message, origin = "unknown") {
1534
2241
  if (!/^\d+$/.test(cursor) || BigInt(cursor) < BigInt(this.value.cursor)) throw new Error("Native journal cursor cannot move backward");
1535
2242
  if (message && (!message.id || message.accountId !== this.value.accountId)) throw new Error("Native journal message crosses account boundary");
2243
+ let replaced = false;
1536
2244
  this.mutate(() => {
1537
- if (message && !this.value.items[message.id]) {
2245
+ if (message?.serverId && nativeRecallInfo(message)) this.rememberRecall({ messageId: message.id, threadId: message.threadId, serverId: message.serverId, ...nativeRecallInfo(message) });
2246
+ if (message?.serverId) {
2247
+ const recall = this.value.recalls?.[nativeRecallIdentity(message.threadId, message.serverId)];
2248
+ if (recall) message = recalledNativeMessage(message, recall);
2249
+ }
2250
+ const existing = message ? this.value.items[message.id] : void 0;
2251
+ replaced = !!message && !nativeRecallInfo(message) && !!existing && (existing.message.threadId !== message.threadId || existing.message.serverId !== message.serverId);
2252
+ if (message && (!existing || replaced)) {
1538
2253
  const completed = Object.entries(this.value.items).filter(([, item]) => !item.readPending && !item.groupContext && item.phoneReadState !== "needs_review" && item.phoneReadState !== "rejected" && ["completed", "ignored"].includes(item.state));
1539
2254
  for (const [key] of completed.slice(0, Math.max(0, completed.length - 1e3))) delete this.value.items[key];
1540
- if (Object.keys(this.value.items).length >= 5e3) throw new Error("Native custody queue is full; operator review required");
1541
- this.value.items[message.id] = { message, origin, state: "received", cursor };
2255
+ if (!existing && Object.keys(this.value.items).length >= 5e3) throw new Error("Native custody queue is full; operator review required");
2256
+ if (replaced) {
2257
+ for (const item of this.items()) {
2258
+ const manifest = item.dispatchManifest;
2259
+ if (!manifest || ![
2260
+ ...manifest.messageIds,
2261
+ ...(manifest.historyInputs ?? []).map((input) => input.id),
2262
+ ...manifest.assets.flatMap((asset) => asset.sourceMessageId ? [asset.sourceMessageId] : [])
2263
+ ].includes(message.id)) continue;
2264
+ if (["dispatching", "handed_off"].includes(item.state)) item.state = "needs_review";
2265
+ item.dispatchManifest = void 0;
2266
+ item.manifestHash = void 0;
2267
+ item.readPending = false;
2268
+ }
2269
+ }
2270
+ this.value.items[message.id] = { message, revision: randomUUID3(), origin, state: nativeRecallInfo(message) ? "ignored" : "received", cursor };
1542
2271
  }
1543
2272
  this.value.cursor = cursor;
1544
2273
  });
2274
+ return replaced;
1545
2275
  }
1546
- update(messageId, update) {
2276
+ /** Persist invalidation and the event cursor together, before consumer ACK. */
2277
+ acceptRecall(cursor, recall) {
2278
+ validateNativeRecall(recall);
2279
+ if (!/^\d+$/.test(cursor) || BigInt(cursor) < BigInt(this.value.cursor)) throw Error("Native journal cursor cannot move backward");
2280
+ let affected = [];
2281
+ this.mutate(() => {
2282
+ affected = this.rememberRecall(recall);
2283
+ this.value.cursor = cursor;
2284
+ });
2285
+ return affected;
2286
+ }
2287
+ rememberRecall(recall) {
2288
+ const hinted = recall.messageId ? this.get(recall.messageId)?.message : void 0;
2289
+ if (hinted && (hinted.threadId !== recall.threadId || hinted.serverId !== recall.serverId)) {
2290
+ const { messageId: _stale, ...exact } = recall;
2291
+ recall = exact;
2292
+ }
2293
+ const key = nativeRecallIdentity(recall.threadId, recall.serverId);
2294
+ this.value.recalls ??= {};
2295
+ const remembered = mergeNativeRecall(this.value.recalls[key] ?? recall, recall);
2296
+ this.value.recalls[key] = remembered;
2297
+ const affected = /* @__PURE__ */ new Set();
2298
+ for (const item of this.items()) {
2299
+ if (item.message.threadId !== recall.threadId) continue;
2300
+ const target = item.message.serverId === recall.serverId;
2301
+ const quote = item.message.quote?.serverId === recall.serverId;
2302
+ if (!target && !quote) continue;
2303
+ affected.add(item.message.id);
2304
+ item.message = target ? recalledNativeMessage(item.message, remembered) : { ...item.message, quote: void 0 };
2305
+ if (target) item.groupContext = false;
2306
+ item.readPending = false;
2307
+ if (["dispatching", "handed_off"].includes(item.state)) item.state = "needs_review";
2308
+ else if (target && item.state === "received") item.state = "ignored";
2309
+ item.invalidatedByRecall = true;
2310
+ item.dispatchManifest = void 0;
2311
+ item.manifestHash = void 0;
2312
+ }
2313
+ for (const item of this.items()) {
2314
+ const manifest = item.dispatchManifest;
2315
+ if (item.message.threadId !== recall.threadId || !manifest) continue;
2316
+ const references = [
2317
+ ...manifest.messageIds,
2318
+ ...(manifest.historyInputs ?? []).map((input) => input.id),
2319
+ ...manifest.assets.flatMap((asset) => asset.sourceMessageId ? [asset.sourceMessageId] : [])
2320
+ ];
2321
+ if (!references.some((id2) => affected.has(id2) || id2 === recall.messageId)) continue;
2322
+ affected.add(item.message.id);
2323
+ item.invalidatedByRecall = true;
2324
+ item.readPending = false;
2325
+ if (["dispatching", "handed_off"].includes(item.state)) item.state = "needs_review";
2326
+ item.dispatchManifest = void 0;
2327
+ item.manifestHash = void 0;
2328
+ }
2329
+ return [...affected];
2330
+ }
2331
+ update(messageId, update, revision) {
1547
2332
  const item = this.value.items[messageId];
2333
+ if (revision !== void 0 && item?.revision !== revision) return false;
1548
2334
  if (!item) throw new Error("Unknown native custody message");
1549
2335
  this.mutate(() => Object.assign(this.value.items[messageId], update));
2336
+ return true;
1550
2337
  }
1551
2338
  groupHistory(threadId2, beforeId, limit) {
1552
2339
  const before = this.value.items[beforeId]?.cursor;
1553
2340
  if (!before || limit <= 0) return [];
1554
2341
  return this.items().filter((item) => item.groupContext && item.state === "ignored" && item.origin === "live" && item.message.threadId === threadId2 && item.cursor && BigInt(item.cursor) < BigInt(before)).sort((a, b) => BigInt(a.cursor) < BigInt(b.cursor) ? -1 : BigInt(a.cursor) > BigInt(b.cursor) ? 1 : 0).slice(-limit);
1555
2342
  }
1556
- bufferGroupMessage(messageId, limit) {
2343
+ bufferGroupMessage(messageId, limit, revision) {
1557
2344
  const item = this.value.items[messageId];
2345
+ if (revision !== void 0 && item?.revision !== revision) return false;
1558
2346
  if (!item || item.state !== "received" || item.origin !== "live" || item.message.direction !== "incoming" || !item.cursor || !item.message.threadId.endsWith("@chatroom") || !Number.isInteger(limit) || limit < 0 || limit > 200) throw new Error("Invalid native group history admission");
1559
2347
  this.mutate(() => {
1560
2348
  Object.assign(this.value.items[messageId], { state: "ignored", groupContext: limit > 0 });
1561
2349
  const history = this.items().filter((value) => value.groupContext).sort((a, b) => BigInt(a.cursor) < BigInt(b.cursor) ? -1 : 1);
1562
- const thread = history.filter((value) => value.message.threadId === item.message.threadId);
1563
- for (const value of thread.slice(0, Math.max(0, thread.length - limit))) value.groupContext = false;
2350
+ const thread3 = history.filter((value) => value.message.threadId === item.message.threadId);
2351
+ for (const value of thread3.slice(0, Math.max(0, thread3.length - limit))) value.groupContext = false;
1564
2352
  const retained = history.filter((value) => value.groupContext);
1565
2353
  for (const value of retained.slice(0, Math.max(0, retained.length - 1e3))) value.groupContext = false;
1566
2354
  });
2355
+ return true;
1567
2356
  }
1568
2357
  beginDispatch(messageId, dispatchManifest, historyIds = []) {
1569
- if (this.value.items[messageId]?.state !== "received" || historyIds.some((id2) => !this.value.items[id2]?.groupContext || this.value.items[id2].message.threadId !== this.value.items[messageId].message.threadId)) throw new Error("Invalid native context dispatch custody");
2358
+ if (this.value.items[messageId]?.state !== "received" || this.isRecalled(this.value.items[messageId].message) || historyIds.some((id2) => !this.value.items[id2]?.groupContext || this.value.items[id2].message.threadId !== this.value.items[messageId].message.threadId)) throw new Error("Invalid native context dispatch custody");
1570
2359
  this.mutate(() => {
1571
- Object.assign(this.value.items[messageId], { state: "dispatching", dispatchManifest });
2360
+ Object.assign(this.value.items[messageId], { state: "dispatching", dispatchManifest, invalidatedByRecall: false });
1572
2361
  for (const id2 of historyIds) this.value.items[id2].groupContext = false;
1573
2362
  });
1574
2363
  }
@@ -1581,8 +2370,9 @@ var NativeConsumerState = class {
1581
2370
  if (!item || item.state !== "dispatching") throw new Error("Prepared input manifest is not in dispatch custody");
1582
2371
  return item;
1583
2372
  });
2373
+ const revisions = items.map((item) => item.revision);
1584
2374
  if (new Set(items.map((item) => item.message.threadId)).size !== 1) throw new Error("Prepared input manifest crosses threads");
1585
- const manifestHash = createHash6("sha256").update(JSON.stringify({
2375
+ const manifestHash = createHash7("sha256").update(JSON.stringify({
1586
2376
  accountId: this.value.accountId,
1587
2377
  messageIds: exact,
1588
2378
  dispatchManifests: items.map((item) => item.dispatchManifest ?? null)
@@ -1591,8 +2381,15 @@ var NativeConsumerState = class {
1591
2381
  const runId = typeof args[0] === "string" ? args[0] : args[0]?.runId;
1592
2382
  if (typeof runId !== "string" || !runId || runId.length > 256) throw new Error("Prepared run callback has no valid runId");
1593
2383
  this.mutate(() => {
1594
- for (const id2 of exact) {
2384
+ const currentHash = createHash7("sha256").update(JSON.stringify({
2385
+ accountId: this.value.accountId,
2386
+ messageIds: exact,
2387
+ dispatchManifests: exact.map((id2) => this.value.items[id2]?.dispatchManifest ?? null)
2388
+ })).digest("hex");
2389
+ for (const [index, id2] of exact.entries()) {
1595
2390
  const item = this.value.items[id2];
2391
+ if (!item || item.invalidatedByRecall || this.isRecalled(item.message)) throw Error("Native prepared input was invalidated by a recall");
2392
+ if (item.revision !== revisions[index] || currentHash !== manifestHash) throw Error("Native prepared input source identity changed");
1596
2393
  if (item.runId && item.runId !== runId) throw new Error("Native prepared manifest was assigned to another run; operator review required");
1597
2394
  Object.assign(item, { state: "handed_off", runId, manifestHash, readPending: readPolicy === "on_model_dispatch", handoffUnconfirmed: false });
1598
2395
  }
@@ -1603,22 +2400,25 @@ var NativeConsumerState = class {
1603
2400
  };
1604
2401
 
1605
2402
  // src/native-prepared-boundary.ts
1606
- import { createHash as createHash7, randomUUID as randomUUID4 } from "node:crypto";
2403
+ import { createHash as createHash8, randomUUID as randomUUID4 } from "node:crypto";
1607
2404
  import { basename as basename2, isAbsolute as isAbsolute3 } from "node:path";
1608
2405
  var pending = /* @__PURE__ */ new Map();
1609
2406
  var enabled = false;
1610
- var digest = (value) => createHash7("sha256").update(value).digest("hex");
2407
+ var digest = (value) => createHash8("sha256").update(value).digest("hex");
1611
2408
  function prune() {
1612
2409
  for (const [id2, item] of pending) if (item.expires < Date.now()) pending.delete(id2);
1613
2410
  }
2411
+ function nativeSourceMessageSid(message) {
2412
+ return `wechat-native:${message.accountId}:${message.id}:${digest(JSON.stringify([message.threadId, message.serverId ?? null]))}`;
2413
+ }
1614
2414
  function nativeDispatchManifest(params) {
1615
2415
  const history = params.history ?? [];
1616
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");
1617
2417
  const assets = Object.freeze((params.assets ?? []).map((asset) => {
1618
- 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");
1619
2419
  return Object.freeze({ ...asset });
1620
2420
  }));
1621
- const messageSid = `wechat-native:${params.message.accountId}:${params.message.id}`;
2421
+ const messageSid = nativeSourceMessageSid(params.message);
1622
2422
  const manifest = {
1623
2423
  schemaVersion: 2,
1624
2424
  runId: randomUUID4(),
@@ -1643,19 +2443,20 @@ function nativeDispatchManifest(params) {
1643
2443
  params.message.mentions,
1644
2444
  params.message.serverId,
1645
2445
  params.message.appMessageType,
1646
- params.message.quote
2446
+ params.message.quote,
2447
+ params.message.link
1647
2448
  ])),
1648
2449
  role: "trigger"
1649
2450
  })]),
1650
2451
  ...history.length ? { historyInputs: Object.freeze(history.map((message) => Object.freeze({
1651
2452
  id: message.id,
1652
2453
  version: message.version ?? "",
1653
- contentSha256: digest(JSON.stringify([message.id, message.version, message.senderId, message.type, message.body, message.mentions, message.serverId, message.appMessageType, message.quote])),
2454
+ contentSha256: digest(JSON.stringify([message.id, message.version, message.senderId, message.type, message.body, message.mentions, message.serverId, message.appMessageType, message.quote, message.link])),
1654
2455
  role: "history"
1655
2456
  }))) } : {},
1656
2457
  assets,
1657
2458
  policySha256: digest(JSON.stringify(params.policy ?? null)),
1658
- // 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
1659
2460
  // snapshot prevents an identical older image/body from proving this input.
1660
2461
  hostSourceTurnId: `channel-user:v1:${digest(JSON.stringify(["agent-wechat", params.channelAccountId, `wechat:${params.message.threadId}`, messageSid]))}`
1661
2462
  };
@@ -1666,30 +2467,40 @@ function trackNativePreparedInput(manifest, record) {
1666
2467
  if (!enabled || pending.size >= 1024) return;
1667
2468
  pending.set(manifest.runId, { manifest, record, expires: Date.now() + 15 * 60 * 1e3 });
1668
2469
  }
2470
+ function invalidateNativePreparedInputs(accountId, messageIds) {
2471
+ const ids = new Set(messageIds);
2472
+ for (const [runId, item] of pending) {
2473
+ if (item.manifest.accountId === accountId && [
2474
+ ...item.manifest.messageIds,
2475
+ ...(item.manifest.historyInputs ?? []).map((input) => input.id),
2476
+ ...item.manifest.assets.flatMap((asset) => asset.sourceMessageId ? [asset.sourceMessageId] : [])
2477
+ ].some((id2) => ids.has(id2))) pending.delete(runId);
2478
+ }
2479
+ }
1669
2480
  function promptMatches(prompt, manifest) {
1670
2481
  if (typeof prompt !== "string" || Buffer.byteLength(prompt) > 1024 * 1024) return false;
1671
- const text = prompt.replace(/^\[[^\]\r\n]{1,96}\] /, "");
1672
- const candidates = [text];
2482
+ const text3 = prompt.replace(/^\[[^\]\r\n]{1,96}\] /, "");
2483
+ const candidates = [text3];
1673
2484
  const sender = `Conversation info: \u27E6openclaw:ctx\u27E7
1674
2485
  \`\`\`json
1675
2486
  ${JSON.stringify({ sender: { id: manifest.senderId } })}
1676
2487
  \`\`\`
1677
2488
 
1678
2489
  `;
1679
- if (manifest.threadId.endsWith("@chatroom") && text.startsWith(sender)) candidates.push(text.slice(sender.length));
1680
- return candidates.some((text2) => normalizedPromptMatches(text2, manifest));
2490
+ if (manifest.threadId.endsWith("@chatroom") && text3.startsWith(sender)) candidates.push(text3.slice(sender.length));
2491
+ return candidates.some((text4) => normalizedPromptMatches(text4, manifest));
1681
2492
  }
1682
- function normalizedPromptMatches(text, manifest) {
2493
+ function normalizedPromptMatches(text3, manifest) {
1683
2494
  const runtimeAssets = manifest.assets.filter((asset) => asset.runtimeMedia);
1684
2495
  if (runtimeAssets.length) {
1685
2496
  if (runtimeAssets.length !== 1) return false;
1686
2497
  const asset = runtimeAssets[0];
1687
- const header = /^\[media attached: ([^\r\n]+) \(([^)\r\n]+)\) \| (media:\/\/inbound\/[^\]\r\n]+)\]\n/.exec(text);
2498
+ const header = /^\[media attached: ([^\r\n]+) \(([^)\r\n]+)\) \| (media:\/\/inbound\/[^\]\r\n]+)\]\n/.exec(text3);
1688
2499
  if (!header || !isAbsolute3(header[1]) || basename2(header[1]) !== `input-${basename2(asset.path)}` || header[2] !== asset.mime || header[3] !== `media://inbound/${basename2(asset.path)}`) return false;
1689
- text = text.slice(header[0].length);
1690
- if (asset.kind === "video") text = text.replace(/\n\n\[Video attachment not analyzed: video understanding is disabled\]$/, "");
2500
+ text3 = text3.slice(header[0].length);
2501
+ if (asset.kind === "video") text3 = text3.replace(/\n\n\[Video attachment not analyzed: video understanding is disabled\]$/, "");
1691
2502
  }
1692
- return digest(text) === manifest.inputBodySha256;
2503
+ return digest(text3) === manifest.inputBodySha256;
1693
2504
  }
1694
2505
  function currentMessageFacts(messages) {
1695
2506
  if (!Array.isArray(messages) || messages.length > 1e3) return [];
@@ -1750,8 +2561,8 @@ function observeNativeAgentEnd(event, ctx) {
1750
2561
  const blocks = typeof user.content === "string" ? [{ type: "text", text: user.content }] : user.content;
1751
2562
  if (!Array.isArray(blocks) || blocks.length > 32) return;
1752
2563
  if (blocks.some((block) => !["text", "image"].includes(block?.type) || block.type === "text" && typeof block.text !== "string")) return;
1753
- const text = blocks.filter((block) => block?.type === "text").map((block) => block.text).join("\n");
1754
- if (!promptMatches(text, m)) return;
2564
+ const text3 = blocks.filter((block) => block?.type === "text").map((block) => block.text).join("\n");
2565
+ if (!promptMatches(text3, m)) return;
1755
2566
  const images = blocks.filter((block) => block?.type === "image");
1756
2567
  const expectedImages = m.assets.filter((asset) => asset.role === "model_image");
1757
2568
  if (images.length !== expectedImages.length) return;
@@ -1761,7 +2572,7 @@ function observeNativeAgentEnd(event, ctx) {
1761
2572
  const bytes = Buffer.from(image.data, "base64");
1762
2573
  if (bytes.length !== asset.byteLength || digest(bytes) !== asset.sha256) return;
1763
2574
  }
1764
- if (m.assets.some((asset) => asset.role === "file_reference" && !text.includes(asset.path))) return;
2575
+ if (m.assets.some((asset) => asset.role === "file_reference" && !text3.includes(asset.path))) return;
1765
2576
  item.record(m.runId);
1766
2577
  pending.delete(m.runId);
1767
2578
  }
@@ -1876,22 +2687,22 @@ async function projectNativeRead(client, accountId, state) {
1876
2687
  for (const threadId2 of threads) {
1877
2688
  for (let attempt = 0; attempt < 2; attempt++) {
1878
2689
  let cursor;
1879
- let thread;
2690
+ let thread3;
1880
2691
  const seen = /* @__PURE__ */ new Set();
1881
2692
  for (let pageIndex = 0; pageIndex < 100; pageIndex++) {
1882
2693
  const page = await client.threads(accountId, cursor);
1883
- thread = page.items.find((value) => !isNativeTombstone(value) && value.id === threadId2);
1884
- if (thread || !page.nextCursor) break;
2694
+ thread3 = page.items.find((value) => !isNativeTombstone(value) && value.id === threadId2);
2695
+ if (thread3 || !page.nextCursor) break;
1885
2696
  if (seen.has(page.nextCursor)) throw new Error("Native thread pagination did not advance");
1886
2697
  seen.add(page.nextCursor);
1887
2698
  cursor = page.nextCursor;
1888
2699
  }
1889
- if (!thread) break;
2700
+ if (!thread3) break;
1890
2701
  try {
1891
- const receipt = await client.markRead(accountId, thread.id, thread.readStateVersion);
2702
+ const receipt = await client.markRead(accountId, thread3.id, thread3.readStateVersion);
1892
2703
  const notification = receipt?.phoneNotification?.state;
1893
2704
  const phoneReadState = notification === "accepted" || notification === "rejected" || notification === "needs_review" ? notification : void 0;
1894
- for (const item of pending2.filter((item2) => item2.message.threadId === threadId2)) state.update(item.message.id, { readPending: false, phoneReadState });
2705
+ for (const item of pending2.filter((item2) => item2.message.threadId === threadId2)) state.update(item.message.id, { readPending: false, phoneReadState }, item.revision);
1895
2706
  break;
1896
2707
  } catch (error) {
1897
2708
  if (error instanceof NativeApiError && error.status === 409 && attempt === 0) continue;
@@ -1900,13 +2711,72 @@ async function projectNativeRead(client, accountId, state) {
1900
2711
  }
1901
2712
  }
1902
2713
  }
2714
+ var NativeInputInvalidated = class extends Error {
2715
+ };
2716
+ async function acceptNativeEvent(client, accountId, state, event) {
2717
+ if (state.accountId !== accountId) throw Error("Native event crosses its custody account boundary");
2718
+ if (event.kind === "message.recalled") {
2719
+ const affected = state.acceptRecall(event.cursor, event.data);
2720
+ invalidateNativePreparedInputs(accountId, affected);
2721
+ return void 0;
2722
+ }
2723
+ let message;
2724
+ if (event.kind === "message.committed") {
2725
+ if (typeof event.data.messageId !== "string") throw Error("Native committed message identity is missing; cursor retained");
2726
+ message = await client.message(accountId, event.data.messageId);
2727
+ if (message.id !== event.data.messageId || message.accountId !== accountId || message.threadId !== event.data.threadId) throw Error("Native committed message identity mismatch");
2728
+ }
2729
+ const replaced = state.accept(event.cursor, message, typeof event.data.origin === "string" ? event.data.origin : "unknown");
2730
+ if (replaced && message) invalidateNativePreparedInputs(accountId, [message.id]);
2731
+ return message;
2732
+ }
2733
+ async function recheckNativeInputs(client, state, messages) {
2734
+ for (const message of messages) {
2735
+ if (!state.isCurrent(message)) throw new NativeInputInvalidated();
2736
+ const current = await client.message(message.accountId, message.id);
2737
+ if (current.accountId !== message.accountId || current.threadId !== message.threadId || current.id !== message.id || current.serverId !== message.serverId) throw Error("Native input identity changed; delivery held for review");
2738
+ const recall = nativeRecallInfo(current);
2739
+ if (recall && current.serverId) {
2740
+ const affected = state.acceptRecall(state.cursor, { ...recall, messageId: current.id, threadId: current.threadId, serverId: current.serverId });
2741
+ invalidateNativePreparedInputs(message.accountId, [current.id, ...affected]);
2742
+ throw new NativeInputInvalidated();
2743
+ }
2744
+ if (message.quote) {
2745
+ const quote = current.quote;
2746
+ if (quote?.state === "recalled") {
2747
+ const affected = state.acceptRecall(state.cursor, {
2748
+ threadId: message.threadId,
2749
+ serverId: message.quote.serverId,
2750
+ observedAt: (/* @__PURE__ */ new Date()).toISOString()
2751
+ });
2752
+ invalidateNativePreparedInputs(message.accountId, affected);
2753
+ throw new NativeInputInvalidated();
2754
+ }
2755
+ if (!quote || !sameEmbeddedQuote(message.quote, quote)) throw Error("Native embedded quote changed; delivery held for review");
2756
+ }
2757
+ if (!state.isCurrent(message)) throw new NativeInputInvalidated();
2758
+ }
2759
+ }
1903
2760
  async function dispatchNativeMessage(params) {
2761
+ const revision = params.state.get(params.message.id)?.revision;
2762
+ try {
2763
+ return await dispatchNativeMessageInput(params, revision);
2764
+ } catch (error) {
2765
+ const item = params.state.get(params.message.id);
2766
+ if (params.state.isRecalled(params.message)) return "ignored";
2767
+ if (error instanceof NativeInputInvalidated && item?.state === "received") return "pending";
2768
+ if (item) params.state.update(params.message.id, { state: "needs_review" }, revision);
2769
+ return "needs_review";
2770
+ }
2771
+ }
2772
+ async function dispatchNativeMessageInput(params, revision) {
1904
2773
  const { client, state, account, message, cfg, core } = params;
1905
2774
  const readPolicy = account.native?.readPolicy ?? "on_inbound";
1906
2775
  const custody = state.get(message.id);
1907
- if (!custody || custody.state !== "received") return "needs_review";
2776
+ if (state.isRecalled(message)) return "ignored";
2777
+ if (!custody || custody.state !== "received" || !state.isCurrent(message, revision)) return "needs_review";
1908
2778
  if (custody.origin !== "live" || message.direction !== "incoming" || ![1, 3, 34, 43, 47, 49].includes(message.type) || message.type === 1 && !message.body || !message.senderId) {
1909
- state.update(message.id, { state: "ignored" });
2779
+ state.update(message.id, { state: "ignored" }, revision);
1910
2780
  return "ignored";
1911
2781
  }
1912
2782
  const isGroup = message.threadId.endsWith("@chatroom");
@@ -1941,32 +2811,50 @@ async function dispatchNativeMessage(params) {
1941
2811
  const unauthorizedDirectCommand = !isGroup && ingress.ingress.reasonCode === "control_command_unauthorized";
1942
2812
  if (ingress.ingress.admission !== "dispatch" && !unauthorizedDirectCommand) {
1943
2813
  if (isGroup && policy.requireMention && !wasMentioned && !hasControlCommand && (await senderAdmission(message.senderId)).ingress.admission === "dispatch") {
1944
- state.bufferGroupMessage(message.id, nativeGroupHistoryLimit(cfg));
2814
+ state.bufferGroupMessage(message.id, nativeGroupHistoryLimit(cfg), revision);
1945
2815
  return "ignored";
1946
2816
  }
1947
- state.update(message.id, { state: "ignored" });
2817
+ state.update(message.id, { state: "ignored" }, revision);
1948
2818
  return "ignored";
1949
2819
  }
1950
2820
  let preparedMedia;
1951
2821
  const allowQuotedMessage = async (original) => original.direction === "outgoing" || !!original.senderId && (await senderAdmission(original.senderId)).ingress.admission === "dispatch";
1952
- try {
1953
- preparedMedia = await (params.prepareAttachment ?? prepareNativeAttachment)({ client, account, message, core, cfg, allowQuotedMessage });
1954
- } catch {
1955
- state.update(message.id, { state: "needs_review" });
1956
- return "needs_review";
1957
- }
2822
+ const assertCurrent = () => {
2823
+ params.signal?.throwIfAborted();
2824
+ if (!state.isCurrent(message, revision)) throw new NativeInputInvalidated();
2825
+ };
2826
+ const recheck = async (inputs) => {
2827
+ assertCurrent();
2828
+ await recheckNativeInputs(client, state, inputs);
2829
+ assertCurrent();
2830
+ };
2831
+ await recheck([message]);
2832
+ preparedMedia = await (params.prepareAttachment ?? prepareNativeAttachment)({ client, account, message, core, cfg, allowQuotedMessage, assertCurrent });
1958
2833
  if (preparedMedia.pending) return "pending";
1959
2834
  preparedMedia = await transcribeNativeAttachment(preparedMedia, core, cfg);
2835
+ await recheck([message]);
1960
2836
  const buffered = isGroup && !hasControlCommand ? state.groupHistory(message.threadId, message.id, nativeGroupHistoryLimit(cfg)) : [];
1961
2837
  const admitted = [];
1962
2838
  for (const item of buffered) {
1963
2839
  if (item.message.senderId && (await senderAdmission(item.message.senderId)).ingress.admission === "dispatch") admitted.push(item.message);
1964
2840
  }
1965
2841
  const history = await prepareNativeHistory(admitted, async (historical) => transcribeNativeAttachment(
1966
- await (params.prepareAttachment ?? prepareNativeAttachment)({ client, account, message: historical, core, cfg, allowQuotedMessage }),
2842
+ await (params.prepareAttachment ?? prepareNativeAttachment)({
2843
+ client,
2844
+ account,
2845
+ message: historical,
2846
+ core,
2847
+ cfg,
2848
+ allowQuotedMessage,
2849
+ assertCurrent: () => {
2850
+ assertCurrent();
2851
+ if (!state.isCurrent(historical)) throw new NativeInputInvalidated();
2852
+ }
2853
+ }),
1967
2854
  core,
1968
2855
  cfg
1969
2856
  ));
2857
+ await recheck([message, ...admitted]);
1970
2858
  const context = buildNativeContext(history, message, preparedMedia);
1971
2859
  const inputBody = context.inputBody;
1972
2860
  const route = core.channel.routing.resolveAgentRoute({
@@ -1996,7 +2884,7 @@ async function dispatchNativeMessage(params) {
1996
2884
  SenderId: message.senderId,
1997
2885
  Provider: "agent-wechat",
1998
2886
  Surface: "agent-wechat",
1999
- MessageSid: `wechat-native:${account.native.accountId}:${message.id}`,
2887
+ MessageSid: nativeSourceMessageSid(message),
2000
2888
  WasMentioned: isGroup ? wasMentioned : void 0,
2001
2889
  Attachments: context.attachments,
2002
2890
  InboundHistory: context.history,
@@ -2006,6 +2894,7 @@ async function dispatchNativeMessage(params) {
2006
2894
  ...context.mediaPath ? { MediaPath: context.mediaPath, MediaUrl: context.mediaPath, MediaType: context.mediaMime } : {}
2007
2895
  });
2008
2896
  await core.channel.session.recordInboundSession({ storePath, sessionKey: route.sessionKey, ctx });
2897
+ await recheck([message, ...admitted]);
2009
2898
  const pipeline = (params.createPipeline ?? createChannelMessageReplyPipeline)({ cfg, agentId: route.agentId, channel: "agent-wechat", accountId: account.accountId });
2010
2899
  const { onModelSelected, ...prefixOptions } = pipeline;
2011
2900
  const dispatchManifest = nativeDispatchManifest({
@@ -2018,9 +2907,11 @@ async function dispatchNativeMessage(params) {
2018
2907
  assets: context.assets,
2019
2908
  history: admitted
2020
2909
  });
2910
+ assertCurrent();
2021
2911
  state.beginDispatch(message.id, dispatchManifest, buffered.map((item) => item.message.id));
2022
- const callback = readPolicy !== "on_inbound" && (message.type === 1 || message.type === 49 && message.appMessageType === 19 && !!message.body || 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;
2023
2913
  if (callback) trackNativePreparedInput(dispatchManifest, callback);
2914
+ const beforeSend = () => recheck([message, ...admitted]);
2024
2915
  let failed = false;
2025
2916
  let delivery = 0;
2026
2917
  try {
@@ -2030,15 +2921,19 @@ async function dispatchNativeMessage(params) {
2030
2921
  dispatcherOptions: {
2031
2922
  ...prefixOptions,
2032
2923
  deliver: async (payload) => {
2924
+ params.signal?.throwIfAborted();
2925
+ if (state.get(message.id)?.invalidatedByRecall) return;
2926
+ await beforeSend();
2033
2927
  const urls = payload.mediaUrls?.length ? payload.mediaUrls : payload.mediaUrl ? [payload.mediaUrl] : [];
2034
2928
  if (urls.length > 16) throw new Error("Native reply media count exceeds its bound");
2035
2929
  if (payload.audioAsVoice && !urls.length) throw new Error("Native voice reply requires an audio attachment");
2036
- for (const url of urls) {
2037
- const key = createHash8("sha256").update(`${account.native.accountId}\0${message.id}\0${delivery++}`).digest("hex");
2038
- await sendNativeAttachment(client, account, message.threadId, url, payload.audioAsVoice === true, key);
2930
+ for (const url2 of urls) {
2931
+ const key = createHash9("sha256").update(`${dispatchManifest.messageSid}\0${delivery++}`).digest("hex");
2932
+ await sendNativeAttachment(client, account, message.threadId, url2, payload.audioAsVoice === true, key, beforeSend);
2039
2933
  }
2040
2934
  if (payload.text) {
2041
- const key = createHash8("sha256").update(`${account.native.accountId}\0${message.id}\0${delivery++}`).digest("hex");
2935
+ await beforeSend();
2936
+ const key = createHash9("sha256").update(`${dispatchManifest.messageSid}\0${delivery++}`).digest("hex");
2042
2937
  await submitNativeText(client, account.native.accountId, message.threadId, payload.text, key);
2043
2938
  }
2044
2939
  if (urls.length || payload.text) params.onDelivered?.();
@@ -2053,18 +2948,34 @@ async function dispatchNativeMessage(params) {
2053
2948
  // and media-snapshot bridge; unsupported or ambiguous handoffs leave reads unchanged.
2054
2949
  replyOptions: { runId: dispatchManifest.runId, onModelSelected, onPreparedAgentRunStart: callback }
2055
2950
  });
2951
+ params.signal?.throwIfAborted();
2952
+ if (state.get(message.id)?.revision !== revision || state.get(message.id)?.dispatchManifest?.runId !== dispatchManifest.runId) return state.isRecalled(message) ? "ignored" : "needs_review";
2953
+ if (state.get(message.id)?.invalidatedByRecall) return state.isRecalled(message) ? "ignored" : "needs_review";
2056
2954
  const readPending = readPolicy === "on_inbound" && !failed && ingress.ingress.admission === "dispatch" ? true : state.get(message.id)?.readPending;
2057
2955
  state.update(message.id, {
2058
2956
  state: failed ? "needs_review" : "completed",
2059
2957
  readPending,
2060
2958
  handoffUnconfirmed: readPolicy === "on_model_dispatch" && !state.get(message.id)?.runId
2061
- });
2959
+ }, revision);
2062
2960
  return failed ? "needs_review" : "completed";
2063
2961
  } catch {
2064
- state.update(message.id, { state: "needs_review" });
2962
+ if (state.isRecalled(message)) return "ignored";
2963
+ state.update(message.id, { state: "needs_review" }, revision);
2065
2964
  return "needs_review";
2066
2965
  }
2067
2966
  }
2967
+ async function synchronizeNativeEvents(client, accountId, state) {
2968
+ for (let index = 0; index < 100; index++) {
2969
+ const page = await client.events(accountId, state.cursor, 200);
2970
+ if (!page.items.length) return;
2971
+ const before = state.cursor;
2972
+ for (const event of page.items) await acceptNativeEvent(client, accountId, state, event);
2973
+ if (state.cursor === before) throw Error("Native recovery event cursor did not advance");
2974
+ await client.ack(accountId, "openclaw", state.cursor);
2975
+ if (page.items.length < 200) return;
2976
+ }
2977
+ throw Error("Native recovery backlog remains; no model input was dispatched");
2978
+ }
2068
2979
  function startNativeReadPump(task, failed, intervalMs = 5e3) {
2069
2980
  let active2 = false, stopped = false;
2070
2981
  const timer = setInterval(() => {
@@ -2110,6 +3021,7 @@ async function startNativeMonitor(opts) {
2110
3021
  message: item.message,
2111
3022
  cfg,
2112
3023
  core,
3024
+ signal: opts.abortSignal,
2113
3025
  onDelivered: () => opts.setStatus({ accountId: account.accountId, lastOutboundAt: Date.now() })
2114
3026
  });
2115
3027
  }
@@ -2130,9 +3042,24 @@ async function startNativeMonitor(opts) {
2130
3042
  handoffUnconfirmed
2131
3043
  });
2132
3044
  };
2133
- await process2();
3045
+ let processing;
3046
+ let processAgain = false;
3047
+ let intakeReady = false;
3048
+ const scheduleProcess = () => {
3049
+ processAgain = true;
3050
+ if (processing || opts.abortSignal.aborted || !intakeReady) return;
3051
+ processing = (async () => {
3052
+ do {
3053
+ processAgain = false;
3054
+ await process2();
3055
+ } while (processAgain && !opts.abortSignal.aborted);
3056
+ })().catch(() => opts.log?.error?.("Native input processing was interrupted; durable custody was retained")).finally(() => {
3057
+ processing = void 0;
3058
+ });
3059
+ };
2134
3060
  const stopReadPump = startNativeReadPump(async () => {
2135
3061
  await flushRead();
3062
+ scheduleProcess();
2136
3063
  if (!opts.abortSignal.aborted) opts.setStatus({
2137
3064
  accountId: opts.account.accountId,
2138
3065
  handoffUnconfirmed: native.readPolicy === "on_model_dispatch" && state.items().some((value) => value.handoffUnconfirmed)
@@ -2142,18 +3069,15 @@ async function startNativeMonitor(opts) {
2142
3069
  while (!opts.abortSignal.aborted) {
2143
3070
  try {
2144
3071
  if (state.cursor !== "0") await host2.client.ack(native.accountId, "openclaw", state.cursor);
2145
- await process2();
3072
+ intakeReady = false;
3073
+ await synchronizeNativeEvents(host2.client, native.accountId, state);
3074
+ intakeReady = true;
3075
+ scheduleProcess();
2146
3076
  for await (const event of host2.client.watch(native.accountId, state.cursor, opts.abortSignal)) {
2147
- let message;
2148
- if (event.kind === "message.committed") {
2149
- if (typeof event.data.messageId !== "string") throw new Error("Native committed message identity is missing; cursor retained");
2150
- message = await host2.client.message(native.accountId, event.data.messageId);
2151
- if (message.threadId !== event.data.threadId) throw new Error("Native committed message thread identity mismatch");
2152
- }
2153
- state.accept(event.cursor, message, typeof event.data.origin === "string" ? event.data.origin : "unknown");
2154
- if (message?.direction === "incoming" && event.data.origin === "live") opts.setStatus({ accountId: opts.account.accountId, lastInboundAt: Date.now() });
3077
+ const message = await acceptNativeEvent(host2.client, native.accountId, state, event);
3078
+ if (message?.direction === "incoming" && event.data.origin === "live" && !nativeRecallInfo(message)) opts.setStatus({ accountId: opts.account.accountId, lastInboundAt: Date.now() });
2155
3079
  await host2.client.ack(native.accountId, "openclaw", state.cursor);
2156
- await process2();
3080
+ scheduleProcess();
2157
3081
  backoff = 250;
2158
3082
  }
2159
3083
  if (!opts.abortSignal.aborted) throw new Error("Native event stream closed");
@@ -2185,80 +3109,143 @@ async function startNativeMonitor(opts) {
2185
3109
 
2186
3110
  // src/native-login.ts
2187
3111
  import { randomUUID as randomUUID5 } from "node:crypto";
3112
+ import { setTimeout as delay } from "node:timers/promises";
2188
3113
  var operations = /* @__PURE__ */ new Map();
2189
3114
  var terminal = /* @__PURE__ */ new Set(["succeeded", "failed", "cancelled", "expired", "rejected", "needs_login"]);
2190
- 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);
2191
3124
  const native = account.native;
2192
- const { client } = await ensureNativeHost(native);
3125
+ const { client } = await (access2.host ?? ensureNativeHost)(native);
3126
+ guard(access2);
3127
+ const configurationKey = nativeConfigurationKey(native);
2193
3128
  const existing = operations.get(account.accountId);
2194
- if (existing && existing.accountId === native.accountId && !options.force) {
2195
- existing.operation = await client.operation(native.accountId, existing.operation.id);
2196
- if (!terminal.has(existing.operation.state)) return nativeLoginWait(account.accountId, Math.min(options.timeoutMs ?? 3e4, 3e4), true);
2197
- }
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);
2198
3138
  const operation = await client.login(native.accountId, {
2199
3139
  allowQr: true,
2200
3140
  forceQr: options.force === true,
2201
3141
  timeoutSeconds: Math.max(10, Math.min(900, Math.ceil((options.timeoutMs ?? 3e5) / 1e3))),
2202
3142
  computerName: "agent-wechat"
2203
- });
2204
- operations.set(account.accountId, { client, accountId: native.accountId, operation });
2205
- 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);
2206
3148
  }
2207
- async function nativeLoginWait(accountId, timeoutMs = 3e4, stopAtQr = false) {
2208
- const active2 = operations.get(accountId);
2209
- 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" };
2210
3153
  const deadline = Date.now() + Math.max(1e3, Math.min(timeoutMs, 3e5));
2211
3154
  while (Date.now() < deadline) {
2212
- 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;
2213
3160
  const state = active2.operation.state;
2214
- if (state === "succeeded") return { connected: true, message: "Native login succeeded" };
2215
- 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" };
2216
3165
  if (stopAtQr && active2.operation.result?.qrAvailable === true) {
2217
3166
  const generation = active2.operation.result?.qrGeneration;
2218
3167
  const png = await active2.client.qr(active2.accountId, active2.operation.id, typeof generation === "number" ? generation : void 0);
2219
- 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" };
2220
3170
  }
2221
- if (stopAtQr && state === "awaiting_approval") return { connected: false, message: "Approve native login on your phone" };
2222
- await new Promise((resolve) => setTimeout(resolve, 500));
3171
+ await delay(Math.min(500, Math.max(0, deadline - Date.now())), void 0, { signal: access2.signal });
2223
3172
  }
2224
- 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" };
2225
3175
  }
2226
- async function sendNativeText(account, threadId2, text, key = randomUUID5()) {
3176
+ async function sendNativeText(account, threadId2, text3, key = randomUUID5()) {
2227
3177
  const native = account.native;
2228
3178
  const { client } = await ensureNativeHost(native);
2229
- const send = await submitNativeText(client, native.accountId, threadId2, text, key);
2230
- return `agent-wechat-native:${native.accountId}:${send.id}`;
3179
+ const send = await submitNativeText(client, native.accountId, threadId2, text3, key);
3180
+ return nativeOutboundDelivery(
3181
+ client,
3182
+ native.accountId,
3183
+ threadId2,
3184
+ send.localMessageId ? [send.localMessageId] : [],
3185
+ { sendId: send.id, state: send.state, serverIds: send.serverId ? [send.serverId] : void 0 }
3186
+ );
2231
3187
  }
2232
- function createNativeLoginTool(account) {
3188
+ function createNativeLoginTool(account, dependencies = {}) {
3189
+ const actions = ["status", "start", "wait", "disconnect", "logout", "forget"];
3190
+ const configurationKey = nativeConfigurationKey(account.native);
2233
3191
  return {
2234
3192
  label: "WeChat Login",
2235
3193
  name: "wechat_login",
2236
- 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.",
2237
- parameters: { type: "object", properties: { action: { type: "string", enum: ["status", "start", "disconnect", "logout", "forget"] }, force: { type: "boolean" }, confirm: { type: "boolean" } }, required: ["action"] },
2238
- 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");
2239
3204
  const args = params;
2240
- const native = account.native;
2241
- const { client } = await ensureNativeHost(native);
2242
- if (args.action === "start") {
2243
- 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);
2244
3218
  const content = [{ type: "text", text: result2.message }];
2245
3219
  if (result2.qrDataUrl) content.push({ type: "image", data: result2.qrDataUrl.split(",")[1], mimeType: "image/png" });
2246
- return { content, details: { connected: result2.connected } };
3220
+ return { content, details: { connected: result2.connected, state: result2.state, operationId: result2.operationId } };
2247
3221
  }
3222
+ const native = account.native;
3223
+ const { client } = await (access2.host ?? ensureNativeHost)(native);
3224
+ guard(access2);
2248
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) : (() => {
2249
3226
  throw new Error("Unknown native login action");
2250
3227
  })();
3228
+ if (args.action !== "status") operations.delete(account.accountId);
3229
+ guard(access2);
2251
3230
  return { content: [{ type: "text", text: JSON.stringify(result) }], details: result };
2252
3231
  }
2253
3232
  };
2254
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
+ }
2255
3241
 
2256
3242
  // src/channel.ts
2257
- async function sendWeChatText(cfg, to, text) {
3243
+ async function sendWeChatText(cfg, to, text3) {
2258
3244
  const account = resolveWeChatAccount(cfg);
2259
3245
  if (!account?.serverUrl) throw new Error("No native daemon configured");
2260
- return sendNativeText(account, to, text);
3246
+ return sendNativeText(account, to, text3);
2261
3247
  }
3248
+ var mediaHandlers = createWeChatMediaHandlers();
2262
3249
  var wechatMessageAdapter = createChannelMessageAdapterFromOutbound({
2263
3250
  id: "agent-wechat",
2264
3251
  capabilities: {
@@ -2267,14 +3254,11 @@ var wechatMessageAdapter = createChannelMessageAdapterFromOutbound({
2267
3254
  messageSendingHooks: true
2268
3255
  },
2269
3256
  outbound: {
2270
- sendText: async ({ cfg, to, text }) => ({
3257
+ sendText: async ({ cfg, to, text: text3 }) => ({
2271
3258
  channel: "agent-wechat",
2272
- messageId: await sendWeChatText(cfg, to, text)
3259
+ ...await sendWeChatText(cfg, to, text3)
2273
3260
  }),
2274
- sendMedia: async ({ cfg, to, text, mediaUrl, audioAsVoice }) => ({
2275
- channel: "agent-wechat",
2276
- messageId: await sendWeChatMedia(cfg, to, text, mediaUrl, audioAsVoice)
2277
- })
3261
+ ...mediaHandlers
2278
3262
  }
2279
3263
  });
2280
3264
  var meta = {
@@ -2298,6 +3282,7 @@ var wechatPlugin = {
2298
3282
  tts: { voice: { synthesisTarget: "voice-note", transcodesAudio: true } }
2299
3283
  },
2300
3284
  reload: { configPrefixes: ["channels.agent-wechat"] },
3285
+ actions: wechatMediaActions,
2301
3286
  configSchema: {
2302
3287
  uiHints: { "native.token": { sensitive: true } },
2303
3288
  schema: {
@@ -2396,7 +3381,7 @@ var wechatPlugin = {
2396
3381
  },
2397
3382
  // ---- Mention adapter ----
2398
3383
  mentions: {
2399
- stripMentions: ({ text, ctx }) => normalizeWeChatCommandBody(text, {
3384
+ stripMentions: ({ text: text3, ctx }) => normalizeWeChatCommandBody(text3, {
2400
3385
  isGroup: ctx.ChatType === "group",
2401
3386
  wasMentioned: ctx.WasMentioned === true
2402
3387
  })
@@ -2415,14 +3400,11 @@ var wechatPlugin = {
2415
3400
  // ---- Outbound adapter for OpenClaw hosts using the outbound hook ----
2416
3401
  outbound: {
2417
3402
  deliveryMode: "direct",
2418
- sendText: async ({ cfg, to, text }) => ({
3403
+ sendText: async ({ cfg, to, text: text3 }) => ({
2419
3404
  channel: "agent-wechat",
2420
- messageId: await sendWeChatText(cfg, to, text)
3405
+ ...await sendWeChatText(cfg, to, text3)
2421
3406
  }),
2422
- sendMedia: async ({ cfg, to, text, mediaUrl, audioAsVoice }) => ({
2423
- channel: "agent-wechat",
2424
- messageId: await sendWeChatMedia(cfg, to, text, mediaUrl, audioAsVoice)
2425
- })
3407
+ ...mediaHandlers
2426
3408
  },
2427
3409
  message: wechatMessageAdapter,
2428
3410
  gateway: {
@@ -2452,7 +3434,7 @@ var wechatPlugin = {
2452
3434
  loginWithQrWait: async ({ accountId, timeoutMs }) => {
2453
3435
  const account = resolveWeChatAccount(getWeChatRuntime().config.current(), accountId ?? void 0);
2454
3436
  if (!account?.native) return { connected: false, message: "No native daemon configured" };
2455
- return nativeLoginWait(account.accountId, timeoutMs);
3437
+ return nativeLoginWait(account, timeoutMs);
2456
3438
  }
2457
3439
  },
2458
3440
  auth: {
@@ -2478,10 +3460,6 @@ var wechatPlugin = {
2478
3460
  linked: runtime2?.linked ?? false
2479
3461
  })
2480
3462
  },
2481
- agentTools: (({ cfg }) => {
2482
- const account = resolveWeChatAccount(cfg);
2483
- return account?.native ? [createNativeLoginTool(account)] : [];
2484
- }),
2485
3463
  directory: {
2486
3464
  self: async ({ cfg }) => {
2487
3465
  const account = resolveWeChatAccount(cfg);
@@ -2589,7 +3567,7 @@ function createNativeFacade(config, dependencies = {}) {
2589
3567
  fail(res, 403, "facade_account_forbidden");
2590
3568
  return true;
2591
3569
  }
2592
- if (!["GET", "HEAD", "POST", "PATCH", "DELETE"].includes(req.method ?? "")) {
3570
+ if (!["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"].includes(req.method ?? "")) {
2593
3571
  fail(res, 405, "method_not_allowed");
2594
3572
  return true;
2595
3573
  }
@@ -2602,19 +3580,23 @@ function createNativeFacade(config, dependencies = {}) {
2602
3580
  try {
2603
3581
  const host2 = dependencies.endpoint ? void 0 : await ensureNativeHost(config);
2604
3582
  const headers = new Headers();
2605
- for (const name of ["content-type", "accept", "range", "if-none-match", "if-range", "last-event-id", "idempotency-key"]) {
2606
- const value = req.headers[name];
2607
- if (typeof value === "string") headers.set(name, 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);
2608
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;
2609
3591
  const length = req.headers["content-length"];
2610
- if (length && (!/^\d+$/.test(length) || Number(length) > MAX_BODY)) {
3592
+ if (length && (!/^\d+$/.test(length) || Number(length) > requestLimit)) {
2611
3593
  fail(res, 413, "payload_too_large");
2612
3594
  return true;
2613
3595
  }
2614
3596
  let size = 0;
2615
3597
  const body = ["GET", "HEAD"].includes(req.method ?? "") ? void 0 : Readable.toWeb(req).pipeThrough(new NodeTransformStream({ transform(chunk, controller) {
2616
3598
  size += chunk.byteLength;
2617
- if (size > MAX_BODY) {
3599
+ if (size > requestLimit) {
2618
3600
  tooLarge = true;
2619
3601
  throw new Error("payload_too_large");
2620
3602
  }
@@ -2627,10 +3609,16 @@ function createNativeFacade(config, dependencies = {}) {
2627
3609
  headers.set("Authorization", `Bearer ${dependencies.token}`);
2628
3610
  response = await (dependencies.fetch ?? fetch)(new URL(relative, dependencies.endpoint), init);
2629
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
+ }
2630
3618
  res.statusCode = response.status;
2631
- for (const name of ["content-type", "content-length", "content-range", "accept-ranges", "etag", "cache-control", "content-disposition", "x-content-type-options"]) {
2632
- const value = response.headers.get(name);
2633
- if (value) res.setHeader(name, 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);
2634
3622
  }
2635
3623
  res.setHeader("x-content-type-options", "nosniff");
2636
3624
  const reader = response.body?.getReader();
@@ -2645,7 +3633,7 @@ function createNativeFacade(config, dependencies = {}) {
2645
3633
  const { value, done } = await reader.read();
2646
3634
  if (done) break;
2647
3635
  emitted += value.length;
2648
- if (!sse && emitted > MAX_BODY) throw new Error("upstream_response_too_large");
3636
+ if (!sse && emitted > responseLimit) throw new Error("upstream_response_too_large");
2649
3637
  if (!res.write(value)) await drain(res, abort.signal);
2650
3638
  }
2651
3639
  } finally {
@@ -2689,19 +3677,37 @@ function object(value) {
2689
3677
  if (!value || typeof value !== "object" || Array.isArray(value)) throw Error("Expected tool arguments");
2690
3678
  return value;
2691
3679
  }
2692
- function string(value, name, max = 4096) {
2693
- if (typeof value !== "string" || !value.trim() || value.length > max || /[\u0000-\u001f\u007f]/.test(value)) throw Error(`Invalid ${name}`);
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}`);
2694
3682
  return value.trim();
2695
3683
  }
2696
3684
  function threadId(value) {
2697
3685
  return string(string(value, "thread ID").replace(/^(?:agent-)?wechat:(?:group:)?/i, ""), "thread ID");
2698
3686
  }
2699
- function messageResult(message, retrievalTool = "wechat_media") {
3687
+ function messageResult(message, retrievalTool = "wechat_media", quotePermitted = false) {
3688
+ if (nativeRecallInfo(message)) return {
3689
+ id: message.id,
3690
+ threadId: message.threadId,
3691
+ serverId: message.serverId,
3692
+ direction: message.direction,
3693
+ type: 1e4,
3694
+ body: "[Message recalled]",
3695
+ status: "recalled",
3696
+ recall: nativeRecallInfo(message)
3697
+ };
2700
3698
  const isQuote = message.type === 49 && message.appMessageType === 57;
2701
3699
  const isForward = message.type === 49 && message.appMessageType === 19;
2702
- const kind2 = isQuote ? "quote" : isForward ? "forwarded_history" : 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";
2703
- const body = message.type === 1 || isForward ? message.body ?? "" : isQuote ? `${message.body ?? ""}
2704
- [Quoted original not retrieved; use ${retrievalTool} with this message ID]` : `[WeChat ${kind2} message; attachment content has not been retrieved by this tool]`;
3700
+ const isLink = message.type === 49 && [3, 4, 5].includes(message.appMessageType ?? 0) && !!message.link;
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";
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
+ };
2705
3711
  return {
2706
3712
  id: message.id,
2707
3713
  threadId: message.threadId,
@@ -2710,7 +3716,8 @@ function messageResult(message, retrievalTool = "wechat_media") {
2710
3716
  direction: message.direction,
2711
3717
  type: message.type,
2712
3718
  appMessageType: message.appMessageType,
2713
- quote: message.quote,
3719
+ quote,
3720
+ link: isLink ? message.link : void 0,
2714
3721
  createdAt: message.createdAt,
2715
3722
  body: body.slice(0, 4e3),
2716
3723
  bodyTruncated: body.length > 4e3,
@@ -2728,6 +3735,7 @@ function createLookupTools(context, dependencies, archive) {
2728
3735
  if (!currentConfig()) return [];
2729
3736
  const selected = resolveWeChatAccount(currentConfig());
2730
3737
  if (!selected?.native || !selected.enabled) return [];
3738
+ const configurationKey = nativeConfigurationKey(selected.native);
2731
3739
  if (!archive && context.messageChannel !== "agent-wechat") return [];
2732
3740
  if (!archive && context.agentAccountId && context.agentAccountId !== selected.accountId) return [];
2733
3741
  if (!archive && context.deliveryContext?.channel === "agent-wechat" && context.deliveryContext.accountId && context.deliveryContext.accountId !== selected.accountId) return [];
@@ -2749,9 +3757,9 @@ function createLookupTools(context, dependencies, archive) {
2749
3757
  if (!currentThread) return [];
2750
3758
  }
2751
3759
  const selectedId = selected.native.accountId;
2752
- const tool = (name, action, description, properties, required = []) => ({
2753
- name,
2754
- label: name.replaceAll("_", " "),
3760
+ const tool = (name3, action, description, properties, required = []) => ({
3761
+ name: name3,
3762
+ label: name3.replaceAll("_", " "),
2755
3763
  description,
2756
3764
  // The pinned host's tool_call wrapper JSON-serializes image blocks. Its
2757
3765
  // public direct-only surface preserves actual image content for vision.
@@ -2759,15 +3767,15 @@ function createLookupTools(context, dependencies, archive) {
2759
3767
  parameters: { type: "object", additionalProperties: false, properties, required },
2760
3768
  execute: async (_callId, input, signal) => {
2761
3769
  const args = object(input);
2762
- const guard = () => {
3770
+ const guard2 = () => {
2763
3771
  signal?.throwIfAborted();
2764
3772
  context.assertInvocationCurrent?.();
2765
3773
  const cfg2 = currentConfig();
2766
3774
  const account2 = resolveWeChatAccount(cfg2);
2767
- if (!account2?.enabled || !account2.native || account2.native.accountId !== selectedId || account2.accountId !== selected.accountId) throw Error("WeChat account configuration changed; start a new turn");
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");
2768
3776
  return { cfg: cfg2, account: account2, native: account2.native };
2769
3777
  };
2770
- const { cfg, account, native } = guard();
3778
+ const { cfg, account, native } = guard2();
2771
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");
2772
3780
  const limit = args.limit ?? 20;
2773
3781
  if (!Number.isInteger(limit) || limit < 1 || limit > 50) throw Error("limit must be 1\u201350");
@@ -2784,7 +3792,7 @@ function createLookupTools(context, dependencies, archive) {
2784
3792
  const core = dependencies.core ?? getWeChatRuntime();
2785
3793
  const allowed = async (sender) => {
2786
3794
  if (archive) return true;
2787
- const { cfg: cfg2, account: account2 } = guard();
3795
+ const { cfg: cfg2, account: account2 } = guard2();
2788
3796
  const result2 = await resolveWeChatIngress({
2789
3797
  resolve: core.channel.inbound?.ingress?.resolveStable ?? resolveStableChannelMessageIngress2,
2790
3798
  cfg: cfg2,
@@ -2798,27 +3806,43 @@ function createLookupTools(context, dependencies, archive) {
2798
3806
  return result2.ingress.admission === "dispatch";
2799
3807
  };
2800
3808
  if (!await allowed(requesterSenderId)) throw Error("WeChat conversation access is no longer allowed");
2801
- guard();
3809
+ guard2();
2802
3810
  const { client } = await (dependencies.host ?? ensureNativeHost)(native);
2803
- guard();
3811
+ guard2();
2804
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
+ );
2805
3818
  let result;
2806
3819
  if (action === "threads") {
2807
3820
  const page = await client.threads(accountId, { limit, cursor, ...query ? { query } : {} });
2808
3821
  const items = [];
2809
- for (const thread of page.items) {
2810
- if (isNativeTombstone(thread)) continue;
2811
- if (thread.accountId !== accountId) throw Error("Thread response crosses an account boundary");
2812
- items.push({ id: thread.id, peerId: thread.peerId, kind: thread.kind, displayName: thread.displayName, unreadCount: thread.unreadCount });
3822
+ for (const thread3 of page.items) {
3823
+ if (isNativeTombstone(thread3)) continue;
3824
+ if (thread3.accountId !== accountId) throw Error("Thread response crosses an account boundary");
3825
+ items.push({ id: thread3.id, peerId: thread3.peerId, kind: thread3.kind, displayName: thread3.displayName, unreadCount: thread3.unreadCount });
2813
3826
  }
2814
3827
  result = { ...page, items, scope: "local_profile", note: "Locally stored threads; coverage may be partial. This lookup does not mark threads read." };
2815
3828
  } else if (action === "message" || action === "media") {
2816
3829
  const message = await client.message(accountId, messageId);
2817
- guard();
3830
+ guard2();
2818
3831
  if (!await allowed(requesterSenderId)) throw Error("WeChat conversation access is no longer allowed");
2819
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");
2820
- result = messageResult(message, archive ? "wechat_archive_media" : "wechat_media");
3833
+ if (action === "message") result = await visibleMessage(message);
2821
3834
  if (action === "media") {
3835
+ const checkRecall = async () => {
3836
+ guard2();
3837
+ const latest = await client.message(accountId, messageId);
3838
+ guard2();
3839
+ if (latest.id !== message.id || latest.accountId !== accountId || latest.threadId !== message.threadId || latest.serverId !== message.serverId) throw Error("Native media message identity changed");
3840
+ if (nativeRecallInfo(latest)) throw new NativeApiError(410, "message_recalled", false);
3841
+ if (message.quote) {
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);
3844
+ }
3845
+ };
2822
3846
  let prepared;
2823
3847
  try {
2824
3848
  prepared = await prepareNativeAttachment({
@@ -2831,32 +3855,34 @@ function createLookupTools(context, dependencies, archive) {
2831
3855
  download: args.download !== false,
2832
3856
  waitMs: 2e3,
2833
3857
  signal,
2834
- assertCurrent: guard,
3858
+ assertCurrent: guard2,
2835
3859
  allowQuotedMessage: async (original) => original.direction === "outgoing" || await allowed(original.senderId ?? void 0),
2836
3860
  beforeMediaAccess: async () => {
2837
3861
  if (!await allowed(requesterSenderId) || message.direction !== "outgoing" && !await allowed(message.senderId ?? void 0)) throw Error("WeChat conversation access is no longer allowed");
3862
+ await checkRecall();
2838
3863
  }
2839
3864
  });
2840
3865
  } catch (error) {
2841
- guard();
3866
+ guard2();
2842
3867
  if (!(error instanceof NativeApiError)) throw error;
2843
3868
  const details2 = {
2844
3869
  messageId: message.id,
2845
3870
  threadId: message.threadId,
2846
- status: error.retryable ? "pending" : ["unsupported_profile", "unsupported_media", "unsupported_media_variant"].includes(error.code) ? "unsupported" : "unavailable",
3871
+ status: error.code === "message_recalled" ? "recalled" : error.retryable ? "pending" : ["unsupported_profile", "unsupported_media", "unsupported_media_variant"].includes(error.code) ? "unsupported" : "unavailable",
2847
3872
  retryable: error.retryable,
2848
3873
  reason: error.code
2849
3874
  };
2850
3875
  return { content: [{ type: "text", text: JSON.stringify(details2) }], details: details2 };
2851
3876
  }
2852
- guard();
3877
+ guard2();
2853
3878
  if (!await allowed(requesterSenderId) || message.direction !== "outgoing" && !await allowed(message.senderId ?? void 0)) throw Error("WeChat conversation access is no longer allowed");
2854
3879
  const details = {
2855
3880
  messageId: message.id,
2856
3881
  threadId: message.threadId,
2857
- status: prepared.pending ? "pending" : prepared.attachment?.status ?? prepared.quote?.state ?? "unsupported",
3882
+ status: prepared.reason === "message_recalled" ? "recalled" : prepared.pending ? "pending" : prepared.attachment?.status ?? prepared.quote?.state ?? "unsupported",
2858
3883
  attachment: prepared.attachment,
2859
3884
  quote: prepared.quote,
3885
+ link: ["message_recalled", "media_identity_unavailable", "media_source_changed"].includes(prepared.reason ?? "") ? void 0 : message.link,
2860
3886
  variant: prepared.variant,
2861
3887
  jobId: prepared.jobId,
2862
3888
  retryable: prepared.retryable ?? false,
@@ -2865,7 +3891,14 @@ function createLookupTools(context, dependencies, archive) {
2865
3891
  };
2866
3892
  const image = prepared.suppliedAssets?.find((asset) => asset.role === "model_image");
2867
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 };
2868
- guard();
3894
+ guard2();
3895
+ try {
3896
+ await checkRecall();
3897
+ } catch (error) {
3898
+ if (!(error instanceof NativeApiError) || error.code !== "message_recalled") throw error;
3899
+ const details2 = { messageId: message.id, threadId: message.threadId, status: "recalled", reason: "message_recalled", retryable: false };
3900
+ return { content: [{ type: "text", text: JSON.stringify(details2) }], details: details2 };
3901
+ }
2869
3902
  return output;
2870
3903
  }
2871
3904
  } else {
@@ -2875,7 +3908,7 @@ function createLookupTools(context, dependencies, archive) {
2875
3908
  for (const message of page.items) {
2876
3909
  if (isNativeTombstone(message)) continue;
2877
3910
  if (conversation && message.threadId !== conversation || message.accountId !== accountId) throw Error("WeChat history response crosses a conversation boundary");
2878
- 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));
2879
3912
  }
2880
3913
  result = {
2881
3914
  ...page,
@@ -2885,7 +3918,7 @@ function createLookupTools(context, dependencies, archive) {
2885
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."
2886
3919
  };
2887
3920
  }
2888
- guard();
3921
+ guard2();
2889
3922
  return { content: [{ type: "text", text: JSON.stringify(result) }], details: result };
2890
3923
  }
2891
3924
  });
@@ -2900,13 +3933,13 @@ function createLookupTools(context, dependencies, archive) {
2900
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"]),
2901
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"]),
2902
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"]),
2903
- 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"])
2904
3937
  ];
2905
3938
  return [
2906
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 }),
2907
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"]),
2908
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"]),
2909
- 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"])
2910
3943
  ];
2911
3944
  }
2912
3945
  function registerNativeHistoryTools(api) {
@@ -2914,6 +3947,306 @@ function registerNativeHistoryTools(api) {
2914
3947
  api.registerTool({ contextVersion: 2, create: (context) => createNativeArchiveTools(context) }, { names: archiveNames, optional: true });
2915
3948
  }
2916
3949
 
3950
+ // src/native-share-tool.ts
3951
+ import { resolveStableChannelMessageIngress as resolveStableChannelMessageIngress3 } from "openclaw/plugin-sdk/channel-ingress-runtime";
3952
+ var name = "wechat_send_share";
3953
+ function text(value, label, max, multiline = false) {
3954
+ if (typeof value !== "string" || !value.trim() || Buffer.byteLength(value) > max || (multiline ? /[\u0000-\u0008\u000b-\u001f\u007f]/ : /[\u0000-\u001f\u007f]/).test(value)) throw Error(`Invalid ${label}`);
3955
+ return value;
3956
+ }
3957
+ function thread(value) {
3958
+ return text(text(value, "current conversation", 256).replace(/^(?:agent-)?wechat:(?:group:)?/i, "").trim(), "current conversation", 256);
3959
+ }
3960
+ function url(value, label) {
3961
+ const raw = text(value, label, 8192);
3962
+ const parsed = new URL(raw);
3963
+ if (!["https:", "http:"].includes(parsed.protocol) || !parsed.hostname || parsed.username || parsed.password) throw Error(`Invalid ${label}`);
3964
+ return raw;
3965
+ }
3966
+ function createNativeShareTools(context, dependencies = {}) {
3967
+ const currentConfig = () => context.getRuntimeConfig?.() ?? context.runtimeConfig ?? context.config;
3968
+ if (!currentConfig()) return [];
3969
+ const selected = resolveWeChatAccount(currentConfig());
3970
+ if (!selected?.enabled || !selected.native || context.messageChannel !== "agent-wechat" || context.agentAccountId && context.agentAccountId !== selected.accountId || context.deliveryContext?.channel === "agent-wechat" && context.deliveryContext.accountId && context.deliveryContext.accountId !== selected.accountId) return [];
3971
+ let conversation, requester;
3972
+ try {
3973
+ const native = context.nativeChannelId ? thread(context.nativeChannelId) : void 0;
3974
+ const delivery = context.deliveryContext?.channel === "agent-wechat" && context.deliveryContext.to ? thread(context.deliveryContext.to) : void 0;
3975
+ if (native && delivery && native !== delivery) return [];
3976
+ conversation = native ?? delivery;
3977
+ if (!conversation) return [];
3978
+ requester = text(context.requesterSenderId, "requester sender", 256);
3979
+ } catch {
3980
+ return [];
3981
+ }
3982
+ const configurationKey = nativeConfigurationKey(selected.native);
3983
+ const fields = ["title", "url", "description", "thumbnailUrl", "idempotencyKey"];
3984
+ return [{
3985
+ name,
3986
+ label: "Send WeChat share",
3987
+ description: "Send a URL share card to the current WeChat conversation, with an explicit title, URL, optional description and public thumbnail URL. Does not fetch or summarize the linked page. Use one idempotencyKey per intended share and reuse it after timeouts; never retry an uncertain send with a new key. Returns a durable send ID and state. Accepted means server acceptance; recipient rendering requires verification.",
3988
+ parameters: { type: "object", additionalProperties: false, required: ["title", "url", "idempotencyKey"], properties: {
3989
+ title: { type: "string", minLength: 1, maxLength: 16384 },
3990
+ url: { type: "string", minLength: 1, maxLength: 8192 },
3991
+ description: { type: "string", maxLength: 16384 },
3992
+ thumbnailUrl: { type: "string", minLength: 1, maxLength: 8192, description: "Public HTTP(S) image URL advertised as the card thumbnail; no upload or page scraping." },
3993
+ idempotencyKey: { type: "string", minLength: 1, maxLength: 200, description: "Stable unique key for this logical share. Reuse the same key and identical fields when inspecting/retrying this request." }
3994
+ } },
3995
+ execute: async (_callId, input, signal) => {
3996
+ if (!input || typeof input !== "object" || Array.isArray(input)) throw Error("Expected share arguments");
3997
+ const args = input;
3998
+ if (Object.keys(args).some((key2) => !fields.includes(key2))) throw Error("Share sending is restricted to the current conversation");
3999
+ const key = text(args.idempotencyKey, "idempotency key", 200);
4000
+ const request = {
4001
+ kind: "share",
4002
+ threadId: conversation,
4003
+ title: text(args.title, "title", 16384, true),
4004
+ url: url(args.url, "URL"),
4005
+ ...args.description !== void 0 ? { description: args.description === "" ? "" : text(args.description, "description", 16384, true) } : {},
4006
+ ...args.thumbnailUrl !== void 0 ? { thumbnailUrl: url(args.thumbnailUrl, "thumbnail URL") } : {}
4007
+ };
4008
+ const guard2 = () => {
4009
+ signal?.throwIfAborted();
4010
+ context.assertInvocationCurrent?.();
4011
+ const cfg = currentConfig(), account = resolveWeChatAccount(cfg);
4012
+ if (!account?.enabled || !account.native || account.accountId !== selected.accountId || account.native.accountId !== selected.native.accountId || nativeConfigurationKey(account.native) !== configurationKey) throw Error("WeChat account configuration changed; start a new turn");
4013
+ return { cfg, account, native: account.native };
4014
+ };
4015
+ const core = dependencies.core ?? getWeChatRuntime();
4016
+ const authorize = async () => {
4017
+ const { cfg, account } = guard2();
4018
+ const result = await resolveWeChatIngress({
4019
+ resolve: core.channel.inbound?.ingress?.resolveStable ?? resolveStableChannelMessageIngress3,
4020
+ cfg,
4021
+ accountId: account.accountId,
4022
+ policy: resolveWeChatPolicyContext({ account, cfg, chatId: conversation }),
4023
+ isGroup: conversation.endsWith("@chatroom"),
4024
+ chatId: conversation,
4025
+ senderId: requester,
4026
+ readStoreAllowFrom: async () => core.channel.pairing.readAllowFromStore({ channel: "agent-wechat", accountId: account.accountId, env: process.env }).catch(() => [])
4027
+ });
4028
+ guard2();
4029
+ if (result.ingress.admission !== "dispatch") throw Error("WeChat conversation access is no longer allowed");
4030
+ };
4031
+ await authorize();
4032
+ const { native } = guard2();
4033
+ const { client } = await (dependencies.host ?? ensureNativeHost)(native);
4034
+ await authorize();
4035
+ let intent;
4036
+ try {
4037
+ intent = await client.sendShare(native.accountId, request, key, signal);
4038
+ } catch (error) {
4039
+ if (!(error instanceof NativeApiError) || error.status >= 500 || error.code === "timeout") {
4040
+ const details2 = { threadId: conversation, idempotencyKey: key, state: "submission_unknown", note: "Inspect the send by this idempotency key. Do not resend with a new key." };
4041
+ return { content: [{ type: "text", text: JSON.stringify(details2) }], details: details2, isError: true };
4042
+ }
4043
+ throw error;
4044
+ }
4045
+ if (intent.accountId !== native.accountId || intent.destination !== conversation || !intent.id) throw Error("Share receipt crosses an account or conversation boundary; inspect the original idempotency key before another send");
4046
+ const delivery = intent.state === "accepted" && intent.localMessageId && intent.serverId ? await nativeOutboundDelivery(client, native.accountId, conversation, [intent.localMessageId], { sendId: intent.id, state: intent.state, serverIds: [intent.serverId] }) : void 0;
4047
+ const details = {
4048
+ id: intent.id,
4049
+ threadId: conversation,
4050
+ idempotencyKey: key,
4051
+ state: intent.state,
4052
+ serverId: intent.serverId,
4053
+ messageId: delivery?.messageId || void 0,
4054
+ receiptState: delivery?.meta.receiptState,
4055
+ reason: intent.errorCode,
4056
+ note: ["accepted", "sent", "server_accepted"].includes(intent.state) ? "Server accepted; recipient rendering is not confirmed." : "Inspect this send ID or reuse the identical request/key. Do not send again with a new key."
4057
+ };
4058
+ return { content: [{ type: "text", text: JSON.stringify(details) }], details, isError: ["failed", "needs_review", "cancelled"].includes(intent.state) };
4059
+ }
4060
+ }];
4061
+ }
4062
+ function registerNativeShareTools(api) {
4063
+ api.registerTool({ contextVersion: 2, create: (context) => createNativeShareTools(context) }, { names: [name] });
4064
+ }
4065
+
4066
+ // src/native-recall-tools.ts
4067
+ import { createHash as createHash10 } from "node:crypto";
4068
+ import { resolveStableChannelMessageIngress as resolveStableChannelMessageIngress4 } from "openclaw/plugin-sdk/channel-ingress-runtime";
4069
+ var names2 = ["wechat_recall"];
4070
+ function text2(value, label) {
4071
+ if (typeof value !== "string" || !value.trim() || value.length > 4096 || /[\u0000-\u001f\u007f]/.test(value)) throw Error(`Invalid ${label}`);
4072
+ return value.trim();
4073
+ }
4074
+ function thread2(value) {
4075
+ return text2(text2(value, "conversation").replace(/^(?:agent-)?wechat:(?:group:)?/i, ""), "conversation");
4076
+ }
4077
+ function nativeRecallKey(accountId, threadId2, messageId, serverId) {
4078
+ return `openclaw-recall-${createHash10("sha256").update(JSON.stringify([accountId, threadId2, messageId, serverId])).digest("hex")}`;
4079
+ }
4080
+ function createNativeRecallTools(context, dependencies = {}) {
4081
+ const currentConfig = () => context.getRuntimeConfig?.() ?? context.runtimeConfig ?? context.config;
4082
+ if (!currentConfig()) return [];
4083
+ const selected = resolveWeChatAccount(currentConfig());
4084
+ if (!selected?.enabled || !selected.native || context.messageChannel !== "agent-wechat" || context.agentAccountId && context.agentAccountId !== selected.accountId || context.deliveryContext?.channel === "agent-wechat" && context.deliveryContext.accountId && context.deliveryContext.accountId !== selected.accountId) return [];
4085
+ let conversation, requester;
4086
+ try {
4087
+ const nativeThread = context.nativeChannelId ? thread2(context.nativeChannelId) : void 0;
4088
+ const delivered = context.deliveryContext?.channel === "agent-wechat" && context.deliveryContext.to ? thread2(context.deliveryContext.to) : void 0;
4089
+ if (nativeThread && delivered && nativeThread !== delivered) return [];
4090
+ conversation = text2(nativeThread ?? delivered, "conversation");
4091
+ requester = text2(context.requesterSenderId, "requester");
4092
+ } catch {
4093
+ return [];
4094
+ }
4095
+ const accountId = selected.native.accountId;
4096
+ const configurationKey = nativeConfigurationKey(selected.native);
4097
+ return [{
4098
+ name: names2[0],
4099
+ label: "WeChat Recall",
4100
+ description: "Recall one own sent message in the current WeChat conversation by its exact opaque message ID from a verified send receipt or wechat_history, or inspect a retained recalled placeholder without another native mutation. The daemon checks eligibility. Returns the durable operation and confirmed, rejected, pending or uncertain result. Never invent IDs or resubmit an uncertain action with a new key; prior model input and completed actions cannot be erased.",
4101
+ parameters: { type: "object", additionalProperties: false, properties: {
4102
+ messageId: { type: "string", minLength: 1, maxLength: 4096, description: "Exact stored message ID in this conversation; send/job/operation IDs are not message IDs." },
4103
+ serverId: { type: "string", pattern: "^[1-9][0-9]{0,19}$", description: "Exact decimal server ID from the same verified receipt or history entry. The stored local message ID alone may be reused." }
4104
+ }, required: ["messageId", "serverId"] },
4105
+ execute: async (_callId, input, signal) => {
4106
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((key2) => !["messageId", "serverId"].includes(key2))) throw Error("Recall is restricted to a message ID in the current conversation");
4107
+ const messageId = text2(input.messageId, "message ID");
4108
+ const serverId = text2(input.serverId, "server ID");
4109
+ if (!/^[1-9]\d{0,19}$/.test(serverId) || BigInt(serverId) > 18446744073709551615n) throw Error("Invalid exact server message ID");
4110
+ const guard2 = () => {
4111
+ signal?.throwIfAborted();
4112
+ context.assertInvocationCurrent?.();
4113
+ const cfg = currentConfig(), account = resolveWeChatAccount(cfg);
4114
+ 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");
4115
+ return { cfg, account, native: account.native };
4116
+ };
4117
+ const allowed = async () => {
4118
+ const { cfg, account } = guard2();
4119
+ const core = dependencies.core ?? getWeChatRuntime();
4120
+ const ingress = await resolveWeChatIngress({
4121
+ resolve: core.channel.inbound?.ingress?.resolveStable ?? resolveStableChannelMessageIngress4,
4122
+ cfg,
4123
+ accountId: account.accountId,
4124
+ policy: resolveWeChatPolicyContext({ account, cfg, chatId: conversation }),
4125
+ isGroup: conversation.endsWith("@chatroom"),
4126
+ chatId: conversation,
4127
+ senderId: requester,
4128
+ readStoreAllowFrom: async () => core.channel.pairing.readAllowFromStore({ channel: "agent-wechat", accountId: account.accountId, env: process.env }).catch(() => [])
4129
+ });
4130
+ guard2();
4131
+ if (ingress.ingress.admission !== "dispatch") throw Error("WeChat conversation access is no longer allowed");
4132
+ };
4133
+ await allowed();
4134
+ const { native } = guard2();
4135
+ const { client } = await (dependencies.host ?? ensureNativeHost)(native);
4136
+ guard2();
4137
+ const message = await client.message(accountId, messageId);
4138
+ guard2();
4139
+ const retainedRecall = !!nativeRecallInfo(message);
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");
4141
+ if (message.serverId !== serverId) throw Error("The exact server identity does not match this receipt; the local message identity may have been reused");
4142
+ await allowed();
4143
+ guard2();
4144
+ const key = nativeRecallKey(accountId, conversation, messageId, serverId);
4145
+ let operation;
4146
+ let operationId;
4147
+ const result = (status2, extra = {}) => {
4148
+ const details = {
4149
+ messageId,
4150
+ serverId,
4151
+ threadId: conversation,
4152
+ accountId,
4153
+ action: retainedRecall ? "inspect_recalled" : "recall",
4154
+ idempotencyKey: key,
4155
+ operationId,
4156
+ operationState: operation?.state,
4157
+ status: status2,
4158
+ retryable: false,
4159
+ ...extra
4160
+ };
4161
+ return { content: [{ type: "text", text: JSON.stringify(details) }], details };
4162
+ };
4163
+ try {
4164
+ operation = await client.recallMessage(accountId, messageId, serverId, key, signal);
4165
+ const checkOperation = (candidate) => {
4166
+ if (!candidate || typeof candidate.id !== "string" || !candidate.id || operationId && candidate.id !== operationId || candidate.accountId !== accountId || candidate.kind !== "message_recall") throw Error("Recall operation identity is invalid");
4167
+ };
4168
+ checkOperation(operation);
4169
+ operationId = operation.id;
4170
+ const deadline = Date.now() + Math.max(0, Math.min(dependencies.waitMs ?? 2e3, 1e4));
4171
+ while (["queued", "running", "submitting"].includes(operation.state) && Date.now() < deadline) {
4172
+ await new Promise((resolve) => setTimeout(resolve, Math.min(250, deadline - Date.now())));
4173
+ guard2();
4174
+ const remaining = Math.max(1, deadline - Date.now());
4175
+ const next = await client.operation(accountId, operation.id, signal ? AbortSignal.any([signal, AbortSignal.timeout(remaining)]) : AbortSignal.timeout(remaining));
4176
+ checkOperation(next);
4177
+ operation = next;
4178
+ }
4179
+ guard2();
4180
+ } catch (error) {
4181
+ const reason = error instanceof NativeApiError ? error.code : "recall_result_unavailable";
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." });
4183
+ }
4184
+ const receipt = operation.result && typeof operation.result === "object" ? operation.result : {};
4185
+ if (receipt.messageId !== void 0 && receipt.messageId !== messageId || receipt.threadId !== void 0 && receipt.threadId !== conversation || receipt.serverId !== void 0 && receipt.serverId !== serverId) throw Error("Recall operation target identity is invalid");
4186
+ const exactReceipt = receipt.messageId === messageId && receipt.threadId === conversation && receipt.serverId === serverId;
4187
+ const status = operation.state === "succeeded" && exactReceipt && ["recalled", "already_recalled"].includes(String(receipt.status)) ? String(receipt.status) : ["queued", "running", "submitting"].includes(operation.state) ? "pending" : operation.state === "failed" && exactReceipt && ["not_self", "not_eligible", "unavailable", "not_found"].includes(String(receipt.status)) ? String(receipt.status) : "needs_review";
4188
+ const boundedState = (value) => typeof value === "string" && /^[a-z0-9_]{1,80}$/.test(value) ? value : void 0;
4189
+ return result(status, {
4190
+ remoteOutcome: boundedState(receipt.remoteOutcome),
4191
+ profileProjection: boundedState(receipt.profileProjection),
4192
+ note: status === "pending" || status === "needs_review" ? "Inspect this durable operation; do not automatically submit a replacement recall." : void 0
4193
+ });
4194
+ }
4195
+ }];
4196
+ }
4197
+ function registerNativeRecallTools(api) {
4198
+ api.registerTool({ contextVersion: 2, create: (context) => createNativeRecallTools(context) }, { names: names2 });
4199
+ }
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
+
2917
4250
  // index.ts
2918
4251
  var plugin = {
2919
4252
  id: "agent-wechat",
@@ -2925,6 +4258,10 @@ var plugin = {
2925
4258
  const selected = resolveWeChatAccount(api.config);
2926
4259
  api.registerChannel({ plugin: wechatPlugin });
2927
4260
  registerNativeHistoryTools(api);
4261
+ registerNativeShareTools(api);
4262
+ registerNativeRecallTools(api);
4263
+ registerNativeGroupTools(api);
4264
+ registerNativeLoginTool(api);
2928
4265
  const stopFacade = selected?.native ? registerNativeFacade(api, selected.native) : () => {
2929
4266
  };
2930
4267
  const stopPreparedBoundary = selected?.native?.readPolicy && selected.native.readPolicy !== "on_inbound" ? registerNativePreparedBoundary(api) : () => {