@agent-wechat/agent-wechat 2.2.1 → 2.3.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 (2) hide show
  1. package/dist/index.js +94 -36
  2. package/package.json +1 -1
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 });
@@ -2348,7 +2348,7 @@ ${reference}` : reference;
2348
2348
  function safeDisplayName(name3) {
2349
2349
  return name3.replace(/[\r\n\0]/g, " ").trim() || "attachment";
2350
2350
  }
2351
- function renderAttachmentBody(originalBody, attachment, exposeNonVisualPath = true) {
2351
+ function renderAttachmentBody(originalBody, attachment) {
2352
2352
  if (!attachment) return originalBody;
2353
2353
  const name3 = safeDisplayName(attachment.filename);
2354
2354
  if (attachment.status !== "ready" || !attachment.path) {
@@ -2363,19 +2363,9 @@ function renderAttachmentBody(originalBody, attachment, exposeNonVisualPath = tr
2363
2363
  }
2364
2364
  if (attachment.kind === "file") {
2365
2365
  const prefix2 = originalBody.trim() === name3 ? "" : originalBody;
2366
- return appendReference(prefix2, `[File: ${name3}]
2367
- [Local file: <${attachment.path}>]`);
2366
+ return appendReference(prefix2, `[File: ${name3}]`);
2368
2367
  }
2369
- if (exposeNonVisualPath) {
2370
- if (attachment.kind === "audio") {
2371
- return appendReference(originalBody || "<media:audio>", `[Voice message file: <${attachment.path}>]`);
2372
- }
2373
- if (attachment.kind === "video") {
2374
- return appendReference(originalBody || "<media:video>", `[Video file: <${attachment.path}>]`);
2375
- }
2376
- }
2377
- let body = originalBody || (attachment.kind === "image" ? "<media:image>" : originalBody);
2378
- if (attachment.kind === "image") body = appendReference(body, `[Image file: <${attachment.path}>]`);
2368
+ const body = originalBody || `<media:${attachment.kind}>`;
2379
2369
  if (attachment.kind === "image" && attachment.quality === "thumbnail") {
2380
2370
  return appendReference(body, "[Image preview only: thumbnail quality]");
2381
2371
  }
@@ -2547,7 +2537,7 @@ function sameEmbeddedQuote(stored, current) {
2547
2537
  if (stored.state === "unsupported" && current.state === "embedded")
2548
2538
  return ["serverId", "type", "appMessageType", "senderId", "direction"].every((field) => (stored[field] ?? null) === (current[field] ?? null));
2549
2539
  const compared = { ...current };
2550
- for (const field of ["embeddedLink", "embeddedSticker"]) {
2540
+ for (const field of ["embeddedLink", "embeddedSticker", "senderName"]) {
2551
2541
  if (!Object.hasOwn(stored, field)) delete compared[field];
2552
2542
  }
2553
2543
  return JSON.stringify(stored) === JSON.stringify(compared);
@@ -2570,8 +2560,10 @@ function renderEmbeddedQuote(message, permitted = true, imageBody) {
2570
2560
  if (state === "embedded" && !image && !source.embeddedText) return unavailable("invalid");
2571
2561
  const content = state === "missing" ? "" : image ? imageBody ?? "[Image metadata embedded in quote; image not retrieved]" : source.embeddedText ?? "";
2572
2562
  const status = state === "unsupported" ? `[${label2} attachment unavailable from embedded quote]` : state === "missing" ? "[Embedded quote content unavailable]" : "";
2563
+ const suppliedName = source.senderName;
2564
+ const author = typeof suppliedName === "string" && suppliedName.trim() && suppliedName.length <= 4096 && !/[\u0000-\u001f\u007f-\u009f]/.test(suppliedName) ? suppliedName : source.senderId ?? "unknown sender";
2573
2565
  return {
2574
- body: `${comment}${comment ? "\n\n" : ""}[Quoted ${label2} from ${source.senderId ?? "unknown sender"}; embedded in reply]
2566
+ body: `${comment}${comment ? "\n\n" : ""}[Quoted ${label2} from ${author}; embedded in reply]
2575
2567
  ${[content, status].filter(Boolean).join("\n")}
2576
2568
  [/Quoted message]`,
2577
2569
  image,
