@agent-wechat/agent-wechat 1.0.0 → 1.2.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 +503 -297
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -483,15 +483,46 @@ var NativeWeChatClient = class {
|
|
|
483
483
|
}
|
|
484
484
|
return result;
|
|
485
485
|
}
|
|
486
|
-
/**
|
|
487
|
-
*
|
|
486
|
+
/** Send text with optional group mentions, or quote a locally stored message in the same chat.
|
|
487
|
+
* Quoted-reply live acceptance and recipient rendering remain unverified; unsupported targets are rejected.
|
|
488
488
|
*/
|
|
489
|
-
sendText(accountId, threadId2, text3, idempotencyKey,
|
|
489
|
+
sendText(accountId, threadId2, text3, idempotencyKey, quoteOrOptions) {
|
|
490
490
|
if (!idempotencyKey || /[\r\n]/.test(idempotencyKey))
|
|
491
491
|
throw new Error("An idempotency key is required");
|
|
492
|
+
const options = quoteOrOptions && typeof quoteOrOptions === "object" && "mentions" in quoteOrOptions ? quoteOrOptions : void 0;
|
|
493
|
+
const quote = options === void 0 ? quoteOrOptions : void 0;
|
|
494
|
+
if (options !== void 0) {
|
|
495
|
+
const mentions = options.mentions;
|
|
496
|
+
const ids = mentions?.userIds ?? [];
|
|
497
|
+
if (Object.keys(options).some((key) => key !== "mentions") || !threadId2.endsWith("@chatroom") || !mentions || typeof mentions !== "object" || Array.isArray(mentions) || Object.keys(mentions).some((key) => key !== "userIds" && key !== "all" && key !== "positions") || mentions.userIds !== void 0 && !Array.isArray(mentions.userIds) || mentions.all !== void 0 && typeof mentions.all !== "boolean" || !Array.isArray(ids) || ids.length > 128 || new Set(ids).size !== ids.length || mentions.all === true === ids.length > 0 || ids.some((id2) => typeof id2 !== "string" || !/^[A-Za-z0-9_@.-]{1,256}$/.test(id2) || id2 === "notify@all"))
|
|
498
|
+
throw new Error("Invalid text mentions");
|
|
499
|
+
const positions = mentions.positions ?? [];
|
|
500
|
+
if (mentions.positions !== void 0 && !Array.isArray(mentions.positions) || positions.length > 256)
|
|
501
|
+
throw new Error("Invalid text mentions");
|
|
502
|
+
if (positions.length) {
|
|
503
|
+
const boundary = (offset) => !(offset > 0 && offset < text3.length && text3.charCodeAt(offset - 1) >= 55296 && text3.charCodeAt(offset - 1) <= 56319 && text3.charCodeAt(offset) >= 56320 && text3.charCodeAt(offset) <= 57343);
|
|
504
|
+
const covered = /* @__PURE__ */ new Set();
|
|
505
|
+
const recipients = mentions.all === true ? 1 : ids.length;
|
|
506
|
+
let previous = 0;
|
|
507
|
+
if (!text3 || text3.includes("\0") || new TextEncoder().encode(text3).length > 65536)
|
|
508
|
+
throw new Error("Invalid text mentions");
|
|
509
|
+
for (const position of positions) {
|
|
510
|
+
if (!position || typeof position !== "object" || Array.isArray(position) || Object.keys(position).some((key) => !["start", "end", "index"].includes(key)) || !Number.isSafeInteger(position.start) || !Number.isSafeInteger(position.end) || !Number.isSafeInteger(position.index) || position.start < previous || position.start >= position.end || position.end > text3.length || position.index < 0 || position.index >= recipients || !boundary(position.start) || !boundary(position.end))
|
|
511
|
+
throw new Error("Invalid text mentions");
|
|
512
|
+
const span = text3.slice(position.start, position.end);
|
|
513
|
+
const label = span.slice(1, -1);
|
|
514
|
+
if (!span.startsWith("@") || !span.endsWith("\u2005") || !label.trim() || new TextEncoder().encode(label).length > 1024 || /[\u0000-\u001f\u007f-\u009f\u2005\ud800-\udfff]/u.test(label))
|
|
515
|
+
throw new Error("Invalid text mentions");
|
|
516
|
+
covered.add(position.index);
|
|
517
|
+
previous = position.end;
|
|
518
|
+
}
|
|
519
|
+
if (covered.size !== recipients)
|
|
520
|
+
throw new Error("Invalid text mentions");
|
|
521
|
+
}
|
|
522
|
+
}
|
|
492
523
|
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
524
|
throw new Error("Invalid quote message identity");
|
|
494
|
-
const input = quote === void 0 ? { threadId: threadId2, text: text3 } : { kind: "text", threadId: threadId2, text: text3, quote };
|
|
525
|
+
const input = options !== void 0 ? { kind: "text", threadId: threadId2, text: text3, mentions: options.mentions } : quote === void 0 ? { threadId: threadId2, text: text3 } : { kind: "text", threadId: threadId2, text: text3, quote };
|
|
495
526
|
return this.request(`v1/accounts/${id(accountId)}/sends`, { method: "POST", headers: { "Idempotency-Key": idempotencyKey }, body: JSON.stringify(input) });
|
|
496
527
|
}
|
|
497
528
|
send(accountId, sendId, signal) {
|
|
@@ -1101,8 +1132,8 @@ function normalizeWeChatCommandBody(raw, params) {
|
|
|
1101
1132
|
if (!prefix) {
|
|
1102
1133
|
return trimmed.slice(commandStart).trimStart();
|
|
1103
1134
|
}
|
|
1104
|
-
const
|
|
1105
|
-
if (!
|
|
1135
|
+
const hasMentionSeparator = rawPrefix.includes("\u2005") || trimmed[commandStart] === "\u2005";
|
|
1136
|
+
if (!hasMentionSeparator) {
|
|
1106
1137
|
return trimmed;
|
|
1107
1138
|
}
|
|
1108
1139
|
const mentionRegion = rawPrefix + (trimmed[commandStart] === "\u2005" ? "\u2005" : "");
|
|
@@ -1222,12 +1253,9 @@ function resolveWeChatIngress(params) {
|
|
|
1222
1253
|
});
|
|
1223
1254
|
}
|
|
1224
1255
|
|
|
1225
|
-
// src/outbound-options.ts
|
|
1226
|
-
import { createHash as createHash6 } from "node:crypto";
|
|
1227
|
-
|
|
1228
1256
|
// src/outbound-media.ts
|
|
1229
|
-
import { createHash as
|
|
1230
|
-
import { randomUUID as
|
|
1257
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
1258
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
1231
1259
|
|
|
1232
1260
|
// src/native-media.ts
|
|
1233
1261
|
import { createHash as createHash4, randomUUID } from "node:crypto";
|
|
@@ -1343,6 +1371,24 @@ function renderAttachmentBody(originalBody, attachment, exposeNonVisualPath = tr
|
|
|
1343
1371
|
return body;
|
|
1344
1372
|
}
|
|
1345
1373
|
|
|
1374
|
+
// src/outbound-mentions.ts
|
|
1375
|
+
function parseWeChatTextMentions(value) {
|
|
1376
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw Error("Invalid WeChat mentions");
|
|
1377
|
+
const mentions = value;
|
|
1378
|
+
const ids = mentions.userIds;
|
|
1379
|
+
if (Object.keys(mentions).some((key) => key !== "userIds" && key !== "all") || mentions.all !== void 0 && mentions.all !== true || (mentions.all === true ? ids !== void 0 : !Array.isArray(ids) || !ids.length) || Array.isArray(ids) && (ids.length > 128 || new Set(ids).size !== ids.length || ids.some((id2) => typeof id2 !== "string" || !/^[A-Za-z0-9_@.-]{1,256}$/.test(id2) || id2 === "notify@all"))) throw Error("Invalid WeChat mentions");
|
|
1380
|
+
return mentions.all === true ? { all: true } : { userIds: [...ids] };
|
|
1381
|
+
}
|
|
1382
|
+
function validateWeChatMentionSend(mentions, input) {
|
|
1383
|
+
if (!mentions) return;
|
|
1384
|
+
parseWeChatTextMentions(mentions);
|
|
1385
|
+
if (!input.to.endsWith("@chatroom")) throw Error("WeChat mentions require a group conversation");
|
|
1386
|
+
if (typeof input.text !== "string" || !input.text.trim()) throw Error("WeChat mentions require a text message");
|
|
1387
|
+
if (input.mediaUrl || input.mediaUrls?.length || input.audioAsVoice || input.forceDocument || input.videoQuality != null || input.replyToId != null) {
|
|
1388
|
+
throw Error("WeChat mentions support group text only; do not combine with attachments, voice, document, video quality or quoted replies");
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1346
1392
|
// src/native-send.ts
|
|
1347
1393
|
async function nativeOutboundDelivery(client, accountId, threadId2, messageIds, source) {
|
|
1348
1394
|
const receipts = [];
|
|
@@ -1375,18 +1421,59 @@ async function nativeOutboundDelivery(client, accountId, threadId2, messageIds,
|
|
|
1375
1421
|
receiptState: "verified"
|
|
1376
1422
|
} };
|
|
1377
1423
|
}
|
|
1424
|
+
var NativeTextSendInspectionError = class extends Error {
|
|
1425
|
+
code = "native_text_send_inspection_required";
|
|
1426
|
+
retryable = false;
|
|
1427
|
+
accountId;
|
|
1428
|
+
threadId;
|
|
1429
|
+
idempotencyKey;
|
|
1430
|
+
state;
|
|
1431
|
+
sendId;
|
|
1432
|
+
constructor(accountId, threadId2, idempotencyKey, state, sendId) {
|
|
1433
|
+
super(`Native text send requires inspection (${state}); retain the original idempotency key and do not automatically resend`);
|
|
1434
|
+
this.name = "NativeTextSendInspectionError";
|
|
1435
|
+
this.accountId = accountId;
|
|
1436
|
+
this.threadId = threadId2;
|
|
1437
|
+
this.idempotencyKey = idempotencyKey;
|
|
1438
|
+
this.state = state;
|
|
1439
|
+
this.sendId = sendId;
|
|
1440
|
+
}
|
|
1441
|
+
};
|
|
1378
1442
|
async function submitNativeText(client, accountId, threadId2, text3, key, options = {}) {
|
|
1379
|
-
|
|
1443
|
+
const mentions = options.mentions === void 0 ? void 0 : parseWeChatTextMentions(options.mentions);
|
|
1444
|
+
validateWeChatMentionSend(mentions, { to: threadId2, text: text3, replyToId: options.quote?.messageId });
|
|
1445
|
+
const inspect = (value, sendId) => {
|
|
1446
|
+
const intent2 = value;
|
|
1447
|
+
if (!intent2 || typeof intent2 !== "object" || Array.isArray(intent2) || typeof intent2.id !== "string" || !intent2.id || intent2.accountId !== void 0 && intent2.accountId !== accountId || intent2.destination !== void 0 && intent2.destination !== threadId2 || intent2.kind !== void 0 || intent2.threadId !== void 0 || typeof intent2.state !== "string" || sendId !== void 0 && intent2.id !== sendId) throw new NativeTextSendInspectionError(accountId, threadId2, key, "receipt_identity_mismatch", sendId);
|
|
1448
|
+
return { ...intent2, accountId, destination: threadId2 };
|
|
1449
|
+
};
|
|
1450
|
+
let intent;
|
|
1451
|
+
try {
|
|
1452
|
+
intent = inspect(await client.sendText(accountId, threadId2, text3, key, options.quote ?? (mentions ? { mentions } : void 0)));
|
|
1453
|
+
} catch (error) {
|
|
1454
|
+
if (error instanceof NativeTextSendInspectionError || error instanceof NativeApiError && error.status < 500 && error.code !== "timeout") throw error;
|
|
1455
|
+
try {
|
|
1456
|
+
intent = inspect(await client.sendByKey(accountId, key));
|
|
1457
|
+
} catch (lookupError) {
|
|
1458
|
+
if (lookupError instanceof NativeTextSendInspectionError) throw lookupError;
|
|
1459
|
+
throw new NativeTextSendInspectionError(accountId, threadId2, key, "submission_unknown");
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1380
1462
|
const deadline = Date.now() + Math.max(1, Math.min(options.timeoutMs ?? 65e3, 65e3));
|
|
1381
1463
|
let delay2 = Math.max(1, Math.min(options.initialDelayMs ?? 250, 1e3));
|
|
1382
1464
|
while (["queued", "submitting"].includes(intent.state) && Date.now() < deadline) {
|
|
1383
1465
|
await new Promise((resolve) => setTimeout(resolve, Math.min(delay2, deadline - Date.now())));
|
|
1384
1466
|
const remaining = deadline - Date.now();
|
|
1385
1467
|
if (remaining <= 0) break;
|
|
1386
|
-
|
|
1468
|
+
try {
|
|
1469
|
+
intent = inspect(await client.send(accountId, intent.id, AbortSignal.timeout(remaining)), intent.id);
|
|
1470
|
+
} catch (error) {
|
|
1471
|
+
if (error instanceof NativeTextSendInspectionError) throw error;
|
|
1472
|
+
throw new NativeTextSendInspectionError(accountId, threadId2, key, "status_unavailable", intent.id);
|
|
1473
|
+
}
|
|
1387
1474
|
delay2 = Math.min(delay2 * 2, 1e3);
|
|
1388
1475
|
}
|
|
1389
|
-
if (!["accepted", "sent", "server_accepted"].includes(intent.state)) throw new
|
|
1476
|
+
if (!["accepted", "sent", "server_accepted"].includes(intent.state)) throw new NativeTextSendInspectionError(accountId, threadId2, key, intent.state, intent.id);
|
|
1390
1477
|
return intent;
|
|
1391
1478
|
}
|
|
1392
1479
|
|
|
@@ -1460,7 +1547,7 @@ function renderEmbeddedQuote(message, permitted = true, imageBody) {
|
|
|
1460
1547
|
const state = source.state ?? "missing";
|
|
1461
1548
|
if (state === "recalled") return unavailable("recalled");
|
|
1462
1549
|
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";
|
|
1550
|
+
const label = source.type === 1 || source.type === 49 && source.appMessageType === 1 ? "text" : source.type === 3 ? "image" : source.type === 34 ? "voice" : source.type === 43 ? "video" : source.type === 49 && source.appMessageType === 51 ? "Channels card" : source.type === 49 && source.appMessageType === 74 ? "file upload notice" : source.type === 49 && source.appMessageType === 87 ? "group announcement" : source.type === 49 && [3, 4, 5].includes(source.appMessageType ?? 0) ? "link" : source.type === 49 && source.appMessageType === 6 ? "file" : "message";
|
|
1464
1551
|
const image = state === "embedded" && source.type === 3 && source.embeddedImage === true;
|
|
1465
1552
|
if (state === "embedded" && !image && !source.embeddedText) return unavailable("invalid");
|
|
1466
1553
|
const content = state === "missing" ? "" : image ? imageBody ?? "[Image metadata embedded in quote; image not retrieved]" : source.embeddedText ?? "";
|
|
@@ -1696,8 +1783,9 @@ async function prepareNativeAttachmentInput(params) {
|
|
|
1696
1783
|
guard2();
|
|
1697
1784
|
};
|
|
1698
1785
|
if (message.type === 49 && message.appMessageType === 57) return prepareNativeQuote(params);
|
|
1786
|
+
if (message.type === 49 && [1, 74, 87].includes(message.appMessageType ?? 0)) return { body: message.body?.slice(0, 32768) || "[Shared text unavailable]", pending: false };
|
|
1699
1787
|
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);
|
|
1788
|
+
if (message.type === 49 && [3, 4, 5, 51].includes(message.appMessageType ?? 0) && message.link) return prepareNativeLink(params);
|
|
1701
1789
|
if (message.type === 49 && message.appMessageType != null && message.appMessageType !== 6) return { body: `[Unsupported WeChat app message subtype ${message.appMessageType}]`, pending: false, retryable: false };
|
|
1702
1790
|
if (!attachmentKind) return { body: message.type === 1 ? message.body ?? "" : `[Unsupported WeChat message type ${message.type}]`, pending: false };
|
|
1703
1791
|
const accountId = account.native.accountId;
|
|
@@ -2024,18 +2112,242 @@ async function sendNativeAttachment(client, account, threadId2, mediaUrl, audioA
|
|
|
2024
2112
|
return nativeOutboundDelivery(client, accountId, threadId2, mediaSendReceiptIds(job, audioAsVoice), { jobId: job.id, state: job.state, serverIds });
|
|
2025
2113
|
}
|
|
2026
2114
|
|
|
2115
|
+
// src/native-prepared-boundary.ts
|
|
2116
|
+
import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
|
|
2117
|
+
import { basename as basename2, isAbsolute as isAbsolute2 } from "node:path";
|
|
2118
|
+
var pending = /* @__PURE__ */ new Map();
|
|
2119
|
+
var enabled = false;
|
|
2120
|
+
var digest = (value) => createHash5("sha256").update(value).digest("hex");
|
|
2121
|
+
function prune() {
|
|
2122
|
+
for (const [id2, item] of pending) if (item.expires < Date.now()) pending.delete(id2);
|
|
2123
|
+
}
|
|
2124
|
+
function nativeSourceMessageSid(message) {
|
|
2125
|
+
return `wechat-native:${message.accountId}:${message.id}:${digest(JSON.stringify([message.threadId, message.serverId ?? null]))}`;
|
|
2126
|
+
}
|
|
2127
|
+
function nativeDispatchManifest(params) {
|
|
2128
|
+
const history = params.history ?? [];
|
|
2129
|
+
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");
|
|
2130
|
+
const assets = Object.freeze((params.assets ?? []).map((asset) => {
|
|
2131
|
+
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");
|
|
2132
|
+
return Object.freeze({ ...asset });
|
|
2133
|
+
}));
|
|
2134
|
+
const messageSid = nativeSourceMessageSid(params.message);
|
|
2135
|
+
const manifest = {
|
|
2136
|
+
schemaVersion: 2,
|
|
2137
|
+
runId: randomUUID2(),
|
|
2138
|
+
accountId: params.message.accountId,
|
|
2139
|
+
messageIds: Object.freeze([params.message.id]),
|
|
2140
|
+
messageSid,
|
|
2141
|
+
threadId: params.message.threadId,
|
|
2142
|
+
senderId: params.message.senderId ?? "",
|
|
2143
|
+
sessionKey: params.sessionKey,
|
|
2144
|
+
agentId: params.agentId,
|
|
2145
|
+
channelAccountId: params.channelAccountId,
|
|
2146
|
+
inputBodySha256: digest(params.inputBody),
|
|
2147
|
+
newInputs: Object.freeze([Object.freeze({
|
|
2148
|
+
id: params.message.id,
|
|
2149
|
+
version: params.message.version ?? "",
|
|
2150
|
+
contentSha256: digest(JSON.stringify([
|
|
2151
|
+
params.message.id,
|
|
2152
|
+
params.message.version,
|
|
2153
|
+
params.message.senderId,
|
|
2154
|
+
params.message.type,
|
|
2155
|
+
params.message.body,
|
|
2156
|
+
params.message.mentions,
|
|
2157
|
+
params.message.serverId,
|
|
2158
|
+
params.message.appMessageType,
|
|
2159
|
+
params.message.quote,
|
|
2160
|
+
params.message.link
|
|
2161
|
+
])),
|
|
2162
|
+
role: "trigger"
|
|
2163
|
+
})]),
|
|
2164
|
+
...history.length ? { historyInputs: Object.freeze(history.map((message) => Object.freeze({
|
|
2165
|
+
id: message.id,
|
|
2166
|
+
version: message.version ?? "",
|
|
2167
|
+
contentSha256: digest(JSON.stringify([message.id, message.version, message.senderId, message.type, message.body, message.mentions, message.serverId, message.appMessageType, message.quote, message.link])),
|
|
2168
|
+
role: "history"
|
|
2169
|
+
}))) } : {},
|
|
2170
|
+
assets,
|
|
2171
|
+
policySha256: digest(JSON.stringify(params.policy ?? null)),
|
|
2172
|
+
// Exact source-turn identity of OpenClaw 2026.10.2 through 2026.10.7. Requiring it in the later
|
|
2173
|
+
// snapshot prevents an identical older image/body from proving this input.
|
|
2174
|
+
hostSourceTurnId: `channel-user:v1:${digest(JSON.stringify(["agent-wechat", params.channelAccountId, `wechat:${params.message.threadId}`, messageSid]))}`
|
|
2175
|
+
};
|
|
2176
|
+
return Object.freeze({ ...manifest, manifestSha256: digest(JSON.stringify(manifest)) });
|
|
2177
|
+
}
|
|
2178
|
+
function trackNativePreparedInput(manifest, record) {
|
|
2179
|
+
prune();
|
|
2180
|
+
if (!enabled || pending.size >= 1024) return;
|
|
2181
|
+
pending.set(manifest.runId, { manifest, record, expires: Date.now() + 15 * 60 * 1e3 });
|
|
2182
|
+
}
|
|
2183
|
+
function invalidateNativePreparedInputs(accountId, messageIds) {
|
|
2184
|
+
const ids = new Set(messageIds);
|
|
2185
|
+
for (const [runId, item] of pending) {
|
|
2186
|
+
if (item.manifest.accountId === accountId && [
|
|
2187
|
+
...item.manifest.messageIds,
|
|
2188
|
+
...(item.manifest.historyInputs ?? []).map((input) => input.id),
|
|
2189
|
+
...item.manifest.assets.flatMap((asset) => asset.sourceMessageId ? [asset.sourceMessageId] : [])
|
|
2190
|
+
].some((id2) => ids.has(id2))) pending.delete(runId);
|
|
2191
|
+
}
|
|
2192
|
+
}
|
|
2193
|
+
function promptMatches(prompt, manifest) {
|
|
2194
|
+
if (typeof prompt !== "string" || Buffer.byteLength(prompt) > 1024 * 1024) return false;
|
|
2195
|
+
const text3 = prompt.replace(/^\[[^\]\r\n]{1,96}\] /, "");
|
|
2196
|
+
const candidates = [text3];
|
|
2197
|
+
const sender = `Conversation info: \u27E6openclaw:ctx\u27E7
|
|
2198
|
+
\`\`\`json
|
|
2199
|
+
${JSON.stringify({ sender: { id: manifest.senderId } })}
|
|
2200
|
+
\`\`\`
|
|
2201
|
+
|
|
2202
|
+
`;
|
|
2203
|
+
if (manifest.threadId.endsWith("@chatroom") && text3.startsWith(sender)) candidates.push(text3.slice(sender.length));
|
|
2204
|
+
return candidates.some((text4) => normalizedPromptMatches(text4, manifest));
|
|
2205
|
+
}
|
|
2206
|
+
function normalizedPromptMatches(text3, manifest) {
|
|
2207
|
+
const runtimeAssets = manifest.assets.filter((asset) => asset.runtimeMedia);
|
|
2208
|
+
if (runtimeAssets.length) {
|
|
2209
|
+
if (runtimeAssets.length !== 1) return false;
|
|
2210
|
+
const asset = runtimeAssets[0];
|
|
2211
|
+
const header = /^\[media attached: ([^\r\n]+) \(([^)\r\n]+)\) \| (media:\/\/inbound\/[^\]\r\n]+)\]\n/.exec(text3);
|
|
2212
|
+
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;
|
|
2213
|
+
text3 = text3.slice(header[0].length);
|
|
2214
|
+
if (asset.kind === "video") text3 = text3.replace(/\n\n\[Video attachment not analyzed: video understanding is disabled\]$/, "");
|
|
2215
|
+
}
|
|
2216
|
+
return digest(text3) === manifest.inputBodySha256;
|
|
2217
|
+
}
|
|
2218
|
+
function currentMessageFacts(messages) {
|
|
2219
|
+
if (!Array.isArray(messages) || messages.length > 1e3) return [];
|
|
2220
|
+
const facts = [];
|
|
2221
|
+
for (const message of messages) {
|
|
2222
|
+
if (message?.role !== "custom" || message.customType !== "openclaw.runtime-context" || message.details?.source !== "openclaw-runtime-context" || message.details?.runtimeContextCarrier !== true) continue;
|
|
2223
|
+
const fragments = message.details?.fragments;
|
|
2224
|
+
if (!Array.isArray(fragments) || fragments.length > 64) return [];
|
|
2225
|
+
for (const fragment of fragments) {
|
|
2226
|
+
if (fragment?.kind !== "conversation-data" || typeof fragment.text !== "string" || fragment.text.length > 65536) continue;
|
|
2227
|
+
const match = /^Conversation info: ⟦openclaw:ctx⟧\n```json\n([^\n]+)\n```$/.exec(fragment.text);
|
|
2228
|
+
if (!match) continue;
|
|
2229
|
+
try {
|
|
2230
|
+
const value = JSON.parse(match[1]);
|
|
2231
|
+
if (typeof value.message_id === "string" && typeof value.chat_id === "string") facts.push({ messageId: value.message_id, chatId: value.chat_id });
|
|
2232
|
+
} catch {
|
|
2233
|
+
}
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
return facts;
|
|
2237
|
+
}
|
|
2238
|
+
function matchingContext(ctx, manifest) {
|
|
2239
|
+
return ctx?.runId === manifest.runId && ctx?.sessionKey === manifest.sessionKey && ctx?.agentId === manifest.agentId;
|
|
2240
|
+
}
|
|
2241
|
+
function observeNativePreparedInput(event, ctx) {
|
|
2242
|
+
prune();
|
|
2243
|
+
const item = pending.get(event?.runId);
|
|
2244
|
+
if (!item) return;
|
|
2245
|
+
item.proof = void 0;
|
|
2246
|
+
item.started = false;
|
|
2247
|
+
const m = item.manifest;
|
|
2248
|
+
if (!matchingContext(ctx, m) || ctx?.channel !== "agent-wechat" || ctx?.accountId !== m.channelAccountId || ctx?.chatId !== (m.threadId.endsWith("@chatroom") ? m.threadId : `wechat:${m.threadId}`) || ctx?.sessionId !== event.sessionId || typeof event.sessionId !== "string" || !event.sessionId || typeof event.provider !== "string" || typeof event.model !== "string" || !promptMatches(event.prompt, m)) return;
|
|
2249
|
+
const facts = currentMessageFacts(event.historyMessages);
|
|
2250
|
+
if (facts.length !== 1 || facts[0].messageId !== m.messageSid || facts[0].chatId !== `wechat:${m.threadId}`) return;
|
|
2251
|
+
if (m.assets.length && event.imagesCount !== m.assets.filter((asset) => asset.role === "model_image").length) return;
|
|
2252
|
+
item.proof = { sessionId: event.sessionId, provider: event.provider, model: event.model };
|
|
2253
|
+
}
|
|
2254
|
+
function observeNativeModelCall(event, ctx) {
|
|
2255
|
+
prune();
|
|
2256
|
+
const item = pending.get(event?.runId);
|
|
2257
|
+
if (!item?.proof) return;
|
|
2258
|
+
const m = item.manifest, proof = item.proof;
|
|
2259
|
+
if (!matchingContext(ctx, m) || event.sessionKey !== m.sessionKey || event.sessionId !== proof.sessionId || ctx?.sessionId !== proof.sessionId || event.provider !== proof.provider || event.model !== proof.model || typeof event.callId !== "string" || !event.callId) return;
|
|
2260
|
+
item.started = true;
|
|
2261
|
+
if (!m.assets.length) {
|
|
2262
|
+
item.record(m.runId);
|
|
2263
|
+
pending.delete(m.runId);
|
|
2264
|
+
}
|
|
2265
|
+
}
|
|
2266
|
+
function observeNativeAgentEnd(event, ctx) {
|
|
2267
|
+
prune();
|
|
2268
|
+
const item = pending.get(event?.runId);
|
|
2269
|
+
if (!item?.proof || !item.started || !item.manifest.assets.length) return;
|
|
2270
|
+
const m = item.manifest, proof = item.proof;
|
|
2271
|
+
if (!matchingContext(ctx, m) || ctx?.sessionId !== proof.sessionId || ctx?.channel !== "agent-wechat" || ctx?.accountId !== m.channelAccountId || ctx?.chatId !== (m.threadId.endsWith("@chatroom") ? m.threadId : `wechat:${m.threadId}`) || ctx?.modelProviderId !== proof.provider || ctx?.modelId !== proof.model || !Array.isArray(event.messages) || event.messages.length > 1e3) return;
|
|
2272
|
+
const user = event.messages.findLast((message) => message?.role === "user");
|
|
2273
|
+
if (user?.idempotencyKey !== m.hostSourceTurnId) return;
|
|
2274
|
+
const blocks = typeof user.content === "string" ? [{ type: "text", text: user.content }] : user.content;
|
|
2275
|
+
if (!Array.isArray(blocks) || blocks.length > 32) return;
|
|
2276
|
+
if (blocks.some((block) => !["text", "image"].includes(block?.type) || block.type === "text" && typeof block.text !== "string")) return;
|
|
2277
|
+
const text3 = blocks.filter((block) => block?.type === "text").map((block) => block.text).join("\n");
|
|
2278
|
+
if (!promptMatches(text3, m)) return;
|
|
2279
|
+
const images = blocks.filter((block) => block?.type === "image");
|
|
2280
|
+
const expectedImages = m.assets.filter((asset) => asset.role === "model_image");
|
|
2281
|
+
if (images.length !== expectedImages.length) return;
|
|
2282
|
+
for (const [index, asset] of expectedImages.entries()) {
|
|
2283
|
+
const image = images[index];
|
|
2284
|
+
if (image.mimeType !== asset.mime || typeof image.data !== "string" || image.data.length > 8 * 1024 * 1024 || image.data.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(image.data)) return;
|
|
2285
|
+
const bytes = Buffer.from(image.data, "base64");
|
|
2286
|
+
if (bytes.length !== asset.byteLength || digest(bytes) !== asset.sha256) return;
|
|
2287
|
+
}
|
|
2288
|
+
if (m.assets.some((asset) => asset.role === "file_reference" && !text3.includes(asset.path))) return;
|
|
2289
|
+
item.record(m.runId);
|
|
2290
|
+
pending.delete(m.runId);
|
|
2291
|
+
}
|
|
2292
|
+
function registerNativePreparedBoundary(api) {
|
|
2293
|
+
const access2 = api.config?.plugins?.entries?.["agent-wechat"]?.hooks?.allowConversationAccess === true;
|
|
2294
|
+
enabled = access2;
|
|
2295
|
+
if (access2) {
|
|
2296
|
+
api.on("llm_input", observeNativePreparedInput);
|
|
2297
|
+
api.on("model_call_started", observeNativeModelCall);
|
|
2298
|
+
api.on("agent_end", observeNativeAgentEnd);
|
|
2299
|
+
}
|
|
2300
|
+
return () => {
|
|
2301
|
+
enabled = false;
|
|
2302
|
+
pending.clear();
|
|
2303
|
+
};
|
|
2304
|
+
}
|
|
2305
|
+
|
|
2306
|
+
// src/outbound-reply.ts
|
|
2307
|
+
function parseWeChatReplyTo(value) {
|
|
2308
|
+
if (value == null) return void 0;
|
|
2309
|
+
if (typeof value !== "string" || !value || value.length > 4096 || value === "." || value === ".." || /[\u0000-\u001f\u007f]/.test(value)) throw Error("Use an exact stored WeChat message ID for replyTo");
|
|
2310
|
+
return value;
|
|
2311
|
+
}
|
|
2312
|
+
function nativeReplyMessageId(replyToId, accountId) {
|
|
2313
|
+
if (!replyToId.startsWith("wechat-native:")) return replyToId;
|
|
2314
|
+
const prefix = `wechat-native:${accountId}:`;
|
|
2315
|
+
const end = replyToId.lastIndexOf(":");
|
|
2316
|
+
const id2 = replyToId.slice(prefix.length, end);
|
|
2317
|
+
if (!replyToId.startsWith(prefix) || !/^[a-f0-9]{64}$/.test(replyToId.slice(end + 1)) || !parseWeChatReplyTo(id2)) throw Error("WeChat reply target identity is invalid for this account");
|
|
2318
|
+
return id2;
|
|
2319
|
+
}
|
|
2320
|
+
function validateWeChatReplySend(replyToId, input) {
|
|
2321
|
+
if (parseWeChatReplyTo(replyToId) === void 0) return;
|
|
2322
|
+
if (input.mediaUrl || input.mediaUrls?.length || input.audioAsVoice || input.forceDocument || input.videoQuality != null) {
|
|
2323
|
+
throw Error("WeChat quoted replies support text only; send attachments separately");
|
|
2324
|
+
}
|
|
2325
|
+
if (typeof input.text !== "string" || !input.text.trim()) throw Error("WeChat quoted replies require message text");
|
|
2326
|
+
}
|
|
2327
|
+
function nativeReplyReference(message, accountId, threadId2, replyToId) {
|
|
2328
|
+
const messageId = nativeReplyMessageId(replyToId, accountId);
|
|
2329
|
+
if (message.id !== messageId || message.accountId !== accountId || message.threadId !== threadId2 || typeof message.serverId !== "string" || !/^[1-9]\d{0,19}$/.test(message.serverId) || BigInt(message.serverId) > 18446744073709551615n || replyToId.startsWith("wechat-native:") && nativeSourceMessageSid(message) !== replyToId) throw Error("WeChat reply target is unavailable or outside this conversation");
|
|
2330
|
+
return { messageId, serverId: message.serverId };
|
|
2331
|
+
}
|
|
2332
|
+
|
|
2027
2333
|
// src/outbound-media.ts
|
|
2028
2334
|
async function sendWeChatMedia(cfg, to, text3, mediaUrl, audioAsVoice = false, idempotencyKey, options = {}, beforeSend) {
|
|
2335
|
+
validateWeChatMentionSend(options.mentions, { to, text: text3, mediaUrl, audioAsVoice, ...options });
|
|
2336
|
+
const replyToId = parseWeChatReplyTo(options.replyToId);
|
|
2337
|
+
validateWeChatReplySend(replyToId, { text: text3, mediaUrl, audioAsVoice, ...options });
|
|
2029
2338
|
validateNativeMediaSendOptions(options, audioAsVoice);
|
|
2030
2339
|
if (!mediaUrl && (options.forceDocument || options.videoQuality != null)) throw new Error("WeChat media options require an attachment");
|
|
2031
2340
|
const account = resolveWeChatAccount(cfg);
|
|
2032
2341
|
if (!account?.native) throw new Error("No native daemon configured");
|
|
2033
2342
|
const { client } = await ensureNativeHost(account.native);
|
|
2034
|
-
const key = idempotencyKey ??
|
|
2343
|
+
const key = idempotencyKey ?? randomUUID3();
|
|
2035
2344
|
if (!mediaUrl) {
|
|
2036
2345
|
if (audioAsVoice) throw new Error("Voice sending requires an audio attachment");
|
|
2346
|
+
const original = replyToId ? await client.message(account.native.accountId, nativeReplyMessageId(replyToId, account.native.accountId)) : void 0;
|
|
2347
|
+
const quote = replyToId && original ? nativeReplyReference(original, account.native.accountId, to, replyToId) : void 0;
|
|
2348
|
+
if (original?.recall) throw Error("The WeChat reply target has been recalled; choose another message");
|
|
2037
2349
|
await beforeSend?.();
|
|
2038
|
-
const send = await submitNativeText(client, account.native.accountId, to, text3, key);
|
|
2350
|
+
const send = await submitNativeText(client, account.native.accountId, to, text3, key, { mentions: options.mentions, quote });
|
|
2039
2351
|
return nativeOutboundDelivery(
|
|
2040
2352
|
client,
|
|
2041
2353
|
account.native.accountId,
|
|
@@ -2047,30 +2359,56 @@ async function sendWeChatMedia(cfg, to, text3, mediaUrl, audioAsVoice = false, i
|
|
|
2047
2359
|
const result = await sendNativeAttachment(client, account, to, mediaUrl, audioAsVoice, key, beforeSend, options);
|
|
2048
2360
|
if (text3) {
|
|
2049
2361
|
await beforeSend?.();
|
|
2050
|
-
await submitNativeText(client, account.native.accountId, to, text3,
|
|
2362
|
+
await submitNativeText(client, account.native.accountId, to, text3, createHash6("sha256").update(`${key}\0caption`).digest("hex"));
|
|
2051
2363
|
}
|
|
2052
2364
|
return result;
|
|
2053
2365
|
}
|
|
2054
2366
|
|
|
2367
|
+
// src/native-send-key.ts
|
|
2368
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
2369
|
+
function nativeOutboundKey(queueId, partIndex = 0, attachmentIndex = 0) {
|
|
2370
|
+
return createHash7("sha256").update(JSON.stringify(["wechat-media", queueId, partIndex, attachmentIndex])).digest("hex");
|
|
2371
|
+
}
|
|
2372
|
+
|
|
2055
2373
|
// src/outbound-options.ts
|
|
2056
2374
|
function nativePayloadMediaOptions(payload) {
|
|
2057
2375
|
const value = payload.channelData?.["agent-wechat"];
|
|
2058
2376
|
if (value == null) return {};
|
|
2059
|
-
if (typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => key !== "videoQuality"
|
|
2060
|
-
|
|
2377
|
+
if (typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => key !== "videoQuality" && key !== "mentions")) throw Error("Invalid WeChat send options");
|
|
2378
|
+
const options = value;
|
|
2379
|
+
if (!Object.keys(options).length || options.videoQuality !== void 0 && !["normal", "original"].includes(options.videoQuality)) throw Error("Invalid WeChat media options");
|
|
2380
|
+
return {
|
|
2381
|
+
...options.videoQuality !== void 0 ? { videoQuality: options.videoQuality } : {},
|
|
2382
|
+
...options.mentions !== void 0 ? { mentions: parseWeChatTextMentions(options.mentions) } : {}
|
|
2383
|
+
};
|
|
2061
2384
|
}
|
|
2062
2385
|
var wechatMediaActions = {
|
|
2063
2386
|
describeMessageTool: () => ({ actions: ["send"], schema: { actions: ["send"], visibility: "all-configured", properties: {
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2387
|
+
replyTo: { type: "string", minLength: 1, maxLength: 4096, description: "Quote a stored WeChat message in this same chat. Use its exact id from wechat_history, wechat_search or wechat_message, or the current inbound message ID; not a server ID or send/job ID. Text replies only; cannot combine with attachments or mentions. The hub validates the original message." },
|
|
2388
|
+
channelData: { type: "object", description: "WeChat send options: mentions for ordinary group text, or videoQuality for one video attachment.", additionalProperties: true, properties: {
|
|
2389
|
+
"agent-wechat": { type: "object", additionalProperties: false, anyOf: [{ required: ["videoQuality"] }, { required: ["mentions"] }], properties: {
|
|
2390
|
+
videoQuality: { type: "string", enum: ["normal", "original"], description: "WeChat video mode: normal prepares playback; original also retains the unchanged source video. Cannot combine with forceDocument." },
|
|
2391
|
+
mentions: {
|
|
2392
|
+
type: "object",
|
|
2393
|
+
additionalProperties: false,
|
|
2394
|
+
description: "Mention exact members in an ordinary group text message. Get userIds from wechat_group_info, not display names. The hub adds visible @names and metadata. Use all=true only when the sender has permission. Cannot combine with DMs, media, voice, video quality or quoted replies.",
|
|
2395
|
+
properties: {
|
|
2396
|
+
userIds: { type: "array", minItems: 1, maxItems: 128, uniqueItems: true, items: { type: "string", minLength: 1, maxLength: 256, pattern: "^[A-Za-z0-9_@.-]+$" } },
|
|
2397
|
+
all: { type: "boolean", const: true }
|
|
2398
|
+
},
|
|
2399
|
+
oneOf: [{ required: ["userIds"], not: { required: ["all"] } }, { required: ["all"], not: { required: ["userIds"] } }]
|
|
2400
|
+
}
|
|
2067
2401
|
} }
|
|
2068
2402
|
} }
|
|
2069
2403
|
} } }),
|
|
2070
|
-
prepareSendPayload: ({ ctx, payload }) => {
|
|
2404
|
+
prepareSendPayload: ({ ctx, to, payload, replyToId }) => {
|
|
2071
2405
|
const options = nativePayloadMediaOptions(payload);
|
|
2072
|
-
|
|
2073
|
-
|
|
2406
|
+
const forceDocument = ctx.params.forceDocument ?? ctx.params.asDocument;
|
|
2407
|
+
validateWeChatMentionSend(options.mentions, { ...payload, ...options, to, forceDocument, replyToId: replyToId ?? payload.replyToId });
|
|
2408
|
+
const reply = parseWeChatReplyTo(replyToId ?? payload.replyToId);
|
|
2409
|
+
validateWeChatReplySend(reply, { ...payload, ...options, forceDocument });
|
|
2410
|
+
if (options.videoQuality == null && options.mentions == null && reply == null) return void 0;
|
|
2411
|
+
validateNativeMediaSendOptions({ ...options, forceDocument }, payload.audioAsVoice);
|
|
2074
2412
|
return payload;
|
|
2075
2413
|
}
|
|
2076
2414
|
};
|
|
@@ -2087,55 +2425,71 @@ var NativeMediaPayloadInspectionError = class extends Error {
|
|
|
2087
2425
|
}
|
|
2088
2426
|
};
|
|
2089
2427
|
function createWeChatMediaHandlers(send = sendWeChatMedia) {
|
|
2090
|
-
const key = (ctx, index = 0) => ctx.deliveryQueueId ?
|
|
2428
|
+
const key = (ctx, index = 0) => ctx.deliveryQueueId ? nativeOutboundKey(ctx.deliveryQueueId, ctx.deliveryPartIndex ?? 0, index) : void 0;
|
|
2091
2429
|
const guard2 = (ctx) => async () => {
|
|
2092
2430
|
ctx.signal?.throwIfAborted();
|
|
2093
2431
|
await ctx.onPlatformSendDispatch?.();
|
|
2094
2432
|
ctx.signal?.throwIfAborted();
|
|
2095
2433
|
ctx.assertDirectAdapterHandoff?.();
|
|
2096
2434
|
};
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2435
|
+
const sendPayload = async (ctx) => {
|
|
2436
|
+
const replyToId = parseWeChatReplyTo(ctx.replyToId ?? ctx.payload.replyToId);
|
|
2437
|
+
const options = { ...nativePayloadMediaOptions(ctx.payload), forceDocument: ctx.forceDocument, ...replyToId && { replyToId } };
|
|
2438
|
+
const audioAsVoice = ctx.payload.audioAsVoice ?? ctx.audioAsVoice;
|
|
2439
|
+
validateWeChatMentionSend(options.mentions, {
|
|
2440
|
+
...ctx.payload,
|
|
2441
|
+
...options,
|
|
2442
|
+
to: ctx.to,
|
|
2443
|
+
text: ctx.payload.text ?? ctx.text,
|
|
2444
|
+
mediaUrl: ctx.payload.mediaUrl ?? ctx.mediaUrl,
|
|
2445
|
+
audioAsVoice,
|
|
2446
|
+
replyToId: ctx.replyToId ?? ctx.payload.replyToId
|
|
2447
|
+
});
|
|
2448
|
+
validateWeChatReplySend(replyToId, {
|
|
2449
|
+
...ctx.payload,
|
|
2450
|
+
...options,
|
|
2451
|
+
text: ctx.payload.text ?? ctx.text,
|
|
2452
|
+
mediaUrl: ctx.payload.mediaUrl ?? ctx.mediaUrl,
|
|
2453
|
+
audioAsVoice
|
|
2454
|
+
});
|
|
2455
|
+
validateNativeMediaSendOptions(options, audioAsVoice);
|
|
2456
|
+
const urls = [...new Set([...ctx.payload.mediaUrls ?? [], ctx.payload.mediaUrl ?? ctx.mediaUrl].filter((url2) => typeof url2 === "string" && !!url2))];
|
|
2457
|
+
if (urls.length > 16 || options.videoQuality != null && urls.length !== 1) throw Error("WeChat video quality requires one attachment per send");
|
|
2458
|
+
const deliveries = [];
|
|
2459
|
+
for (const [index, mediaUrl] of (urls.length ? urls : [void 0]).entries()) {
|
|
2460
|
+
let delivered;
|
|
2461
|
+
try {
|
|
2462
|
+
delivered = await send(ctx.cfg, ctx.to, index === 0 ? ctx.payload.text ?? ctx.text : "", mediaUrl, audioAsVoice, key(ctx, index), options, guard2(ctx));
|
|
2463
|
+
} catch (error) {
|
|
2464
|
+
if (!deliveries.length) throw error;
|
|
2465
|
+
throw new NativeMediaPayloadInspectionError(deliveries, error instanceof NativeMediaJobInspectionError ? { jobId: error.jobId, accountId: error.accountId, threadId: error.threadId, idempotencyKey: error.idempotencyKey } : void 0);
|
|
2466
|
+
}
|
|
2467
|
+
deliveries.push(delivered);
|
|
2468
|
+
if (urls.length > 1) {
|
|
2111
2469
|
try {
|
|
2112
|
-
|
|
2113
|
-
} catch
|
|
2114
|
-
|
|
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
|
-
}
|
|
2470
|
+
await ctx.onDeliveryResult?.({ channel: "agent-wechat", ...delivered });
|
|
2471
|
+
} catch {
|
|
2472
|
+
throw new NativeMediaPayloadInspectionError(deliveries);
|
|
2124
2473
|
}
|
|
2125
|
-
if (delivered.meta.outcome === "unknown") break;
|
|
2126
2474
|
}
|
|
2127
|
-
|
|
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
|
-
};
|
|
2475
|
+
if (delivered.meta.outcome === "unknown") break;
|
|
2138
2476
|
}
|
|
2477
|
+
const first = deliveries[0];
|
|
2478
|
+
return {
|
|
2479
|
+
channel: "agent-wechat",
|
|
2480
|
+
...first,
|
|
2481
|
+
...deliveries.length > 1 ? { meta: {
|
|
2482
|
+
...first.meta,
|
|
2483
|
+
parts: deliveries,
|
|
2484
|
+
retryable: false,
|
|
2485
|
+
...deliveries.some((part) => part.meta.outcome === "unknown") ? { outcome: "unknown", receiptState: "needs_review" } : {}
|
|
2486
|
+
} } : {}
|
|
2487
|
+
};
|
|
2488
|
+
};
|
|
2489
|
+
return {
|
|
2490
|
+
sendText: async (ctx) => sendPayload({ ...ctx, payload: ctx.payload ?? { text: ctx.text } }),
|
|
2491
|
+
sendMedia: async (ctx) => sendPayload({ ...ctx, payload: ctx.payload ?? { text: ctx.text, mediaUrl: ctx.mediaUrl } }),
|
|
2492
|
+
sendPayload
|
|
2139
2493
|
};
|
|
2140
2494
|
}
|
|
2141
2495
|
|
|
@@ -2145,15 +2499,15 @@ import { createChannelMessageReplyPipeline } from "openclaw/plugin-sdk/channel-o
|
|
|
2145
2499
|
import { resolveStableChannelMessageIngress } from "openclaw/plugin-sdk/channel-ingress-runtime";
|
|
2146
2500
|
|
|
2147
2501
|
// src/native-consumer-state.ts
|
|
2148
|
-
import { createHash as
|
|
2502
|
+
import { createHash as createHash8, randomUUID as randomUUID4 } from "node:crypto";
|
|
2149
2503
|
import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2150
|
-
import { dirname as dirname2, isAbsolute as
|
|
2504
|
+
import { dirname as dirname2, isAbsolute as isAbsolute3, join as join3 } from "node:path";
|
|
2151
2505
|
var NativeConsumerState = class {
|
|
2152
2506
|
file;
|
|
2153
2507
|
value;
|
|
2154
2508
|
constructor(directory, serverId, accountId) {
|
|
2155
|
-
if (!
|
|
2156
|
-
this.file = join3(directory, `${
|
|
2509
|
+
if (!isAbsolute3(directory) || !serverId || !accountId) throw new Error("Native consumer state requires absolute storage and bound server/account identities");
|
|
2510
|
+
this.file = join3(directory, `${createHash8("sha256").update(`${serverId}\0${accountId}`).digest("hex")}.json`);
|
|
2157
2511
|
this.value = { schemaVersion: 1, serverId, accountId, cursor: "0", items: {} };
|
|
2158
2512
|
if (existsSync(this.file)) {
|
|
2159
2513
|
const stat = lstatSync(this.file);
|
|
@@ -2165,7 +2519,7 @@ var NativeConsumerState = class {
|
|
|
2165
2519
|
nativeRecallInfo(item.message);
|
|
2166
2520
|
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
2521
|
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 ??=
|
|
2522
|
+
item.revision ??= randomUUID4();
|
|
2169
2523
|
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");
|
|
2170
2524
|
if (item.state === "dispatching") item.state = "needs_review";
|
|
2171
2525
|
}
|
|
@@ -2204,7 +2558,7 @@ var NativeConsumerState = class {
|
|
|
2204
2558
|
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.mode & 63) throw new Error("Native consumer directory must be private (0700)");
|
|
2205
2559
|
const bytes = JSON.stringify(this.value);
|
|
2206
2560
|
if (Buffer.byteLength(bytes) > 16 * 1024 * 1024) throw new Error("Native custody state is full; intake paused without advancing acknowledgement");
|
|
2207
|
-
const temporary = `${this.file}.${
|
|
2561
|
+
const temporary = `${this.file}.${randomUUID4()}.tmp`;
|
|
2208
2562
|
let fd;
|
|
2209
2563
|
try {
|
|
2210
2564
|
fd = openSync(temporary, "wx", 384);
|
|
@@ -2267,7 +2621,7 @@ var NativeConsumerState = class {
|
|
|
2267
2621
|
item.readPending = false;
|
|
2268
2622
|
}
|
|
2269
2623
|
}
|
|
2270
|
-
this.value.items[message.id] = { message, revision:
|
|
2624
|
+
this.value.items[message.id] = { message, revision: randomUUID4(), origin, state: nativeRecallInfo(message) ? "ignored" : "received", cursor };
|
|
2271
2625
|
}
|
|
2272
2626
|
this.value.cursor = cursor;
|
|
2273
2627
|
});
|
|
@@ -2372,7 +2726,7 @@ var NativeConsumerState = class {
|
|
|
2372
2726
|
});
|
|
2373
2727
|
const revisions = items.map((item) => item.revision);
|
|
2374
2728
|
if (new Set(items.map((item) => item.message.threadId)).size !== 1) throw new Error("Prepared input manifest crosses threads");
|
|
2375
|
-
const manifestHash =
|
|
2729
|
+
const manifestHash = createHash8("sha256").update(JSON.stringify({
|
|
2376
2730
|
accountId: this.value.accountId,
|
|
2377
2731
|
messageIds: exact,
|
|
2378
2732
|
dispatchManifests: items.map((item) => item.dispatchManifest ?? null)
|
|
@@ -2381,7 +2735,7 @@ var NativeConsumerState = class {
|
|
|
2381
2735
|
const runId = typeof args[0] === "string" ? args[0] : args[0]?.runId;
|
|
2382
2736
|
if (typeof runId !== "string" || !runId || runId.length > 256) throw new Error("Prepared run callback has no valid runId");
|
|
2383
2737
|
this.mutate(() => {
|
|
2384
|
-
const currentHash =
|
|
2738
|
+
const currentHash = createHash8("sha256").update(JSON.stringify({
|
|
2385
2739
|
accountId: this.value.accountId,
|
|
2386
2740
|
messageIds: exact,
|
|
2387
2741
|
dispatchManifests: exact.map((id2) => this.value.items[id2]?.dispatchManifest ?? null)
|
|
@@ -2399,197 +2753,6 @@ var NativeConsumerState = class {
|
|
|
2399
2753
|
}
|
|
2400
2754
|
};
|
|
2401
2755
|
|
|
2402
|
-
// src/native-prepared-boundary.ts
|
|
2403
|
-
import { createHash as createHash8, randomUUID as randomUUID4 } from "node:crypto";
|
|
2404
|
-
import { basename as basename2, isAbsolute as isAbsolute3 } from "node:path";
|
|
2405
|
-
var pending = /* @__PURE__ */ new Map();
|
|
2406
|
-
var enabled = false;
|
|
2407
|
-
var digest = (value) => createHash8("sha256").update(value).digest("hex");
|
|
2408
|
-
function prune() {
|
|
2409
|
-
for (const [id2, item] of pending) if (item.expires < Date.now()) pending.delete(id2);
|
|
2410
|
-
}
|
|
2411
|
-
function nativeSourceMessageSid(message) {
|
|
2412
|
-
return `wechat-native:${message.accountId}:${message.id}:${digest(JSON.stringify([message.threadId, message.serverId ?? null]))}`;
|
|
2413
|
-
}
|
|
2414
|
-
function nativeDispatchManifest(params) {
|
|
2415
|
-
const history = params.history ?? [];
|
|
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");
|
|
2417
|
-
const assets = Object.freeze((params.assets ?? []).map((asset) => {
|
|
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");
|
|
2419
|
-
return Object.freeze({ ...asset });
|
|
2420
|
-
}));
|
|
2421
|
-
const messageSid = nativeSourceMessageSid(params.message);
|
|
2422
|
-
const manifest = {
|
|
2423
|
-
schemaVersion: 2,
|
|
2424
|
-
runId: randomUUID4(),
|
|
2425
|
-
accountId: params.message.accountId,
|
|
2426
|
-
messageIds: Object.freeze([params.message.id]),
|
|
2427
|
-
messageSid,
|
|
2428
|
-
threadId: params.message.threadId,
|
|
2429
|
-
senderId: params.message.senderId ?? "",
|
|
2430
|
-
sessionKey: params.sessionKey,
|
|
2431
|
-
agentId: params.agentId,
|
|
2432
|
-
channelAccountId: params.channelAccountId,
|
|
2433
|
-
inputBodySha256: digest(params.inputBody),
|
|
2434
|
-
newInputs: Object.freeze([Object.freeze({
|
|
2435
|
-
id: params.message.id,
|
|
2436
|
-
version: params.message.version ?? "",
|
|
2437
|
-
contentSha256: digest(JSON.stringify([
|
|
2438
|
-
params.message.id,
|
|
2439
|
-
params.message.version,
|
|
2440
|
-
params.message.senderId,
|
|
2441
|
-
params.message.type,
|
|
2442
|
-
params.message.body,
|
|
2443
|
-
params.message.mentions,
|
|
2444
|
-
params.message.serverId,
|
|
2445
|
-
params.message.appMessageType,
|
|
2446
|
-
params.message.quote,
|
|
2447
|
-
params.message.link
|
|
2448
|
-
])),
|
|
2449
|
-
role: "trigger"
|
|
2450
|
-
})]),
|
|
2451
|
-
...history.length ? { historyInputs: Object.freeze(history.map((message) => Object.freeze({
|
|
2452
|
-
id: message.id,
|
|
2453
|
-
version: message.version ?? "",
|
|
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])),
|
|
2455
|
-
role: "history"
|
|
2456
|
-
}))) } : {},
|
|
2457
|
-
assets,
|
|
2458
|
-
policySha256: digest(JSON.stringify(params.policy ?? null)),
|
|
2459
|
-
// Exact source-turn identity of OpenClaw 2026.10.2 through 2026.10.7. Requiring it in the later
|
|
2460
|
-
// snapshot prevents an identical older image/body from proving this input.
|
|
2461
|
-
hostSourceTurnId: `channel-user:v1:${digest(JSON.stringify(["agent-wechat", params.channelAccountId, `wechat:${params.message.threadId}`, messageSid]))}`
|
|
2462
|
-
};
|
|
2463
|
-
return Object.freeze({ ...manifest, manifestSha256: digest(JSON.stringify(manifest)) });
|
|
2464
|
-
}
|
|
2465
|
-
function trackNativePreparedInput(manifest, record) {
|
|
2466
|
-
prune();
|
|
2467
|
-
if (!enabled || pending.size >= 1024) return;
|
|
2468
|
-
pending.set(manifest.runId, { manifest, record, expires: Date.now() + 15 * 60 * 1e3 });
|
|
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
|
-
}
|
|
2480
|
-
function promptMatches(prompt, manifest) {
|
|
2481
|
-
if (typeof prompt !== "string" || Buffer.byteLength(prompt) > 1024 * 1024) return false;
|
|
2482
|
-
const text3 = prompt.replace(/^\[[^\]\r\n]{1,96}\] /, "");
|
|
2483
|
-
const candidates = [text3];
|
|
2484
|
-
const sender = `Conversation info: \u27E6openclaw:ctx\u27E7
|
|
2485
|
-
\`\`\`json
|
|
2486
|
-
${JSON.stringify({ sender: { id: manifest.senderId } })}
|
|
2487
|
-
\`\`\`
|
|
2488
|
-
|
|
2489
|
-
`;
|
|
2490
|
-
if (manifest.threadId.endsWith("@chatroom") && text3.startsWith(sender)) candidates.push(text3.slice(sender.length));
|
|
2491
|
-
return candidates.some((text4) => normalizedPromptMatches(text4, manifest));
|
|
2492
|
-
}
|
|
2493
|
-
function normalizedPromptMatches(text3, manifest) {
|
|
2494
|
-
const runtimeAssets = manifest.assets.filter((asset) => asset.runtimeMedia);
|
|
2495
|
-
if (runtimeAssets.length) {
|
|
2496
|
-
if (runtimeAssets.length !== 1) return false;
|
|
2497
|
-
const asset = runtimeAssets[0];
|
|
2498
|
-
const header = /^\[media attached: ([^\r\n]+) \(([^)\r\n]+)\) \| (media:\/\/inbound\/[^\]\r\n]+)\]\n/.exec(text3);
|
|
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;
|
|
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\]$/, "");
|
|
2502
|
-
}
|
|
2503
|
-
return digest(text3) === manifest.inputBodySha256;
|
|
2504
|
-
}
|
|
2505
|
-
function currentMessageFacts(messages) {
|
|
2506
|
-
if (!Array.isArray(messages) || messages.length > 1e3) return [];
|
|
2507
|
-
const facts = [];
|
|
2508
|
-
for (const message of messages) {
|
|
2509
|
-
if (message?.role !== "custom" || message.customType !== "openclaw.runtime-context" || message.details?.source !== "openclaw-runtime-context" || message.details?.runtimeContextCarrier !== true) continue;
|
|
2510
|
-
const fragments = message.details?.fragments;
|
|
2511
|
-
if (!Array.isArray(fragments) || fragments.length > 64) return [];
|
|
2512
|
-
for (const fragment of fragments) {
|
|
2513
|
-
if (fragment?.kind !== "conversation-data" || typeof fragment.text !== "string" || fragment.text.length > 65536) continue;
|
|
2514
|
-
const match = /^Conversation info: ⟦openclaw:ctx⟧\n```json\n([^\n]+)\n```$/.exec(fragment.text);
|
|
2515
|
-
if (!match) continue;
|
|
2516
|
-
try {
|
|
2517
|
-
const value = JSON.parse(match[1]);
|
|
2518
|
-
if (typeof value.message_id === "string" && typeof value.chat_id === "string") facts.push({ messageId: value.message_id, chatId: value.chat_id });
|
|
2519
|
-
} catch {
|
|
2520
|
-
}
|
|
2521
|
-
}
|
|
2522
|
-
}
|
|
2523
|
-
return facts;
|
|
2524
|
-
}
|
|
2525
|
-
function matchingContext(ctx, manifest) {
|
|
2526
|
-
return ctx?.runId === manifest.runId && ctx?.sessionKey === manifest.sessionKey && ctx?.agentId === manifest.agentId;
|
|
2527
|
-
}
|
|
2528
|
-
function observeNativePreparedInput(event, ctx) {
|
|
2529
|
-
prune();
|
|
2530
|
-
const item = pending.get(event?.runId);
|
|
2531
|
-
if (!item) return;
|
|
2532
|
-
item.proof = void 0;
|
|
2533
|
-
item.started = false;
|
|
2534
|
-
const m = item.manifest;
|
|
2535
|
-
if (!matchingContext(ctx, m) || ctx?.channel !== "agent-wechat" || ctx?.accountId !== m.channelAccountId || ctx?.chatId !== (m.threadId.endsWith("@chatroom") ? m.threadId : `wechat:${m.threadId}`) || ctx?.sessionId !== event.sessionId || typeof event.sessionId !== "string" || !event.sessionId || typeof event.provider !== "string" || typeof event.model !== "string" || !promptMatches(event.prompt, m)) return;
|
|
2536
|
-
const facts = currentMessageFacts(event.historyMessages);
|
|
2537
|
-
if (facts.length !== 1 || facts[0].messageId !== m.messageSid || facts[0].chatId !== `wechat:${m.threadId}`) return;
|
|
2538
|
-
if (m.assets.length && event.imagesCount !== m.assets.filter((asset) => asset.role === "model_image").length) return;
|
|
2539
|
-
item.proof = { sessionId: event.sessionId, provider: event.provider, model: event.model };
|
|
2540
|
-
}
|
|
2541
|
-
function observeNativeModelCall(event, ctx) {
|
|
2542
|
-
prune();
|
|
2543
|
-
const item = pending.get(event?.runId);
|
|
2544
|
-
if (!item?.proof) return;
|
|
2545
|
-
const m = item.manifest, proof = item.proof;
|
|
2546
|
-
if (!matchingContext(ctx, m) || event.sessionKey !== m.sessionKey || event.sessionId !== proof.sessionId || ctx?.sessionId !== proof.sessionId || event.provider !== proof.provider || event.model !== proof.model || typeof event.callId !== "string" || !event.callId) return;
|
|
2547
|
-
item.started = true;
|
|
2548
|
-
if (!m.assets.length) {
|
|
2549
|
-
item.record(m.runId);
|
|
2550
|
-
pending.delete(m.runId);
|
|
2551
|
-
}
|
|
2552
|
-
}
|
|
2553
|
-
function observeNativeAgentEnd(event, ctx) {
|
|
2554
|
-
prune();
|
|
2555
|
-
const item = pending.get(event?.runId);
|
|
2556
|
-
if (!item?.proof || !item.started || !item.manifest.assets.length) return;
|
|
2557
|
-
const m = item.manifest, proof = item.proof;
|
|
2558
|
-
if (!matchingContext(ctx, m) || ctx?.sessionId !== proof.sessionId || ctx?.channel !== "agent-wechat" || ctx?.accountId !== m.channelAccountId || ctx?.chatId !== (m.threadId.endsWith("@chatroom") ? m.threadId : `wechat:${m.threadId}`) || ctx?.modelProviderId !== proof.provider || ctx?.modelId !== proof.model || !Array.isArray(event.messages) || event.messages.length > 1e3) return;
|
|
2559
|
-
const user = event.messages.findLast((message) => message?.role === "user");
|
|
2560
|
-
if (user?.idempotencyKey !== m.hostSourceTurnId) return;
|
|
2561
|
-
const blocks = typeof user.content === "string" ? [{ type: "text", text: user.content }] : user.content;
|
|
2562
|
-
if (!Array.isArray(blocks) || blocks.length > 32) return;
|
|
2563
|
-
if (blocks.some((block) => !["text", "image"].includes(block?.type) || block.type === "text" && typeof block.text !== "string")) return;
|
|
2564
|
-
const text3 = blocks.filter((block) => block?.type === "text").map((block) => block.text).join("\n");
|
|
2565
|
-
if (!promptMatches(text3, m)) return;
|
|
2566
|
-
const images = blocks.filter((block) => block?.type === "image");
|
|
2567
|
-
const expectedImages = m.assets.filter((asset) => asset.role === "model_image");
|
|
2568
|
-
if (images.length !== expectedImages.length) return;
|
|
2569
|
-
for (const [index, asset] of expectedImages.entries()) {
|
|
2570
|
-
const image = images[index];
|
|
2571
|
-
if (image.mimeType !== asset.mime || typeof image.data !== "string" || image.data.length > 8 * 1024 * 1024 || image.data.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(image.data)) return;
|
|
2572
|
-
const bytes = Buffer.from(image.data, "base64");
|
|
2573
|
-
if (bytes.length !== asset.byteLength || digest(bytes) !== asset.sha256) return;
|
|
2574
|
-
}
|
|
2575
|
-
if (m.assets.some((asset) => asset.role === "file_reference" && !text3.includes(asset.path))) return;
|
|
2576
|
-
item.record(m.runId);
|
|
2577
|
-
pending.delete(m.runId);
|
|
2578
|
-
}
|
|
2579
|
-
function registerNativePreparedBoundary(api) {
|
|
2580
|
-
const access2 = api.config?.plugins?.entries?.["agent-wechat"]?.hooks?.allowConversationAccess === true;
|
|
2581
|
-
enabled = access2;
|
|
2582
|
-
if (access2) {
|
|
2583
|
-
api.on("llm_input", observeNativePreparedInput);
|
|
2584
|
-
api.on("model_call_started", observeNativeModelCall);
|
|
2585
|
-
api.on("agent_end", observeNativeAgentEnd);
|
|
2586
|
-
}
|
|
2587
|
-
return () => {
|
|
2588
|
-
enabled = false;
|
|
2589
|
-
pending.clear();
|
|
2590
|
-
};
|
|
2591
|
-
}
|
|
2592
|
-
|
|
2593
2756
|
// src/native-history.ts
|
|
2594
2757
|
import { buildHistoryContextFromEntries, buildInboundHistoryFromEntries, DEFAULT_GROUP_HISTORY_LIMIT } from "openclaw/plugin-sdk/reply-history";
|
|
2595
2758
|
function nativeGroupHistoryLimit(cfg) {
|
|
@@ -2679,7 +2842,7 @@ function buildNativeContext(history, message, prepared) {
|
|
|
2679
2842
|
|
|
2680
2843
|
// src/native-monitor.ts
|
|
2681
2844
|
function nativeWasMentioned(message) {
|
|
2682
|
-
return message.mentions?.state === "known" && message.mentions.self === true;
|
|
2845
|
+
return message.mentions?.state === "known" && (message.mentions.self === true || message.mentions.all === true);
|
|
2683
2846
|
}
|
|
2684
2847
|
async function projectNativeRead(client, accountId, state) {
|
|
2685
2848
|
const pending2 = state.items().filter((value) => value.readPending);
|
|
@@ -2775,6 +2938,10 @@ async function dispatchNativeMessageInput(params, revision) {
|
|
|
2775
2938
|
const custody = state.get(message.id);
|
|
2776
2939
|
if (state.isRecalled(message)) return "ignored";
|
|
2777
2940
|
if (!custody || custody.state !== "received" || !state.isCurrent(message, revision)) return "needs_review";
|
|
2941
|
+
if (message.type === 49 && message.appMessageType === 74) {
|
|
2942
|
+
state.update(message.id, { state: "ignored" }, revision);
|
|
2943
|
+
return "ignored";
|
|
2944
|
+
}
|
|
2778
2945
|
if (custody.origin !== "live" || message.direction !== "incoming" || ![1, 3, 34, 43, 47, 49].includes(message.type) || message.type === 1 && !message.body || !message.senderId) {
|
|
2779
2946
|
state.update(message.id, { state: "ignored" }, revision);
|
|
2780
2947
|
return "ignored";
|
|
@@ -2909,7 +3076,7 @@ async function dispatchNativeMessageInput(params, revision) {
|
|
|
2909
3076
|
});
|
|
2910
3077
|
assertCurrent();
|
|
2911
3078
|
state.beginDispatch(message.id, dispatchManifest, buffered.map((item) => item.message.id));
|
|
2912
|
-
const callback = readPolicy !== "on_inbound" && (message.type === 1 || message.type === 49 && message.appMessageType
|
|
3079
|
+
const callback = readPolicy !== "on_inbound" && (message.type === 1 || message.type === 49 && [1, 19, 87].includes(message.appMessageType ?? 0) && !!message.body || message.type === 49 && [3, 4, 5, 51].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;
|
|
2913
3080
|
if (callback) trackNativePreparedInput(dispatchManifest, callback);
|
|
2914
3081
|
const beforeSend = () => recheck([message, ...admitted]);
|
|
2915
3082
|
let failed = false;
|
|
@@ -2924,6 +3091,8 @@ async function dispatchNativeMessageInput(params, revision) {
|
|
|
2924
3091
|
params.signal?.throwIfAborted();
|
|
2925
3092
|
if (state.get(message.id)?.invalidatedByRecall) return;
|
|
2926
3093
|
await beforeSend();
|
|
3094
|
+
const options = nativePayloadMediaOptions(payload);
|
|
3095
|
+
validateWeChatMentionSend(options.mentions, { ...payload, ...options, to: message.threadId });
|
|
2927
3096
|
const urls = payload.mediaUrls?.length ? payload.mediaUrls : payload.mediaUrl ? [payload.mediaUrl] : [];
|
|
2928
3097
|
if (urls.length > 16) throw new Error("Native reply media count exceeds its bound");
|
|
2929
3098
|
if (payload.audioAsVoice && !urls.length) throw new Error("Native voice reply requires an audio attachment");
|
|
@@ -2934,7 +3103,7 @@ async function dispatchNativeMessageInput(params, revision) {
|
|
|
2934
3103
|
if (payload.text) {
|
|
2935
3104
|
await beforeSend();
|
|
2936
3105
|
const key = createHash9("sha256").update(`${dispatchManifest.messageSid}\0${delivery++}`).digest("hex");
|
|
2937
|
-
await submitNativeText(client, account.native.accountId, message.threadId, payload.text, key);
|
|
3106
|
+
await submitNativeText(client, account.native.accountId, message.threadId, payload.text, key, { mentions: options.mentions });
|
|
2938
3107
|
}
|
|
2939
3108
|
if (urls.length || payload.text) params.onDelivered?.();
|
|
2940
3109
|
},
|
|
@@ -3173,18 +3342,6 @@ async function nativeLoginWait(account, timeoutMs = 3e4, stopAtQr = false, acces
|
|
|
3173
3342
|
guard(access2);
|
|
3174
3343
|
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" };
|
|
3175
3344
|
}
|
|
3176
|
-
async function sendNativeText(account, threadId2, text3, key = randomUUID5()) {
|
|
3177
|
-
const native = account.native;
|
|
3178
|
-
const { client } = await ensureNativeHost(native);
|
|
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
|
-
);
|
|
3187
|
-
}
|
|
3188
3345
|
function createNativeLoginTool(account, dependencies = {}) {
|
|
3189
3346
|
const actions = ["status", "start", "wait", "disconnect", "logout", "forget"];
|
|
3190
3347
|
const configurationKey = nativeConfigurationKey(account.native);
|
|
@@ -3239,28 +3396,81 @@ function registerNativeLoginTool(api) {
|
|
|
3239
3396
|
} }, { names: ["wechat_login"] });
|
|
3240
3397
|
}
|
|
3241
3398
|
|
|
3242
|
-
// src/
|
|
3243
|
-
|
|
3244
|
-
|
|
3245
|
-
|
|
3246
|
-
|
|
3399
|
+
// src/native-outbound-recovery.ts
|
|
3400
|
+
import { createMessageReceiptFromOutboundResults } from "openclaw/plugin-sdk/channel-outbound";
|
|
3401
|
+
function createWeChatDurableFinal(host2 = ensureNativeHost) {
|
|
3402
|
+
return {
|
|
3403
|
+
capabilities: { text: true, media: true, payload: true, replyTo: true, messageSendingHooks: true, reconcileUnknownSend: true },
|
|
3404
|
+
automaticUnknownSendReconciliation: true,
|
|
3405
|
+
reconcileUnknownSendKinds: { text: true, payload: true },
|
|
3406
|
+
reconcileUnknownSend: async (ctx) => {
|
|
3407
|
+
const unresolved = {
|
|
3408
|
+
status: "unresolved",
|
|
3409
|
+
retryable: false,
|
|
3410
|
+
error: "Inspect the original WeChat send receipt; do not send again with a new key."
|
|
3411
|
+
};
|
|
3412
|
+
try {
|
|
3413
|
+
if (ctx.channel !== "agent-wechat" || !ctx.queueId || ctx.payloads.length !== 1) return unresolved;
|
|
3414
|
+
const payload = ctx.payloads[0];
|
|
3415
|
+
const options = nativePayloadMediaOptions(payload);
|
|
3416
|
+
const replyToId = parseWeChatReplyTo(ctx.effectiveReplyToId ?? ctx.replyToId ?? payload.replyToId);
|
|
3417
|
+
if (payload.mediaUrl || payload.mediaUrls?.length || payload.audioAsVoice || payload.videoAsNote || payload.location || payload.presentation || payload.interactive || options.videoQuality != null || typeof payload.text !== "string" || !payload.text.trim()) return unresolved;
|
|
3418
|
+
validateWeChatMentionSend(options.mentions, { ...payload, to: ctx.to, replyToId });
|
|
3419
|
+
validateWeChatReplySend(replyToId, payload);
|
|
3420
|
+
const account = resolveWeChatAccount(ctx.cfg);
|
|
3421
|
+
if (!account?.enabled || !account.native || ctx.accountId && ctx.accountId !== account.accountId) return unresolved;
|
|
3422
|
+
const configurationKey = nativeConfigurationKey(account.native);
|
|
3423
|
+
const current = () => {
|
|
3424
|
+
const selected = resolveWeChatAccount(ctx.cfg);
|
|
3425
|
+
return selected?.enabled && selected.native && nativeConfigurationKey(selected.native) === configurationKey;
|
|
3426
|
+
};
|
|
3427
|
+
const { client } = await host2(account.native);
|
|
3428
|
+
if (!current()) return unresolved;
|
|
3429
|
+
const intent = await client.sendByKey(account.native.accountId, nativeOutboundKey(ctx.queueId));
|
|
3430
|
+
if (!current() || !("destination" in intent) || intent.accountId !== account.native.accountId || intent.destination !== ctx.to || !["accepted", "sent", "server_accepted"].includes(intent.state) || !intent.localMessageId || !intent.serverId) return unresolved;
|
|
3431
|
+
if (!options.mentions) {
|
|
3432
|
+
const message = await client.message(account.native.accountId, intent.localMessageId);
|
|
3433
|
+
if (!current() || message.body !== payload.text) return unresolved;
|
|
3434
|
+
if (replyToId) {
|
|
3435
|
+
const original = await client.message(account.native.accountId, nativeReplyMessageId(replyToId, account.native.accountId));
|
|
3436
|
+
const quote = nativeReplyReference(original, account.native.accountId, ctx.to, replyToId);
|
|
3437
|
+
if (!current() || message.type !== 49 || message.appMessageType !== 57 || message.quote?.serverId !== quote.serverId) return unresolved;
|
|
3438
|
+
} else if (message.type !== 1 || message.quote) return unresolved;
|
|
3439
|
+
}
|
|
3440
|
+
const delivery = await nativeOutboundDelivery(
|
|
3441
|
+
client,
|
|
3442
|
+
account.native.accountId,
|
|
3443
|
+
ctx.to,
|
|
3444
|
+
[intent.localMessageId],
|
|
3445
|
+
{ sendId: intent.id, state: intent.state, serverIds: [intent.serverId] }
|
|
3446
|
+
);
|
|
3447
|
+
if (!current() || delivery.meta.outcome !== "sent" || !delivery.messageId) return unresolved;
|
|
3448
|
+
const receipt = createMessageReceiptFromOutboundResults({
|
|
3449
|
+
results: [{ channel: "agent-wechat", ...delivery }],
|
|
3450
|
+
kind: "text",
|
|
3451
|
+
threadId: ctx.threadId == null ? void 0 : String(ctx.threadId)
|
|
3452
|
+
});
|
|
3453
|
+
return { status: "sent", receipt, messageId: delivery.messageId };
|
|
3454
|
+
} catch {
|
|
3455
|
+
return unresolved;
|
|
3456
|
+
}
|
|
3457
|
+
}
|
|
3458
|
+
};
|
|
3247
3459
|
}
|
|
3460
|
+
|
|
3461
|
+
// src/channel.ts
|
|
3248
3462
|
var mediaHandlers = createWeChatMediaHandlers();
|
|
3249
3463
|
var wechatMessageAdapter = createChannelMessageAdapterFromOutbound({
|
|
3250
3464
|
id: "agent-wechat",
|
|
3251
3465
|
capabilities: {
|
|
3252
3466
|
text: true,
|
|
3253
3467
|
media: true,
|
|
3468
|
+
replyTo: true,
|
|
3254
3469
|
messageSendingHooks: true
|
|
3255
3470
|
},
|
|
3256
|
-
outbound:
|
|
3257
|
-
sendText: async ({ cfg, to, text: text3 }) => ({
|
|
3258
|
-
channel: "agent-wechat",
|
|
3259
|
-
...await sendWeChatText(cfg, to, text3)
|
|
3260
|
-
}),
|
|
3261
|
-
...mediaHandlers
|
|
3262
|
-
}
|
|
3471
|
+
outbound: mediaHandlers
|
|
3263
3472
|
});
|
|
3473
|
+
wechatMessageAdapter.durableFinal = createWeChatDurableFinal();
|
|
3264
3474
|
var meta = {
|
|
3265
3475
|
id: "agent-wechat",
|
|
3266
3476
|
label: "WeChat",
|
|
@@ -3400,10 +3610,6 @@ var wechatPlugin = {
|
|
|
3400
3610
|
// ---- Outbound adapter for OpenClaw hosts using the outbound hook ----
|
|
3401
3611
|
outbound: {
|
|
3402
3612
|
deliveryMode: "direct",
|
|
3403
|
-
sendText: async ({ cfg, to, text: text3 }) => ({
|
|
3404
|
-
channel: "agent-wechat",
|
|
3405
|
-
...await sendWeChatText(cfg, to, text3)
|
|
3406
|
-
}),
|
|
3407
3613
|
...mediaHandlers
|
|
3408
3614
|
},
|
|
3409
3615
|
message: wechatMessageAdapter,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agent-wechat/agent-wechat",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist",
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
"esbuild": "^0.25.0",
|
|
12
12
|
"openclaw": "2026.10.7",
|
|
13
13
|
"typescript": "^5.4.5",
|
|
14
|
-
"@agent-wechat/shared": "1.
|
|
14
|
+
"@agent-wechat/shared": "1.1.0"
|
|
15
15
|
},
|
|
16
16
|
"openclaw": {
|
|
17
17
|
"extensions": [
|