@agent-wechat/agent-wechat 2.4.1 → 2.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +51 -26
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -2144,15 +2144,6 @@ function collectWeChatStatusIssues(accounts) {
2144
2144
  fix: "Select native.readPolicy=on_inbound to mark successfully handled conversations read without model hooks, or use a compatible prepared-run SDK hook."
2145
2145
  });
2146
2146
  }
2147
- if ((snapshot.needsReview ?? 0) > 0) {
2148
- issues.push({
2149
- channel: "agent-wechat",
2150
- accountId: snapshot.accountId,
2151
- kind: "runtime",
2152
- message: "Native consumer work needs review after an uncertain model dispatch or reply.",
2153
- fix: "Inspect the retained consumer receipts before retrying; do not automatically resend uncertain work."
2154
- });
2155
- }
2156
2147
  if (snapshot.connected === false) {
2157
2148
  issues.push({
2158
2149
  channel: "agent-wechat",
@@ -2796,7 +2787,11 @@ async function prepareImageRepresentation(bytes, mime, cfg) {
2796
2787
  async function prepareNativeLink(params) {
2797
2788
  const { message } = params;
2798
2789
  const link = message.link;
2799
- const body = [`[Link]${link.title ? ` ${link.title}` : ""}`, link.description, link.url].filter(Boolean).join("\n").slice(0, 65536);
2790
+ const channels = message.appMessageType === 51;
2791
+ const body = (channels ? [
2792
+ message.body?.trim() || "[Channels]",
2793
+ message.body?.startsWith("[Channels video]") ? "[Video not downloaded: call wechat_media with this message's ID to retrieve it]" : void 0
2794
+ ] : [`[Link]${link.title ? ` ${link.title}` : ""}`, link.description, link.url]).filter(Boolean).join("\n").slice(0, 65536);
2800
2795
  const unavailable = (status, reason) => ({
2801
2796
  body: `${body}
2802
2797
  [Link preview ${status}]`,
@@ -2901,6 +2896,16 @@ async function prepareNativeAttachmentInput(params) {
2901
2896
  if (message.type === 48) return { body: message.location && message.body ? message.body.slice(0, 32768) : "[Location unavailable]", pending: false };
2902
2897
  if (message.type === 49 && [1, 17, 74, 87].includes(message.appMessageType ?? 0)) return { body: message.body?.slice(0, 32768) || "[Shared text unavailable]", pending: false };
2903
2898
  if (message.type === 49 && message.appMessageType === 19) return { body: message.body?.slice(0, 65536) || "[Forwarded chat history unavailable]", pending: false };
2899
+ if (message.type === 49 && message.appMessageType === 51 && message.link && params.channelsVideo && (params.quality ?? "best") !== "thumbnail") {
2900
+ const prepared = await prepareNativeAttachment({
2901
+ ...params,
2902
+ channelsVideo: false,
2903
+ quality: "normal",
2904
+ message: { ...message, type: 43, appMessageType: void 0, quote: void 0, link: void 0 }
2905
+ });
2906
+ return { ...prepared, body: `${message.body?.trim() || "[Channels video]"}
2907
+ ${prepared.body}`.slice(0, 65536) };
2908
+ }
2904
2909
  if (message.type === 49 && [3, 4, 5, 51].includes(message.appMessageType ?? 0) && message.link) return prepareNativeLink(params);
2905
2910
  if (message.type === 49 && message.appMessageType != null && message.appMessageType !== 6) return { body: `[Unsupported WeChat app message subtype ${message.appMessageType}]`, pending: false, retryable: false };
2906
2911
  if (!attachmentKind) return { body: message.type === 1 ? message.body ?? "" : `[Unsupported WeChat message type ${message.type}]`, pending: false };
@@ -3641,8 +3646,8 @@ async function handleNativeStickerAction(ctx, dependencies = { host: ensureNativ
3641
3646
  if (!account?.enabled || !account.native) throw Error("No native WeChat account configured");
3642
3647
  const binding = nativeConfigurationKey(account.native);
3643
3648
  const guard2 = async () => {
3644
- if (ctx.senderIsOwner !== true || !ctx.onPlatformSendDispatch || !ctx.assertDirectAdapterHandoff) throw Error("WeChat sticker send requires live host handoff authority");
3645
- await ctx.onPlatformSendDispatch();
3649
+ if (ctx.senderIsOwner !== true || !ctx.assertDirectAdapterHandoff) throw Error("WeChat sticker send requires live host handoff authority");
3650
+ await ctx.onPlatformSendDispatch?.();
3646
3651
  ctx.assertDirectAdapterHandoff();
3647
3652
  const current = resolveWeChatAccount(ctx.cfg, ctx.accountId ?? void 0);
3648
3653
  if (!current?.enabled || !current.native || current.accountId !== account.accountId || nativeConfigurationKey(current.native) !== binding) throw Error("WeChat account configuration changed");
@@ -3929,7 +3934,7 @@ var NativeConsumerState = class {
3929
3934
  const existing = message ? this.value.items[message.id] : void 0;
3930
3935
  replaced = !!message && !nativeRecallInfo(message) && !!existing && (existing.message.threadId !== message.threadId || existing.message.serverId !== message.serverId);
3931
3936
  if (message && (!existing || replaced)) {
3932
- 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));
3937
+ const completed = Object.entries(this.value.items).filter(([, item]) => !item.readPending && !item.groupContext && ["completed", "ignored", "needs_review"].includes(item.state));
3933
3938
  for (const [key2] of completed.slice(0, Math.max(0, completed.length - 1e3))) delete this.value.items[key2];
3934
3939
  if (!existing && Object.keys(this.value.items).length >= 5e3) throw new Error("Native custody queue is full; operator review required");
3935
3940
  if (replaced) {
@@ -4527,7 +4532,7 @@ async function startNativeMonitor(opts) {
4527
4532
  const account = resolveWeChatAccount(cfg, opts.account.accountId) ?? opts.account;
4528
4533
  if (account.backend !== "native" || JSON.stringify(account.native) !== JSON.stringify(native)) throw new Error("Native service configuration changed; restart required before processing");
4529
4534
  for (const item of state.items().filter((value) => value.state === "received")) {
4530
- await dispatchNativeMessage({
4535
+ const outcome = await dispatchNativeMessage({
4531
4536
  client: host2.client,
4532
4537
  state,
4533
4538
  account,
@@ -4537,13 +4542,17 @@ async function startNativeMonitor(opts) {
4537
4542
  signal: opts.abortSignal,
4538
4543
  onDelivered: () => opts.setStatus({ accountId: account.accountId, lastOutboundAt: Date.now() })
4539
4544
  });
4545
+ if (outcome === "needs_review") {
4546
+ const line = `WeChat message ${item.message.id} was not retried: its model dispatch or reply could not be confirmed`;
4547
+ if (opts.log?.warn) opts.log.warn(line);
4548
+ else opts.log?.error?.(line);
4549
+ }
4540
4550
  }
4541
4551
  try {
4542
4552
  await flushRead();
4543
4553
  } catch {
4544
4554
  opts.log?.error?.("Native read projection is pending; thread read receipt retained for retry");
4545
4555
  }
4546
- const needsReview = state.items().filter((value) => value.state === "needs_review" || value.phoneReadState === "needs_review" || value.phoneReadState === "rejected").length;
4547
4556
  const handoffUnconfirmed = native.readPolicy === "on_model_dispatch" && state.items().some((value) => value.handoffUnconfirmed);
4548
4557
  const accountStatus = await host2.client.account(native.accountId);
4549
4558
  opts.setStatus({
@@ -4551,7 +4560,6 @@ async function startNativeMonitor(opts) {
4551
4560
  running: true,
4552
4561
  connected: true,
4553
4562
  linked: accountStatus.authenticated === true && accountStatus.connection === "online",
4554
- needsReview,
4555
4563
  handoffUnconfirmed
4556
4564
  });
4557
4565
  };
@@ -4597,7 +4605,7 @@ async function startNativeMonitor(opts) {
4597
4605
  } catch (error) {
4598
4606
  if (opts.abortSignal.aborted) break;
4599
4607
  if (error instanceof NativeApiError && error.code === "event_cursor_expired") {
4600
- opts.setStatus({ accountId: opts.account.accountId, connected: false, running: false, needsReview: 1, lastError: "event_cursor_expired" });
4608
+ opts.setStatus({ accountId: opts.account.accountId, connected: false, running: false, lastError: "event_cursor_expired" });
4601
4609
  throw new Error("Native journal cursor expired; explicit snapshot/replay is required before resuming");
4602
4610
  }
4603
4611
  opts.setStatus({ accountId: opts.account.accountId, connected: false, running: true });
@@ -5008,7 +5016,6 @@ var wechatPlugin = {
5008
5016
  accountId: account?.accountId ?? "default",
5009
5017
  backend: "native",
5010
5018
  handoffUnconfirmed: runtime2?.handoffUnconfirmed,
5011
- needsReview: runtime2?.needsReview,
5012
5019
  enabled: account?.enabled ?? false,
5013
5020
  configured: Boolean(account?.native),
5014
5021
  running: runtime2?.running ?? false,
@@ -5255,8 +5262,9 @@ function messageResult(message, retrievalTool = "wechat_media", quotePermitted =
5255
5262
  const isQuote = message.type === 49 && message.appMessageType === 57;
5256
5263
  const isForward = message.type === 49 && message.appMessageType === 19;
5257
5264
  const isLink = message.type === 49 && [3, 4, 5].includes(message.appMessageType ?? 0) && !!message.link;
5258
- 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";
5259
- 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]`;
5265
+ const isChannels = message.type === 49 && message.appMessageType === 51 && !!message.link;
5266
+ const kind2 = isQuote ? "quote" : isForward ? "forwarded_history" : isLink ? "link_preview" : isChannels ? "channels_video" : 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";
5267
+ const body = message.type === 1 || isForward || isLink || isChannels ? message.body ?? "" : isQuote ? renderEmbeddedQuote(message, quotePermitted).body : `[WeChat ${kind2} message; attachment content has not been retrieved by this tool]`;
5260
5268
  const quote = message.quote && {
5261
5269
  serverId: message.quote.serverId,
5262
5270
  type: message.quote.type,
@@ -5274,7 +5282,7 @@ function messageResult(message, retrievalTool = "wechat_media", quotePermitted =
5274
5282
  type: message.type,
5275
5283
  appMessageType: message.appMessageType,
5276
5284
  quote,
5277
- link: isLink ? message.link : void 0,
5285
+ link: isLink || isChannels ? message.link : void 0,
5278
5286
  createdAt: message.createdAt,
5279
5287
  body: body.slice(0, 4e3),
5280
5288
  bodyTruncated: body.length > 4e3,
@@ -5413,6 +5421,7 @@ function createLookupTools(context, dependencies, archive) {
5413
5421
  waitMs: 2e3,
5414
5422
  signal,
5415
5423
  assertCurrent: guard2,
5424
+ channelsVideo: true,
5416
5425
  allowQuotedMessage: async (original) => original.direction === "outgoing" || await allowed(original.senderId ?? void 0),
5417
5426
  beforeMediaAccess: async () => {
5418
5427
  if (!await allowed(requesterSenderId) || message.direction !== "outgoing" && !await allowed(message.senderId ?? void 0)) throw Error("WeChat conversation access is no longer allowed");
@@ -5433,11 +5442,13 @@ function createLookupTools(context, dependencies, archive) {
5433
5442
  }
5434
5443
  guard2();
5435
5444
  if (!await allowed(requesterSenderId) || message.direction !== "outgoing" && !await allowed(message.senderId ?? void 0)) throw Error("WeChat conversation access is no longer allowed");
5445
+ const unreachable = context.sandboxed === true && prepared.attachment?.status === "ready" && prepared.attachment.kind !== "image";
5446
+ const attachment = unreachable ? { ...prepared.attachment, path: void 0, reachableFromSandbox: false } : prepared.attachment;
5436
5447
  const details = {
5437
5448
  messageId: message.id,
5438
5449
  threadId: message.threadId,
5439
5450
  status: prepared.reason === "message_recalled" ? "recalled" : prepared.pending ? "pending" : prepared.attachment?.status ?? prepared.quote?.state ?? "unsupported",
5440
- attachment: prepared.attachment,
5451
+ attachment,
5441
5452
  quote: prepared.quote,
5442
5453
  link: ["message_recalled", "media_identity_unavailable", "media_source_changed"].includes(prepared.reason ?? "") ? void 0 : message.link,
5443
5454
  variant: prepared.variant,
@@ -5491,13 +5502,13 @@ function createLookupTools(context, dependencies, archive) {
5491
5502
  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: threadIdSchema, ...pageSchema }, ["query"]),
5492
5503
  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: threadIdSchema, ...pageSchema }, ["threadId"]),
5493
5504
  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"]),
5494
- 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"])
5505
+ tool(archiveNames[4], "media", "Retrieve an attachment, a Channels card's video, 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; quality thumbnail returns a Channels card's cover. 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"])
5495
5506
  ];
5496
5507
  return [
5497
5508
  tool(names2[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 }),
5498
5509
  tool(names2[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"]),
5499
5510
  tool(names2[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"]),
5500
- tool(names2[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"])
5511
+ tool(names2[3], "media", "Retrieve a message attachment, a Channels card's video, or quoted text/image/link from the current WeChat conversation. Use the parent quote message ID for quotes; quality thumbnail returns a Channels card's cover. 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"])
5501
5512
  ];
5502
5513
  }
5503
5514
  function registerNativeHistoryTools(api) {
@@ -5832,6 +5843,12 @@ function text3(value, label2) {
5832
5843
  if (typeof value !== "string" || !value || value.length > 4096 || /[\u0000-\u001f\u007f]/.test(value)) throw Error(`Invalid ${label2}`);
5833
5844
  return value;
5834
5845
  }
5846
+ async function receivedStickerOriginal(client, accountId, messageId, signal) {
5847
+ const { items } = await client.mediaAssets(accountId, messageId, signal);
5848
+ const originals = (Array.isArray(items) ? items : []).filter((item) => item.accountId === accountId && item.messageId === messageId && item.kind === "sticker" && item.variant === "original");
5849
+ if (originals.length !== 1) throw Error(originals.length ? "The message has more than one original sticker" : "The message has no received sticker to add");
5850
+ return text3(originals[0].id, "asset identity");
5851
+ }
5835
5852
  function createNativeStickerTools(context, dependencies = { host: ensureNativeHost, files: withStickerFiles }) {
5836
5853
  if (context.senderIsOwner !== true || !context.assertInvocationCurrent) return [];
5837
5854
  const config = () => context.getRuntimeConfig?.() ?? context.runtimeConfig ?? context.config;
@@ -5892,8 +5909,16 @@ function createNativeStickerTools(context, dependencies = { host: ensureNativeHo
5892
5909
  context.assertInputCommitAllowed?.();
5893
5910
  let job2;
5894
5911
  if (args.action === "add") {
5895
- if (args.preparationId != null === (args.messageId != null || args.assetId != null)) throw Error("Provide a preparation or one message/asset pair");
5896
- const source = args.preparationId != null ? { kind: "prepared", preparationId: text3(args.preparationId, "preparation identity") } : { kind: "message", messageId: text3(args.messageId, "message identity"), assetId: text3(args.assetId, "asset identity") };
5912
+ if (args.preparationId != null === (args.messageId != null || args.assetId != null)) throw Error("Provide a preparation or a received sticker message");
5913
+ let source;
5914
+ if (args.preparationId != null) source = { kind: "prepared", preparationId: text3(args.preparationId, "preparation identity") };
5915
+ else {
5916
+ const messageId = text3(args.messageId, "message identity");
5917
+ const assetId = args.assetId != null ? text3(args.assetId, "asset identity") : await receivedStickerOriginal(client, accountId, messageId, signal);
5918
+ guard2();
5919
+ context.assertInputCommitAllowed?.();
5920
+ source = { kind: "message", messageId, assetId };
5921
+ }
5897
5922
  job2 = await client.addCustomSticker(accountId, { source }, key2, signal);
5898
5923
  } else {
5899
5924
  const stickerId = text3(args.stickerId, "sticker identity"), revision = text3(args.revision, "collection revision");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-wechat/agent-wechat",
3
- "version": "2.4.1",
3
+ "version": "2.4.2",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "files": [