@@ -2986,8 +2978,8 @@ async function prepareNativeAttachmentInput(params) {
2986
2978
  suppliedHash = normalized.sha256;
2987
2979
  suppliedLength = normalized.size;
2988
2980
  body += wxgf ? `
2989
- [Model image: WXGF still preview; original retained separately; animation and transparency are not represented]` : `
2990
- [Model image: prepared still preview; original retained separately]`;
2981
+ [Model image: WXGF still preview; original attached separately; animation and transparency are not represented]` : `
2982
+ [Model image: prepared still preview; original attached separately]`;
2991
2983
  }
2992
2984
  }
2993
2985
  guard2();
@@ -3157,6 +3149,33 @@ async function sendNativeAttachment(client, account, threadId2, mediaUrl, audioA
3157
3149
  // src/native-prepared-boundary.ts
3158
3150
  import { createHash as createHash7, randomUUID as randomUUID3 } from "node:crypto";
3159
3151
  import { basename as basename2, isAbsolute as isAbsolute2 } from "node:path";
3152
+
3153
+ // src/native-media-facts.ts
3154
+ function nativeMediaFacts(assets, transcribedMessageIds = /* @__PURE__ */ new Set()) {
3155
+ const facts = [];
3156
+ for (const asset of assets) {
3157
+ const kind2 = asset.kind !== "file" ? asset.kind : asset.mime.startsWith("image/") ? "image" : "document";
3158
+ const shared = {
3159
+ kind: kind2,
3160
+ ...asset.fileName ? { fileName: asset.fileName } : {},
3161
+ ...asset.messageId ? { messageId: asset.messageId } : {}
3162
+ };
3163
+ facts.push({
3164
+ path: asset.path,
3165
+ url: asset.path,
3166
+ contentType: asset.mime,
3167
+ ...shared,
3168
+ ...asset.kind === "audio" && asset.messageId && transcribedMessageIds.has(asset.messageId) ? { transcribed: true } : {},
3169
+ ...kind2 === "image" && !asset.runtimeMedia ? { hydrationSuppressed: true } : {}
3170
+ });
3171
+ if (asset.role === "model_image" && asset.sourcePath && asset.sourcePath !== asset.path) {
3172
+ facts.push({ path: asset.sourcePath, url: asset.sourcePath, contentType: asset.sourceMime ?? asset.mime, ...shared, hydrationSuppressed: true });
3173
+ }
3174
+ }
3175
+ return facts;
3176
+ }
3177
+
3178
+ // src/native-prepared-boundary.ts
3160
3179
  var pending = /* @__PURE__ */ new Map();
3161
3180
  var enabled = false;
3162
3181
  var digest = (value) => createHash7("sha256").update(value).digest("hex");
@@ -3170,7 +3189,7 @@ function nativeDispatchManifest(params) {
3170
3189
  const history = params.history ?? [];
3171
3190
  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");
3172
3191
  const assets = Object.freeze((params.assets ?? []).map((asset) => {
3173
- 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" || !isAbsolute2(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");
3192
+ 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" || !isAbsolute2(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.fileName != null && (typeof asset.fileName !== "string" || !asset.fileName || asset.fileName.length > 4096) || 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");
3174
3193
  return Object.freeze({ ...asset });
3175
3194
  }));
3176
3195
  const messageSid = nativeSourceMessageSid(params.message);
@@ -3247,17 +3266,48 @@ ${JSON.stringify({ sender: { id: manifest.senderId } })}
3247
3266
  return candidates.some((text4) => normalizedPromptMatches(text4, manifest));
3248
3267
  }
3249
3268
  function normalizedPromptMatches(text3, manifest) {
3250
- const runtimeAssets = manifest.assets.filter((asset) => asset.runtimeMedia);
3251
- if (runtimeAssets.length) {
3252
- if (runtimeAssets.length !== 1) return false;
3253
- const asset = runtimeAssets[0];
3254
- const header = /^\[media attached: ([^\r\n]+) \(([^)\r\n]+)\) \| (media:\/\/inbound\/[^\]\r\n]+)\]\n/.exec(text3);
3255
- if (!header || !isAbsolute2(header[1]) || basename2(header[1]) !== `input-${basename2(asset.path)}` || header[2] !== asset.mime || header[3] !== `media://inbound/${basename2(asset.path)}`) return false;
3256
- text3 = text3.slice(header[0].length);
3257
- if (asset.kind === "video") text3 = text3.replace(/\n\n\[Video attachment not analyzed: video understanding is disabled\]$/, "");
3258
- }
3269
+ const facts = nativeMediaFacts(manifest.assets);
3270
+ const rest = stripMediaNote(text3, facts);
3271
+ if (rest === void 0) return false;
3272
+ text3 = facts.some((fact) => fact.kind === "video") ? rest.replace(/\n\n\[Video attachment not analyzed: video understanding is disabled\]$/, "") : rest;
3259
3273
  return digest(text3) === manifest.inputBodySha256;
