@agent-wechat/agent-wechat 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +6 -4
  2. package/dist/index.js +46 -18
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -80,9 +80,11 @@ By default, `readPolicy: "on_inbound"` marks a whole thread read after its incom
80
80
 
81
81
  A whole-thread read also clears earlier unread messages in that thread, including messages the model did not receive. The daemon freezes the latest local message boundary, checks the expected version, updates local unread state and submits one native read-status notification. Server acceptance alone does not prove that a phone badge changed. A lost notification response remains `needs_review` and is never automatically resubmitted. Pending reads survive a Gateway restart and retry independently of model execution or new SSE traffic. `readPolicy: "never"` disables both local and remote marking, including previously queued reads. Crashes during an unfinished dispatch retain `needs_review`; the plugin does not automatically duplicate model turns or uncertain outgoing sends.
82
82
 
83
- The optional `readPolicy: "on_model_dispatch"` instead requires a confirmed model handoff. OpenClaw **2026.10.9** lacks `onPreparedAgentRunStart`, so its released public hooks provide a bounded compatibility path. Before dispatch, the adapter persists an immutable manifest binding the exact new message ID/version/content hash, policy hash, source and supplied asset hashes, and context roles. Text requires the exact current input and host-created message/account/session facts plus a matching `model_call_started`. Media additionally waits for the same run's `agent_end` snapshot and source-turn identity. Image bytes/MIME/length must match the frozen supplied representation; file/video/voice references must appear in the exact current body. Image count, model selection and reply delivery alone cannot confirm a model handoff. Unknown, omitted, rewritten, merged or ambiguous inputs remain unconfirmed. Host/provider history formats can prevent confirmation even when a reply was delivered; use `on_inbound` for ordinary bot read behavior.
83
+ The optional `readPolicy: "on_model_dispatch"` instead requires a confirmed model handoff. On OpenClaw **2026.11.2**, the host calls `onPreparedAgentRunStart` for the run that contains the dispatched message once its transcript is prepared, and that call confirms the handoff. It does not need `hooks.allowConversationAccess`. It happens before the provider request and before the host drops images for a text-only model, so it shows that the run started with the message, not that the model received every image. Built-in commands, rejected messages, and media without a ready supplied asset are never confirmed, and status reports `handoffUnconfirmed`.
84
84
 
85
- The model-handoff compatibility path requires the operator's explicit host permission, `plugins.entries.agent-wechat.hooks.allowConversationAccess: true`. It observes only run IDs issued by this adapter and never enables that permission itself. Without the grant, or on an unsupported host, the explicit `on_model_dispatch` policy leaves messages unread and status reports `handoffUnconfirmed`. The older `onAgentRunStart` also reports direct tools and early lifecycle phases and is never used as proof. Access and mention gates still precede model dispatch; a rejected message does not itself trigger a read.
85
+ Hosts without `onPreparedAgentRunStart`, such as OpenClaw 2026.10.9, use a stricter compatibility path. Before dispatch, the adapter persists an immutable manifest binding the exact new message ID/version/content hash, policy hash, source and supplied asset hashes, and context roles. Text requires the exact current input and host-created message/account/session facts plus a matching `model_call_started`. Media additionally waits for the same run's `agent_end` snapshot and source-turn identity. Image bytes/MIME/length must match the frozen supplied representation; file/video/voice references must appear in the exact current body. Unknown, omitted, rewritten, merged or ambiguous inputs remain unconfirmed. This path requires the operator's explicit host permission, `plugins.entries.agent-wechat.hooks.allowConversationAccess: true`; it observes only run IDs issued by this adapter and never enables that permission itself. Without the grant, it leaves messages unread. The older `onAgentRunStart` also reports direct tools and early lifecycle phases and is never used as proof. Host/provider history formats can prevent confirmation even when a reply was delivered; use `on_inbound` for ordinary bot read behavior.
86
+
87
+ Access and mention gates still precede model dispatch; a rejected message does not itself trigger a read.
86
88
 
