@agent-wechat/agent-wechat 2.1.0 → 2.2.1

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 +40 -14
  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
@@ -3022,6 +3022,27 @@ function validateNativeMediaSendOptions(options, audioAsVoice = false) {
3022
3022
  if (options.videoQuality != null && !["normal", "original"].includes(options.videoQuality)) throw new Error("Invalid WeChat video quality");
3023
3023
  if (options.forceDocument && (audioAsVoice || options.videoQuality != null)) throw new Error("Document sending cannot also request voice or video quality");
3024
3024
  }
3025
+ var nameMediaTypes = /* @__PURE__ */ new Map([
3026
+ [".png", "image/png"],
3027
+ [".jpg", "image/jpeg"],
3028
+ [".jpeg", "image/jpeg"],
3029
+ [".gif", "image/gif"],
3030
+ [".webp", "image/webp"],
3031
+ [".mp4", "video/mp4"],
3032
+ [".wav", "audio/wav"],
3033
+ [".mp3", "audio/mp3"],
3034
+ [".ogg", "audio/ogg"],
3035
+ [".oga", "audio/ogg"],
3036
+ [".opus", "audio/ogg"],
3037
+ [".m4a", "audio/m4a"],
3038
+ [".flac", "audio/flac"],
3039
+ [".aac", "audio/aac"],
3040
+ [".caf", "audio/x-caf"],
3041
+ [".amr", "audio/amr"]
3042
+ ]);
3043
+ function mediaTypeForName(filename) {
3044
+ return nameMediaTypes.get(extname(filename).toLowerCase()) ?? "application/octet-stream";
3045
+ }
3025
3046
  function outboundMediaKind(mime, audioAsVoice, options) {
3026
3047
  if (options.forceDocument) return "file";
3027
3048
  if (audioAsVoice && !mime.startsWith("audio/")) throw new Error("Voice sending requires an explicit audio attachment");
@@ -3029,22 +3050,28 @@ function outboundMediaKind(mime, audioAsVoice, options) {
3029
3050
  if (options.videoQuality != null && selected !== "video") throw new Error("Video quality requires a video attachment");
3030
3051
  return selected;
3031
3052
  }
3053
+ function localOutboundSource(mediaUrl, audioAsVoice, options) {
3054
+ const path = mediaUrl.startsWith("file:") ? new URL(mediaUrl) : mediaUrl, filename = basename(path instanceof URL ? path.pathname : path), mime = mediaTypeForName(filename);
3055
+ return { path, filename, mime, kind: outboundMediaKind(mime, audioAsVoice, options) };
3056
+ }
3032
3057
  function outboundSourceLimit(account, selectedKind) {
3033
3058
  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
3059
  }
3035
3060
  async function sendNativeAttachment(client, account, threadId2, mediaUrl, audioAsVoice = false, key2 = randomUUID2(), beforeSend, options = {}) {
3036
3061
  validateNativeMediaSendOptions(options, audioAsVoice);
3062
+ const local = /^https?:/.test(mediaUrl) ? void 0 : localOutboundSource(mediaUrl, audioAsVoice, options);
3037
3063
  await beforeSend?.();
3038
3064
  let filename, mime, selectedKind, sourceBytes, source;
3039
3065
  let temporary;
3040
3066
  const accountId = account.native.accountId;
3041
3067
  try {
3042
3068
  let blob;
3043
- if (/^https?:/.test(mediaUrl)) {
3069
+ if (!local) {
3044
3070
  const response = await fetch(mediaUrl, { redirect: "error", signal: AbortSignal.timeout(60 * 6e4) });
3045
3071
  if (!response.ok) throw new Error(`Native outbound source unavailable (${response.status})`);
3046
3072
  filename = basename(new URL(mediaUrl).pathname) || "attachment";
3047
- mime = response.headers.get("content-type")?.split(";")[0].trim().toLowerCase() ?? "application/octet-stream";
3073
+ const declared = response.headers.get("content-type")?.split(";")[0].trim().toLowerCase();
3074
+ mime = declared && declared !== "application/octet-stream" ? declared : mediaTypeForName(filename);
3048
3075
  try {
3049
3076
  selectedKind = outboundMediaKind(mime, audioAsVoice, options);
3050
3077
  } catch (error) {
@@ -3080,12 +3107,8 @@ async function sendNativeAttachment(client, account, threadId2, mediaUrl, audioA
3080
3107
  }
3081
3108
  blob = await openAsBlob(path, { type: mime });
3082
3109
  } 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");
3110
+ ({ filename, mime, kind: selectedKind } = local);
3111
+ const max = outboundSourceLimit(account, selectedKind), file = await open(local.path, "r");
3089
3112
  let size;
3090
3113
  try {
3091
3114
  const stat = await file.stat();
@@ -3094,7 +3117,7 @@ async function sendNativeAttachment(client, account, threadId2, mediaUrl, audioA
3094
3117
  } finally {
3095
3118
  await file.close();
3096
3119
  }
3097
- blob = await openAsBlob(path, { type: mime });
3120
+ blob = await openAsBlob(local.path, { type: mime });
3098
3121
  if (blob.size !== size) throw new Error("Native outbound source changed before staging");
3099
3122
  }
3100
3123
  sourceBytes = blob.size;
@@ -3189,7 +3212,7 @@ function nativeDispatchManifest(params) {
3189
3212
  }))) } : {},
3190
3213
  assets,
3191
3214
  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
3215
+ // Exact source-turn identity of OpenClaw 2026.10.2 through 2026.11.2. Requiring it in the later
3193
3216
  // snapshot prevents an identical older image/body from proving this input.
3194
3217
  hostSourceTurnId: `channel-user:v1:${digest(JSON.stringify(["agent-wechat", params.channelAccountId, `wechat:${params.message.threadId}`, messageSid]))}`
3195
3218
  };
@@ -4140,9 +4163,12 @@ async function dispatchNativeMessageInput(params, revision) {
4140
4163
  }
4141
4164
  },
4142
4165
  // 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.
4166
+ // onAgentRunStart (which can also report direct-tool execution). Hosts that
4167
+ // implement it (OpenClaw 2026.11.2+) call it once the run's transcript is
4168
+ // prepared, before provider image filtering, and it confirms the handoff
4169
+ // without the conversation-hook grant. Hosts without it need the separately
4170
+ // verified text input/model-call and media-snapshot bridge; unsupported or
4171
+ // ambiguous handoffs leave reads unchanged.
4146
4172
  replyOptions: { runId: dispatchManifest.runId, onModelSelected, onPreparedAgentRunStart: callback }
4147
4173
  });
4148
4174
  params.signal?.throwIfAborted();
@@ -5054,7 +5080,7 @@ function createLookupTools(context, dependencies, archive) {
5054
5080
  name: name3,
5055
5081
  label: name3.replaceAll("_", " "),
5056
5082
  description,
5057
- // The pinned host's tool_call wrapper JSON-serializes image blocks. Its
5083
+ // The pinned host's dispatch_action wrapper JSON-serializes image blocks. Its
5058
5084
  // public direct-only surface preserves actual image content for vision.
5059
5085
  ...action === "media" ? { catalogMode: "direct-only" } : {},
5060
5086
  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.1.0",
3
+ "version": "2.2.1",
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
  },