3260
3274
  }
3275
+ function stripMediaNote(text3, facts) {
3276
+ if (!facts.length) return text3;
3277
+ const lines = text3.split("\n");
3278
+ const summary = /^\[media attached: (\d{1,3}) files\]$/.exec(lines[0] ?? "");
3279
+ const count = summary ? Number(summary[1]) : lines[0]?.startsWith("[media attached: ") ? 1 : 0;
3280
+ if (summary && count < 2 || count > facts.length) return void 0;
3281
+ let line = summary ? 1 : 0, next = 0;
3282
+ for (let index = 1; index <= count; index++, line++) {
3283
+ const prefix2 = count > 1 ? `[media attached ${index}/${count}: ` : "[media attached: ";
3284
+ const value = lines[line];
3285
+ if (!value?.startsWith(prefix2) || !value.endsWith("]")) return void 0;
3286
+ for (; ; ) {
3287
+ const fact = facts[next++];
3288
+ if (!fact) return void 0;
3289
+ if (mediaLineMatches(value.slice(prefix2.length, -1), fact)) break;
3290
+ if (fact.kind !== "audio") return void 0;
3291
+ }
3292
+ }
3293
+ return facts.slice(next).every((fact) => fact.kind === "audio") ? lines.slice(line).join("\n") : void 0;
3294
+ }
3295
+ function mediaLineMatches(line, fact) {
3296
+ const name3 = basename2(fact.path), ref = `media://inbound/${name3}`, type = ` (${fact.contentType})`;
3297
+ let shown = fact.fileName ? basename2(fact.fileName).replace(/[\p{Cc}\]]+/gu, " ").replace(/\s+/g, " ").trim().slice(0, 256) : "";
3298
+ if (/[\uD800-\uDBFF]$/.test(shown)) shown = shown.slice(0, -1);
3299
+ const suffix = shown ? ` ${JSON.stringify(shown)}` : "";
3300
+ if (!line.endsWith(suffix)) return false;
3301
+ const value = suffix ? line.slice(0, -suffix.length) : line;
3302
+ if (value === `${ref}${type}` || value === `${fact.path}${type}`) return true;
3303
+ const staged = (path2) => !!path2 && !path2.split("/").includes("..") && basename2(path2).startsWith("input-");
3304
+ for (const origin of [ref, fact.path]) {
3305
+ const tail = `${type} | ${origin}`;
3306
+ if (value.endsWith(tail) && staged(value.slice(0, -tail.length))) return true;
3307
+ }
3308
+ const path = value.endsWith(type) ? value.slice(0, -type.length) : "";
3309
+ return staged(path) && basename2(path) === `input-${name3}`;
3310
+ }
3261
3311
  function currentMessageFacts(messages) {
3262
3312
  if (!Array.isArray(messages) || messages.length > 1e3) return [];
3263
3313
  const facts = [];
@@ -3328,7 +3378,6 @@ function observeNativeAgentEnd(event, ctx) {
3328
3378
  const bytes = Buffer.from(image.data, "base64");
3329
3379
  if (bytes.length !== asset.byteLength || digest(bytes) !== asset.sha256) return;
3330
3380
  }
3331
- if (m.assets.some((asset) => asset.role === "file_reference" && !text3.includes(asset.path))) return;
3332
3381
  item.record(m.runId);
3333
3382
  pending.delete(m.runId);
3334
3383
  }