87
89
  Images exceeding the host's bounded representation, or formats requiring conversion, receive a separately stored JPEG still preview using the public SDK image processor. The original stays intact; both hashes are recorded and the model input labels the preview. Prepared images fit within 5 MiB and at most 1200 pixels per side (or a smaller configured limit). Files and videos can be supplied as available local references; this does not claim their contents were analyzed. Voice retains its verified file and includes configured transcription output or an explicit unavailable status. A placeholder does not confirm a model handoff under `on_model_dispatch`; default `on_inbound` can mark a thread after successfully handling an explicit expired/unsupported status.
88
90
 
@@ -127,7 +129,7 @@ A media result includes `messageId`, `threadId`, `status` and `retryable`, with
127
129
 
128
130
  For example, the agent can call `wechat_search` with `{"query":"project notes"}` in the current conversation. These four default tools are restricted to the current WeChat account and thread derived from trusted OpenClaw context. Owners and agents with archive access have the same restriction when invoking a default tool. Default tools accept no thread/account selector, and the plugin rejects messages or assets from another conversation or account. Requester and historical sender policy are rechecked. Missing or conflicting trusted conversation context hides the default tools; webchat and other channels cannot use them.
129
131
 
130
- History/search return opaque string message IDs, a bounded text preview, coverage metadata and `nextCursor`. Pass the cursor back with the same tool, query and thread to continue; the page limit is 1–50 (default 20). Search queries are limited to 256 UTF-8 bytes. Long message bodies are labeled as truncated. A sender-filtered page may be empty and still have a continuation. Search covers locally stored history and does not fetch missing remote history or maintain an official FTS index. Media messages receive a type/status description; these tools do not return raw transport XML or download attachments. History, search and exact-message lookup are read-only. Their attachment descriptions name `wechat_media` and the exact message ID without automatically retrieving media. None of these tools mark a conversation read, send messages or modify the inbound consumer cursor. Lookup requires the selected account's API `read` scope and remains subject to normal OpenClaw tool policy. With OpenClaw's compact tool catalog, the agent discovers history/search/message lookup through `tool_search` and invokes the returned tool with `tool_call`. The media tool stays directly callable as `wechat_media`: the pinned host's generic wrapper serializes nested image blocks as JSON text, while direct invocation preserves image content for vision.
132
+ History/search return opaque string message IDs, a bounded text preview, coverage metadata and `nextCursor`. Pass the cursor back with the same tool, query and thread to continue; the page limit is 1–50 (default 20). Search queries are limited to 256 UTF-8 bytes. Long message bodies are labeled as truncated. A sender-filtered page may be empty and still have a continuation. Search covers locally stored history and does not fetch missing remote history or maintain an official FTS index. Media messages receive a type/status description; these tools do not return raw transport XML or download attachments. History, search and exact-message lookup are read-only. Their attachment descriptions name `wechat_media` and the exact message ID without automatically retrieving media. None of these tools mark a conversation read, send messages or modify the inbound consumer cursor. Lookup requires the selected account's API `read` scope and remains subject to normal OpenClaw tool policy. With OpenClaw's compact tool catalog, the agent discovers history/search/message lookup through `tool_search` and invokes the returned tool with `dispatch_action`; earlier OpenClaw releases named that dispatcher `tool_call`. The media tool stays directly callable as `wechat_media`: the pinned host's generic wrapper serializes nested image blocks as JSON text, while direct invocation preserves image content for vision.
131
133
 
132
134
  `wechat_media` accepts `{"messageId":"<returned opaque ID>"}`. It verifies message/thread/sender admission before accessing assets, uses cached bytes first, checks identity, hash and size, and saves verified bytes to OpenClaw's managed media store. Files, videos and voice return local paths; images also return a bounded prepared preview as image content for vision. This retrieval does not itself transcribe voice or analyze files/videos. Cached bytes remain usable after CDN expiry.
133
135
 
@@ -216,6 +218,6 @@ Set `native.gatewayFacade: {"enabled": true}` to register `/plugins/agent-wechat
216
218
 
217
219
  The actual Gateway authenticates requests before the proxy runs. Its bearer is never forwarded to the daemon; the plugin uses its private daemon token reference. Routes are restricted to the configured account, with no daemon-wide token/account administration. Binary bodies, byte ranges, status codes and SSE are preserved within explicit size limits. Client disconnect/plugin shutdown closes upstream streaming work without cancelling durable sends.
218
220
 
219
- `scripts/native-gateway-smoke.mjs` tests the built plugin on an isolated OpenClaw **2026.10.9** Gateway with synthetic loopback data: auth rejection, separate credentials, account boundaries, Range206, SSE and cancellation. This transport test is separate from the local model-boundary test above; neither uses an external model provider or a real WeChat account.
221
+ `scripts/native-gateway-smoke.mjs` tests the built plugin on an isolated OpenClaw **2026.11.2** Gateway with synthetic loopback data: auth rejection, separate credentials, account boundaries, Range206, SSE and cancellation. This transport test is separate from the local model-boundary test above; neither uses an external model provider or a real WeChat account.
220
222
 
221
223
  See [native deployment examples](../../deploy/native/README.md) and [native CLI installation](../cli/README.md).
package/dist/index.js CHANGED
@@ -1435,8 +1435,8 @@ var NativeWeChatClient = class {
1435
1435
  groupMutationByKey(accountId, key2, signal) {
1436
1436
  return this.request(`v1/accounts/${id(accountId)}/group-mutations/by-idempotency-key?${new URLSearchParams({ key: key2 })}`, { signal });
1437
1437
  }
1438
- refreshAvatar(accountId, username) {
1439
- return this.request(`v1/accounts/${id(accountId)}/avatars/${id(username)}/refresh`, { method: "POST", body: "{}" });
1438
+ refreshAvatar(accountId, username, options = {}) {
1439
+ return this.request(`v1/accounts/${id(accountId)}/avatars/${id(username)}/refresh`, { method: "POST", body: JSON.stringify(options) });
1440
1440
  }
1441
1441
  async avatar(accountId, username, signal) {
1442
1442
  const response = await this.response(`v1/accounts/${id(accountId)}/avatars/${id(username)}`, { signal });
@@ -2547,7 +2547,7 @@ function sameEmbeddedQuote(stored, current) {
2547
2547
  if (stored.state === "unsupported" && current.state === "embedded")
2548
2548
  return ["serverId", "type", "appMessageType", "senderId", "direction"].every((field) => (stored[field] ?? null) === (current[field] ?? null));
2549
2549
  const compared = { ...current };
2550
- for (const field of ["embeddedLink", "embeddedSticker"]) {
2550
+ for (const field of ["embeddedLink", "embeddedSticker", "senderName"]) {
2551
2551
  if (!Object.hasOwn(stored, field)) delete compared[field];
2552
2552
  }
2553
2553
  return JSON.stringify(stored) === JSON.stringify(compared);
@@ -2570,8 +2570,10 @@ function renderEmbeddedQuote(message, permitted = true, imageBody) {
2570
2570
  if (state === "embedded" && !image && !source.embeddedText) return unavailable("invalid");
2571
2571
  const content = state === "missing" ? "" : image ? imageBody ?? "[Image metadata embedded in quote; image not retrieved]" : source.embeddedText ?? "";
2572
2572
  const status = state === "unsupported" ? `[${label2} attachment unavailable from embedded quote]` : state === "missing" ? "[Embedded quote content unavailable]" : "";
2573
+ const suppliedName = source.senderName;
2574
+ const author = typeof suppliedName === "string" && suppliedName.trim() && suppliedName.length <= 4096 && !/[\u0000-\u001f\u007f-\u009f]/.test(suppliedName) ? suppliedName : source.senderId ?? "unknown sender";
2573
2575
  return {
2574
- body: `${comment}${comment ? "\n\n" : ""}[Quoted ${label2} from ${source.senderId ?? "unknown sender"}; embedded in reply]
2576
+ body: `${comment}${comment ? "\n\n" : ""}[Quoted ${label2} from ${author}; embedded in reply]
2575
2577
  ${[content, status].filter(Boolean).join("\n")}
2576
2578
  [/Quoted message]`,
2577
2579
  image,
@@ -3022,6 +3024,27 @@ function validateNativeMediaSendOptions(options, audioAsVoice = false) {
3022
3024
  if (options.videoQuality != null && !["normal", "original"].includes(options.videoQuality)) throw new Error("Invalid WeChat video quality");
3023
3025
  if (options.forceDocument && (audioAsVoice || options.videoQuality != null)) throw new Error("Document sending cannot also request voice or video quality");
3024
3026
  }