@@ -3540,6 +3589,7 @@ function createWeChatMediaHandlers(send = sendWeChatMedia) {
3540
3589
  import { createHash as createHash11 } from "node:crypto";
3541
3590
  import { createChannelMessageReplyPipeline } from "openclaw/plugin-sdk/channel-outbound";
3542
3591
  import { resolveStableChannelMessageIngress } from "openclaw/plugin-sdk/channel-ingress-runtime";
3592
+ import { toInboundMediaFacts } from "openclaw/plugin-sdk/channel-inbound";
3543
3593
 
3544
3594
  // src/native-consumer-state.ts
3545
3595
  import { createHash as createHash10, randomUUID as randomUUID5 } from "node:crypto";
@@ -3810,8 +3860,12 @@ async function transcribeNativeAttachment(prepared, core, cfg) {
3810
3860
  transcript = (await core.mediaUnderstanding.transcribeAudioFile({ filePath: attachment.path, cfg, mime: attachment.mime })).text?.trim() ?? "";
3811
3861
  } catch {
3812
3862
  }
3813
- return { ...prepared, body: `${prepared.body}
3814
- ${transcript ? `[Voice transcript: ${transcript.slice(0, 1e4)}]` : "[Voice transcription unavailable]"}` };
3863
+ return {
3864
+ ...prepared,
3865
+ body: `${prepared.body}
3866
+ ${transcript ? `[Voice transcript: ${transcript.slice(0, 1e4)}]` : "[Voice transcription unavailable]"}`,
3867
+ ...transcript ? { transcribed: true } : {}
3868
+ };
3815
3869
  }
3816
3870
  async function prepareNativeHistory(messages, prepare) {
3817
3871
  const result = new Array(messages.length);
@@ -3838,9 +3892,11 @@ function buildNativeContext(history, message, prepared) {
3838
3892
  const selected = history.length ? image : all.at(-1);
3839
3893
  const assets = all.flatMap((item) => (item.prepared.suppliedAssets ?? []).map((asset) => {
3840
3894
  const contextRole = item.message.id === message.id ? "trigger" : "history";
3841
- if (item === selected) return { ...asset, contextRole, messageId: item.message.id };
3895
+ const fileName = item.prepared.attachment?.filename ? { fileName: item.prepared.attachment.filename } : {};
3896
+ if (item === selected) return { ...asset, ...fileName, contextRole, messageId: item.message.id };
3842
3897
  return {
3843
3898
  ...asset,
3899
+ ...fileName,
3844
3900
  contextRole,
3845
3901
  messageId: item.message.id,
3846
3902
  runtimeMedia: false,
@@ -3873,13 +3929,13 @@ function buildNativeContext(history, message, prepared) {
3873
3929
  sender: item.message.senderId
3874
3930
  }] : [];
3875
3931
  });
3932
+ const transcribed = new Set(all.flatMap((item) => item.prepared.transcribed ? [item.message.id] : []));
3876
3933
  return {
3877
3934
  inputBody,
3878
3935
  attachments,
3879
3936
  assets,
3880
3937
  history: buildInboundHistoryFromEntries({ entries, limit: entries.length }),
3881
- mediaPath: selected?.prepared.mediaPath,
3882
- mediaMime: selected?.prepared.mediaMime
3938
+ media: nativeMediaFacts(assets, transcribed)
3883
3939
  };
3884
3940
  }
3885
3941
 
@@ -4104,7 +4160,9 @@ async function dispatchNativeMessageInput(params, revision) {
4104
4160
  CommandAuthorized: core.channel.commands.shouldComputeCommandAuthorized(commandBody, cfg) ? ingress.commandAccess.authorized : void 0,
4105
4161
  OriginatingChannel: "agent-wechat",
4106
4162
  OriginatingTo: `wechat:${message.threadId}`,
4107
- ...context.mediaPath ? { MediaPath: context.mediaPath, MediaUrl: context.mediaPath, MediaType: context.mediaMime } : {}
4163
+ // OpenClaw's media contract: it lists each attachment for the agent, stages
4164
+ // it into a sandboxed workspace and hydrates only unsuppressed images/video.
4165
+ ...context.media.length ? { media: toInboundMediaFacts(context.media) } : {}
4108
4166
  });
4109
4167
  await core.channel.session.recordInboundSession({ storePath, sessionKey: route.sessionKey, ctx });
4110
4168
  await recheck([message, ...admitted]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-wechat/agent-wechat",
3
- "version": "2.2.1",
3
+ "version": "2.3.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "files": [