3027
+ var nameMediaTypes = /* @__PURE__ */ new Map([
3028
+ [".png", "image/png"],
3029
+ [".jpg", "image/jpeg"],
3030
+ [".jpeg", "image/jpeg"],
3031
+ [".gif", "image/gif"],
3032
+ [".webp", "image/webp"],
3033
+ [".mp4", "video/mp4"],
3034
+ [".wav", "audio/wav"],
3035
+ [".mp3", "audio/mp3"],
3036
+ [".ogg", "audio/ogg"],
3037
+ [".oga", "audio/ogg"],
3038
+ [".opus", "audio/ogg"],
3039
+ [".m4a", "audio/m4a"],
3040
+ [".flac", "audio/flac"],
3041
+ [".aac", "audio/aac"],
3042
+ [".caf", "audio/x-caf"],
3043
+ [".amr", "audio/amr"]
3044
+ ]);
3045
+ function mediaTypeForName(filename) {
3046
+ return nameMediaTypes.get(extname(filename).toLowerCase()) ?? "application/octet-stream";
3047
+ }
3025
3048
  function outboundMediaKind(mime, audioAsVoice, options) {
3026
3049
  if (options.forceDocument) return "file";
3027
3050
  if (audioAsVoice && !mime.startsWith("audio/")) throw new Error("Voice sending requires an explicit audio attachment");
@@ -3029,22 +3052,28 @@ function outboundMediaKind(mime, audioAsVoice, options) {
3029
3052
  if (options.videoQuality != null && selected !== "video") throw new Error("Video quality requires a video attachment");
3030
3053
  return selected;
3031
3054
  }
3055
+ function localOutboundSource(mediaUrl, audioAsVoice, options) {
3056
+ const path = mediaUrl.startsWith("file:") ? new URL(mediaUrl) : mediaUrl, filename = basename(path instanceof URL ? path.pathname : path), mime = mediaTypeForName(filename);
3057
+ return { path, filename, mime, kind: outboundMediaKind(mime, audioAsVoice, options) };
3058
+ }
3032
3059
  function outboundSourceLimit(account, selectedKind) {
3033
3060
  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);
3034
3061
  }
3035
3062
  async function sendNativeAttachment(client, account, threadId2, mediaUrl, audioAsVoice = false, key2 = randomUUID2(), beforeSend, options = {}) {
3036
3063
  validateNativeMediaSendOptions(options, audioAsVoice);
3064
+ const local = /^https?:/.test(mediaUrl) ? void 0 : localOutboundSource(mediaUrl, audioAsVoice, options);
3037
3065
  await beforeSend?.();
3038
3066
  let filename, mime, selectedKind, sourceBytes, source;
3039
3067
  let temporary;
3040
3068
  const accountId = account.native.accountId;
3041
3069
  try {
3042
3070
  let blob;
3043
- if (/^https?:/.test(mediaUrl)) {
3071
+ if (!local) {
3044
3072
  const response = await fetch(mediaUrl, { redirect: "error", signal: AbortSignal.timeout(60 * 6e4) });
3045
3073
  if (!response.ok) throw new Error(`Native outbound source unavailable (${response.status})`);
3046
3074
  filename = basename(new URL(mediaUrl).pathname) || "attachment";
3047
- mime = response.headers.get("content-type")?.split(";")[0].trim().toLowerCase() ?? "application/octet-stream";
3075
+ const declared = response.headers.get("content-type")?.split(";")[0].trim().toLowerCase();
3076
+ mime = declared && declared !== "application/octet-stream" ? declared : mediaTypeForName(filename);
3048
3077
  try {
3049
3078
  selectedKind = outboundMediaKind(mime, audioAsVoice, options);
3050
3079
  } catch (error) {
@@ -3080,12 +3109,8 @@ async function sendNativeAttachment(client, account, threadId2, mediaUrl, audioA
3080
3109
  }
3081
3110
  blob = await openAsBlob(path, { type: mime });
3082
3111
  } else {
3083
- const path = mediaUrl.startsWith("file:") ? new URL(mediaUrl) : mediaUrl;
3084
- filename = basename(path instanceof URL ? path.pathname : path);
3085
- const extension = extname(filename).toLowerCase();
3086
- 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";
3087
- selectedKind = outboundMediaKind(mime, audioAsVoice, options);
3088
- const max = outboundSourceLimit(account, selectedKind), file = await open(path, "r");
3112
+ ({ filename, mime, kind: selectedKind } = local);
3113
+ const max = outboundSourceLimit(account, selectedKind), file = await open(local.path, "r");
3089
3114
  let size;
3090
3115
  try {
3091
3116
  const stat = await file.stat();
@@ -3094,7 +3119,7 @@ async function sendNativeAttachment(client, account, threadId2, mediaUrl, audioA
3094
3119
  } finally {
3095
3120
  await file.close();
3096
3121
  }
3097
- blob = await openAsBlob(path, { type: mime });
3122
+ blob = await openAsBlob(local.path, { type: mime });
3098
3123
  if (blob.size !== size) throw new Error("Native outbound source changed before staging");
3099
3124
  }
3100
3125
  sourceBytes = blob.size;
@@ -3189,7 +3214,7 @@ function nativeDispatchManifest(params) {
3189
3214
  }))) } : {},
3190
3215
  assets,
3191
3216
  policySha256: digest(JSON.stringify(params.policy ?? null)),
3192
- // Exact source-turn identity of OpenClaw 2026.10.2 through 2026.10.9. Requiring it in the later
3217
+ // Exact source-turn identity of OpenClaw 2026.10.2 through 2026.11.2. Requiring it in the later
3193
3218
  // snapshot prevents an identical older image/body from proving this input.
3194
3219
  hostSourceTurnId: `channel-user:v1:${digest(JSON.stringify(["agent-wechat", params.channelAccountId, `wechat:${params.message.threadId}`, messageSid]))}`
3195
3220
  };
@@ -4140,9 +4165,12 @@ async function dispatchNativeMessageInput(params, revision) {
4140
4165
  }
4141
4166
  },
4142
4167
  // This hook is intentionally separate from onModelSelected and old
4143
- // onAgentRunStart (which can also report direct-tool execution). Released
4144
- // hosts without it need the separately verified text input/model-call
4145
- // and media-snapshot bridge; unsupported or ambiguous handoffs leave reads unchanged.
4168
+ // onAgentRunStart (which can also report direct-tool execution). Hosts that
4169
+ // implement it (OpenClaw 2026.11.2+) call it once the run's transcript is
4170
+ // prepared, before provider image filtering, and it confirms the handoff
4171
+ // without the conversation-hook grant. Hosts without it need the separately
4172
+ // verified text input/model-call and media-snapshot bridge; unsupported or
4173
+ // ambiguous handoffs leave reads unchanged.
4146
4174
  replyOptions: { runId: dispatchManifest.runId, onModelSelected, onPreparedAgentRunStart: callback }
4147
4175
  });
4148
4176
  params.signal?.throwIfAborted();
@@ -5054,7 +5082,7 @@ function createLookupTools(context, dependencies, archive) {
5054
5082
  name: name3,
5055
5083
  label: name3.replaceAll("_", " "),
5056
5084
  description,
5057
- // The pinned host's tool_call wrapper JSON-serializes image blocks. Its
5085
+ // The pinned host's dispatch_action wrapper JSON-serializes image blocks. Its
5058
5086
  // public direct-only surface preserves actual image content for vision.
5059
5087
  ...action === "media" ? { catalogMode: "direct-only" } : {},
5060
5088
  parameters: { type: "object", additionalProperties: false, properties, required },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-wechat/agent-wechat",
3
- "version": "2.2.0",
3
+ "version": "2.3.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "files": [
@@ -11,7 +11,7 @@
11
11
  "devDependencies": {
12
12
  "@types/node": "^22",
13
13
  "esbuild": "^0.25.0",
14
- "openclaw": "2026.10.9",
14
+ "openclaw": "2026.11.2",
15
15
  "typescript": "^5.4.5",
16
16
  "@agent-wechat/shared": "2.0.0"
17
17
  },