@agent-wechat/agent-wechat 1.0.0-beta.2 → 1.0.0-beta.20
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/README.md +143 -8
- package/dist/index.js +2299 -356
- package/openclaw.plugin.json +12 -0
- package/package.json +4 -3
package/dist/index.js
CHANGED
|
@@ -22,7 +22,7 @@ var nativeConfigSchema = {
|
|
|
22
22
|
}
|
|
23
23
|
}] },
|
|
24
24
|
consumerStateDir: { type: "string" },
|
|
25
|
-
readPolicy: { type: "string", enum: ["never", "on_model_dispatch"] },
|
|
25
|
+
readPolicy: { type: "string", enum: ["never", "on_inbound", "on_model_dispatch"] },
|
|
26
26
|
gatewayFacade: { type: "object", additionalProperties: false, required: ["enabled"], properties: { enabled: { type: "boolean" }, prefix: { type: "string" } } }
|
|
27
27
|
}
|
|
28
28
|
};
|
|
@@ -110,17 +110,30 @@ import { constants } from "node:fs";
|
|
|
110
110
|
import { access, lstat, readFile, realpath } from "node:fs/promises";
|
|
111
111
|
import { spawn, execFile } from "node:child_process";
|
|
112
112
|
import { promisify } from "node:util";
|
|
113
|
-
import { delimiter, dirname, isAbsolute, join } from "node:path";
|
|
113
|
+
import { delimiter, dirname, isAbsolute, join, toNamespacedPath } from "node:path";
|
|
114
114
|
import { createConnection } from "node:net";
|
|
115
115
|
|
|
116
116
|
// ../shared/dist/native.generated.js
|
|
117
|
-
var NATIVE_MAX_SOURCE_BYTES =
|
|
117
|
+
var NATIVE_MAX_SOURCE_BYTES = 536870912;
|
|
118
|
+
var NATIVE_MAX_ORDINARY_SOURCE_BYTES = 26214383;
|
|
119
|
+
var NATIVE_MAX_VIDEO_SOURCE_BYTES = 52428800;
|
|
118
120
|
|
|
119
121
|
// ../shared/dist/native-client.js
|
|
120
122
|
function isNativeTombstone(value) {
|
|
121
123
|
const item = value;
|
|
122
124
|
return item?.deleted === true && typeof item.id === "string" && typeof item.version === "string";
|
|
123
125
|
}
|
|
126
|
+
function validateNativeRecallMetadata(value) {
|
|
127
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
128
|
+
throw new Error("Invalid native recall metadata");
|
|
129
|
+
const recall = value;
|
|
130
|
+
if (recall.replacementText != null && (typeof recall.replacementText !== "string" || !recall.replacementText || recall.replacementText.length > 16384 || new TextEncoder().encode(recall.replacementText).length > 16384 || /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\ufffe\uffff]/.test(recall.replacementText)))
|
|
131
|
+
throw new Error("Invalid native recall metadata");
|
|
132
|
+
}
|
|
133
|
+
function validateMessageRecall(message) {
|
|
134
|
+
if (message.recall != null)
|
|
135
|
+
validateNativeRecallMetadata(message.recall);
|
|
136
|
+
}
|
|
124
137
|
function listQuery(input) {
|
|
125
138
|
const options = typeof input === "string" ? { cursor: input } : input;
|
|
126
139
|
if (!options)
|
|
@@ -146,13 +159,13 @@ var NativeApiError = class extends Error {
|
|
|
146
159
|
}
|
|
147
160
|
};
|
|
148
161
|
function validateNativeBaseUrl(input) {
|
|
149
|
-
const
|
|
150
|
-
const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(
|
|
151
|
-
if (
|
|
162
|
+
const url2 = new URL(input);
|
|
163
|
+
const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url2.hostname.toLowerCase());
|
|
164
|
+
if (url2.username || url2.password || url2.search || url2.hash || !["http:", "https:"].includes(url2.protocol) || url2.protocol === "http:" && !loopback)
|
|
152
165
|
throw new Error("Native API requires verified HTTPS or a loopback HTTP endpoint, without embedded credentials");
|
|
153
|
-
if (!
|
|
154
|
-
|
|
155
|
-
return
|
|
166
|
+
if (!url2.pathname.endsWith("/"))
|
|
167
|
+
url2.pathname += "/";
|
|
168
|
+
return url2;
|
|
156
169
|
}
|
|
157
170
|
var id = (value) => {
|
|
158
171
|
if (typeof value !== "string" || !value || value === "." || value === ".." || value.length > 4096 || /[\u0000-\u001f\u007f]/.test(value))
|
|
@@ -165,10 +178,13 @@ var decimal = (value) => {
|
|
|
165
178
|
return value;
|
|
166
179
|
};
|
|
167
180
|
var NativeWeChatClient = class {
|
|
181
|
+
mediaBatchSupported = true;
|
|
168
182
|
baseUrl;
|
|
169
183
|
token;
|
|
170
184
|
fetchImpl;
|
|
171
185
|
timeoutMs;
|
|
186
|
+
mediaTimeoutMs;
|
|
187
|
+
streamIdleTimeoutMs;
|
|
172
188
|
constructor(options) {
|
|
173
189
|
this.baseUrl = validateNativeBaseUrl(options.baseUrl);
|
|
174
190
|
const nodeEnvironment = globalThis.process?.env;
|
|
@@ -177,15 +193,21 @@ var NativeWeChatClient = class {
|
|
|
177
193
|
if (typeof options.token !== "string" || !options.token || /[\r\n]/.test(options.token))
|
|
178
194
|
throw new Error("Native API bearer token is required");
|
|
179
195
|
this.token = options.token;
|
|
180
|
-
this.fetchImpl = options.fetch ?? fetch;
|
|
196
|
+
this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
181
197
|
this.timeoutMs = options.timeoutMs ?? 3e4;
|
|
198
|
+
this.mediaTimeoutMs = options.mediaTimeoutMs ?? 60 * 6e4;
|
|
199
|
+
if (!Number.isInteger(this.mediaTimeoutMs) || this.mediaTimeoutMs < 1 || this.mediaTimeoutMs > 60 * 6e4)
|
|
200
|
+
throw new Error("Invalid native media timeout");
|
|
201
|
+
this.streamIdleTimeoutMs = options.streamIdleTimeoutMs ?? 45e3;
|
|
202
|
+
if (!Number.isInteger(this.streamIdleTimeoutMs) || this.streamIdleTimeoutMs < 1 || this.streamIdleTimeoutMs > 3e5)
|
|
203
|
+
throw new Error("Invalid native stream idle timeout");
|
|
182
204
|
}
|
|
183
|
-
async response(path, init = {}, stream = false) {
|
|
205
|
+
async response(path, init = {}, stream = false, timeoutMs = this.timeoutMs) {
|
|
184
206
|
const headers = new Headers(init.headers);
|
|
185
207
|
headers.set("Authorization", `Bearer ${this.token}`);
|
|
186
208
|
if (init.body != null && !(init.body instanceof FormData))
|
|
187
209
|
headers.set("Content-Type", "application/json");
|
|
188
|
-
const timeout = stream ? void 0 : AbortSignal.timeout(
|
|
210
|
+
const timeout = stream ? void 0 : AbortSignal.timeout(timeoutMs);
|
|
189
211
|
const signal = init.signal && timeout ? AbortSignal.any([init.signal, timeout]) : init.signal ?? timeout;
|
|
190
212
|
const response = await this.fetchImpl(new URL(path, this.baseUrl), { ...init, headers, redirect: "error", signal });
|
|
191
213
|
if (!response.ok) {
|
|
@@ -258,9 +280,22 @@ var NativeWeChatClient = class {
|
|
|
258
280
|
throw new Error("Account ID or alias is required");
|
|
259
281
|
return this.request("v1/accounts", { method: "POST", body: JSON.stringify(body) });
|
|
260
282
|
}
|
|
283
|
+
removeAccount(accountId, confirmAccountId) {
|
|
284
|
+
if (accountId !== confirmAccountId)
|
|
285
|
+
throw new Error("Account confirmation does not match");
|
|
286
|
+
return this.request(`v1/accounts/${id(accountId)}`, { method: "DELETE", body: JSON.stringify({ confirmAccountId }) });
|
|
287
|
+
}
|
|
261
288
|
updateAccount(accountId, options) {
|
|
262
289
|
return this.request(`v1/accounts/${id(accountId)}`, { method: "PATCH", body: JSON.stringify(options) });
|
|
263
290
|
}
|
|
291
|
+
accountSettings(accountId, signal) {
|
|
292
|
+
return this.request(`v1/accounts/${id(accountId)}/settings`, { signal });
|
|
293
|
+
}
|
|
294
|
+
updateAccountSettings(accountId, settings, signal) {
|
|
295
|
+
if (!Number.isSafeInteger(settings.autoDownloadMaxBytes) || settings.autoDownloadMaxBytes < 0 || settings.autoDownloadMaxBytes > NATIVE_MAX_SOURCE_BYTES)
|
|
296
|
+
throw new Error("Invalid automatic download limit");
|
|
297
|
+
return this.request(`v1/accounts/${id(accountId)}/settings`, { method: "PATCH", body: JSON.stringify(settings), signal });
|
|
298
|
+
}
|
|
264
299
|
capabilities(accountId) {
|
|
265
300
|
return this.request(`v1/accounts/${id(accountId)}/capabilities`);
|
|
266
301
|
}
|
|
@@ -279,8 +314,24 @@ var NativeWeChatClient = class {
|
|
|
279
314
|
throw new Error("Invalid login idempotency key");
|
|
280
315
|
return this.request(`v1/accounts/${id(accountId)}/auth/login`, { method: "POST", headers: key ? { "Idempotency-Key": key } : void 0, body: JSON.stringify(options) });
|
|
281
316
|
}
|
|
282
|
-
operation(accountId, operationId) {
|
|
283
|
-
return this.request(`v1/accounts/${id(accountId)}/operations/${id(operationId)}
|
|
317
|
+
operation(accountId, operationId, signal) {
|
|
318
|
+
return this.request(`v1/accounts/${id(accountId)}/operations/${id(operationId)}`, { signal });
|
|
319
|
+
}
|
|
320
|
+
/** Submit once with a stable key; inspect the returned operation after uncertainty. */
|
|
321
|
+
async recallMessage(accountId, messageId, serverId, idempotencyKey, signal) {
|
|
322
|
+
if (typeof serverId !== "string" || !/^[1-9]\d{0,19}$/.test(serverId) || BigInt(serverId) > 18446744073709551615n)
|
|
323
|
+
throw new Error("Invalid exact recall server ID");
|
|
324
|
+
if (typeof idempotencyKey !== "string" || !idempotencyKey || idempotencyKey.length > 200 || /[\r\n]/.test(idempotencyKey))
|
|
325
|
+
throw new Error("Invalid recall idempotency key");
|
|
326
|
+
const operation = await this.request(`v1/accounts/${id(accountId)}/messages/${id(messageId)}/recall`, {
|
|
327
|
+
method: "POST",
|
|
328
|
+
headers: { "Idempotency-Key": idempotencyKey },
|
|
329
|
+
body: JSON.stringify({ serverId }),
|
|
330
|
+
signal
|
|
331
|
+
});
|
|
332
|
+
if (!operation || operation.accountId !== accountId || operation.kind !== "message_recall" || typeof operation.id !== "string" || !operation.id || typeof operation.state !== "string")
|
|
333
|
+
throw new Error("Native recall operation identity is invalid");
|
|
334
|
+
return operation;
|
|
284
335
|
}
|
|
285
336
|
cancelOperation(accountId, operationId) {
|
|
286
337
|
return this.request(`v1/accounts/${id(accountId)}/operations/${id(operationId)}`, { method: "DELETE" });
|
|
@@ -318,17 +369,62 @@ var NativeWeChatClient = class {
|
|
|
318
369
|
groups(accountId, options) {
|
|
319
370
|
return this.request(`v1/accounts/${id(accountId)}/groups${listQuery(options)}`);
|
|
320
371
|
}
|
|
321
|
-
thread(accountId,
|
|
322
|
-
return this.request(`v1/accounts/${id(accountId)}/threads/${id(
|
|
372
|
+
thread(accountId, threadId2, signal) {
|
|
373
|
+
return this.request(`v1/accounts/${id(accountId)}/threads/${id(threadId2)}`, { signal });
|
|
323
374
|
}
|
|
324
375
|
contact(accountId, username) {
|
|
325
376
|
return this.request(`v1/accounts/${id(accountId)}/contacts/${id(username)}`);
|
|
326
377
|
}
|
|
327
|
-
group(accountId, roomId) {
|
|
328
|
-
return this.request(`v1/accounts/${id(accountId)}/groups/${id(roomId)}
|
|
378
|
+
group(accountId, roomId, signal) {
|
|
379
|
+
return this.request(`v1/accounts/${id(accountId)}/groups/${id(roomId)}`, { signal });
|
|
380
|
+
}
|
|
381
|
+
groupMembers(accountId, roomId, options, signal) {
|
|
382
|
+
return this.request(`v1/accounts/${id(accountId)}/groups/${id(roomId)}/members${listQuery(options)}`, { signal });
|
|
383
|
+
}
|
|
384
|
+
groupMember(accountId, roomId, username, signal) {
|
|
385
|
+
return this.request(`v1/accounts/${id(accountId)}/groups/${id(roomId)}/members/${id(username)}`, { signal });
|
|
386
|
+
}
|
|
387
|
+
async groupMutation(accountId, path, method, body, key, action, target, signal) {
|
|
388
|
+
if (typeof key !== "string" || !key || key.length > 200 || /[\u0000-\u001f\u007f]/.test(key))
|
|
389
|
+
throw new Error("A stable group idempotency key is required");
|
|
390
|
+
const operation = await this.request(`v1/accounts/${id(accountId)}/${path}`, { method, body: JSON.stringify(body), headers: { "Idempotency-Key": key }, signal });
|
|
391
|
+
const result = operation?.result;
|
|
392
|
+
if (!operation || operation.accountId !== accountId || operation.kind !== "group_mutation" || typeof operation.id !== "string" || !operation.id || !result || result.action !== action || result.targetId !== target)
|
|
393
|
+
throw new Error("Native group operation identity is invalid");
|
|
394
|
+
return operation;
|
|
395
|
+
}
|
|
396
|
+
/** A repeated key returns the same operation. Uncertain mutations must be inspected, never repeated with a new key. */
|
|
397
|
+
createGroup(accountId, input, key, signal) {
|
|
398
|
+
return this.groupMutation(accountId, "groups", "POST", input, key, "create", null, signal);
|
|
399
|
+
}
|
|
400
|
+
renameGroup(accountId, groupId, name3, key, signal) {
|
|
401
|
+
return this.groupMutation(accountId, `groups/${id(groupId)}`, "PATCH", { name: name3 }, key, "rename", groupId, signal);
|
|
402
|
+
}
|
|
403
|
+
leaveGroup(accountId, groupId, key, signal) {
|
|
404
|
+
return this.groupMutation(accountId, `groups/${id(groupId)}/leave`, "POST", {}, key, "leave", groupId, signal);
|
|
405
|
+
}
|
|
406
|
+
addGroupMembers(accountId, groupId, members, key, signal) {
|
|
407
|
+
return this.groupMutation(accountId, `groups/${id(groupId)}/members`, "POST", { members }, key, "add_members", groupId, signal);
|
|
408
|
+
}
|
|
409
|
+
removeGroupMembers(accountId, groupId, members, key, signal) {
|
|
410
|
+
return this.groupMutation(accountId, `groups/${id(groupId)}/members`, "DELETE", { members }, key, "remove_members", groupId, signal);
|
|
329
411
|
}
|
|
330
|
-
|
|
331
|
-
return this.
|
|
412
|
+
setMyGroupName(accountId, groupId, displayName, key, signal) {
|
|
413
|
+
return this.groupMutation(accountId, `groups/${id(groupId)}/my-name`, "PUT", { displayName }, key, "my_name", groupId, signal);
|
|
414
|
+
}
|
|
415
|
+
clearGroupAnnouncement(accountId, groupId, key, signal) {
|
|
416
|
+
return this.groupMutation(accountId, `groups/${id(groupId)}/announcement`, "DELETE", {}, key, "clear_announcement", groupId, signal);
|
|
417
|
+
}
|
|
418
|
+
setThreadMuted(accountId, threadId2, muted, key, signal) {
|
|
419
|
+
return this.groupMutation(accountId, `threads/${id(threadId2)}/notifications`, "PUT", { muted }, key, "mute", threadId2, signal);
|
|
420
|
+
}
|
|
421
|
+
setThreadPinned(accountId, threadId2, pinned, key, signal) {
|
|
422
|
+
if (typeof pinned !== "boolean")
|
|
423
|
+
throw new Error("Thread pinned state must be a boolean");
|
|
424
|
+
return this.groupMutation(accountId, `threads/${id(threadId2)}/pin`, "PUT", { pinned }, key, "pin", threadId2, signal);
|
|
425
|
+
}
|
|
426
|
+
groupMutationByKey(accountId, key, signal) {
|
|
427
|
+
return this.request(`v1/accounts/${id(accountId)}/group-mutations/by-idempotency-key?${new URLSearchParams({ key })}`, { signal });
|
|
332
428
|
}
|
|
333
429
|
refreshAvatar(accountId, username) {
|
|
334
430
|
return this.request(`v1/accounts/${id(accountId)}/avatars/${id(username)}/refresh`, { method: "POST", body: "{}" });
|
|
@@ -357,13 +453,14 @@ var NativeWeChatClient = class {
|
|
|
357
453
|
syncGroups(accountId) {
|
|
358
454
|
return this.request(`v1/accounts/${id(accountId)}/group-sync`, { method: "POST", body: "{}" });
|
|
359
455
|
}
|
|
360
|
-
async messages(accountId,
|
|
361
|
-
const result = await this.request(`v1/accounts/${id(accountId)}/threads/${id(
|
|
456
|
+
async messages(accountId, threadId2, options, signal) {
|
|
457
|
+
const result = await this.request(`v1/accounts/${id(accountId)}/threads/${id(threadId2)}/messages${listQuery(options)}`, { signal });
|
|
362
458
|
for (const msg of result.items) {
|
|
363
459
|
if (isNativeTombstone(msg))
|
|
364
460
|
continue;
|
|
365
|
-
if (typeof msg.id !== "string" || msg.accountId !== accountId || msg.threadId !==
|
|
461
|
+
if (typeof msg.id !== "string" || msg.accountId !== accountId || msg.threadId !== threadId2 || msg.serverId != null && (typeof msg.serverId !== "string" || !/^\d+$/.test(msg.serverId)))
|
|
366
462
|
throw new Error("Invalid native message identity");
|
|
463
|
+
validateMessageRecall(msg);
|
|
367
464
|
}
|
|
368
465
|
return result;
|
|
369
466
|
}
|
|
@@ -371,16 +468,40 @@ var NativeWeChatClient = class {
|
|
|
371
468
|
const message = await this.request(`v1/accounts/${id(accountId)}/messages/${id(messageId)}`);
|
|
372
469
|
if (message.id !== messageId || message.accountId !== accountId || message.serverId != null && (typeof message.serverId !== "string" || !/^\d+$/.test(message.serverId)))
|
|
373
470
|
throw new Error("Invalid native message identity");
|
|
471
|
+
validateMessageRecall(message);
|
|
374
472
|
return message;
|
|
375
473
|
}
|
|
376
|
-
|
|
474
|
+
/** Account-wide local search, with the daemon's query-bound opaque cursor. */
|
|
475
|
+
async searchMessages(accountId, options) {
|
|
476
|
+
const result = await this.request(`v1/accounts/${id(accountId)}/messages${listQuery(options)}`);
|
|
477
|
+
for (const message of result.items) {
|
|
478
|
+
if (isNativeTombstone(message))
|
|
479
|
+
continue;
|
|
480
|
+
if (typeof message.id !== "string" || message.accountId !== accountId || typeof message.threadId !== "string" || !message.threadId || message.serverId != null && (typeof message.serverId !== "string" || !/^\d+$/.test(message.serverId)))
|
|
481
|
+
throw new Error("Invalid native archive message identity");
|
|
482
|
+
validateMessageRecall(message);
|
|
483
|
+
}
|
|
484
|
+
return result;
|
|
485
|
+
}
|
|
486
|
+
/** Quote a locally stored text, image, voice, video, link, file or quoted reply in the same chat.
|
|
487
|
+
* Live acceptance and recipient rendering remain unverified; other source kinds are rejected.
|
|
488
|
+
*/
|
|
489
|
+
sendText(accountId, threadId2, text3, idempotencyKey, quote) {
|
|
377
490
|
if (!idempotencyKey || /[\r\n]/.test(idempotencyKey))
|
|
378
491
|
throw new Error("An idempotency key is required");
|
|
379
|
-
|
|
492
|
+
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
|
+
throw new Error("Invalid quote message identity");
|
|
494
|
+
const input = quote === void 0 ? { threadId: threadId2, text: text3 } : { kind: "text", threadId: threadId2, text: text3, quote };
|
|
495
|
+
return this.request(`v1/accounts/${id(accountId)}/sends`, { method: "POST", headers: { "Idempotency-Key": idempotencyKey }, body: JSON.stringify(input) });
|
|
380
496
|
}
|
|
381
497
|
send(accountId, sendId, signal) {
|
|
382
498
|
return this.request(`v1/accounts/${id(accountId)}/sends/${id(sendId)}`, { signal });
|
|
383
499
|
}
|
|
500
|
+
sendShare(accountId, input, key, signal) {
|
|
501
|
+
if (!key || key.length > 200 || /[\u0000-\u001f\u007f]/.test(key))
|
|
502
|
+
throw new Error("An idempotency key is required");
|
|
503
|
+
return this.request(`v1/accounts/${id(accountId)}/sends`, { method: "POST", headers: { "Idempotency-Key": key }, body: JSON.stringify(input), signal });
|
|
504
|
+
}
|
|
384
505
|
sendByKey(accountId, key) {
|
|
385
506
|
if (!key || key.length > 200)
|
|
386
507
|
throw new Error("Invalid idempotency key");
|
|
@@ -389,20 +510,54 @@ var NativeWeChatClient = class {
|
|
|
389
510
|
cancelSend(accountId, sendId) {
|
|
390
511
|
return this.request(`v1/accounts/${id(accountId)}/sends/${id(sendId)}/cancel`, { method: "POST", body: "{}" });
|
|
391
512
|
}
|
|
392
|
-
|
|
393
|
-
|
|
513
|
+
/** A disk-backed Blob avoids holding the source in memory before staging. */
|
|
514
|
+
async upload(accountId, bytes, name3, contentType = "application/octet-stream", signal) {
|
|
515
|
+
const size = bytes instanceof Blob ? bytes.size : bytes.byteLength;
|
|
516
|
+
if (!size || size > NATIVE_MAX_SOURCE_BYTES || !name3 || name3.length > 255 || /[\r\n/\\]/.test(name3))
|
|
394
517
|
throw new Error("Invalid bounded media upload");
|
|
518
|
+
const part = bytes instanceof Blob ? bytes.slice(0, bytes.size, contentType) : new Blob([bytes.buffer instanceof ArrayBuffer ? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength) : new Uint8Array(bytes)], { type: contentType });
|
|
395
519
|
const form = new FormData();
|
|
396
|
-
form.set("file",
|
|
397
|
-
|
|
520
|
+
form.set("file", part, name3);
|
|
521
|
+
const response = await this.response(`v1/accounts/${id(accountId)}/uploads`, { method: "POST", body: form, signal }, false, this.mediaTimeoutMs);
|
|
522
|
+
return JSON.parse(new TextDecoder().decode(await this.readBounded(response)));
|
|
398
523
|
}
|
|
399
524
|
sendMedia(accountId, input, key) {
|
|
400
525
|
if (!key || /[\r\n]/.test(key))
|
|
401
526
|
throw new Error("An idempotency key is required");
|
|
402
527
|
return this.request(`v1/accounts/${id(accountId)}/sends`, { method: "POST", headers: { "Idempotency-Key": key }, body: JSON.stringify(input) });
|
|
403
528
|
}
|
|
404
|
-
mediaAssets(accountId, messageId) {
|
|
405
|
-
return this.request(`v1/accounts/${id(accountId)}/messages/${id(messageId)}/media
|
|
529
|
+
mediaAssets(accountId, messageId, signal) {
|
|
530
|
+
return this.request(`v1/accounts/${id(accountId)}/messages/${id(messageId)}/media`, { signal });
|
|
531
|
+
}
|
|
532
|
+
async mediaAssetsBatch(accountId, messageIds, signal) {
|
|
533
|
+
if (!messageIds.length || messageIds.length > 40 || messageIds.some((id2) => !id2 || id2.length > 8192) || new Set(messageIds).size !== messageIds.length)
|
|
534
|
+
throw new Error("Invalid media lookup batch");
|
|
535
|
+
if (this.mediaBatchSupported) {
|
|
536
|
+
try {
|
|
537
|
+
const batch = await this.request(`v1/accounts/${id(accountId)}/media/lookup`, { method: "POST", body: JSON.stringify({ messageIds }), signal });
|
|
538
|
+
const expected = new Set(messageIds);
|
|
539
|
+
if (!Array.isArray(batch.items) || batch.items.length !== expected.size)
|
|
540
|
+
throw new Error("Invalid media lookup response");
|
|
541
|
+
for (const item of batch.items) {
|
|
542
|
+
if (!expected.delete(item.messageId) || !Array.isArray(item.assets) || item.error !== null && typeof item.error !== "string" || item.assets.some((asset) => asset.accountId !== accountId || asset.messageId !== item.messageId))
|
|
543
|
+
throw new Error("Invalid media lookup identity");
|
|
544
|
+
}
|
|
545
|
+
return batch;
|
|
546
|
+
} catch (error) {
|
|
547
|
+
if (!(error instanceof NativeApiError) || ![404, 405].includes(error.status))
|
|
548
|
+
throw error;
|
|
549
|
+
this.mediaBatchSupported = false;
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
return { items: await Promise.all(messageIds.map(async (messageId) => {
|
|
553
|
+
try {
|
|
554
|
+
return { messageId, assets: (await this.mediaAssets(accountId, messageId, signal)).items, error: null };
|
|
555
|
+
} catch (error) {
|
|
556
|
+
if (!(error instanceof NativeApiError))
|
|
557
|
+
throw error;
|
|
558
|
+
return { messageId, assets: [], error: error.code };
|
|
559
|
+
}
|
|
560
|
+
})) };
|
|
406
561
|
}
|
|
407
562
|
transferMedia(accountId, input) {
|
|
408
563
|
return this.request(`v1/accounts/${id(accountId)}/messages/${id(input.messageId)}/media-transfers`, { method: "POST", body: JSON.stringify(input) });
|
|
@@ -416,52 +571,135 @@ var NativeWeChatClient = class {
|
|
|
416
571
|
cancelJob(accountId, jobId) {
|
|
417
572
|
return this.request(`v1/accounts/${id(accountId)}/jobs/${id(jobId)}/cancel`, { method: "POST", body: "{}" });
|
|
418
573
|
}
|
|
419
|
-
retryJob(accountId, jobId) {
|
|
420
|
-
|
|
574
|
+
retryJob(accountId, jobId, options = {}) {
|
|
575
|
+
if (!options || typeof options !== "object" || Array.isArray(options) || Object.keys(options).some((key) => key !== "reuseCompletedUpload"))
|
|
576
|
+
throw new Error("Invalid media retry options");
|
|
577
|
+
const reuse = options.reuseCompletedUpload;
|
|
578
|
+
if (reuse !== void 0 && typeof reuse !== "boolean")
|
|
579
|
+
throw new Error("Invalid media retry options");
|
|
580
|
+
return this.request(`v1/accounts/${id(accountId)}/jobs/${id(jobId)}/${reuse === true ? "retry-completed-upload" : "retry"}`, { method: "POST", body: JSON.stringify(reuse === void 0 ? {} : { reuseCompletedUpload: reuse }) });
|
|
421
581
|
}
|
|
422
582
|
repairMediaWriteback(accountId, limit = 25) {
|
|
423
583
|
if (!Number.isInteger(limit) || limit < 1 || limit > 100)
|
|
424
584
|
throw new Error("Invalid media writeback limit");
|
|
425
585
|
return this.request(`v1/accounts/${id(accountId)}/media-writeback/repair`, { method: "POST", body: JSON.stringify({ limit }) });
|
|
426
586
|
}
|
|
427
|
-
|
|
587
|
+
/** Consume the bounded stream once, or cancel it; this never starts a CDN transfer. */
|
|
588
|
+
async mediaContentStream(accountId, assetId, options = {}) {
|
|
428
589
|
const max = options.maxBytes ?? 128 * 1024 * 1024;
|
|
429
|
-
if (!Number.isInteger(max) || max < 1 || max > 128 * 1024 * 1024 || options.range && !/^bytes=(?:\d+-\d*|-\d+)$/.test(options.range))
|
|
590
|
+
if (!Number.isInteger(max) || max < 1 || max > Math.max(128 * 1024 * 1024, NATIVE_MAX_SOURCE_BYTES) || options.range && !/^bytes=(?:\d+-\d*|-\d+)$/.test(options.range) || options.representation != null && !["original", "preview"].includes(options.representation))
|
|
430
591
|
throw new Error("Invalid bounded content request");
|
|
431
|
-
const
|
|
592
|
+
const query = options.representation === "preview" ? "?representation=preview" : "";
|
|
593
|
+
const cancellation = new AbortController();
|
|
594
|
+
const response = await this.response(`v1/accounts/${id(accountId)}/media/${id(assetId)}/content${query}`, { signal: options.signal ? AbortSignal.any([options.signal, cancellation.signal]) : cancellation.signal, headers: options.range ? { Range: options.range } : {} }, false, this.mediaTimeoutMs);
|
|
432
595
|
const length = response.headers.get("content-length");
|
|
433
596
|
if (length && (!/^\d+$/.test(length) || Number(length) > max)) {
|
|
434
597
|
await response.body?.cancel();
|
|
435
598
|
throw new Error("Native media response exceeds its bound");
|
|
436
599
|
}
|
|
437
|
-
|
|
600
|
+
if (!response.body && length && Number(length) > 0)
|
|
601
|
+
throw new Error("Native media response length mismatch");
|
|
602
|
+
let activeReader;
|
|
603
|
+
const iterate = async function* () {
|
|
604
|
+
cancellation.signal.throwIfAborted();
|
|
605
|
+
options.signal?.throwIfAborted();
|
|
606
|
+
const reader = response.body?.getReader();
|
|
607
|
+
if (!reader)
|
|
608
|
+
return;
|
|
609
|
+
activeReader = reader;
|
|
610
|
+
let size = 0;
|
|
611
|
+
try {
|
|
612
|
+
while (true) {
|
|
613
|
+
cancellation.signal.throwIfAborted();
|
|
614
|
+
options.signal?.throwIfAborted();
|
|
615
|
+
const { value, done } = await reader.read();
|
|
616
|
+
cancellation.signal.throwIfAborted();
|
|
617
|
+
options.signal?.throwIfAborted();
|
|
618
|
+
if (done)
|
|
619
|
+
break;
|
|
620
|
+
size += value.byteLength;
|
|
621
|
+
if (size > max)
|
|
622
|
+
throw new Error("Native media response exceeds its bound");
|
|
623
|
+
yield value;
|
|
624
|
+
}
|
|
625
|
+
if (length && size !== Number(length))
|
|
626
|
+
throw new Error("Native media response length mismatch");
|
|
627
|
+
} finally {
|
|
628
|
+
await reader.cancel().catch(() => {
|
|
629
|
+
});
|
|
630
|
+
reader.releaseLock();
|
|
631
|
+
activeReader = void 0;
|
|
632
|
+
}
|
|
633
|
+
};
|
|
634
|
+
let claimed = false;
|
|
635
|
+
const stream = { [Symbol.asyncIterator]() {
|
|
636
|
+
if (claimed)
|
|
637
|
+
throw new Error("Native media stream was already consumed");
|
|
638
|
+
claimed = true;
|
|
639
|
+
return iterate();
|
|
640
|
+
} };
|
|
641
|
+
return { stream, cancel: async () => {
|
|
642
|
+
cancellation.abort();
|
|
643
|
+
await (activeReader ? activeReader.cancel() : response.body?.cancel())?.catch(() => {
|
|
644
|
+
});
|
|
645
|
+
}, contentType: response.headers.get("content-type") ?? "application/octet-stream", etag: response.headers.get("etag"), contentRange: response.headers.get("content-range"), sourceSha256: response.headers.get("x-source-sha256"), status: response.status };
|
|
438
646
|
}
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
647
|
+
async mediaContent(accountId, assetId, options = {}) {
|
|
648
|
+
const { stream, cancel: _cancel, ...metadata } = await this.mediaContentStream(accountId, assetId, options);
|
|
649
|
+
const chunks = [];
|
|
650
|
+
let size = 0;
|
|
651
|
+
for await (const chunk of stream) {
|
|
652
|
+
chunks.push(chunk);
|
|
653
|
+
size += chunk.byteLength;
|
|
654
|
+
}
|
|
655
|
+
const bytes = new Uint8Array(size);
|
|
656
|
+
let offset = 0;
|
|
657
|
+
for (const chunk of chunks) {
|
|
658
|
+
bytes.set(chunk, offset);
|
|
659
|
+
offset += chunk.byteLength;
|
|
660
|
+
}
|
|
661
|
+
return { ...metadata, bytes };
|
|
443
662
|
}
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
if (typeof expectedVersion !== "string" || !expectedVersion)
|
|
663
|
+
markRead(accountId, threadId2, expectedVersion) {
|
|
664
|
+
if (typeof expectedVersion !== "string" || !expectedVersion || expectedVersion.length > 128)
|
|
447
665
|
throw new Error("Read version is required");
|
|
448
|
-
return this.request(`v1/accounts/${id(accountId)}/threads/${id(
|
|
666
|
+
return this.request(`v1/accounts/${id(accountId)}/threads/${id(threadId2)}/read-state`, { method: "POST", body: JSON.stringify({ expectedVersion }) });
|
|
449
667
|
}
|
|
450
668
|
events(accountId, after = "0", limit = 100) {
|
|
451
669
|
if (!Number.isInteger(limit) || limit < 1 || limit > 200)
|
|
452
670
|
throw new Error("Invalid event page limit");
|
|
453
|
-
return this.request(`v1/accounts/${id(accountId)}/events?after=${decimal(after)}&limit=${limit}`)
|
|
671
|
+
return this.request(`v1/accounts/${id(accountId)}/events?after=${decimal(after)}&limit=${limit}`).then((page) => {
|
|
672
|
+
for (const event of page.items)
|
|
673
|
+
if (event.kind === "message.recalled")
|
|
674
|
+
validateNativeRecallMetadata(event.data);
|
|
675
|
+
return page;
|
|
676
|
+
});
|
|
454
677
|
}
|
|
455
678
|
ack(accountId, consumerId, cursor) {
|
|
456
679
|
return this.request(`v1/accounts/${id(accountId)}/consumers/${id(consumerId)}/ack`, { method: "POST", body: JSON.stringify({ cursor: decimal(cursor) }) });
|
|
457
680
|
}
|
|
458
|
-
async *watch(accountId, after = "0", signal) {
|
|
459
|
-
const
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
681
|
+
async *watch(accountId, after = "0", signal, options = {}) {
|
|
682
|
+
const connection = new AbortController();
|
|
683
|
+
const streamSignal = signal ? AbortSignal.any([signal, connection.signal]) : connection.signal;
|
|
684
|
+
const bounded = async (work, milliseconds, reason) => {
|
|
685
|
+
if (streamSignal.aborted)
|
|
686
|
+
throw streamSignal.reason;
|
|
687
|
+
let timer;
|
|
688
|
+
let onAbort = () => {
|
|
689
|
+
};
|
|
690
|
+
const interrupted = new Promise((_resolve, reject) => {
|
|
691
|
+
onAbort = () => reject(streamSignal.reason ?? new Error("Native SSE cancelled"));
|
|
692
|
+
streamSignal.addEventListener("abort", onAbort, { once: true });
|
|
693
|
+
timer = setTimeout(() => connection.abort(new Error(reason)), milliseconds);
|
|
694
|
+
});
|
|
695
|
+
try {
|
|
696
|
+
return await Promise.race([work(), interrupted]);
|
|
697
|
+
} finally {
|
|
698
|
+
clearTimeout(timer);
|
|
699
|
+
streamSignal.removeEventListener("abort", onAbort);
|
|
700
|
+
}
|
|
701
|
+
};
|
|
702
|
+
let reader;
|
|
465
703
|
const decoder = new TextDecoder();
|
|
466
704
|
let buffer = "";
|
|
467
705
|
let data = [];
|
|
@@ -469,10 +707,20 @@ var NativeWeChatClient = class {
|
|
|
469
707
|
let eventCursor = "";
|
|
470
708
|
let eventType = "";
|
|
471
709
|
try {
|
|
710
|
+
const response = await bounded(() => this.response(`v1/accounts/${id(accountId)}/events/stream?after=${decimal(after)}`, { signal: streamSignal, headers: { Accept: "text/event-stream" } }, true), this.timeoutMs, "Native SSE connection timeout");
|
|
711
|
+
if (!response.headers.get("content-type")?.startsWith("text/event-stream")) {
|
|
712
|
+
await response.body?.cancel();
|
|
713
|
+
throw new Error("Expected native SSE response");
|
|
714
|
+
}
|
|
715
|
+
reader = response.body?.getReader();
|
|
716
|
+
if (!reader)
|
|
717
|
+
throw new Error("Native SSE has no body");
|
|
472
718
|
while (true) {
|
|
473
|
-
const
|
|
719
|
+
const activeReader = reader;
|
|
720
|
+
const { value, done } = await bounded(() => activeReader.read(), this.streamIdleTimeoutMs, "Native SSE idle timeout");
|
|
474
721
|
if (done)
|
|
475
722
|
break;
|
|
723
|
+
options.onActivity?.();
|
|
476
724
|
buffer += decoder.decode(value, { stream: true });
|
|
477
725
|
if (buffer.length > 1024 * 1024)
|
|
478
726
|
throw new Error("Native SSE frame exceeds its bound");
|
|
@@ -490,6 +738,8 @@ var NativeWeChatClient = class {
|
|
|
490
738
|
const event = payload;
|
|
491
739
|
if (!event || typeof event.kind !== "string" || !event.data || typeof event.data !== "object")
|
|
492
740
|
throw new Error("Invalid native event");
|
|
741
|
+
if (event.kind === "message.recalled")
|
|
742
|
+
validateNativeRecallMetadata(event.data);
|
|
493
743
|
event.cursor = decimal(event.cursor ?? eventCursor);
|
|
494
744
|
yield event;
|
|
495
745
|
}
|
|
@@ -510,9 +760,12 @@ var NativeWeChatClient = class {
|
|
|
510
760
|
}
|
|
511
761
|
}
|
|
512
762
|
} finally {
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
763
|
+
connection.abort();
|
|
764
|
+
if (reader) {
|
|
765
|
+
await reader.cancel().catch(() => {
|
|
766
|
+
});
|
|
767
|
+
reader.releaseLock();
|
|
768
|
+
}
|
|
516
769
|
}
|
|
517
770
|
}
|
|
518
771
|
};
|
|
@@ -533,11 +786,22 @@ function requireNativeIdentity(value) {
|
|
|
533
786
|
}
|
|
534
787
|
}
|
|
535
788
|
function nativeChildEnvironment(token, environment = process.env) {
|
|
536
|
-
return Object.fromEntries(["PATH", "HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "TMPDIR", "TMP", "TEMP", "LANG", "LC_ALL", "TZ", "SSL_CERT_FILE", "SSL_CERT_DIR"].filter((
|
|
789
|
+
return Object.fromEntries(["PATH", "HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "SystemRoot", "WINDIR", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "TMPDIR", "TMP", "TEMP", "LANG", "LC_ALL", "TZ", "SSL_CERT_FILE", "SSL_CERT_DIR"].filter((name3) => environment[name3] !== void 0 && environment[name3] !== token).map((name3) => [name3, environment[name3]]));
|
|
537
790
|
}
|
|
538
791
|
function nativeHostTarget(platform = process.platform, arch = process.arch) {
|
|
539
|
-
|
|
540
|
-
|
|
792
|
+
const cpu = arch === "arm64" ? "aarch64" : "x86_64";
|
|
793
|
+
const suffix = { linux: "unknown-linux-gnu", darwin: "apple-darwin", win32: "pc-windows-msvc" }[platform];
|
|
794
|
+
if (!suffix || !["x64", "arm64"].includes(arch) || platform === "darwin" && arch !== "arm64") throw new Error("native_binary_incompatible: unsupported host platform; use external mode for remote daemons");
|
|
795
|
+
return { platform, arch, rustTarget: `${cpu}-${suffix}`, key: `${platform}-${arch}${platform === "linux" ? "-gnu" : ""}`, executable: platform === "win32" ? "wx.exe" : "wx" };
|
|
796
|
+
}
|
|
797
|
+
function nativeExecutableFormat(bytes, platform = process.platform) {
|
|
798
|
+
if (platform === "linux") return bytes.subarray(0, 4).equals(Buffer.from([127, 69, 76, 70]));
|
|
799
|
+
if (platform === "darwin") return bytes.subarray(0, 4).equals(Buffer.from([207, 250, 237, 254]));
|
|
800
|
+
if (platform === "win32" && bytes.length >= 64 && bytes[0] === 77 && bytes[1] === 90) {
|
|
801
|
+
const offset = bytes.readUInt32LE(60);
|
|
802
|
+
return offset >= 64 && offset <= bytes.length - 4 && bytes.subarray(offset, offset + 4).equals(Buffer.from([80, 69, 0, 0]));
|
|
803
|
+
}
|
|
804
|
+
return false;
|
|
541
805
|
}
|
|
542
806
|
async function resolveNativeExecutable(explicit, path = process.env.PATH ?? "", environment = nativeChildEnvironment("")) {
|
|
543
807
|
const target = nativeHostTarget();
|
|
@@ -546,40 +810,48 @@ async function resolveNativeExecutable(explicit, path = process.env.PATH ?? "",
|
|
|
546
810
|
if (!candidate) {
|
|
547
811
|
for (const directory of path.split(delimiter).filter(isAbsolute)) {
|
|
548
812
|
try {
|
|
549
|
-
await access(join(directory,
|
|
550
|
-
candidate = join(directory,
|
|
813
|
+
await access(join(directory, target.executable), constants.X_OK);
|
|
814
|
+
candidate = join(directory, target.executable);
|
|
551
815
|
break;
|
|
552
816
|
} catch {
|
|
553
817
|
}
|
|
818
|
+
if (process.platform === "win32") {
|
|
819
|
+
const payload = join(directory, "node_modules", "@agent-wechat", "cli", "scripts", "native-launcher.mjs");
|
|
820
|
+
try {
|
|
821
|
+
await access(payload);
|
|
822
|
+
candidate = payload;
|
|
823
|
+
break;
|
|
824
|
+
} catch {
|
|
825
|
+
}
|
|
826
|
+
}
|
|
554
827
|
}
|
|
555
828
|
}
|
|
556
829
|
if (!candidate) throw new Error("native_binary_missing: install native wx separately or configure its absolute path");
|
|
557
830
|
candidate = await realpath(candidate);
|
|
558
|
-
if (candidate.endsWith("/scripts/native-launcher.mjs")) {
|
|
831
|
+
if (candidate.replaceAll("\\", "/").endsWith("/scripts/native-launcher.mjs")) {
|
|
559
832
|
const root = dirname(dirname(candidate));
|
|
560
833
|
const pkg = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
|
|
561
834
|
if (pkg.name !== "@agent-wechat/cli" || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(pkg.version)) throw new Error("Unsupported native CLI launcher");
|
|
562
835
|
const manifest = JSON.parse(await readFile(join(root, "native-release.json"), "utf8"));
|
|
563
|
-
const asset = manifest.assets?.find((value) => value.rustTarget === target.rustTarget && value.platform ===
|
|
836
|
+
const asset = manifest.assets?.find((value) => value.rustTarget === target.rustTarget && value.platform === target.platform && value.arch === target.arch && (target.platform !== "linux" || value.libc === "gnu"));
|
|
564
837
|
if (manifest.version !== pkg.version || !asset || !/^[a-f0-9]{64}$/.test(asset.sha256)) throw new Error("Native CLI manifest is incompatible");
|
|
565
|
-
candidate = await realpath(join(root, "native", pkg.version,
|
|
838
|
+
candidate = await realpath(join(root, "native", pkg.version, target.key, target.executable));
|
|
566
839
|
const bytes = await readFile(candidate);
|
|
567
840
|
if (bytes.length !== asset.bytes || createHash2("sha256").update(bytes).digest("hex") !== asset.sha256) throw new Error("Installed native executable checksum mismatch");
|
|
568
841
|
}
|
|
569
842
|
const stat = await lstat(candidate);
|
|
570
843
|
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("Native executable must be a regular file");
|
|
571
844
|
await access(candidate, constants.X_OK);
|
|
572
|
-
|
|
573
|
-
if (!magic.equals(Buffer.from([127, 69, 76, 70]))) throw new Error("native_binary_required: configure the actual native ELF executable, not an unverified process wrapper");
|
|
845
|
+
if (!nativeExecutableFormat(await readFile(candidate))) throw new Error("native_binary_required: configure the actual native executable for this OS");
|
|
574
846
|
const { stdout } = await exec(candidate, ["--json", "version"], { env: environment, timeout: 5e3, maxBuffer: 65536 });
|
|
575
847
|
const version = JSON.parse(stdout);
|
|
576
848
|
requireNativeIdentity(version);
|
|
577
849
|
if (version.target !== target.rustTarget) throw new Error("native_binary_incompatible: executable architecture differs from this host");
|
|
578
850
|
return candidate;
|
|
579
851
|
}
|
|
580
|
-
async function portOccupied(
|
|
852
|
+
async function portOccupied(url2) {
|
|
581
853
|
return new Promise((resolve, reject) => {
|
|
582
|
-
const socket = createConnection({ host:
|
|
854
|
+
const socket = createConnection({ host: url2.hostname.replace(/^\[|\]$/g, ""), port: Number(url2.port || (url2.protocol === "https:" ? 443 : 80)) });
|
|
583
855
|
socket.setTimeout(1e3);
|
|
584
856
|
socket.once("connect", () => {
|
|
585
857
|
socket.destroy();
|
|
@@ -596,7 +868,7 @@ async function portOccupied(url) {
|
|
|
596
868
|
});
|
|
597
869
|
});
|
|
598
870
|
}
|
|
599
|
-
async function stopOwnedChild(child) {
|
|
871
|
+
async function stopOwnedChild(child, graceful) {
|
|
600
872
|
if (!child.pid || child.exitCode !== null || child.signalCode !== null) return;
|
|
601
873
|
await new Promise((resolve) => {
|
|
602
874
|
const kill = setTimeout(() => {
|
|
@@ -606,7 +878,10 @@ async function stopOwnedChild(child) {
|
|
|
606
878
|
clearTimeout(kill);
|
|
607
879
|
resolve();
|
|
608
880
|
});
|
|
609
|
-
|
|
881
|
+
if (graceful) void graceful().catch(() => {
|
|
882
|
+
if (child.exitCode === null && child.signalCode === null) child.kill("SIGTERM");
|
|
883
|
+
});
|
|
884
|
+
else child.kill("SIGTERM");
|
|
610
885
|
});
|
|
611
886
|
}
|
|
612
887
|
async function startNativeHost(config) {
|
|
@@ -621,11 +896,11 @@ async function startNativeHost(config) {
|
|
|
621
896
|
});
|
|
622
897
|
}
|
|
623
898
|
if (config.mode !== "managed" || config.endpoint || !config.dataDir || !isAbsolute(config.dataDir) || config.serverConfig && !isAbsolute(config.serverConfig)) throw new Error("Managed native mode requires absolute dataDir/config paths and no remote endpoint");
|
|
624
|
-
const
|
|
625
|
-
if (await portOccupied(
|
|
899
|
+
const url2 = validateNativeBaseUrl(`http://${config.listen ?? "127.0.0.1:6174"}`);
|
|
900
|
+
if (await portOccupied(url2)) throw new Error("native_owner_conflict: configured port is already owned; use external mode for an independently operated daemon");
|
|
626
901
|
const executable = await resolveNativeExecutable(config.executable, void 0, nativeChildEnvironment(token));
|
|
627
|
-
const client = new NativeWeChatClient({ baseUrl:
|
|
628
|
-
const args = ["serve", "--data-dir", config.dataDir, "--token-stdin", "--listen",
|
|
902
|
+
const client = new NativeWeChatClient({ baseUrl: url2.href, token, timeoutMs: 1e3 });
|
|
903
|
+
const args = ["serve", "--data-dir", config.dataDir, "--token-stdin", "--listen", url2.host];
|
|
629
904
|
if (config.serverConfig) args.push("--server-config", config.serverConfig);
|
|
630
905
|
const child = spawn(executable, args, { env: nativeChildEnvironment(token), stdio: ["pipe", "ignore", "pipe"], shell: false });
|
|
631
906
|
child.stderr?.on("data", () => {
|
|
@@ -648,10 +923,21 @@ async function startNativeHost(config) {
|
|
|
648
923
|
if (exited) throw new Error("Native owned child exited before readiness");
|
|
649
924
|
try {
|
|
650
925
|
const status = await client.status();
|
|
651
|
-
const
|
|
926
|
+
const canonical = await realpath(config.dataDir);
|
|
927
|
+
const dataDir = process.platform === "win32" ? toNamespacedPath(canonical) : canonical;
|
|
652
928
|
if (exited || status.version.backend !== "native" || status.version.apiVersion !== 1 || status.pid !== child.pid || status.dataDir !== dataDir || typeof status.serverId !== "string" || typeof status.ownershipGeneration !== "string") throw new Error("native_owner_conflict: readiness identity does not match the owned process/store");
|
|
653
929
|
requireNativeIdentity(status.version);
|
|
654
|
-
return host(new NativeWeChatClient({ baseUrl:
|
|
930
|
+
return host(new NativeWeChatClient({ baseUrl: url2.href, token }), token, () => stopOwnedChild(child, async () => {
|
|
931
|
+
const response = await fetch(new URL("v1/daemon/shutdown", url2), {
|
|
932
|
+
method: "POST",
|
|
933
|
+
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
|
|
934
|
+
body: JSON.stringify({ pid: status.pid, serverId: status.serverId, ownershipGeneration: status.ownershipGeneration }),
|
|
935
|
+
redirect: "error",
|
|
936
|
+
signal: AbortSignal.timeout(3e3)
|
|
937
|
+
});
|
|
938
|
+
if (!response.ok) throw new Error("Owned daemon refused graceful shutdown");
|
|
939
|
+
await response.body?.cancel();
|
|
940
|
+
}));
|
|
655
941
|
} catch (error) {
|
|
656
942
|
if (String(error).includes("native_owner_conflict")) throw error;
|
|
657
943
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
@@ -709,7 +995,7 @@ function collectWeChatStatusIssues(accounts) {
|
|
|
709
995
|
accountId: snapshot.accountId,
|
|
710
996
|
kind: "runtime",
|
|
711
997
|
message: "Prepared model handoff was not confirmed by this OpenClaw host; automatic read state remains unchanged.",
|
|
712
|
-
fix: "
|
|
998
|
+
fix: "Select native.readPolicy=on_inbound to mark successfully handled conversations read without model hooks, or use a compatible prepared-run SDK hook."
|
|
713
999
|
});
|
|
714
1000
|
}
|
|
715
1001
|
if ((snapshot.needsReview ?? 0) > 0) {
|
|
@@ -936,15 +1222,21 @@ function resolveWeChatIngress(params) {
|
|
|
936
1222
|
});
|
|
937
1223
|
}
|
|
938
1224
|
|
|
1225
|
+
// src/outbound-options.ts
|
|
1226
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
1227
|
+
|
|
939
1228
|
// src/outbound-media.ts
|
|
940
1229
|
import { createHash as createHash5 } from "node:crypto";
|
|
941
1230
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
942
1231
|
|
|
943
1232
|
// src/native-media.ts
|
|
944
1233
|
import { createHash as createHash4, randomUUID } from "node:crypto";
|
|
945
|
-
import {
|
|
946
|
-
import {
|
|
1234
|
+
import { openAsBlob } from "node:fs";
|
|
1235
|
+
import { mkdtemp, open, rm } from "node:fs/promises";
|
|
1236
|
+
import { tmpdir } from "node:os";
|
|
1237
|
+
import { basename, extname, join as join2 } from "node:path";
|
|
947
1238
|
import { getImageMetadata, resizeToJpeg, IMAGE_REDUCE_QUALITY_STEPS } from "openclaw/plugin-sdk/media-runtime";
|
|
1239
|
+
import { saveMediaStream } from "openclaw/plugin-sdk/media-store";
|
|
948
1240
|
|
|
949
1241
|
// src/attachment-store.ts
|
|
950
1242
|
import { createHash as createHash3 } from "node:crypto";
|
|
@@ -964,6 +1256,12 @@ async function saveManagedAttachment(params) {
|
|
|
964
1256
|
}
|
|
965
1257
|
const buffer = Buffer.from(params.data, "base64");
|
|
966
1258
|
if (buffer.byteLength !== size) throw new Error("Attachment decoding length mismatch");
|
|
1259
|
+
return saveManagedAttachmentBytes({ ...params, bytes: buffer });
|
|
1260
|
+
}
|
|
1261
|
+
async function saveManagedAttachmentBytes(params) {
|
|
1262
|
+
const size = params.bytes.byteLength;
|
|
1263
|
+
if (size > params.maxBytes) throw new AttachmentTooLargeError(`Attachment exceeds configured ${params.maxBytes} byte limit`);
|
|
1264
|
+
const buffer = Buffer.from(params.bytes.buffer, params.bytes.byteOffset, size);
|
|
967
1265
|
const sha256 = createHash3("sha256").update(buffer).digest("hex");
|
|
968
1266
|
const saved = await params.saveMediaBuffer(
|
|
969
1267
|
buffer,
|
|
@@ -974,73 +1272,312 @@ async function saveManagedAttachment(params) {
|
|
|
974
1272
|
);
|
|
975
1273
|
return { path: saved.path, size, sha256, filename: params.filename };
|
|
976
1274
|
}
|
|
1275
|
+
async function saveVerifiedManagedAttachmentStream(params) {
|
|
1276
|
+
if (!Number.isSafeInteger(params.expectedBytes) || params.expectedBytes < 1 || params.expectedBytes > params.maxBytes || !/^[a-f0-9]{64}$/.test(params.expectedSha256)) throw new Error("Native attachment integrity metadata is invalid");
|
|
1277
|
+
let size = 0, finished = false;
|
|
1278
|
+
const digest2 = createHash3("sha256");
|
|
1279
|
+
const stream = (async function* () {
|
|
1280
|
+
for await (const chunk of params.stream) {
|
|
1281
|
+
params.assertCurrent();
|
|
1282
|
+
size += chunk.byteLength;
|
|
1283
|
+
if (size > params.maxBytes || size > params.expectedBytes) throw new AttachmentTooLargeError("Native attachment stream exceeds its bound");
|
|
1284
|
+
digest2.update(chunk);
|
|
1285
|
+
yield chunk;
|
|
1286
|
+
}
|
|
1287
|
+
params.assertCurrent();
|
|
1288
|
+
if (size !== params.expectedBytes || digest2.digest("hex") !== params.expectedSha256) throw new Error("Native attachment integrity did not verify");
|
|
1289
|
+
finished = true;
|
|
1290
|
+
})();
|
|
1291
|
+
const saved = await params.saveMediaStream(
|
|
1292
|
+
stream,
|
|
1293
|
+
params.mime,
|
|
1294
|
+
"inbound",
|
|
1295
|
+
params.maxBytes,
|
|
1296
|
+
params.filename,
|
|
1297
|
+
void 0,
|
|
1298
|
+
{ assertCommitAllowed: params.assertCurrent, durable: true }
|
|
1299
|
+
);
|
|
1300
|
+
if (!finished || saved.size != null && saved.size !== size) throw new Error("Native attachment stream was not fully saved");
|
|
1301
|
+
return { path: saved.path, size, sha256: params.expectedSha256, filename: params.filename };
|
|
1302
|
+
}
|
|
977
1303
|
|
|
978
1304
|
// src/media-delivery.ts
|
|
979
1305
|
function appendReference(body, reference) {
|
|
980
1306
|
return body ? `${body}
|
|
981
1307
|
${reference}` : reference;
|
|
982
1308
|
}
|
|
983
|
-
function safeDisplayName(
|
|
984
|
-
return
|
|
1309
|
+
function safeDisplayName(name3) {
|
|
1310
|
+
return name3.replace(/[\r\n\0]/g, " ").trim() || "attachment";
|
|
985
1311
|
}
|
|
986
1312
|
function renderAttachmentBody(originalBody, attachment, exposeNonVisualPath = true) {
|
|
987
1313
|
if (!attachment) return originalBody;
|
|
988
|
-
const
|
|
1314
|
+
const name3 = safeDisplayName(attachment.filename);
|
|
989
1315
|
if (attachment.status !== "ready" || !attachment.path) {
|
|
990
1316
|
const label = attachment.kind === "file" ? "File" : attachment.kind === "image" ? "Image" : attachment.kind === "audio" ? "Voice message" : "Video";
|
|
991
1317
|
if (attachment.status === "pending") {
|
|
992
|
-
return appendReference(originalBody, `[${label} pending: ${
|
|
1318
|
+
return appendReference(originalBody, `[${label} pending: ${name3}]`);
|
|
993
1319
|
}
|
|
994
1320
|
if (attachment.status === "expired") {
|
|
995
|
-
return appendReference(originalBody, `[${label} expired: ${
|
|
1321
|
+
return appendReference(originalBody, `[${label} expired: ${name3}; no cached copy available. Ask the sender to resend.]`);
|
|
996
1322
|
}
|
|
997
|
-
return appendReference(originalBody, `[${label} unavailable: ${
|
|
1323
|
+
return appendReference(originalBody, `[${label} unavailable: ${name3} (${attachment.status})]`);
|
|
998
1324
|
}
|
|
999
1325
|
if (attachment.kind === "file") {
|
|
1000
|
-
const prefix = originalBody.trim() ===
|
|
1001
|
-
return appendReference(prefix, `[File: ${
|
|
1002
|
-
[Local file:
|
|
1326
|
+
const prefix = originalBody.trim() === name3 ? "" : originalBody;
|
|
1327
|
+
return appendReference(prefix, `[File: ${name3}]
|
|
1328
|
+
[Local file: <${attachment.path}>]`);
|
|
1003
1329
|
}
|
|
1004
1330
|
if (exposeNonVisualPath) {
|
|
1005
1331
|
if (attachment.kind === "audio") {
|
|
1006
|
-
return appendReference(originalBody || "<media:audio>", `[Voice message file:
|
|
1332
|
+
return appendReference(originalBody || "<media:audio>", `[Voice message file: <${attachment.path}>]`);
|
|
1007
1333
|
}
|
|
1008
1334
|
if (attachment.kind === "video") {
|
|
1009
|
-
return appendReference(originalBody || "<media:video>", `[Video file:
|
|
1335
|
+
return appendReference(originalBody || "<media:video>", `[Video file: <${attachment.path}>]`);
|
|
1010
1336
|
}
|
|
1011
1337
|
}
|
|
1012
|
-
|
|
1338
|
+
let body = originalBody || (attachment.kind === "image" ? "<media:image>" : originalBody);
|
|
1339
|
+
if (attachment.kind === "image") body = appendReference(body, `[Image file: <${attachment.path}>]`);
|
|
1013
1340
|
if (attachment.kind === "image" && attachment.quality === "thumbnail") {
|
|
1014
1341
|
return appendReference(body, "[Image preview only: thumbnail quality]");
|
|
1015
1342
|
}
|
|
1016
1343
|
return body;
|
|
1017
1344
|
}
|
|
1018
1345
|
|
|
1346
|
+
// src/native-send.ts
|
|
1347
|
+
async function nativeOutboundDelivery(client, accountId, threadId2, messageIds, source) {
|
|
1348
|
+
const receipts = [];
|
|
1349
|
+
try {
|
|
1350
|
+
if (!Array.isArray(messageIds) || !messageIds.length || messageIds.length > 256 || messageIds.some((id2) => typeof id2 !== "string" || !id2 || id2.length > 4096) || new Set(messageIds).size !== messageIds.length) throw Error("Message receipts unavailable");
|
|
1351
|
+
for (const [index, messageId] of messageIds.entries()) {
|
|
1352
|
+
const message = await client.message(accountId, messageId);
|
|
1353
|
+
if (message.id !== messageId || message.accountId !== accountId || message.threadId !== threadId2 || message.direction !== "outgoing" || typeof message.serverId !== "string" || !/^[1-9]\d{0,19}$/.test(message.serverId) || BigInt(message.serverId) > 18446744073709551615n || source.serverIds?.[index] != null && source.serverIds[index] !== message.serverId) throw Error("Message receipt identity mismatch");
|
|
1354
|
+
receipts.push({ messageId, serverId: message.serverId, accountId, threadId: threadId2 });
|
|
1355
|
+
}
|
|
1356
|
+
} catch {
|
|
1357
|
+
return { messageId: "", meta: {
|
|
1358
|
+
accountId,
|
|
1359
|
+
threadId: threadId2,
|
|
1360
|
+
...source,
|
|
1361
|
+
messageIds: receipts,
|
|
1362
|
+
outcome: "unknown",
|
|
1363
|
+
receiptState: "needs_review",
|
|
1364
|
+
retryable: false,
|
|
1365
|
+
note: "Send submitted. Inspect the durable send/job and retained receipts; do not resend automatically."
|
|
1366
|
+
} };
|
|
1367
|
+
}
|
|
1368
|
+
return { messageId: receipts[0].messageId, meta: {
|
|
1369
|
+
accountId,
|
|
1370
|
+
threadId: threadId2,
|
|
1371
|
+
serverId: receipts[0].serverId,
|
|
1372
|
+
outcome: "sent",
|
|
1373
|
+
...source,
|
|
1374
|
+
messageIds: receipts,
|
|
1375
|
+
receiptState: "verified"
|
|
1376
|
+
} };
|
|
1377
|
+
}
|
|
1378
|
+
async function submitNativeText(client, accountId, threadId2, text3, key, options = {}) {
|
|
1379
|
+
let intent = await client.sendText(accountId, threadId2, text3, key);
|
|
1380
|
+
const deadline = Date.now() + Math.max(1, Math.min(options.timeoutMs ?? 65e3, 65e3));
|
|
1381
|
+
let delay2 = Math.max(1, Math.min(options.initialDelayMs ?? 250, 1e3));
|
|
1382
|
+
while (["queued", "submitting"].includes(intent.state) && Date.now() < deadline) {
|
|
1383
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(delay2, deadline - Date.now())));
|
|
1384
|
+
const remaining = deadline - Date.now();
|
|
1385
|
+
if (remaining <= 0) break;
|
|
1386
|
+
intent = await client.send(accountId, intent.id, AbortSignal.timeout(remaining));
|
|
1387
|
+
delay2 = Math.min(delay2 * 2, 1e3);
|
|
1388
|
+
}
|
|
1389
|
+
if (!["accepted", "sent", "server_accepted"].includes(intent.state)) throw new Error(`Native send ${intent.id} requires inspection (${intent.state}); do not automatically resend`);
|
|
1390
|
+
return intent;
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
// src/native-recall-state.ts
|
|
1394
|
+
function nativeRecallInfo(message) {
|
|
1395
|
+
if (message.recall) validateNativeRecallMetadata(message.recall);
|
|
1396
|
+
return message.recall;
|
|
1397
|
+
}
|
|
1398
|
+
function nativeRecallIdentity(threadId2, serverId) {
|
|
1399
|
+
return JSON.stringify([threadId2, serverId]);
|
|
1400
|
+
}
|
|
1401
|
+
function validateNativeRecall(value) {
|
|
1402
|
+
validateNativeRecallMetadata(value);
|
|
1403
|
+
if (!value || typeof value.threadId !== "string" || !value.threadId || value.threadId.length > 4096 || typeof value.serverId !== "string" || !/^[1-9]\d{0,19}$/.test(value.serverId) || BigInt(value.serverId) > 18446744073709551615n || typeof value.observedAt !== "string" || value.observedAt.length > 128 || !Number.isFinite(Date.parse(value.observedAt)) || value.recalledAt !== void 0 && (typeof value.recalledAt !== "string" || value.recalledAt.length > 128 || !Number.isFinite(Date.parse(value.recalledAt))) || value.messageId !== void 0 && (typeof value.messageId !== "string" || !value.messageId || value.messageId.length > 4096)) throw Error("Invalid native recall observation; cursor retained");
|
|
1404
|
+
}
|
|
1405
|
+
function mergeNativeRecall(prior, next) {
|
|
1406
|
+
validateNativeRecall(prior);
|
|
1407
|
+
validateNativeRecall(next);
|
|
1408
|
+
if (prior.threadId !== next.threadId || prior.serverId !== next.serverId) throw Error("Conflicting native recall identity; cursor retained");
|
|
1409
|
+
return {
|
|
1410
|
+
threadId: prior.threadId,
|
|
1411
|
+
serverId: prior.serverId,
|
|
1412
|
+
observedAt: prior.observedAt,
|
|
1413
|
+
...prior.messageId ?? next.messageId ? { messageId: prior.messageId ?? next.messageId } : {},
|
|
1414
|
+
...prior.recalledAt ?? next.recalledAt ? { recalledAt: prior.recalledAt ?? next.recalledAt } : {},
|
|
1415
|
+
...(prior.replacementText ?? next.replacementText) != null ? { replacementText: prior.replacementText ?? next.replacementText } : {}
|
|
1416
|
+
};
|
|
1417
|
+
}
|
|
1418
|
+
function recalledNativeMessage(message, recall) {
|
|
1419
|
+
validateNativeRecall(recall);
|
|
1420
|
+
const previous = nativeRecallInfo(message);
|
|
1421
|
+
const replacementText = previous?.replacementText ?? recall.replacementText;
|
|
1422
|
+
return {
|
|
1423
|
+
...message,
|
|
1424
|
+
type: 1e4,
|
|
1425
|
+
body: "[Message recalled]",
|
|
1426
|
+
quote: void 0,
|
|
1427
|
+
link: void 0,
|
|
1428
|
+
media: [],
|
|
1429
|
+
senderId: message.senderId || null,
|
|
1430
|
+
direction: message.senderId ? message.direction : null,
|
|
1431
|
+
mentions: { state: "unknown", userIds: [], self: null, all: null, source: null },
|
|
1432
|
+
recall: {
|
|
1433
|
+
observedAt: previous?.observedAt ?? recall.observedAt,
|
|
1434
|
+
...previous?.recalledAt ?? recall.recalledAt ? { recalledAt: previous?.recalledAt ?? recall.recalledAt } : {},
|
|
1435
|
+
...replacementText != null ? { replacementText } : {}
|
|
1436
|
+
}
|
|
1437
|
+
};
|
|
1438
|
+
}
|
|
1439
|
+
|
|
1440
|
+
// src/native-quote.ts
|
|
1441
|
+
function sameEmbeddedQuote(stored, current) {
|
|
1442
|
+
if (stored.state === "unsupported" && current.state === "embedded")
|
|
1443
|
+
return ["serverId", "type", "appMessageType", "senderId", "direction"].every((field) => (stored[field] ?? null) === (current[field] ?? null));
|
|
1444
|
+
const compared = { ...current };
|
|
1445
|
+
for (const field of ["embeddedLink", "embeddedSticker"]) {
|
|
1446
|
+
if (!Object.hasOwn(stored, field)) delete compared[field];
|
|
1447
|
+
}
|
|
1448
|
+
return JSON.stringify(stored) === JSON.stringify(compared);
|
|
1449
|
+
}
|
|
1450
|
+
function renderEmbeddedQuote(message, permitted = true, imageBody) {
|
|
1451
|
+
const comment = (message.body ?? "").slice(0, 16384);
|
|
1452
|
+
const source = message.quote;
|
|
1453
|
+
const unavailable = (state2) => ({
|
|
1454
|
+
body: `${comment}${comment ? "\n\n" : ""}[Quoted message ${state2}]`,
|
|
1455
|
+
image: false,
|
|
1456
|
+
quote: { state: state2, type: source?.type, senderId: source?.senderId ?? void 0 }
|
|
1457
|
+
});
|
|
1458
|
+
if (!source) return unavailable("unavailable");
|
|
1459
|
+
if (!permitted) return unavailable("not permitted");
|
|
1460
|
+
const state = source.state ?? "missing";
|
|
1461
|
+
if (state === "recalled") return unavailable("recalled");
|
|
1462
|
+
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";
|
|
1464
|
+
const image = state === "embedded" && source.type === 3 && source.embeddedImage === true;
|
|
1465
|
+
if (state === "embedded" && !image && !source.embeddedText) return unavailable("invalid");
|
|
1466
|
+
const content = state === "missing" ? "" : image ? imageBody ?? "[Image metadata embedded in quote; image not retrieved]" : source.embeddedText ?? "";
|
|
1467
|
+
const status = state === "unsupported" ? `[${label} attachment unavailable from embedded quote]` : state === "missing" ? "[Embedded quote content unavailable]" : "";
|
|
1468
|
+
return {
|
|
1469
|
+
body: `${comment}${comment ? "\n\n" : ""}[Quoted ${label} from ${source.senderId ?? "unknown sender"}; embedded in reply]
|
|
1470
|
+
${[content, status].filter(Boolean).join("\n")}
|
|
1471
|
+
[/Quoted message]`,
|
|
1472
|
+
image,
|
|
1473
|
+
quote: { state, type: source.type, senderId: source.senderId ?? void 0 }
|
|
1474
|
+
};
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1019
1477
|
// src/native-media.ts
|
|
1020
1478
|
function kind(type) {
|
|
1021
1479
|
return type === 3 || type === 47 ? "image" : type === 34 ? "audio" : type === 43 ? "video" : type === 49 ? "file" : void 0;
|
|
1022
1480
|
}
|
|
1023
|
-
var terminalJobs = /* @__PURE__ */ new Set(["accepted", "completed", "succeeded", "available", "failed", "cancelled", "expired", "needs_review"]);
|
|
1024
|
-
|
|
1481
|
+
var terminalJobs = /* @__PURE__ */ new Set(["accepted", "completed", "succeeded", "available", "failed", "partial", "cancelled", "expired", "needs_review"]);
|
|
1482
|
+
var successfulSendJobs = /* @__PURE__ */ new Set(["accepted", "completed", "succeeded"]);
|
|
1483
|
+
var terminalIdentityErrors = /* @__PURE__ */ new Set(["media_identity_unavailable", "media_source_changed"]);
|
|
1484
|
+
var NativeMediaJobInspectionError = class extends Error {
|
|
1485
|
+
code = "native_media_job_inspection_required";
|
|
1486
|
+
retryable = false;
|
|
1487
|
+
jobId;
|
|
1488
|
+
accountId;
|
|
1489
|
+
threadId;
|
|
1490
|
+
idempotencyKey;
|
|
1491
|
+
state;
|
|
1492
|
+
reason;
|
|
1493
|
+
constructor(job, accountId, threadId2, key, reason) {
|
|
1494
|
+
super(`Native media job ${job.id} requires inspection (${job.state}); retain the original job and idempotency key and do not automatically resend`);
|
|
1495
|
+
this.name = "NativeMediaJobInspectionError";
|
|
1496
|
+
this.jobId = job.id;
|
|
1497
|
+
this.accountId = accountId;
|
|
1498
|
+
this.threadId = threadId2;
|
|
1499
|
+
this.idempotencyKey = key;
|
|
1500
|
+
this.state = job.state;
|
|
1501
|
+
this.reason = reason;
|
|
1502
|
+
}
|
|
1503
|
+
};
|
|
1504
|
+
function mediaSendResult(job) {
|
|
1505
|
+
return job.result && typeof job.result === "object" && !Array.isArray(job.result) ? job.result : {};
|
|
1506
|
+
}
|
|
1507
|
+
function mediaSendReceiptIds(job, audioAsVoice) {
|
|
1508
|
+
const result = mediaSendResult(job), ids = result.messageIds;
|
|
1509
|
+
if (!successfulSendJobs.has(job.state) || result.profileProjection === "unknown" || !Array.isArray(ids) || !ids.length || ids.length > 256 || ids.some((id2) => typeof id2 !== "string" || !id2 || id2.length > 4096) || new Set(ids).size !== ids.length) return void 0;
|
|
1510
|
+
if (audioAsVoice) {
|
|
1511
|
+
const chunks = result.chunks;
|
|
1512
|
+
if (!Array.isArray(chunks) || !chunks.length || chunks.length !== ids.length || chunks.some((chunk) => !chunk || chunk.state !== "accepted" || typeof chunk.serverMessageId !== "string")) return void 0;
|
|
1513
|
+
} else if (ids.length !== 1) return void 0;
|
|
1514
|
+
return ids;
|
|
1515
|
+
}
|
|
1516
|
+
async function waitNativeMediaSendReceipts(client, accountId, threadId2, initial, audioAsVoice, timeoutMs = 1e4) {
|
|
1517
|
+
if (initial.accountId !== accountId || initial.threadId !== threadId2 || initial.kind !== "send") throw Error("Native media receipt job identity mismatch; inspect the submitted job and do not resend");
|
|
1518
|
+
const deadline = Date.now() + Math.max(0, Math.min(timeoutMs, 1e4));
|
|
1519
|
+
let job = initial, delay2 = 100;
|
|
1520
|
+
while (successfulSendJobs.has(job.state) && !mediaSendReceiptIds(job, audioAsVoice) && Date.now() < deadline) {
|
|
1521
|
+
const result = mediaSendResult(job);
|
|
1522
|
+
if (["unknown", "not_applicable"].includes(String(result.profileProjection)) || audioAsVoice && Array.isArray(result.chunks) && result.chunks.some((chunk) => !chunk || chunk.state !== "accepted")) break;
|
|
1523
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(delay2, Math.max(0, deadline - Date.now()))));
|
|
1524
|
+
const remaining = deadline - Date.now();
|
|
1525
|
+
if (remaining <= 0) break;
|
|
1526
|
+
let next;
|
|
1527
|
+
try {
|
|
1528
|
+
next = await client.job(accountId, initial.id, AbortSignal.timeout(remaining));
|
|
1529
|
+
} catch {
|
|
1530
|
+
break;
|
|
1531
|
+
}
|
|
1532
|
+
if (next.id !== initial.id || next.accountId !== accountId || next.threadId !== threadId2 || next.kind !== "send" || next.sourceId !== initial.sourceId || initial.serverMessageId != null && next.serverMessageId !== initial.serverMessageId) break;
|
|
1533
|
+
job = next;
|
|
1534
|
+
delay2 = Math.min(delay2 * 2, 1e3);
|
|
1535
|
+
}
|
|
1536
|
+
return job;
|
|
1537
|
+
}
|
|
1538
|
+
async function waitNativeMediaJob(client, accountId, initial, timeoutMs = 65e3, signal, assertCurrent) {
|
|
1539
|
+
return waitNativeMediaStatus(initial, timeoutMs, signal, assertCurrent, (job, pollSignal) => client.job(accountId, job.id, pollSignal));
|
|
1540
|
+
}
|
|
1541
|
+
async function waitNativeMediaStatus(initial, timeoutMs, signal, assertCurrent, readStatus) {
|
|
1025
1542
|
const deadline = Date.now() + timeoutMs;
|
|
1026
1543
|
let job = initial;
|
|
1027
|
-
let
|
|
1544
|
+
let delay2 = 250;
|
|
1028
1545
|
while (!terminalJobs.has(job.state) && Date.now() < deadline) {
|
|
1029
|
-
|
|
1546
|
+
signal?.throwIfAborted();
|
|
1547
|
+
assertCurrent?.();
|
|
1548
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(delay2, Math.max(0, deadline - Date.now()))));
|
|
1030
1549
|
const remaining = deadline - Date.now();
|
|
1031
1550
|
if (remaining <= 0) break;
|
|
1032
|
-
|
|
1033
|
-
|
|
1551
|
+
signal?.throwIfAborted();
|
|
1552
|
+
assertCurrent?.();
|
|
1553
|
+
const next = await readStatus(job, signal ? AbortSignal.any([signal, AbortSignal.timeout(remaining)]) : AbortSignal.timeout(remaining));
|
|
1554
|
+
if (!next) break;
|
|
1555
|
+
job = next;
|
|
1556
|
+
delay2 = Math.min(delay2 * 2, 1e3);
|
|
1557
|
+
}
|
|
1558
|
+
return job;
|
|
1559
|
+
}
|
|
1560
|
+
async function incomingMediaJobStatus(client, accountId, jobId, assetId, signal, assertCurrent) {
|
|
1561
|
+
let job;
|
|
1562
|
+
assertCurrent();
|
|
1563
|
+
try {
|
|
1564
|
+
job = await client.job(accountId, jobId, signal);
|
|
1565
|
+
} catch (error) {
|
|
1566
|
+
assertCurrent();
|
|
1567
|
+
if (error instanceof NativeApiError ? error.retryable && !terminalIdentityErrors.has(error.code) && error.code !== "message_recalled" : error instanceof TypeError || error instanceof DOMException && ["TimeoutError", "NetworkError", "AbortError"].includes(error.name)) return void 0;
|
|
1568
|
+
throw error;
|
|
1034
1569
|
}
|
|
1570
|
+
assertCurrent();
|
|
1571
|
+
if (job.id !== jobId || job.accountId !== accountId || job.kind !== "download" || assetId != null && job.assetId != null && job.assetId !== assetId) throw Error("Native download job identity does not match its attachment");
|
|
1035
1572
|
return job;
|
|
1036
1573
|
}
|
|
1037
|
-
function select(assets, type) {
|
|
1574
|
+
function select(assets, type, quality = "best") {
|
|
1038
1575
|
const preferred = type === 34 ? ["normal"] : type === 43 ? ["normal", "original"] : ["original", "standard", "thumbnail", "encoded"];
|
|
1039
1576
|
const rank = (asset) => {
|
|
1040
1577
|
const index = preferred.indexOf(asset.actualVariant ?? asset.variant);
|
|
1041
1578
|
return index < 0 ? preferred.length : index;
|
|
1042
1579
|
};
|
|
1043
|
-
return [...assets].sort((a, b) => rank(a) - rank(b)).find((asset) => asset.state === "available" && (type !== 34 || (asset.actualVariant ?? asset.variant) === "normal"));
|
|
1580
|
+
return [...assets].sort((a, b) => rank(a) - rank(b)).find((asset) => asset.state === "available" && (quality === "best" ? type !== 34 || (asset.actualVariant ?? asset.variant) === "normal" : (asset.actualVariant ?? asset.variant) === quality));
|
|
1044
1581
|
}
|
|
1045
1582
|
async function prepareImageRepresentation(bytes, mime, cfg) {
|
|
1046
1583
|
const configured = cfg?.agents?.defaults?.imageMaxDimensionPx;
|
|
@@ -1054,46 +1591,254 @@ async function prepareImageRepresentation(bytes, mime, cfg) {
|
|
|
1054
1591
|
}
|
|
1055
1592
|
throw Error("Native model image representation exceeds its bound");
|
|
1056
1593
|
}
|
|
1594
|
+
async function prepareNativeLink(params) {
|
|
1595
|
+
const { message } = params;
|
|
1596
|
+
const link = message.link;
|
|
1597
|
+
const body = [`[Link]${link.title ? ` ${link.title}` : ""}`, link.description, link.url].filter(Boolean).join("\n").slice(0, 65536);
|
|
1598
|
+
const unavailable = (status, reason) => ({
|
|
1599
|
+
body: `${body}
|
|
1600
|
+
[Link preview ${status}]`,
|
|
1601
|
+
pending: false,
|
|
1602
|
+
retryable: false,
|
|
1603
|
+
reason,
|
|
1604
|
+
attachment: { kind: "image", status, filename: "link-preview" }
|
|
1605
|
+
});
|
|
1606
|
+
if (params.quality && !["best", "thumbnail"].includes(params.quality)) return unavailable("unsupported", "unsupported_media_variant");
|
|
1607
|
+
let prepared;
|
|
1608
|
+
try {
|
|
1609
|
+
prepared = await prepareNativeAttachment({
|
|
1610
|
+
...params,
|
|
1611
|
+
quality: "thumbnail",
|
|
1612
|
+
message: { ...message, type: 3, appMessageType: void 0, quote: void 0, link: void 0 }
|
|
1613
|
+
});
|
|
1614
|
+
} catch (error) {
|
|
1615
|
+
params.signal?.throwIfAborted();
|
|
1616
|
+
params.assertCurrent?.();
|
|
1617
|
+
if (!(error instanceof NativeApiError)) throw error;
|
|
1618
|
+
if (terminalIdentityErrors.has(error.code) || error.code === "message_recalled") throw error;
|
|
1619
|
+
return { ...unavailable("unavailable", error.code), retryable: error.retryable };
|
|
1620
|
+
}
|
|
1621
|
+
if (prepared.reason === "message_recalled" || terminalIdentityErrors.has(prepared.reason ?? "")) return prepared;
|
|
1622
|
+
return {
|
|
1623
|
+
...prepared,
|
|
1624
|
+
body: `${body}
|
|
1625
|
+
[Link preview]
|
|
1626
|
+
${prepared.body}`,
|
|
1627
|
+
pending: false,
|
|
1628
|
+
...prepared.pending ? { attachment: { kind: "image", status: "pending", filename: "link-preview" } } : {}
|
|
1629
|
+
};
|
|
1630
|
+
}
|
|
1631
|
+
async function prepareNativeQuote(params) {
|
|
1632
|
+
const { message } = params;
|
|
1633
|
+
const guard2 = () => {
|
|
1634
|
+
params.signal?.throwIfAborted();
|
|
1635
|
+
params.assertCurrent?.();
|
|
1636
|
+
};
|
|
1637
|
+
guard2();
|
|
1638
|
+
const author = { senderId: message.quote?.senderId ?? null, direction: message.quote?.direction ?? null };
|
|
1639
|
+
const permitted = !message.quote || !params.allowQuotedMessage || await params.allowQuotedMessage(author);
|
|
1640
|
+
guard2();
|
|
1641
|
+
const rendered = renderEmbeddedQuote(message, permitted);
|
|
1642
|
+
if (!rendered.image) return {
|
|
1643
|
+
body: rendered.body,
|
|
1644
|
+
quote: rendered.quote,
|
|
1645
|
+
pending: false,
|
|
1646
|
+
retryable: false,
|
|
1647
|
+
...rendered.quote.state === "recalled" ? { reason: "message_recalled" } : {}
|
|
1648
|
+
};
|
|
1649
|
+
const beforeMediaAccess = async () => {
|
|
1650
|
+
await params.beforeMediaAccess?.();
|
|
1651
|
+
guard2();
|
|
1652
|
+
if (params.allowQuotedMessage && !await params.allowQuotedMessage(author)) throw Error("Quoted message is no longer permitted");
|
|
1653
|
+
guard2();
|
|
1654
|
+
};
|
|
1655
|
+
const prepared = await prepareNativeAttachment({ ...params, message: { ...message, type: 3, appMessageType: void 0, quote: void 0, link: void 0 }, beforeMediaAccess });
|
|
1656
|
+
if (prepared.reason === "message_recalled" || terminalIdentityErrors.has(prepared.reason ?? "")) return prepared;
|
|
1657
|
+
return {
|
|
1658
|
+
...prepared,
|
|
1659
|
+
body: renderEmbeddedQuote(message, true, prepared.body).body,
|
|
1660
|
+
quote: rendered.quote,
|
|
1661
|
+
pending: false,
|
|
1662
|
+
...prepared.pending ? { attachment: { kind: "image", status: "pending", filename: "quoted-image" } } : {}
|
|
1663
|
+
};
|
|
1664
|
+
}
|
|
1057
1665
|
async function prepareNativeAttachment(params) {
|
|
1666
|
+
try {
|
|
1667
|
+
return await prepareNativeAttachmentInput(params);
|
|
1668
|
+
} catch (error) {
|
|
1669
|
+
params.signal?.throwIfAborted();
|
|
1670
|
+
params.assertCurrent?.();
|
|
1671
|
+
if (!(error instanceof NativeApiError) || !terminalIdentityErrors.has(error.code)) throw error;
|
|
1672
|
+
if (params.message.type === 49 && params.message.appMessageType === 57) return {
|
|
1673
|
+
body: `${(params.message.body ?? "").slice(0, 16384)}
|
|
1674
|
+
[Quoted message unavailable: stored source identity could not be verified]`,
|
|
1675
|
+
quote: { state: "unavailable" },
|
|
1676
|
+
pending: false,
|
|
1677
|
+
retryable: false,
|
|
1678
|
+
reason: error.code
|
|
1679
|
+
};
|
|
1680
|
+
const attachment = { kind: kind(params.message.type) ?? "file", filename: "attachment", status: "unavailable" };
|
|
1681
|
+
return { body: renderAttachmentBody("", attachment), attachment, pending: false, retryable: false, reason: error.code };
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
async function prepareNativeAttachmentInput(params) {
|
|
1058
1685
|
const { client, account, message, core } = params;
|
|
1059
1686
|
const attachmentKind = kind(message.type);
|
|
1687
|
+
const guard2 = () => {
|
|
1688
|
+
params.signal?.throwIfAborted();
|
|
1689
|
+
params.assertCurrent?.();
|
|
1690
|
+
};
|
|
1691
|
+
guard2();
|
|
1692
|
+
if (nativeRecallInfo(message)) return { body: "[Message recalled]", pending: false, retryable: false, reason: "message_recalled" };
|
|
1693
|
+
const authorize = async () => {
|
|
1694
|
+
guard2();
|
|
1695
|
+
await params.beforeMediaAccess?.();
|
|
1696
|
+
guard2();
|
|
1697
|
+
};
|
|
1698
|
+
if (message.type === 49 && message.appMessageType === 57) return prepareNativeQuote(params);
|
|
1699
|
+
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);
|
|
1701
|
+
if (message.type === 49 && message.appMessageType != null && message.appMessageType !== 6) return { body: `[Unsupported WeChat app message subtype ${message.appMessageType}]`, pending: false, retryable: false };
|
|
1060
1702
|
if (!attachmentKind) return { body: message.type === 1 ? message.body ?? "" : `[Unsupported WeChat message type ${message.type}]`, pending: false };
|
|
1061
1703
|
const accountId = account.native.accountId;
|
|
1062
|
-
const maxBytes = Math.min(
|
|
1704
|
+
const maxBytes = Math.min(
|
|
1705
|
+
account.mediaMaxMb * 1024 * 1024,
|
|
1706
|
+
attachmentKind === "file" ? Math.max(NATIVE_MAX_SOURCE_BYTES, 128 * 1024 * 1024) : 128 * 1024 * 1024
|
|
1707
|
+
);
|
|
1063
1708
|
const scopedAssets = async () => {
|
|
1709
|
+
await authorize();
|
|
1064
1710
|
const items = (await client.mediaAssets(accountId, message.id)).items;
|
|
1711
|
+
guard2();
|
|
1065
1712
|
if (items.some((asset2) => asset2.accountId !== accountId || asset2.messageId !== message.id)) throw Error("Native attachment identity does not match its message");
|
|
1066
1713
|
return items;
|
|
1067
1714
|
};
|
|
1715
|
+
const quality = params.quality ?? "best";
|
|
1716
|
+
const transferQuality = quality === "best" && (message.type === 34 || message.type === 43) ? "normal" : quality;
|
|
1068
1717
|
let assets = await scopedAssets();
|
|
1069
|
-
let asset = select(assets, message.type);
|
|
1070
|
-
|
|
1718
|
+
let asset = select(assets, message.type, quality);
|
|
1719
|
+
const relevant = () => assets.filter((value) => transferQuality === "best" || value.variant === transferQuality);
|
|
1720
|
+
const transferCandidate = () => {
|
|
1721
|
+
const order = ["original", "normal", "standard", "thumbnail", "encoded"];
|
|
1722
|
+
return [...relevant()].sort((a, b) => order.indexOf(a.variant) - order.indexOf(b.variant))[0];
|
|
1723
|
+
};
|
|
1724
|
+
const initialCandidate = transferCandidate();
|
|
1725
|
+
if (!asset && initialCandidate?.byteLength != null && initialCandidate.byteLength > maxBytes) {
|
|
1726
|
+
const attachment2 = { kind: attachmentKind, filename: basename(initialCandidate.filename ?? "attachment"), status: "too_large" };
|
|
1727
|
+
return { body: renderAttachmentBody("", attachment2), attachment: attachment2, pending: false, retryable: false };
|
|
1728
|
+
}
|
|
1729
|
+
let job;
|
|
1730
|
+
let transferError;
|
|
1731
|
+
if (!asset && initialCandidate?.jobId && initialCandidate.state !== "recalled") {
|
|
1732
|
+
await authorize();
|
|
1733
|
+
job = await incomingMediaJobStatus(client, accountId, initialCandidate.jobId, initialCandidate.id, params.signal, guard2);
|
|
1734
|
+
guard2();
|
|
1735
|
+
if (!job) return { body: `[${attachmentKind} pending: retrieval is unavailable]`, pending: true, jobId: initialCandidate.jobId, retryable: true };
|
|
1736
|
+
assets = await scopedAssets();
|
|
1737
|
+
asset = select(assets, message.type, quality);
|
|
1738
|
+
if (!asset && transferCandidate()?.state === "recalled") return { body: "[Message recalled]", pending: false, retryable: false, reason: "message_recalled" };
|
|
1739
|
+
if (!asset && ["queued", "running"].includes(job.state)) return { body: `[${attachmentKind} pending]`, pending: true, jobId: job.id, retryable: true };
|
|
1740
|
+
}
|
|
1741
|
+
if (!asset && !job && params.download !== false && !["expired", "unsupported", "recalled"].includes(transferCandidate()?.state ?? "")) {
|
|
1742
|
+
await authorize();
|
|
1071
1743
|
try {
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1744
|
+
job = await client.transferMedia(accountId, { messageId: message.id, assetId: null, quality: transferQuality });
|
|
1745
|
+
guard2();
|
|
1746
|
+
job = await waitNativeMediaStatus(
|
|
1747
|
+
job,
|
|
1748
|
+
params.waitMs ?? 2e4,
|
|
1749
|
+
params.signal,
|
|
1750
|
+
guard2,
|
|
1751
|
+
(known, pollSignal) => incomingMediaJobStatus(client, accountId, known.id, initialCandidate?.id, pollSignal, guard2)
|
|
1752
|
+
);
|
|
1753
|
+
guard2();
|
|
1754
|
+
} catch (error) {
|
|
1755
|
+
guard2();
|
|
1756
|
+
if (!(error instanceof NativeApiError) || terminalIdentityErrors.has(error.code)) throw error;
|
|
1757
|
+
if (error.retryable) return { body: `[${attachmentKind} pending: retrieval is unavailable]`, pending: true, jobId: job?.id, retryable: true };
|
|
1758
|
+
transferError = error;
|
|
1079
1759
|
}
|
|
1760
|
+
assets = await scopedAssets();
|
|
1761
|
+
asset = select(assets, message.type, quality);
|
|
1762
|
+
if (!asset && transferCandidate()?.state === "recalled") return { body: "[Message recalled]", pending: false, retryable: false, reason: "message_recalled" };
|
|
1763
|
+
if (!asset && job && ["queued", "running"].includes(job.state)) return { body: `[${attachmentKind} pending]`, pending: true, jobId: job.id, retryable: true };
|
|
1080
1764
|
}
|
|
1081
|
-
const
|
|
1765
|
+
const candidate = transferCandidate();
|
|
1766
|
+
const filename = basename(asset?.filename ?? candidate?.filename ?? `message-${createHash4("sha256").update(message.id).digest("hex").slice(0, 12)}.bin`).replace(/[\r\n\0]/g, "_");
|
|
1082
1767
|
if (!asset) {
|
|
1083
|
-
|
|
1084
|
-
const
|
|
1085
|
-
|
|
1768
|
+
if (candidate?.state === "recalled" || transferError?.code === "message_recalled") return { body: "[Message recalled]", pending: false, retryable: false, reason: "message_recalled" };
|
|
1769
|
+
const state = candidate?.state === "expired" ? "expired" : candidate?.state === "unsupported" ? "unsupported" : "unavailable";
|
|
1770
|
+
const attachment2 = { kind: attachmentKind, filename, status: state, expiresAt: candidate?.expiresAt ?? void 0 };
|
|
1771
|
+
return {
|
|
1772
|
+
body: renderAttachmentBody("", attachment2),
|
|
1773
|
+
attachment: attachment2,
|
|
1774
|
+
pending: false,
|
|
1775
|
+
jobId: job?.id,
|
|
1776
|
+
retryable: state === "expired" || state === "unsupported" ? false : transferError ? false : job?.retryable ?? params.download === false,
|
|
1777
|
+
reason: transferError?.code ?? (job?.reason && /^[a-z0-9_]{1,80}$/.test(job.reason) ? job.reason : void 0)
|
|
1778
|
+
};
|
|
1086
1779
|
}
|
|
1087
1780
|
if (asset.byteLength != null && asset.byteLength > maxBytes) {
|
|
1088
1781
|
const attachment2 = { kind: attachmentKind, filename, status: "too_large" };
|
|
1089
1782
|
return { body: renderAttachmentBody("", attachment2), attachment: attachment2, pending: false };
|
|
1090
1783
|
}
|
|
1091
|
-
|
|
1784
|
+
await authorize();
|
|
1785
|
+
if (attachmentKind === "file" && asset.byteLength != null && asset.byteLength > 128 * 1024 * 1024) {
|
|
1786
|
+
const content2 = await client.mediaContentStream(accountId, asset.id, { maxBytes, signal: params.signal });
|
|
1787
|
+
const mime2 = content2.contentType.split(";", 1)[0].trim().toLowerCase();
|
|
1788
|
+
if (!/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/.test(mime2)) {
|
|
1789
|
+
await content2.cancel();
|
|
1790
|
+
throw Error("Native attachment MIME type is unsupported");
|
|
1791
|
+
}
|
|
1792
|
+
let saved2;
|
|
1793
|
+
try {
|
|
1794
|
+
saved2 = await saveVerifiedManagedAttachmentStream({
|
|
1795
|
+
stream: content2.stream,
|
|
1796
|
+
mime: mime2,
|
|
1797
|
+
filename,
|
|
1798
|
+
maxBytes,
|
|
1799
|
+
expectedBytes: asset.byteLength,
|
|
1800
|
+
expectedSha256: asset.sha256 ?? "",
|
|
1801
|
+
assertCurrent: guard2,
|
|
1802
|
+
saveMediaStream: params.saveMediaStream ?? saveMediaStream
|
|
1803
|
+
});
|
|
1804
|
+
} finally {
|
|
1805
|
+
await content2.cancel();
|
|
1806
|
+
}
|
|
1807
|
+
await authorize();
|
|
1808
|
+
const attachment2 = { kind: "file", filename, status: "ready", path: saved2.path, mime: mime2 };
|
|
1809
|
+
return {
|
|
1810
|
+
body: renderAttachmentBody("", attachment2),
|
|
1811
|
+
attachment: attachment2,
|
|
1812
|
+
mediaMime: mime2,
|
|
1813
|
+
pending: false,
|
|
1814
|
+
jobId: job?.id,
|
|
1815
|
+
retryable: false,
|
|
1816
|
+
variant: asset.actualVariant ?? asset.variant,
|
|
1817
|
+
suppliedAssets: [{
|
|
1818
|
+
id: asset.id,
|
|
1819
|
+
contextRole: "trigger",
|
|
1820
|
+
role: "file_reference",
|
|
1821
|
+
kind: "file",
|
|
1822
|
+
path: saved2.path,
|
|
1823
|
+
mime: mime2,
|
|
1824
|
+
sha256: saved2.sha256,
|
|
1825
|
+
byteLength: saved2.size,
|
|
1826
|
+
runtimeMedia: false,
|
|
1827
|
+
sourceSha256: saved2.sha256,
|
|
1828
|
+
sourceByteLength: saved2.size,
|
|
1829
|
+
sourceMime: mime2,
|
|
1830
|
+
sourcePath: saved2.path
|
|
1831
|
+
}]
|
|
1832
|
+
};
|
|
1833
|
+
}
|
|
1834
|
+
const content = await client.mediaContent(accountId, asset.id, { maxBytes, signal: params.signal });
|
|
1835
|
+
guard2();
|
|
1092
1836
|
const mime = content.contentType.split(";", 1)[0].trim().toLowerCase();
|
|
1093
1837
|
if (!/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/.test(mime)) throw Error("Native attachment MIME type is unsupported");
|
|
1094
1838
|
const hash = createHash4("sha256").update(content.bytes).digest("hex");
|
|
1095
1839
|
if (!asset.sha256 || hash !== asset.sha256 || asset.byteLength != null && asset.byteLength !== content.bytes.length) throw new Error("Native attachment integrity did not verify");
|
|
1096
|
-
|
|
1840
|
+
await authorize();
|
|
1841
|
+
const saved = await saveManagedAttachmentBytes({ bytes: content.bytes, mime, filename, maxBytes, saveMediaBuffer: core.channel.media.saveMediaBuffer });
|
|
1097
1842
|
const actual = asset.actualVariant ?? asset.variant;
|
|
1098
1843
|
const attachment = {
|
|
1099
1844
|
kind: attachmentKind,
|
|
@@ -1105,13 +1850,27 @@ async function prepareNativeAttachment(params) {
|
|
|
1105
1850
|
};
|
|
1106
1851
|
let suppliedPath = saved.path, suppliedMime = mime, suppliedHash = hash, suppliedLength = content.bytes.length;
|
|
1107
1852
|
let body = renderAttachmentBody("", attachment);
|
|
1108
|
-
if (attachmentKind === "image" && params.cfg) {
|
|
1109
|
-
|
|
1110
|
-
|
|
1853
|
+
if (attachmentKind === "image" && (params.cfg || mime === "image/x-wxgf")) {
|
|
1854
|
+
let imageBytes = Buffer.from(content.bytes), imageMime = mime;
|
|
1855
|
+
const wxgf = mime === "image/x-wxgf";
|
|
1856
|
+
if (wxgf) {
|
|
1857
|
+
const preview = asset.preview;
|
|
1858
|
+
if (!preview || preview.sourceSha256 !== hash || !/^[a-f0-9]{64}$/.test(preview.sha256) || !Number.isInteger(preview.byteLength) || preview.byteLength <= 0 || preview.byteLength > 16 * 1024 * 1024 || !["image/jpeg", "image/png"].includes(preview.contentType)) throw Error("Native WXGF preview metadata did not verify");
|
|
1859
|
+
await authorize();
|
|
1860
|
+
const derived = await client.mediaContent(accountId, asset.id, { maxBytes: preview.byteLength, representation: "preview", signal: params.signal });
|
|
1861
|
+
guard2();
|
|
1862
|
+
const derivedMime = derived.contentType.split(";", 1)[0].trim().toLowerCase();
|
|
1863
|
+
if (derived.sourceSha256 !== hash || derivedMime !== preview.contentType || derived.bytes.length !== preview.byteLength || createHash4("sha256").update(derived.bytes).digest("hex") !== preview.sha256) throw Error("Native WXGF preview integrity did not verify");
|
|
1864
|
+
imageBytes = Buffer.from(derived.bytes);
|
|
1865
|
+
imageMime = derivedMime;
|
|
1866
|
+
}
|
|
1867
|
+
const representation = await prepareImageRepresentation(imageBytes, imageMime, params.cfg);
|
|
1868
|
+
if (wxgf || representation.preview) {
|
|
1869
|
+
const extension = representation.mime === "image/png" ? "png" : "jpg";
|
|
1111
1870
|
const normalized = await saveManagedAttachment({
|
|
1112
1871
|
data: representation.bytes.toString("base64"),
|
|
1113
1872
|
mime: representation.mime,
|
|
1114
|
-
filename: `${filename}.model
|
|
1873
|
+
filename: `${filename}.model.${extension}`,
|
|
1115
1874
|
maxBytes: 5 * 1024 * 1024,
|
|
1116
1875
|
saveMediaBuffer: core.channel.media.saveMediaBuffer
|
|
1117
1876
|
});
|
|
@@ -1119,13 +1878,18 @@ async function prepareNativeAttachment(params) {
|
|
|
1119
1878
|
suppliedMime = representation.mime;
|
|
1120
1879
|
suppliedHash = normalized.sha256;
|
|
1121
1880
|
suppliedLength = normalized.size;
|
|
1122
|
-
body += `
|
|
1881
|
+
body += wxgf ? `
|
|
1882
|
+
[Model image: WXGF still preview; original retained separately; animation and transparency are not represented]` : `
|
|
1123
1883
|
[Model image: prepared still preview; original retained separately]`;
|
|
1124
1884
|
}
|
|
1125
1885
|
}
|
|
1886
|
+
guard2();
|
|
1126
1887
|
return {
|
|
1127
1888
|
body,
|
|
1128
1889
|
attachment,
|
|
1890
|
+
jobId: job?.id,
|
|
1891
|
+
retryable: false,
|
|
1892
|
+
variant: actual,
|
|
1129
1893
|
suppliedAssets: [{
|
|
1130
1894
|
id: asset.id,
|
|
1131
1895
|
sha256: suppliedHash,
|
|
@@ -1146,125 +1910,250 @@ async function prepareNativeAttachment(params) {
|
|
|
1146
1910
|
pending: false
|
|
1147
1911
|
};
|
|
1148
1912
|
}
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1913
|
+
function validateNativeMediaSendOptions(options, audioAsVoice = false) {
|
|
1914
|
+
if (options.forceDocument != null && typeof options.forceDocument !== "boolean") throw new Error("Invalid WeChat document option");
|
|
1915
|
+
if (options.videoQuality != null && !["normal", "original"].includes(options.videoQuality)) throw new Error("Invalid WeChat video quality");
|
|
1916
|
+
if (options.forceDocument && (audioAsVoice || options.videoQuality != null)) throw new Error("Document sending cannot also request voice or video quality");
|
|
1917
|
+
}
|
|
1918
|
+
function outboundMediaKind(mime, audioAsVoice, options) {
|
|
1919
|
+
if (options.forceDocument) return "file";
|
|
1920
|
+
if (audioAsVoice && !mime.startsWith("audio/")) throw new Error("Voice sending requires an explicit audio attachment");
|
|
1921
|
+
const selected = audioAsVoice ? "voice" : mime.startsWith("image/") ? "image" : mime.startsWith("video/") ? "video" : "file";
|
|
1922
|
+
if (options.videoQuality != null && selected !== "video") throw new Error("Video quality requires a video attachment");
|
|
1923
|
+
return selected;
|
|
1924
|
+
}
|
|
1925
|
+
function outboundSourceLimit(account, selectedKind) {
|
|
1926
|
+
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);
|
|
1927
|
+
}
|
|
1928
|
+
async function sendNativeAttachment(client, account, threadId2, mediaUrl, audioAsVoice = false, key = randomUUID(), beforeSend, options = {}) {
|
|
1929
|
+
validateNativeMediaSendOptions(options, audioAsVoice);
|
|
1930
|
+
await beforeSend?.();
|
|
1931
|
+
let filename, mime, selectedKind, sourceBytes, source;
|
|
1932
|
+
let temporary;
|
|
1933
|
+
const accountId = account.native.accountId;
|
|
1934
|
+
try {
|
|
1935
|
+
let blob;
|
|
1936
|
+
if (/^https?:/.test(mediaUrl)) {
|
|
1937
|
+
const response = await fetch(mediaUrl, { redirect: "error", signal: AbortSignal.timeout(60 * 6e4) });
|
|
1938
|
+
if (!response.ok) throw new Error(`Native outbound source unavailable (${response.status})`);
|
|
1939
|
+
filename = basename(new URL(mediaUrl).pathname) || "attachment";
|
|
1940
|
+
mime = response.headers.get("content-type")?.split(";")[0].trim().toLowerCase() ?? "application/octet-stream";
|
|
1941
|
+
try {
|
|
1942
|
+
selectedKind = outboundMediaKind(mime, audioAsVoice, options);
|
|
1943
|
+
} catch (error) {
|
|
1944
|
+
await response.body?.cancel();
|
|
1945
|
+
throw error;
|
|
1173
1946
|
}
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
}
|
|
1180
|
-
bytes = new Uint8Array(size);
|
|
1181
|
-
let offset = 0;
|
|
1182
|
-
for (const chunk of chunks) {
|
|
1183
|
-
bytes.set(chunk, offset);
|
|
1184
|
-
offset += chunk.length;
|
|
1185
|
-
}
|
|
1186
|
-
filename = basename(new URL(mediaUrl).pathname) || "attachment";
|
|
1187
|
-
mime = response.headers.get("content-type")?.split(";")[0] ?? "application/octet-stream";
|
|
1188
|
-
} else {
|
|
1189
|
-
const path = mediaUrl.startsWith("file:") ? new URL(mediaUrl) : mediaUrl;
|
|
1190
|
-
const file = await open(path, "r");
|
|
1191
|
-
try {
|
|
1192
|
-
const stat = await file.stat();
|
|
1193
|
-
if (!stat.isFile() || stat.size === 0 || stat.size > max) throw new Error("Native outbound source must be a bounded regular file");
|
|
1194
|
-
const chunks = [];
|
|
1195
|
-
let size = 0;
|
|
1196
|
-
while (true) {
|
|
1197
|
-
const chunk = Buffer.alloc(Math.min(65536, max + 1 - size));
|
|
1198
|
-
const { bytesRead } = await file.read(chunk, 0, chunk.length, null);
|
|
1199
|
-
if (!bytesRead) break;
|
|
1200
|
-
size += bytesRead;
|
|
1201
|
-
if (size > max) throw new Error("Native outbound source exceeds configured size");
|
|
1202
|
-
chunks.push(chunk.subarray(0, bytesRead));
|
|
1947
|
+
const max = outboundSourceLimit(account, selectedKind);
|
|
1948
|
+
const length = response.headers.get("content-length");
|
|
1949
|
+
if (length && (!/^\d+$/.test(length) || Number(length) > max)) {
|
|
1950
|
+
await response.body?.cancel();
|
|
1951
|
+
throw new Error("Native outbound source exceeds configured size");
|
|
1203
1952
|
}
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1953
|
+
const reader = response.body?.getReader();
|
|
1954
|
+
if (!reader) throw new Error("Native outbound source has no bytes");
|
|
1955
|
+
let path, file, size = 0;
|
|
1956
|
+
try {
|
|
1957
|
+
temporary = await mkdtemp(join2(tmpdir(), "wechat-outbound-"));
|
|
1958
|
+
path = join2(temporary, "source");
|
|
1959
|
+
file = await open(path, "wx", 384);
|
|
1960
|
+
while (true) {
|
|
1961
|
+
const { value, done } = await reader.read();
|
|
1962
|
+
if (done) break;
|
|
1963
|
+
size += value.byteLength;
|
|
1964
|
+
if (size > max) throw new Error("Native outbound source exceeds configured size");
|
|
1965
|
+
await file.writeFile(value);
|
|
1966
|
+
}
|
|
1967
|
+
if (!size || length && size !== Number(length)) throw new Error("Native outbound source length mismatch");
|
|
1968
|
+
} finally {
|
|
1969
|
+
await reader.cancel().catch(() => {
|
|
1970
|
+
});
|
|
1971
|
+
reader.releaseLock();
|
|
1972
|
+
await file?.close();
|
|
1973
|
+
}
|
|
1974
|
+
blob = await openAsBlob(path, { type: mime });
|
|
1975
|
+
} else {
|
|
1976
|
+
const path = mediaUrl.startsWith("file:") ? new URL(mediaUrl) : mediaUrl;
|
|
1977
|
+
filename = basename(path instanceof URL ? path.pathname : path);
|
|
1978
|
+
const extension = extname(filename).toLowerCase();
|
|
1979
|
+
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";
|
|
1980
|
+
selectedKind = outboundMediaKind(mime, audioAsVoice, options);
|
|
1981
|
+
const max = outboundSourceLimit(account, selectedKind), file = await open(path, "r");
|
|
1982
|
+
let size;
|
|
1983
|
+
try {
|
|
1984
|
+
const stat = await file.stat();
|
|
1985
|
+
if (!stat.isFile() || !stat.size || stat.size > max) throw new Error("Native outbound source must be a bounded regular file");
|
|
1986
|
+
size = stat.size;
|
|
1987
|
+
} finally {
|
|
1988
|
+
await file.close();
|
|
1989
|
+
}
|
|
1990
|
+
blob = await openAsBlob(path, { type: mime });
|
|
1991
|
+
if (blob.size !== size) throw new Error("Native outbound source changed before staging");
|
|
1207
1992
|
}
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1993
|
+
sourceBytes = blob.size;
|
|
1994
|
+
if (sourceBytes > outboundSourceLimit(account, selectedKind)) throw new Error("Native outbound source exceeds selected media kind size");
|
|
1995
|
+
await beforeSend?.();
|
|
1996
|
+
source = await client.upload(accountId, blob, filename, mime);
|
|
1997
|
+
} finally {
|
|
1998
|
+
if (temporary) await rm(temporary, { recursive: true, force: true });
|
|
1211
1999
|
}
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
const
|
|
1225
|
-
let
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
intent = await client.send(accountId, intent.id, AbortSignal.timeout(remaining));
|
|
1231
|
-
delay = Math.min(delay * 2, 1e3);
|
|
2000
|
+
const input = {
|
|
2001
|
+
threadId: threadId2,
|
|
2002
|
+
kind: selectedKind,
|
|
2003
|
+
sourceId: source.id,
|
|
2004
|
+
standardSourceId: null,
|
|
2005
|
+
thumbnailSourceId: null,
|
|
2006
|
+
playSeconds: null,
|
|
2007
|
+
durationMs: null,
|
|
2008
|
+
...selectedKind === "video" ? { videoQuality: options.videoQuality ?? "normal" } : {}
|
|
2009
|
+
};
|
|
2010
|
+
await beforeSend?.();
|
|
2011
|
+
const waitMs = audioAsVoice ? 25 * 6e4 : selectedKind === "video" || selectedKind === "file" && sourceBytes > NATIVE_MAX_ORDINARY_SOURCE_BYTES ? 60 * 6e4 : 65e3;
|
|
2012
|
+
const submitted = await client.sendMedia(accountId, input, key);
|
|
2013
|
+
let job;
|
|
2014
|
+
try {
|
|
2015
|
+
job = await waitNativeMediaJob(client, accountId, submitted, waitMs);
|
|
2016
|
+
} catch {
|
|
2017
|
+
throw new NativeMediaJobInspectionError(submitted, accountId, threadId2, key, "status_unavailable");
|
|
1232
2018
|
}
|
|
1233
|
-
if (
|
|
1234
|
-
|
|
2019
|
+
if (successfulSendJobs.has(job.state)) job = await waitNativeMediaSendReceipts(client, accountId, threadId2, job, audioAsVoice);
|
|
2020
|
+
if (!successfulSendJobs.has(job.state)) throw new NativeMediaJobInspectionError(job, accountId, threadId2, key, "job_not_completed");
|
|
2021
|
+
const result = mediaSendResult(job);
|
|
2022
|
+
const chunks = Array.isArray(result.chunks) ? result.chunks.filter((chunk) => chunk && typeof chunk === "object") : [];
|
|
2023
|
+
const serverIds = audioAsVoice ? chunks.filter((chunk) => chunk.state === "accepted" && typeof chunk.serverMessageId === "string").map((chunk) => chunk.serverMessageId) : job.serverMessageId ? [job.serverMessageId] : void 0;
|
|
2024
|
+
return nativeOutboundDelivery(client, accountId, threadId2, mediaSendReceiptIds(job, audioAsVoice), { jobId: job.id, state: job.state, serverIds });
|
|
1235
2025
|
}
|
|
1236
2026
|
|
|
1237
2027
|
// src/outbound-media.ts
|
|
1238
|
-
async function sendWeChatMedia(cfg, to,
|
|
2028
|
+
async function sendWeChatMedia(cfg, to, text3, mediaUrl, audioAsVoice = false, idempotencyKey, options = {}, beforeSend) {
|
|
2029
|
+
validateNativeMediaSendOptions(options, audioAsVoice);
|
|
2030
|
+
if (!mediaUrl && (options.forceDocument || options.videoQuality != null)) throw new Error("WeChat media options require an attachment");
|
|
1239
2031
|
const account = resolveWeChatAccount(cfg);
|
|
1240
2032
|
if (!account?.native) throw new Error("No native daemon configured");
|
|
1241
2033
|
const { client } = await ensureNativeHost(account.native);
|
|
1242
2034
|
const key = idempotencyKey ?? randomUUID2();
|
|
1243
2035
|
if (!mediaUrl) {
|
|
1244
2036
|
if (audioAsVoice) throw new Error("Voice sending requires an audio attachment");
|
|
1245
|
-
|
|
1246
|
-
|
|
2037
|
+
await beforeSend?.();
|
|
2038
|
+
const send = await submitNativeText(client, account.native.accountId, to, text3, key);
|
|
2039
|
+
return nativeOutboundDelivery(
|
|
2040
|
+
client,
|
|
2041
|
+
account.native.accountId,
|
|
2042
|
+
to,
|
|
2043
|
+
send.localMessageId ? [send.localMessageId] : [],
|
|
2044
|
+
{ sendId: send.id, state: send.state, serverIds: send.serverId ? [send.serverId] : void 0 }
|
|
2045
|
+
);
|
|
2046
|
+
}
|
|
2047
|
+
const result = await sendNativeAttachment(client, account, to, mediaUrl, audioAsVoice, key, beforeSend, options);
|
|
2048
|
+
if (text3) {
|
|
2049
|
+
await beforeSend?.();
|
|
2050
|
+
await submitNativeText(client, account.native.accountId, to, text3, createHash5("sha256").update(`${key}\0caption`).digest("hex"));
|
|
1247
2051
|
}
|
|
1248
|
-
const result = await sendNativeAttachment(client, account, to, mediaUrl, audioAsVoice, key);
|
|
1249
|
-
if (text) await submitNativeText(client, account.native.accountId, to, text, createHash5("sha256").update(`${key}\0caption`).digest("hex"));
|
|
1250
2052
|
return result;
|
|
1251
2053
|
}
|
|
1252
2054
|
|
|
2055
|
+
// src/outbound-options.ts
|
|
2056
|
+
function nativePayloadMediaOptions(payload) {
|
|
2057
|
+
const value = payload.channelData?.["agent-wechat"];
|
|
2058
|
+
if (value == null) return {};
|
|
2059
|
+
if (typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => key !== "videoQuality") || !["normal", "original"].includes(value.videoQuality)) throw Error("Invalid WeChat media options");
|
|
2060
|
+
return { videoQuality: value.videoQuality };
|
|
2061
|
+
}
|
|
2062
|
+
var wechatMediaActions = {
|
|
2063
|
+
describeMessageTool: () => ({ actions: ["send"], schema: { actions: ["send"], visibility: "all-configured", properties: {
|
|
2064
|
+
channelData: { type: "object", description: "WeChat per-send media options. Use agent-wechat.videoQuality for a single video attachment.", additionalProperties: true, properties: {
|
|
2065
|
+
"agent-wechat": { type: "object", additionalProperties: false, required: ["videoQuality"], properties: {
|
|
2066
|
+
videoQuality: { type: "string", enum: ["normal", "original"], description: "WeChat video mode: normal prepares playback; original also retains the unchanged source video. Cannot combine with forceDocument." }
|
|
2067
|
+
} }
|
|
2068
|
+
} }
|
|
2069
|
+
} } }),
|
|
2070
|
+
prepareSendPayload: ({ ctx, payload }) => {
|
|
2071
|
+
const options = nativePayloadMediaOptions(payload);
|
|
2072
|
+
if (options.videoQuality == null) return void 0;
|
|
2073
|
+
validateNativeMediaSendOptions({ ...options, forceDocument: ctx.params.forceDocument ?? ctx.params.asDocument }, payload.audioAsVoice);
|
|
2074
|
+
return payload;
|
|
2075
|
+
}
|
|
2076
|
+
};
|
|
2077
|
+
var NativeMediaPayloadInspectionError = class extends Error {
|
|
2078
|
+
retryable = false;
|
|
2079
|
+
code = "native_media_payload_inspection_required";
|
|
2080
|
+
deliveries;
|
|
2081
|
+
pendingJob;
|
|
2082
|
+
constructor(deliveries, pendingJob) {
|
|
2083
|
+
super("WeChat attachment batch requires inspection; retain completed receipts and do not automatically resend");
|
|
2084
|
+
this.name = "NativeMediaPayloadInspectionError";
|
|
2085
|
+
this.deliveries = deliveries;
|
|
2086
|
+
this.pendingJob = pendingJob;
|
|
2087
|
+
}
|
|
2088
|
+
};
|
|
2089
|
+
function createWeChatMediaHandlers(send = sendWeChatMedia) {
|
|
2090
|
+
const key = (ctx, index = 0) => ctx.deliveryQueueId ? createHash6("sha256").update(JSON.stringify(["wechat-media", ctx.deliveryQueueId, ctx.deliveryPartIndex ?? 0, index])).digest("hex") : void 0;
|
|
2091
|
+
const guard2 = (ctx) => async () => {
|
|
2092
|
+
ctx.signal?.throwIfAborted();
|
|
2093
|
+
await ctx.onPlatformSendDispatch?.();
|
|
2094
|
+
ctx.signal?.throwIfAborted();
|
|
2095
|
+
ctx.assertDirectAdapterHandoff?.();
|
|
2096
|
+
};
|
|
2097
|
+
return {
|
|
2098
|
+
sendMedia: async (ctx) => ({
|
|
2099
|
+
channel: "agent-wechat",
|
|
2100
|
+
...await send(ctx.cfg, ctx.to, ctx.text, ctx.mediaUrl, ctx.audioAsVoice, key(ctx), { forceDocument: ctx.forceDocument }, guard2(ctx))
|
|
2101
|
+
}),
|
|
2102
|
+
sendPayload: async (ctx) => {
|
|
2103
|
+
const options = { ...nativePayloadMediaOptions(ctx.payload), forceDocument: ctx.forceDocument };
|
|
2104
|
+
const audioAsVoice = ctx.payload.audioAsVoice ?? ctx.audioAsVoice;
|
|
2105
|
+
validateNativeMediaSendOptions(options, audioAsVoice);
|
|
2106
|
+
const urls = [...new Set([...ctx.payload.mediaUrls ?? [], ctx.payload.mediaUrl ?? ctx.mediaUrl].filter((url2) => typeof url2 === "string" && !!url2))];
|
|
2107
|
+
if (urls.length > 16 || options.videoQuality != null && urls.length !== 1) throw Error("WeChat video quality requires one attachment per send");
|
|
2108
|
+
const deliveries = [];
|
|
2109
|
+
for (const [index, mediaUrl] of (urls.length ? urls : [void 0]).entries()) {
|
|
2110
|
+
let delivered;
|
|
2111
|
+
try {
|
|
2112
|
+
delivered = await send(ctx.cfg, ctx.to, index === 0 ? ctx.payload.text ?? ctx.text : "", mediaUrl, audioAsVoice, key(ctx, index), options, guard2(ctx));
|
|
2113
|
+
} catch (error) {
|
|
2114
|
+
if (!deliveries.length) throw error;
|
|
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
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
if (delivered.meta.outcome === "unknown") break;
|
|
2126
|
+
}
|
|
2127
|
+
const first = deliveries[0];
|
|
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
|
+
};
|
|
2138
|
+
}
|
|
2139
|
+
};
|
|
2140
|
+
}
|
|
2141
|
+
|
|
1253
2142
|
// src/native-monitor.ts
|
|
1254
|
-
import { createHash as
|
|
2143
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
1255
2144
|
import { createChannelMessageReplyPipeline } from "openclaw/plugin-sdk/channel-outbound";
|
|
1256
2145
|
import { resolveStableChannelMessageIngress } from "openclaw/plugin-sdk/channel-ingress-runtime";
|
|
1257
2146
|
|
|
1258
2147
|
// src/native-consumer-state.ts
|
|
1259
|
-
import { createHash as
|
|
2148
|
+
import { createHash as createHash7, randomUUID as randomUUID3 } from "node:crypto";
|
|
1260
2149
|
import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
1261
|
-
import { dirname as dirname2, isAbsolute as isAbsolute2, join as
|
|
2150
|
+
import { dirname as dirname2, isAbsolute as isAbsolute2, join as join3 } from "node:path";
|
|
1262
2151
|
var NativeConsumerState = class {
|
|
1263
2152
|
file;
|
|
1264
2153
|
value;
|
|
1265
2154
|
constructor(directory, serverId, accountId) {
|
|
1266
2155
|
if (!isAbsolute2(directory) || !serverId || !accountId) throw new Error("Native consumer state requires absolute storage and bound server/account identities");
|
|
1267
|
-
this.file =
|
|
2156
|
+
this.file = join3(directory, `${createHash7("sha256").update(`${serverId}\0${accountId}`).digest("hex")}.json`);
|
|
1268
2157
|
this.value = { schemaVersion: 1, serverId, accountId, cursor: "0", items: {} };
|
|
1269
2158
|
if (existsSync(this.file)) {
|
|
1270
2159
|
const stat = lstatSync(this.file);
|
|
@@ -1273,8 +2162,18 @@ var NativeConsumerState = class {
|
|
|
1273
2162
|
if (parsed.schemaVersion !== 1 || parsed.serverId !== serverId || parsed.accountId !== accountId || !/^\d+$/.test(parsed.cursor) || !parsed.items || typeof parsed.items !== "object") throw new Error("Native consumer identity or schema mismatch; state was preserved");
|
|
1274
2163
|
for (const [id2, item] of Object.entries(parsed.items)) {
|
|
1275
2164
|
if (item.message?.id !== id2 || item.message.accountId !== accountId || typeof item.message.threadId !== "string" || !["received", "dispatching", "handed_off", "completed", "ignored", "needs_review"].includes(item.state)) throw new Error("Invalid native custody record; state was preserved");
|
|
2165
|
+
nativeRecallInfo(item.message);
|
|
2166
|
+
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
|
+
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 ??= randomUUID3();
|
|
2169
|
+
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");
|
|
1276
2170
|
if (item.state === "dispatching") item.state = "needs_review";
|
|
1277
2171
|
}
|
|
2172
|
+
if (parsed.recalls != null && (!parsed.recalls || typeof parsed.recalls !== "object" || Array.isArray(parsed.recalls))) throw Error("Invalid native recall state; state was preserved");
|
|
2173
|
+
for (const [key, recall] of Object.entries(parsed.recalls ?? {})) {
|
|
2174
|
+
validateNativeRecall(recall);
|
|
2175
|
+
if (key !== nativeRecallIdentity(recall.threadId, recall.serverId)) throw Error("Invalid native recall identity; state was preserved");
|
|
2176
|
+
}
|
|
1278
2177
|
this.value = parsed;
|
|
1279
2178
|
this.persist();
|
|
1280
2179
|
}
|
|
@@ -1282,12 +2181,22 @@ var NativeConsumerState = class {
|
|
|
1282
2181
|
get cursor() {
|
|
1283
2182
|
return this.value.cursor;
|
|
1284
2183
|
}
|
|
2184
|
+
get accountId() {
|
|
2185
|
+
return this.value.accountId;
|
|
2186
|
+
}
|
|
1285
2187
|
items() {
|
|
1286
2188
|
return Object.values(this.value.items);
|
|
1287
2189
|
}
|
|
1288
2190
|
get(messageId) {
|
|
1289
2191
|
return this.value.items[messageId];
|
|
1290
2192
|
}
|
|
2193
|
+
isRecalled(message) {
|
|
2194
|
+
return !!nativeRecallInfo(message) || !!(message.serverId && this.value.recalls?.[nativeRecallIdentity(message.threadId, message.serverId)]);
|
|
2195
|
+
}
|
|
2196
|
+
isCurrent(message, revision) {
|
|
2197
|
+
const current = this.get(message.id);
|
|
2198
|
+
return !!current && (revision === void 0 || current.revision === revision) && !this.isRecalled(message) && JSON.stringify(current.message) === JSON.stringify(message);
|
|
2199
|
+
}
|
|
1291
2200
|
persist() {
|
|
1292
2201
|
const directory = dirname2(this.file);
|
|
1293
2202
|
mkdirSync(directory, { recursive: true, mode: 448 });
|
|
@@ -1331,20 +2240,126 @@ var NativeConsumerState = class {
|
|
|
1331
2240
|
accept(cursor, message, origin = "unknown") {
|
|
1332
2241
|
if (!/^\d+$/.test(cursor) || BigInt(cursor) < BigInt(this.value.cursor)) throw new Error("Native journal cursor cannot move backward");
|
|
1333
2242
|
if (message && (!message.id || message.accountId !== this.value.accountId)) throw new Error("Native journal message crosses account boundary");
|
|
2243
|
+
let replaced = false;
|
|
1334
2244
|
this.mutate(() => {
|
|
1335
|
-
if (message &&
|
|
1336
|
-
|
|
2245
|
+
if (message?.serverId && nativeRecallInfo(message)) this.rememberRecall({ messageId: message.id, threadId: message.threadId, serverId: message.serverId, ...nativeRecallInfo(message) });
|
|
2246
|
+
if (message?.serverId) {
|
|
2247
|
+
const recall = this.value.recalls?.[nativeRecallIdentity(message.threadId, message.serverId)];
|
|
2248
|
+
if (recall) message = recalledNativeMessage(message, recall);
|
|
2249
|
+
}
|
|
2250
|
+
const existing = message ? this.value.items[message.id] : void 0;
|
|
2251
|
+
replaced = !!message && !nativeRecallInfo(message) && !!existing && (existing.message.threadId !== message.threadId || existing.message.serverId !== message.serverId);
|
|
2252
|
+
if (message && (!existing || replaced)) {
|
|
2253
|
+
const completed = Object.entries(this.value.items).filter(([, item]) => !item.readPending && !item.groupContext && item.phoneReadState !== "needs_review" && item.phoneReadState !== "rejected" && ["completed", "ignored"].includes(item.state));
|
|
1337
2254
|
for (const [key] of completed.slice(0, Math.max(0, completed.length - 1e3))) delete this.value.items[key];
|
|
1338
|
-
if (Object.keys(this.value.items).length >= 5e3) throw new Error("Native custody queue is full; operator review required");
|
|
1339
|
-
|
|
2255
|
+
if (!existing && Object.keys(this.value.items).length >= 5e3) throw new Error("Native custody queue is full; operator review required");
|
|
2256
|
+
if (replaced) {
|
|
2257
|
+
for (const item of this.items()) {
|
|
2258
|
+
const manifest = item.dispatchManifest;
|
|
2259
|
+
if (!manifest || ![
|
|
2260
|
+
...manifest.messageIds,
|
|
2261
|
+
...(manifest.historyInputs ?? []).map((input) => input.id),
|
|
2262
|
+
...manifest.assets.flatMap((asset) => asset.sourceMessageId ? [asset.sourceMessageId] : [])
|
|
2263
|
+
].includes(message.id)) continue;
|
|
2264
|
+
if (["dispatching", "handed_off"].includes(item.state)) item.state = "needs_review";
|
|
2265
|
+
item.dispatchManifest = void 0;
|
|
2266
|
+
item.manifestHash = void 0;
|
|
2267
|
+
item.readPending = false;
|
|
2268
|
+
}
|
|
2269
|
+
}
|
|
2270
|
+
this.value.items[message.id] = { message, revision: randomUUID3(), origin, state: nativeRecallInfo(message) ? "ignored" : "received", cursor };
|
|
1340
2271
|
}
|
|
1341
2272
|
this.value.cursor = cursor;
|
|
1342
2273
|
});
|
|
2274
|
+
return replaced;
|
|
2275
|
+
}
|
|
2276
|
+
/** Persist invalidation and the event cursor together, before consumer ACK. */
|
|
2277
|
+
acceptRecall(cursor, recall) {
|
|
2278
|
+
validateNativeRecall(recall);
|
|
2279
|
+
if (!/^\d+$/.test(cursor) || BigInt(cursor) < BigInt(this.value.cursor)) throw Error("Native journal cursor cannot move backward");
|
|
2280
|
+
let affected = [];
|
|
2281
|
+
this.mutate(() => {
|
|
2282
|
+
affected = this.rememberRecall(recall);
|
|
2283
|
+
this.value.cursor = cursor;
|
|
2284
|
+
});
|
|
2285
|
+
return affected;
|
|
2286
|
+
}
|
|
2287
|
+
rememberRecall(recall) {
|
|
2288
|
+
const hinted = recall.messageId ? this.get(recall.messageId)?.message : void 0;
|
|
2289
|
+
if (hinted && (hinted.threadId !== recall.threadId || hinted.serverId !== recall.serverId)) {
|
|
2290
|
+
const { messageId: _stale, ...exact } = recall;
|
|
2291
|
+
recall = exact;
|
|
2292
|
+
}
|
|
2293
|
+
const key = nativeRecallIdentity(recall.threadId, recall.serverId);
|
|
2294
|
+
this.value.recalls ??= {};
|
|
2295
|
+
const remembered = mergeNativeRecall(this.value.recalls[key] ?? recall, recall);
|
|
2296
|
+
this.value.recalls[key] = remembered;
|
|
2297
|
+
const affected = /* @__PURE__ */ new Set();
|
|
2298
|
+
for (const item of this.items()) {
|
|
2299
|
+
if (item.message.threadId !== recall.threadId) continue;
|
|
2300
|
+
const target = item.message.serverId === recall.serverId;
|
|
2301
|
+
const quote = item.message.quote?.serverId === recall.serverId;
|
|
2302
|
+
if (!target && !quote) continue;
|
|
2303
|
+
affected.add(item.message.id);
|
|
2304
|
+
item.message = target ? recalledNativeMessage(item.message, remembered) : { ...item.message, quote: void 0 };
|
|
2305
|
+
if (target) item.groupContext = false;
|
|
2306
|
+
item.readPending = false;
|
|
2307
|
+
if (["dispatching", "handed_off"].includes(item.state)) item.state = "needs_review";
|
|
2308
|
+
else if (target && item.state === "received") item.state = "ignored";
|
|
2309
|
+
item.invalidatedByRecall = true;
|
|
2310
|
+
item.dispatchManifest = void 0;
|
|
2311
|
+
item.manifestHash = void 0;
|
|
2312
|
+
}
|
|
2313
|
+
for (const item of this.items()) {
|
|
2314
|
+
const manifest = item.dispatchManifest;
|
|
2315
|
+
if (item.message.threadId !== recall.threadId || !manifest) continue;
|
|
2316
|
+
const references = [
|
|
2317
|
+
...manifest.messageIds,
|
|
2318
|
+
...(manifest.historyInputs ?? []).map((input) => input.id),
|
|
2319
|
+
...manifest.assets.flatMap((asset) => asset.sourceMessageId ? [asset.sourceMessageId] : [])
|
|
2320
|
+
];
|
|
2321
|
+
if (!references.some((id2) => affected.has(id2) || id2 === recall.messageId)) continue;
|
|
2322
|
+
affected.add(item.message.id);
|
|
2323
|
+
item.invalidatedByRecall = true;
|
|
2324
|
+
item.readPending = false;
|
|
2325
|
+
if (["dispatching", "handed_off"].includes(item.state)) item.state = "needs_review";
|
|
2326
|
+
item.dispatchManifest = void 0;
|
|
2327
|
+
item.manifestHash = void 0;
|
|
2328
|
+
}
|
|
2329
|
+
return [...affected];
|
|
1343
2330
|
}
|
|
1344
|
-
update(messageId, update) {
|
|
2331
|
+
update(messageId, update, revision) {
|
|
1345
2332
|
const item = this.value.items[messageId];
|
|
2333
|
+
if (revision !== void 0 && item?.revision !== revision) return false;
|
|
1346
2334
|
if (!item) throw new Error("Unknown native custody message");
|
|
1347
2335
|
this.mutate(() => Object.assign(this.value.items[messageId], update));
|
|
2336
|
+
return true;
|
|
2337
|
+
}
|
|
2338
|
+
groupHistory(threadId2, beforeId, limit) {
|
|
2339
|
+
const before = this.value.items[beforeId]?.cursor;
|
|
2340
|
+
if (!before || limit <= 0) return [];
|
|
2341
|
+
return this.items().filter((item) => item.groupContext && item.state === "ignored" && item.origin === "live" && item.message.threadId === threadId2 && item.cursor && BigInt(item.cursor) < BigInt(before)).sort((a, b) => BigInt(a.cursor) < BigInt(b.cursor) ? -1 : BigInt(a.cursor) > BigInt(b.cursor) ? 1 : 0).slice(-limit);
|
|
2342
|
+
}
|
|
2343
|
+
bufferGroupMessage(messageId, limit, revision) {
|
|
2344
|
+
const item = this.value.items[messageId];
|
|
2345
|
+
if (revision !== void 0 && item?.revision !== revision) return false;
|
|
2346
|
+
if (!item || item.state !== "received" || item.origin !== "live" || item.message.direction !== "incoming" || !item.cursor || !item.message.threadId.endsWith("@chatroom") || !Number.isInteger(limit) || limit < 0 || limit > 200) throw new Error("Invalid native group history admission");
|
|
2347
|
+
this.mutate(() => {
|
|
2348
|
+
Object.assign(this.value.items[messageId], { state: "ignored", groupContext: limit > 0 });
|
|
2349
|
+
const history = this.items().filter((value) => value.groupContext).sort((a, b) => BigInt(a.cursor) < BigInt(b.cursor) ? -1 : 1);
|
|
2350
|
+
const thread3 = history.filter((value) => value.message.threadId === item.message.threadId);
|
|
2351
|
+
for (const value of thread3.slice(0, Math.max(0, thread3.length - limit))) value.groupContext = false;
|
|
2352
|
+
const retained = history.filter((value) => value.groupContext);
|
|
2353
|
+
for (const value of retained.slice(0, Math.max(0, retained.length - 1e3))) value.groupContext = false;
|
|
2354
|
+
});
|
|
2355
|
+
return true;
|
|
2356
|
+
}
|
|
2357
|
+
beginDispatch(messageId, dispatchManifest, historyIds = []) {
|
|
2358
|
+
if (this.value.items[messageId]?.state !== "received" || this.isRecalled(this.value.items[messageId].message) || historyIds.some((id2) => !this.value.items[id2]?.groupContext || this.value.items[id2].message.threadId !== this.value.items[messageId].message.threadId)) throw new Error("Invalid native context dispatch custody");
|
|
2359
|
+
this.mutate(() => {
|
|
2360
|
+
Object.assign(this.value.items[messageId], { state: "dispatching", dispatchManifest, invalidatedByRecall: false });
|
|
2361
|
+
for (const id2 of historyIds) this.value.items[id2].groupContext = false;
|
|
2362
|
+
});
|
|
1348
2363
|
}
|
|
1349
2364
|
/** Synchronous bounded receipt at the SDK's prepared-run callback boundary. */
|
|
1350
2365
|
preparedCallback(messageIds, readPolicy, previous) {
|
|
@@ -1355,8 +2370,9 @@ var NativeConsumerState = class {
|
|
|
1355
2370
|
if (!item || item.state !== "dispatching") throw new Error("Prepared input manifest is not in dispatch custody");
|
|
1356
2371
|
return item;
|
|
1357
2372
|
});
|
|
2373
|
+
const revisions = items.map((item) => item.revision);
|
|
1358
2374
|
if (new Set(items.map((item) => item.message.threadId)).size !== 1) throw new Error("Prepared input manifest crosses threads");
|
|
1359
|
-
const manifestHash =
|
|
2375
|
+
const manifestHash = createHash7("sha256").update(JSON.stringify({
|
|
1360
2376
|
accountId: this.value.accountId,
|
|
1361
2377
|
messageIds: exact,
|
|
1362
2378
|
dispatchManifests: items.map((item) => item.dispatchManifest ?? null)
|
|
@@ -1365,8 +2381,15 @@ var NativeConsumerState = class {
|
|
|
1365
2381
|
const runId = typeof args[0] === "string" ? args[0] : args[0]?.runId;
|
|
1366
2382
|
if (typeof runId !== "string" || !runId || runId.length > 256) throw new Error("Prepared run callback has no valid runId");
|
|
1367
2383
|
this.mutate(() => {
|
|
1368
|
-
|
|
2384
|
+
const currentHash = createHash7("sha256").update(JSON.stringify({
|
|
2385
|
+
accountId: this.value.accountId,
|
|
2386
|
+
messageIds: exact,
|
|
2387
|
+
dispatchManifests: exact.map((id2) => this.value.items[id2]?.dispatchManifest ?? null)
|
|
2388
|
+
})).digest("hex");
|
|
2389
|
+
for (const [index, id2] of exact.entries()) {
|
|
1369
2390
|
const item = this.value.items[id2];
|
|
2391
|
+
if (!item || item.invalidatedByRecall || this.isRecalled(item.message)) throw Error("Native prepared input was invalidated by a recall");
|
|
2392
|
+
if (item.revision !== revisions[index] || currentHash !== manifestHash) throw Error("Native prepared input source identity changed");
|
|
1370
2393
|
if (item.runId && item.runId !== runId) throw new Error("Native prepared manifest was assigned to another run; operator review required");
|
|
1371
2394
|
Object.assign(item, { state: "handed_off", runId, manifestHash, readPending: readPolicy === "on_model_dispatch", handoffUnconfirmed: false });
|
|
1372
2395
|
}
|
|
@@ -1377,20 +2400,25 @@ var NativeConsumerState = class {
|
|
|
1377
2400
|
};
|
|
1378
2401
|
|
|
1379
2402
|
// src/native-prepared-boundary.ts
|
|
1380
|
-
import { createHash as
|
|
2403
|
+
import { createHash as createHash8, randomUUID as randomUUID4 } from "node:crypto";
|
|
1381
2404
|
import { basename as basename2, isAbsolute as isAbsolute3 } from "node:path";
|
|
1382
2405
|
var pending = /* @__PURE__ */ new Map();
|
|
1383
2406
|
var enabled = false;
|
|
1384
|
-
var digest = (value) =>
|
|
2407
|
+
var digest = (value) => createHash8("sha256").update(value).digest("hex");
|
|
1385
2408
|
function prune() {
|
|
1386
2409
|
for (const [id2, item] of pending) if (item.expires < Date.now()) pending.delete(id2);
|
|
1387
2410
|
}
|
|
2411
|
+
function nativeSourceMessageSid(message) {
|
|
2412
|
+
return `wechat-native:${message.accountId}:${message.id}:${digest(JSON.stringify([message.threadId, message.serverId ?? null]))}`;
|
|
2413
|
+
}
|
|
1388
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");
|
|
1389
2417
|
const assets = Object.freeze((params.assets ?? []).map((asset) => {
|
|
1390
|
-
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 > 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) || asset.contextRole !== "
|
|
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");
|
|
1391
2419
|
return Object.freeze({ ...asset });
|
|
1392
2420
|
}));
|
|
1393
|
-
const messageSid =
|
|
2421
|
+
const messageSid = nativeSourceMessageSid(params.message);
|
|
1394
2422
|
const manifest = {
|
|
1395
2423
|
schemaVersion: 2,
|
|
1396
2424
|
runId: randomUUID4(),
|
|
@@ -1413,13 +2441,22 @@ function nativeDispatchManifest(params) {
|
|
|
1413
2441
|
params.message.type,
|
|
1414
2442
|
params.message.body,
|
|
1415
2443
|
params.message.mentions,
|
|
1416
|
-
params.message.serverId
|
|
2444
|
+
params.message.serverId,
|
|
2445
|
+
params.message.appMessageType,
|
|
2446
|
+
params.message.quote,
|
|
2447
|
+
params.message.link
|
|
1417
2448
|
])),
|
|
1418
2449
|
role: "trigger"
|
|
1419
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
|
+
}))) } : {},
|
|
1420
2457
|
assets,
|
|
1421
2458
|
policySha256: digest(JSON.stringify(params.policy ?? null)),
|
|
1422
|
-
// Exact
|
|
2459
|
+
// Exact source-turn identity of OpenClaw 2026.10.2 through 2026.10.7. Requiring it in the later
|
|
1423
2460
|
// snapshot prevents an identical older image/body from proving this input.
|
|
1424
2461
|
hostSourceTurnId: `channel-user:v1:${digest(JSON.stringify(["agent-wechat", params.channelAccountId, `wechat:${params.message.threadId}`, messageSid]))}`
|
|
1425
2462
|
};
|
|
@@ -1430,30 +2467,40 @@ function trackNativePreparedInput(manifest, record) {
|
|
|
1430
2467
|
if (!enabled || pending.size >= 1024) return;
|
|
1431
2468
|
pending.set(manifest.runId, { manifest, record, expires: Date.now() + 15 * 60 * 1e3 });
|
|
1432
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
|
+
}
|
|
1433
2480
|
function promptMatches(prompt, manifest) {
|
|
1434
2481
|
if (typeof prompt !== "string" || Buffer.byteLength(prompt) > 1024 * 1024) return false;
|
|
1435
|
-
const
|
|
1436
|
-
const candidates = [
|
|
2482
|
+
const text3 = prompt.replace(/^\[[^\]\r\n]{1,96}\] /, "");
|
|
2483
|
+
const candidates = [text3];
|
|
1437
2484
|
const sender = `Conversation info: \u27E6openclaw:ctx\u27E7
|
|
1438
2485
|
\`\`\`json
|
|
1439
2486
|
${JSON.stringify({ sender: { id: manifest.senderId } })}
|
|
1440
2487
|
\`\`\`
|
|
1441
2488
|
|
|
1442
2489
|
`;
|
|
1443
|
-
if (manifest.threadId.endsWith("@chatroom") &&
|
|
1444
|
-
return candidates.some((
|
|
2490
|
+
if (manifest.threadId.endsWith("@chatroom") && text3.startsWith(sender)) candidates.push(text3.slice(sender.length));
|
|
2491
|
+
return candidates.some((text4) => normalizedPromptMatches(text4, manifest));
|
|
1445
2492
|
}
|
|
1446
|
-
function normalizedPromptMatches(
|
|
2493
|
+
function normalizedPromptMatches(text3, manifest) {
|
|
1447
2494
|
const runtimeAssets = manifest.assets.filter((asset) => asset.runtimeMedia);
|
|
1448
2495
|
if (runtimeAssets.length) {
|
|
1449
2496
|
if (runtimeAssets.length !== 1) return false;
|
|
1450
2497
|
const asset = runtimeAssets[0];
|
|
1451
|
-
const header = /^\[media attached: ([^\r\n]+) \(([^)\r\n]+)\) \| (media:\/\/inbound\/[^\]\r\n]+)\]\n/.exec(
|
|
2498
|
+
const header = /^\[media attached: ([^\r\n]+) \(([^)\r\n]+)\) \| (media:\/\/inbound\/[^\]\r\n]+)\]\n/.exec(text3);
|
|
1452
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;
|
|
1453
|
-
|
|
1454
|
-
if (asset.kind === "video")
|
|
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\]$/, "");
|
|
1455
2502
|
}
|
|
1456
|
-
return digest(
|
|
2503
|
+
return digest(text3) === manifest.inputBodySha256;
|
|
1457
2504
|
}
|
|
1458
2505
|
function currentMessageFacts(messages) {
|
|
1459
2506
|
if (!Array.isArray(messages) || messages.length > 1e3) return [];
|
|
@@ -1514,8 +2561,8 @@ function observeNativeAgentEnd(event, ctx) {
|
|
|
1514
2561
|
const blocks = typeof user.content === "string" ? [{ type: "text", text: user.content }] : user.content;
|
|
1515
2562
|
if (!Array.isArray(blocks) || blocks.length > 32) return;
|
|
1516
2563
|
if (blocks.some((block) => !["text", "image"].includes(block?.type) || block.type === "text" && typeof block.text !== "string")) return;
|
|
1517
|
-
const
|
|
1518
|
-
if (!promptMatches(
|
|
2564
|
+
const text3 = blocks.filter((block) => block?.type === "text").map((block) => block.text).join("\n");
|
|
2565
|
+
if (!promptMatches(text3, m)) return;
|
|
1519
2566
|
const images = blocks.filter((block) => block?.type === "image");
|
|
1520
2567
|
const expectedImages = m.assets.filter((asset) => asset.role === "model_image");
|
|
1521
2568
|
if (images.length !== expectedImages.length) return;
|
|
@@ -1525,7 +2572,7 @@ function observeNativeAgentEnd(event, ctx) {
|
|
|
1525
2572
|
const bytes = Buffer.from(image.data, "base64");
|
|
1526
2573
|
if (bytes.length !== asset.byteLength || digest(bytes) !== asset.sha256) return;
|
|
1527
2574
|
}
|
|
1528
|
-
if (m.assets.some((asset) => asset.role === "file_reference" && !
|
|
2575
|
+
if (m.assets.some((asset) => asset.role === "file_reference" && !text3.includes(asset.path))) return;
|
|
1529
2576
|
item.record(m.runId);
|
|
1530
2577
|
pending.delete(m.runId);
|
|
1531
2578
|
}
|
|
@@ -1543,28 +2590,119 @@ function registerNativePreparedBoundary(api) {
|
|
|
1543
2590
|
};
|
|
1544
2591
|
}
|
|
1545
2592
|
|
|
2593
|
+
// src/native-history.ts
|
|
2594
|
+
import { buildHistoryContextFromEntries, buildInboundHistoryFromEntries, DEFAULT_GROUP_HISTORY_LIMIT } from "openclaw/plugin-sdk/reply-history";
|
|
2595
|
+
function nativeGroupHistoryLimit(cfg) {
|
|
2596
|
+
const limit = cfg?.messages?.groupChat?.historyLimit;
|
|
2597
|
+
return Number.isInteger(limit) && limit >= 0 ? Math.min(limit, 200) : DEFAULT_GROUP_HISTORY_LIMIT;
|
|
2598
|
+
}
|
|
2599
|
+
async function transcribeNativeAttachment(prepared, core, cfg) {
|
|
2600
|
+
const attachment = prepared.attachment;
|
|
2601
|
+
if (attachment?.kind !== "audio" || attachment.status !== "ready" || !attachment.path) return prepared;
|
|
2602
|
+
let transcript = "";
|
|
2603
|
+
try {
|
|
2604
|
+
transcript = (await core.mediaUnderstanding.transcribeAudioFile({ filePath: attachment.path, cfg, mime: attachment.mime })).text?.trim() ?? "";
|
|
2605
|
+
} catch {
|
|
2606
|
+
}
|
|
2607
|
+
return { ...prepared, body: `${prepared.body}
|
|
2608
|
+
${transcript ? `[Voice transcript: ${transcript.slice(0, 1e4)}]` : "[Voice transcription unavailable]"}` };
|
|
2609
|
+
}
|
|
2610
|
+
async function prepareNativeHistory(messages, prepare) {
|
|
2611
|
+
const result = new Array(messages.length);
|
|
2612
|
+
let next = 0;
|
|
2613
|
+
await Promise.all(Array.from({ length: Math.min(3, messages.length) }, async () => {
|
|
2614
|
+
for (let index = next++; index < messages.length; index = next++) {
|
|
2615
|
+
const message = messages[index];
|
|
2616
|
+
let prepared;
|
|
2617
|
+
try {
|
|
2618
|
+
prepared = await prepare(message);
|
|
2619
|
+
} catch {
|
|
2620
|
+
prepared = { body: `[Attachment unavailable for message ${message.id}: retrieval or integrity verification failed]`, pending: false };
|
|
2621
|
+
}
|
|
2622
|
+
if (message.type === 1 && prepared.body.length > 4096) prepared = { ...prepared, body: `${prepared.body.slice(0, 4096)}
|
|
2623
|
+
[Message truncated; use wechat_history or wechat_search for the stored message]` };
|
|
2624
|
+
result[index] = { message, prepared };
|
|
2625
|
+
}
|
|
2626
|
+
}));
|
|
2627
|
+
return result;
|
|
2628
|
+
}
|
|
2629
|
+
function buildNativeContext(history, message, prepared) {
|
|
2630
|
+
const all = [...history, { message, prepared }];
|
|
2631
|
+
const image = history.length ? [...all].reverse().find((item) => item.prepared.attachment?.kind === "image" && item.prepared.attachment.status === "ready" && item.prepared.mediaPath) : void 0;
|
|
2632
|
+
const selected = history.length ? image : all.at(-1);
|
|
2633
|
+
const assets = all.flatMap((item) => (item.prepared.suppliedAssets ?? []).map((asset) => {
|
|
2634
|
+
const contextRole = item.message.id === message.id ? "trigger" : "history";
|
|
2635
|
+
if (item === selected) return { ...asset, contextRole, messageId: item.message.id };
|
|
2636
|
+
return {
|
|
2637
|
+
...asset,
|
|
2638
|
+
contextRole,
|
|
2639
|
+
messageId: item.message.id,
|
|
2640
|
+
runtimeMedia: false,
|
|
2641
|
+
role: "file_reference",
|
|
2642
|
+
path: asset.sourcePath ?? asset.path,
|
|
2643
|
+
sha256: asset.sourceSha256 ?? asset.sha256,
|
|
2644
|
+
byteLength: asset.sourceByteLength ?? asset.byteLength,
|
|
2645
|
+
mime: asset.sourceMime ?? asset.mime
|
|
2646
|
+
};
|
|
2647
|
+
}));
|
|
2648
|
+
const entries = history.map((item) => ({
|
|
2649
|
+
sender: item.message.senderId,
|
|
2650
|
+
body: item.prepared.body,
|
|
2651
|
+
timestamp: item.message.createdAt ? Date.parse(item.message.createdAt) : void 0,
|
|
2652
|
+
messageId: item.message.id
|
|
2653
|
+
}));
|
|
2654
|
+
const inputBody = entries.length ? buildHistoryContextFromEntries({
|
|
2655
|
+
entries,
|
|
2656
|
+
currentMessage: prepared.body,
|
|
2657
|
+
excludeLast: false,
|
|
2658
|
+
formatEntry: (entry) => `${entry.sender}: ${entry.body}`
|
|
2659
|
+
}) : prepared.body;
|
|
2660
|
+
const attachments = all.flatMap((item) => {
|
|
2661
|
+
const attachment = item.prepared.attachment;
|
|
2662
|
+
return attachment?.status === "ready" && attachment.path ? [{
|
|
2663
|
+
path: attachment.path,
|
|
2664
|
+
filename: attachment.filename,
|
|
2665
|
+
kind: attachment.kind,
|
|
2666
|
+
messageId: item.message.id,
|
|
2667
|
+
sender: item.message.senderId
|
|
2668
|
+
}] : [];
|
|
2669
|
+
});
|
|
2670
|
+
return {
|
|
2671
|
+
inputBody,
|
|
2672
|
+
attachments,
|
|
2673
|
+
assets,
|
|
2674
|
+
history: buildInboundHistoryFromEntries({ entries, limit: entries.length }),
|
|
2675
|
+
mediaPath: selected?.prepared.mediaPath,
|
|
2676
|
+
mediaMime: selected?.prepared.mediaMime
|
|
2677
|
+
};
|
|
2678
|
+
}
|
|
2679
|
+
|
|
1546
2680
|
// src/native-monitor.ts
|
|
1547
2681
|
function nativeWasMentioned(message) {
|
|
1548
2682
|
return message.mentions?.state === "known" && message.mentions.self === true;
|
|
1549
2683
|
}
|
|
1550
2684
|
async function projectNativeRead(client, accountId, state) {
|
|
1551
|
-
|
|
2685
|
+
const pending2 = state.items().filter((value) => value.readPending);
|
|
2686
|
+
const threads = [...new Set(pending2.map((item) => item.message.threadId))];
|
|
2687
|
+
for (const threadId2 of threads) {
|
|
1552
2688
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
1553
2689
|
let cursor;
|
|
1554
|
-
let
|
|
2690
|
+
let thread3;
|
|
1555
2691
|
const seen = /* @__PURE__ */ new Set();
|
|
1556
2692
|
for (let pageIndex = 0; pageIndex < 100; pageIndex++) {
|
|
1557
2693
|
const page = await client.threads(accountId, cursor);
|
|
1558
|
-
|
|
1559
|
-
if (
|
|
2694
|
+
thread3 = page.items.find((value) => !isNativeTombstone(value) && value.id === threadId2);
|
|
2695
|
+
if (thread3 || !page.nextCursor) break;
|
|
1560
2696
|
if (seen.has(page.nextCursor)) throw new Error("Native thread pagination did not advance");
|
|
1561
2697
|
seen.add(page.nextCursor);
|
|
1562
2698
|
cursor = page.nextCursor;
|
|
1563
2699
|
}
|
|
1564
|
-
if (!
|
|
2700
|
+
if (!thread3) break;
|
|
1565
2701
|
try {
|
|
1566
|
-
await client.markRead(accountId,
|
|
1567
|
-
|
|
2702
|
+
const receipt = await client.markRead(accountId, thread3.id, thread3.readStateVersion);
|
|
2703
|
+
const notification = receipt?.phoneNotification?.state;
|
|
2704
|
+
const phoneReadState = notification === "accepted" || notification === "rejected" || notification === "needs_review" ? notification : void 0;
|
|
2705
|
+
for (const item of pending2.filter((item2) => item2.message.threadId === threadId2)) state.update(item.message.id, { readPending: false, phoneReadState }, item.revision);
|
|
1568
2706
|
break;
|
|
1569
2707
|
} catch (error) {
|
|
1570
2708
|
if (error instanceof NativeApiError && error.status === 409 && attempt === 0) continue;
|
|
@@ -1573,12 +2711,72 @@ async function projectNativeRead(client, accountId, state) {
|
|
|
1573
2711
|
}
|
|
1574
2712
|
}
|
|
1575
2713
|
}
|
|
2714
|
+
var NativeInputInvalidated = class extends Error {
|
|
2715
|
+
};
|
|
2716
|
+
async function acceptNativeEvent(client, accountId, state, event) {
|
|
2717
|
+
if (state.accountId !== accountId) throw Error("Native event crosses its custody account boundary");
|
|
2718
|
+
if (event.kind === "message.recalled") {
|
|
2719
|
+
const affected = state.acceptRecall(event.cursor, event.data);
|
|
2720
|
+
invalidateNativePreparedInputs(accountId, affected);
|
|
2721
|
+
return void 0;
|
|
2722
|
+
}
|
|
2723
|
+
let message;
|
|
2724
|
+
if (event.kind === "message.committed") {
|
|
2725
|
+
if (typeof event.data.messageId !== "string") throw Error("Native committed message identity is missing; cursor retained");
|
|
2726
|
+
message = await client.message(accountId, event.data.messageId);
|
|
2727
|
+
if (message.id !== event.data.messageId || message.accountId !== accountId || message.threadId !== event.data.threadId) throw Error("Native committed message identity mismatch");
|
|
2728
|
+
}
|
|
2729
|
+
const replaced = state.accept(event.cursor, message, typeof event.data.origin === "string" ? event.data.origin : "unknown");
|
|
2730
|
+
if (replaced && message) invalidateNativePreparedInputs(accountId, [message.id]);
|
|
2731
|
+
return message;
|
|
2732
|
+
}
|
|
2733
|
+
async function recheckNativeInputs(client, state, messages) {
|
|
2734
|
+
for (const message of messages) {
|
|
2735
|
+
if (!state.isCurrent(message)) throw new NativeInputInvalidated();
|
|
2736
|
+
const current = await client.message(message.accountId, message.id);
|
|
2737
|
+
if (current.accountId !== message.accountId || current.threadId !== message.threadId || current.id !== message.id || current.serverId !== message.serverId) throw Error("Native input identity changed; delivery held for review");
|
|
2738
|
+
const recall = nativeRecallInfo(current);
|
|
2739
|
+
if (recall && current.serverId) {
|
|
2740
|
+
const affected = state.acceptRecall(state.cursor, { ...recall, messageId: current.id, threadId: current.threadId, serverId: current.serverId });
|
|
2741
|
+
invalidateNativePreparedInputs(message.accountId, [current.id, ...affected]);
|
|
2742
|
+
throw new NativeInputInvalidated();
|
|
2743
|
+
}
|
|
2744
|
+
if (message.quote) {
|
|
2745
|
+
const quote = current.quote;
|
|
2746
|
+
if (quote?.state === "recalled") {
|
|
2747
|
+
const affected = state.acceptRecall(state.cursor, {
|
|
2748
|
+
threadId: message.threadId,
|
|
2749
|
+
serverId: message.quote.serverId,
|
|
2750
|
+
observedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2751
|
+
});
|
|
2752
|
+
invalidateNativePreparedInputs(message.accountId, affected);
|
|
2753
|
+
throw new NativeInputInvalidated();
|
|
2754
|
+
}
|
|
2755
|
+
if (!quote || !sameEmbeddedQuote(message.quote, quote)) throw Error("Native embedded quote changed; delivery held for review");
|
|
2756
|
+
}
|
|
2757
|
+
if (!state.isCurrent(message)) throw new NativeInputInvalidated();
|
|
2758
|
+
}
|
|
2759
|
+
}
|
|
1576
2760
|
async function dispatchNativeMessage(params) {
|
|
2761
|
+
const revision = params.state.get(params.message.id)?.revision;
|
|
2762
|
+
try {
|
|
2763
|
+
return await dispatchNativeMessageInput(params, revision);
|
|
2764
|
+
} catch (error) {
|
|
2765
|
+
const item = params.state.get(params.message.id);
|
|
2766
|
+
if (params.state.isRecalled(params.message)) return "ignored";
|
|
2767
|
+
if (error instanceof NativeInputInvalidated && item?.state === "received") return "pending";
|
|
2768
|
+
if (item) params.state.update(params.message.id, { state: "needs_review" }, revision);
|
|
2769
|
+
return "needs_review";
|
|
2770
|
+
}
|
|
2771
|
+
}
|
|
2772
|
+
async function dispatchNativeMessageInput(params, revision) {
|
|
1577
2773
|
const { client, state, account, message, cfg, core } = params;
|
|
2774
|
+
const readPolicy = account.native?.readPolicy ?? "on_inbound";
|
|
1578
2775
|
const custody = state.get(message.id);
|
|
1579
|
-
if (
|
|
2776
|
+
if (state.isRecalled(message)) return "ignored";
|
|
2777
|
+
if (!custody || custody.state !== "received" || !state.isCurrent(message, revision)) return "needs_review";
|
|
1580
2778
|
if (custody.origin !== "live" || message.direction !== "incoming" || ![1, 3, 34, 43, 47, 49].includes(message.type) || message.type === 1 && !message.body || !message.senderId) {
|
|
1581
|
-
state.update(message.id, { state: "ignored" });
|
|
2779
|
+
state.update(message.id, { state: "ignored" }, revision);
|
|
1582
2780
|
return "ignored";
|
|
1583
2781
|
}
|
|
1584
2782
|
const isGroup = message.threadId.endsWith("@chatroom");
|
|
@@ -1586,8 +2784,20 @@ async function dispatchNativeMessage(params) {
|
|
|
1586
2784
|
const policy = resolveWeChatPolicyContext({ account, cfg, chatId: message.threadId });
|
|
1587
2785
|
const allowTextCommands = core.channel.commands.shouldHandleTextCommands({ cfg, surface: "agent-wechat" });
|
|
1588
2786
|
const commandBody = normalizeWeChatCommandBody(message.type === 1 ? message.body ?? "" : "", { isGroup, wasMentioned });
|
|
2787
|
+
const hasControlCommand = allowTextCommands && core.channel.commands.isControlCommandMessage(commandBody, cfg);
|
|
2788
|
+
const resolve = core.channel.inbound?.ingress?.resolveStable ?? resolveStableChannelMessageIngress;
|
|
2789
|
+
const senderAdmission = (senderId) => resolveWeChatIngress({
|
|
2790
|
+
resolve,
|
|
2791
|
+
cfg,
|
|
2792
|
+
accountId: account.accountId,
|
|
2793
|
+
policy,
|
|
2794
|
+
isGroup,
|
|
2795
|
+
chatId: message.threadId,
|
|
2796
|
+
senderId,
|
|
2797
|
+
readStoreAllowFrom: async () => core.channel.pairing.readAllowFromStore({ channel: "agent-wechat", accountId: account.accountId, env: process.env }).catch(() => [])
|
|
2798
|
+
});
|
|
1589
2799
|
const ingress = await resolveWeChatIngress({
|
|
1590
|
-
resolve
|
|
2800
|
+
resolve,
|
|
1591
2801
|
cfg,
|
|
1592
2802
|
accountId: account.accountId,
|
|
1593
2803
|
policy,
|
|
@@ -1595,33 +2805,58 @@ async function dispatchNativeMessage(params) {
|
|
|
1595
2805
|
chatId: message.threadId,
|
|
1596
2806
|
senderId: message.senderId,
|
|
1597
2807
|
readStoreAllowFrom: async () => core.channel.pairing.readAllowFromStore({ channel: "agent-wechat", accountId: account.accountId, env: process.env }).catch(() => []),
|
|
1598
|
-
command: { allowTextCommands, hasControlCommand
|
|
2808
|
+
command: { allowTextCommands, hasControlCommand },
|
|
1599
2809
|
mention: { wasMentioned, allowTextCommands }
|
|
1600
2810
|
});
|
|
1601
2811
|
const unauthorizedDirectCommand = !isGroup && ingress.ingress.reasonCode === "control_command_unauthorized";
|
|
1602
2812
|
if (ingress.ingress.admission !== "dispatch" && !unauthorizedDirectCommand) {
|
|
1603
|
-
|
|
2813
|
+
if (isGroup && policy.requireMention && !wasMentioned && !hasControlCommand && (await senderAdmission(message.senderId)).ingress.admission === "dispatch") {
|
|
2814
|
+
state.bufferGroupMessage(message.id, nativeGroupHistoryLimit(cfg), revision);
|
|
2815
|
+
return "ignored";
|
|
2816
|
+
}
|
|
2817
|
+
state.update(message.id, { state: "ignored" }, revision);
|
|
1604
2818
|
return "ignored";
|
|
1605
2819
|
}
|
|
1606
2820
|
let preparedMedia;
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
state.
|
|
1611
|
-
|
|
1612
|
-
|
|
2821
|
+
const allowQuotedMessage = async (original) => original.direction === "outgoing" || !!original.senderId && (await senderAdmission(original.senderId)).ingress.admission === "dispatch";
|
|
2822
|
+
const assertCurrent = () => {
|
|
2823
|
+
params.signal?.throwIfAborted();
|
|
2824
|
+
if (!state.isCurrent(message, revision)) throw new NativeInputInvalidated();
|
|
2825
|
+
};
|
|
2826
|
+
const recheck = async (inputs) => {
|
|
2827
|
+
assertCurrent();
|
|
2828
|
+
await recheckNativeInputs(client, state, inputs);
|
|
2829
|
+
assertCurrent();
|
|
2830
|
+
};
|
|
2831
|
+
await recheck([message]);
|
|
2832
|
+
preparedMedia = await (params.prepareAttachment ?? prepareNativeAttachment)({ client, account, message, core, cfg, allowQuotedMessage, assertCurrent });
|
|
1613
2833
|
if (preparedMedia.pending) return "pending";
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
else inputBody += "\n[Voice transcription unavailable]";
|
|
1621
|
-
} catch {
|
|
1622
|
-
inputBody += "\n[Voice transcription unavailable]";
|
|
1623
|
-
}
|
|
2834
|
+
preparedMedia = await transcribeNativeAttachment(preparedMedia, core, cfg);
|
|
2835
|
+
await recheck([message]);
|
|
2836
|
+
const buffered = isGroup && !hasControlCommand ? state.groupHistory(message.threadId, message.id, nativeGroupHistoryLimit(cfg)) : [];
|
|
2837
|
+
const admitted = [];
|
|
2838
|
+
for (const item of buffered) {
|
|
2839
|
+
if (item.message.senderId && (await senderAdmission(item.message.senderId)).ingress.admission === "dispatch") admitted.push(item.message);
|
|
1624
2840
|
}
|
|
2841
|
+
const history = await prepareNativeHistory(admitted, async (historical) => transcribeNativeAttachment(
|
|
2842
|
+
await (params.prepareAttachment ?? prepareNativeAttachment)({
|
|
2843
|
+
client,
|
|
2844
|
+
account,
|
|
2845
|
+
message: historical,
|
|
2846
|
+
core,
|
|
2847
|
+
cfg,
|
|
2848
|
+
allowQuotedMessage,
|
|
2849
|
+
assertCurrent: () => {
|
|
2850
|
+
assertCurrent();
|
|
2851
|
+
if (!state.isCurrent(historical)) throw new NativeInputInvalidated();
|
|
2852
|
+
}
|
|
2853
|
+
}),
|
|
2854
|
+
core,
|
|
2855
|
+
cfg
|
|
2856
|
+
));
|
|
2857
|
+
await recheck([message, ...admitted]);
|
|
2858
|
+
const context = buildNativeContext(history, message, preparedMedia);
|
|
2859
|
+
const inputBody = context.inputBody;
|
|
1625
2860
|
const route = core.channel.routing.resolveAgentRoute({
|
|
1626
2861
|
cfg,
|
|
1627
2862
|
channel: "agent-wechat",
|
|
@@ -1649,14 +2884,17 @@ async function dispatchNativeMessage(params) {
|
|
|
1649
2884
|
SenderId: message.senderId,
|
|
1650
2885
|
Provider: "agent-wechat",
|
|
1651
2886
|
Surface: "agent-wechat",
|
|
1652
|
-
MessageSid:
|
|
2887
|
+
MessageSid: nativeSourceMessageSid(message),
|
|
1653
2888
|
WasMentioned: isGroup ? wasMentioned : void 0,
|
|
2889
|
+
Attachments: context.attachments,
|
|
2890
|
+
InboundHistory: context.history,
|
|
1654
2891
|
CommandAuthorized: core.channel.commands.shouldComputeCommandAuthorized(commandBody, cfg) ? ingress.commandAccess.authorized : void 0,
|
|
1655
2892
|
OriginatingChannel: "agent-wechat",
|
|
1656
2893
|
OriginatingTo: `wechat:${message.threadId}`,
|
|
1657
|
-
...
|
|
2894
|
+
...context.mediaPath ? { MediaPath: context.mediaPath, MediaUrl: context.mediaPath, MediaType: context.mediaMime } : {}
|
|
1658
2895
|
});
|
|
1659
2896
|
await core.channel.session.recordInboundSession({ storePath, sessionKey: route.sessionKey, ctx });
|
|
2897
|
+
await recheck([message, ...admitted]);
|
|
1660
2898
|
const pipeline = (params.createPipeline ?? createChannelMessageReplyPipeline)({ cfg, agentId: route.agentId, channel: "agent-wechat", accountId: account.accountId });
|
|
1661
2899
|
const { onModelSelected, ...prefixOptions } = pipeline;
|
|
1662
2900
|
const dispatchManifest = nativeDispatchManifest({
|
|
@@ -1666,11 +2904,14 @@ async function dispatchNativeMessage(params) {
|
|
|
1666
2904
|
agentId: route.agentId,
|
|
1667
2905
|
channelAccountId: account.accountId,
|
|
1668
2906
|
policy,
|
|
1669
|
-
assets:
|
|
2907
|
+
assets: context.assets,
|
|
2908
|
+
history: admitted
|
|
1670
2909
|
});
|
|
1671
|
-
|
|
1672
|
-
|
|
2910
|
+
assertCurrent();
|
|
2911
|
+
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 === 19 && !!message.body || message.type === 49 && [3, 4, 5].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;
|
|
1673
2913
|
if (callback) trackNativePreparedInput(dispatchManifest, callback);
|
|
2914
|
+
const beforeSend = () => recheck([message, ...admitted]);
|
|
1674
2915
|
let failed = false;
|
|
1675
2916
|
let delivery = 0;
|
|
1676
2917
|
try {
|
|
@@ -1680,17 +2921,22 @@ async function dispatchNativeMessage(params) {
|
|
|
1680
2921
|
dispatcherOptions: {
|
|
1681
2922
|
...prefixOptions,
|
|
1682
2923
|
deliver: async (payload) => {
|
|
2924
|
+
params.signal?.throwIfAborted();
|
|
2925
|
+
if (state.get(message.id)?.invalidatedByRecall) return;
|
|
2926
|
+
await beforeSend();
|
|
1683
2927
|
const urls = payload.mediaUrls?.length ? payload.mediaUrls : payload.mediaUrl ? [payload.mediaUrl] : [];
|
|
1684
2928
|
if (urls.length > 16) throw new Error("Native reply media count exceeds its bound");
|
|
1685
2929
|
if (payload.audioAsVoice && !urls.length) throw new Error("Native voice reply requires an audio attachment");
|
|
1686
|
-
for (const
|
|
1687
|
-
const key =
|
|
1688
|
-
await sendNativeAttachment(client, account, message.threadId,
|
|
2930
|
+
for (const url2 of urls) {
|
|
2931
|
+
const key = createHash9("sha256").update(`${dispatchManifest.messageSid}\0${delivery++}`).digest("hex");
|
|
2932
|
+
await sendNativeAttachment(client, account, message.threadId, url2, payload.audioAsVoice === true, key, beforeSend);
|
|
1689
2933
|
}
|
|
1690
2934
|
if (payload.text) {
|
|
1691
|
-
|
|
2935
|
+
await beforeSend();
|
|
2936
|
+
const key = createHash9("sha256").update(`${dispatchManifest.messageSid}\0${delivery++}`).digest("hex");
|
|
1692
2937
|
await submitNativeText(client, account.native.accountId, message.threadId, payload.text, key);
|
|
1693
2938
|
}
|
|
2939
|
+
if (urls.length || payload.text) params.onDelivered?.();
|
|
1694
2940
|
},
|
|
1695
2941
|
onError: () => {
|
|
1696
2942
|
failed = true;
|
|
@@ -1702,14 +2948,34 @@ async function dispatchNativeMessage(params) {
|
|
|
1702
2948
|
// and media-snapshot bridge; unsupported or ambiguous handoffs leave reads unchanged.
|
|
1703
2949
|
replyOptions: { runId: dispatchManifest.runId, onModelSelected, onPreparedAgentRunStart: callback }
|
|
1704
2950
|
});
|
|
1705
|
-
|
|
1706
|
-
state.
|
|
2951
|
+
params.signal?.throwIfAborted();
|
|
2952
|
+
if (state.get(message.id)?.revision !== revision || state.get(message.id)?.dispatchManifest?.runId !== dispatchManifest.runId) return state.isRecalled(message) ? "ignored" : "needs_review";
|
|
2953
|
+
if (state.get(message.id)?.invalidatedByRecall) return state.isRecalled(message) ? "ignored" : "needs_review";
|
|
2954
|
+
const readPending = readPolicy === "on_inbound" && !failed && ingress.ingress.admission === "dispatch" ? true : state.get(message.id)?.readPending;
|
|
2955
|
+
state.update(message.id, {
|
|
2956
|
+
state: failed ? "needs_review" : "completed",
|
|
2957
|
+
readPending,
|
|
2958
|
+
handoffUnconfirmed: readPolicy === "on_model_dispatch" && !state.get(message.id)?.runId
|
|
2959
|
+
}, revision);
|
|
1707
2960
|
return failed ? "needs_review" : "completed";
|
|
1708
2961
|
} catch {
|
|
1709
|
-
state.
|
|
2962
|
+
if (state.isRecalled(message)) return "ignored";
|
|
2963
|
+
state.update(message.id, { state: "needs_review" }, revision);
|
|
1710
2964
|
return "needs_review";
|
|
1711
2965
|
}
|
|
1712
2966
|
}
|
|
2967
|
+
async function synchronizeNativeEvents(client, accountId, state) {
|
|
2968
|
+
for (let index = 0; index < 100; index++) {
|
|
2969
|
+
const page = await client.events(accountId, state.cursor, 200);
|
|
2970
|
+
if (!page.items.length) return;
|
|
2971
|
+
const before = state.cursor;
|
|
2972
|
+
for (const event of page.items) await acceptNativeEvent(client, accountId, state, event);
|
|
2973
|
+
if (state.cursor === before) throw Error("Native recovery event cursor did not advance");
|
|
2974
|
+
await client.ack(accountId, "openclaw", state.cursor);
|
|
2975
|
+
if (page.items.length < 200) return;
|
|
2976
|
+
}
|
|
2977
|
+
throw Error("Native recovery backlog remains; no model input was dispatched");
|
|
2978
|
+
}
|
|
1713
2979
|
function startNativeReadPump(task, failed, intervalMs = 5e3) {
|
|
1714
2980
|
let active2 = false, stopped = false;
|
|
1715
2981
|
const timer = setInterval(() => {
|
|
@@ -1737,23 +3003,35 @@ async function startNativeMonitor(opts) {
|
|
|
1737
3003
|
const core = getWeChatRuntime();
|
|
1738
3004
|
let backoff = 250;
|
|
1739
3005
|
let readTask;
|
|
1740
|
-
const flushRead = () =>
|
|
1741
|
-
|
|
1742
|
-
|
|
3006
|
+
const flushRead = () => {
|
|
3007
|
+
if (native.readPolicy === "never") return Promise.resolve();
|
|
3008
|
+
return readTask ??= projectNativeRead(host2.client, native.accountId, state).finally(() => {
|
|
3009
|
+
readTask = void 0;
|
|
3010
|
+
});
|
|
3011
|
+
};
|
|
1743
3012
|
const process2 = async () => {
|
|
1744
3013
|
const cfg = core.config.current();
|
|
1745
3014
|
const account = resolveWeChatAccount(cfg, opts.account.accountId) ?? opts.account;
|
|
1746
3015
|
if (account.backend !== "native" || JSON.stringify(account.native) !== JSON.stringify(native)) throw new Error("Native service configuration changed; restart required before processing");
|
|
1747
3016
|
for (const item of state.items().filter((value) => value.state === "received")) {
|
|
1748
|
-
await dispatchNativeMessage({
|
|
3017
|
+
await dispatchNativeMessage({
|
|
3018
|
+
client: host2.client,
|
|
3019
|
+
state,
|
|
3020
|
+
account,
|
|
3021
|
+
message: item.message,
|
|
3022
|
+
cfg,
|
|
3023
|
+
core,
|
|
3024
|
+
signal: opts.abortSignal,
|
|
3025
|
+
onDelivered: () => opts.setStatus({ accountId: account.accountId, lastOutboundAt: Date.now() })
|
|
3026
|
+
});
|
|
1749
3027
|
}
|
|
1750
3028
|
try {
|
|
1751
3029
|
await flushRead();
|
|
1752
3030
|
} catch {
|
|
1753
|
-
opts.log?.error?.("Native read projection is pending;
|
|
3031
|
+
opts.log?.error?.("Native read projection is pending; thread read receipt retained for retry");
|
|
1754
3032
|
}
|
|
1755
|
-
const needsReview = state.items().filter((value) => value.state === "needs_review").length;
|
|
1756
|
-
const handoffUnconfirmed = native.readPolicy
|
|
3033
|
+
const needsReview = state.items().filter((value) => value.state === "needs_review" || value.phoneReadState === "needs_review" || value.phoneReadState === "rejected").length;
|
|
3034
|
+
const handoffUnconfirmed = native.readPolicy === "on_model_dispatch" && state.items().some((value) => value.handoffUnconfirmed);
|
|
1757
3035
|
const accountStatus = await host2.client.account(native.accountId);
|
|
1758
3036
|
opts.setStatus({
|
|
1759
3037
|
accountId: account.accountId,
|
|
@@ -1764,29 +3042,42 @@ async function startNativeMonitor(opts) {
|
|
|
1764
3042
|
handoffUnconfirmed
|
|
1765
3043
|
});
|
|
1766
3044
|
};
|
|
1767
|
-
|
|
3045
|
+
let processing;
|
|
3046
|
+
let processAgain = false;
|
|
3047
|
+
let intakeReady = false;
|
|
3048
|
+
const scheduleProcess = () => {
|
|
3049
|
+
processAgain = true;
|
|
3050
|
+
if (processing || opts.abortSignal.aborted || !intakeReady) return;
|
|
3051
|
+
processing = (async () => {
|
|
3052
|
+
do {
|
|
3053
|
+
processAgain = false;
|
|
3054
|
+
await process2();
|
|
3055
|
+
} while (processAgain && !opts.abortSignal.aborted);
|
|
3056
|
+
})().catch(() => opts.log?.error?.("Native input processing was interrupted; durable custody was retained")).finally(() => {
|
|
3057
|
+
processing = void 0;
|
|
3058
|
+
});
|
|
3059
|
+
};
|
|
1768
3060
|
const stopReadPump = startNativeReadPump(async () => {
|
|
1769
3061
|
await flushRead();
|
|
3062
|
+
scheduleProcess();
|
|
1770
3063
|
if (!opts.abortSignal.aborted) opts.setStatus({
|
|
1771
3064
|
accountId: opts.account.accountId,
|
|
1772
|
-
handoffUnconfirmed: native.readPolicy
|
|
3065
|
+
handoffUnconfirmed: native.readPolicy === "on_model_dispatch" && state.items().some((value) => value.handoffUnconfirmed)
|
|
1773
3066
|
});
|
|
1774
|
-
}, () => opts.log?.error?.("Native read projection remains pending;
|
|
3067
|
+
}, () => opts.log?.error?.("Native read projection remains pending; thread read receipts retained"));
|
|
1775
3068
|
try {
|
|
1776
3069
|
while (!opts.abortSignal.aborted) {
|
|
1777
3070
|
try {
|
|
1778
3071
|
if (state.cursor !== "0") await host2.client.ack(native.accountId, "openclaw", state.cursor);
|
|
1779
|
-
|
|
3072
|
+
intakeReady = false;
|
|
3073
|
+
await synchronizeNativeEvents(host2.client, native.accountId, state);
|
|
3074
|
+
intakeReady = true;
|
|
3075
|
+
scheduleProcess();
|
|
1780
3076
|
for await (const event of host2.client.watch(native.accountId, state.cursor, opts.abortSignal)) {
|
|
1781
|
-
|
|
1782
|
-
if (event.
|
|
1783
|
-
if (typeof event.data.messageId !== "string") throw new Error("Native committed message identity is missing; cursor retained");
|
|
1784
|
-
message = await host2.client.message(native.accountId, event.data.messageId);
|
|
1785
|
-
if (message.threadId !== event.data.threadId) throw new Error("Native committed message thread identity mismatch");
|
|
1786
|
-
}
|
|
1787
|
-
state.accept(event.cursor, message, typeof event.data.origin === "string" ? event.data.origin : "unknown");
|
|
3077
|
+
const message = await acceptNativeEvent(host2.client, native.accountId, state, event);
|
|
3078
|
+
if (message?.direction === "incoming" && event.data.origin === "live" && !nativeRecallInfo(message)) opts.setStatus({ accountId: opts.account.accountId, lastInboundAt: Date.now() });
|
|
1788
3079
|
await host2.client.ack(native.accountId, "openclaw", state.cursor);
|
|
1789
|
-
|
|
3080
|
+
scheduleProcess();
|
|
1790
3081
|
backoff = 250;
|
|
1791
3082
|
}
|
|
1792
3083
|
if (!opts.abortSignal.aborted) throw new Error("Native event stream closed");
|
|
@@ -1818,80 +3109,143 @@ async function startNativeMonitor(opts) {
|
|
|
1818
3109
|
|
|
1819
3110
|
// src/native-login.ts
|
|
1820
3111
|
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
3112
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
1821
3113
|
var operations = /* @__PURE__ */ new Map();
|
|
1822
3114
|
var terminal = /* @__PURE__ */ new Set(["succeeded", "failed", "cancelled", "expired", "rejected", "needs_login"]);
|
|
1823
|
-
|
|
3115
|
+
function guard(access2) {
|
|
3116
|
+
access2.signal?.throwIfAborted();
|
|
3117
|
+
access2.assertCurrent?.();
|
|
3118
|
+
}
|
|
3119
|
+
function validateOperation(operation, accountId, operationId) {
|
|
3120
|
+
if (operation.accountId !== accountId || operation.kind !== "login" || operationId && operation.id !== operationId) throw Error("Native login operation identity does not match its account");
|
|
3121
|
+
}
|
|
3122
|
+
async function nativeLoginStart(account, options = {}, access2 = {}) {
|
|
3123
|
+
guard(access2);
|
|
1824
3124
|
const native = account.native;
|
|
1825
|
-
const { client } = await ensureNativeHost(native);
|
|
3125
|
+
const { client } = await (access2.host ?? ensureNativeHost)(native);
|
|
3126
|
+
guard(access2);
|
|
3127
|
+
const configurationKey = nativeConfigurationKey(native);
|
|
1826
3128
|
const existing = operations.get(account.accountId);
|
|
1827
|
-
if (existing && existing.
|
|
1828
|
-
|
|
1829
|
-
|
|
3129
|
+
if (existing && existing.configurationKey === configurationKey) {
|
|
3130
|
+
const refreshed = await client.operation(native.accountId, existing.operation.id);
|
|
3131
|
+
guard(access2);
|
|
3132
|
+
validateOperation(refreshed, native.accountId, existing.operation.id);
|
|
3133
|
+
existing.operation = refreshed;
|
|
3134
|
+
existing.client = client;
|
|
3135
|
+
if (!terminal.has(existing.operation.state)) return nativeLoginWait(account, Math.min(options.timeoutMs ?? 3e4, 3e4), true, access2);
|
|
1830
3136
|
}
|
|
3137
|
+
guard(access2);
|
|
1831
3138
|
const operation = await client.login(native.accountId, {
|
|
1832
3139
|
allowQr: true,
|
|
1833
3140
|
forceQr: options.force === true,
|
|
1834
3141
|
timeoutSeconds: Math.max(10, Math.min(900, Math.ceil((options.timeoutMs ?? 3e5) / 1e3))),
|
|
1835
3142
|
computerName: "agent-wechat"
|
|
1836
|
-
});
|
|
1837
|
-
|
|
1838
|
-
|
|
3143
|
+
}, randomUUID5());
|
|
3144
|
+
validateOperation(operation, native.accountId);
|
|
3145
|
+
operations.set(account.accountId, { client, accountId: native.accountId, configurationKey, operation });
|
|
3146
|
+
guard(access2);
|
|
3147
|
+
return nativeLoginWait(account, Math.min(options.timeoutMs ?? 3e4, 3e4), true, access2);
|
|
1839
3148
|
}
|
|
1840
|
-
async function nativeLoginWait(
|
|
1841
|
-
|
|
1842
|
-
|
|
3149
|
+
async function nativeLoginWait(account, timeoutMs = 3e4, stopAtQr = false, access2 = {}) {
|
|
3150
|
+
guard(access2);
|
|
3151
|
+
const active2 = operations.get(account.accountId);
|
|
3152
|
+
if (!active2 || active2.configurationKey !== nativeConfigurationKey(account.native)) return { connected: false, state: "idle", message: "No native login operation; start login first" };
|
|
1843
3153
|
const deadline = Date.now() + Math.max(1e3, Math.min(timeoutMs, 3e5));
|
|
1844
3154
|
while (Date.now() < deadline) {
|
|
1845
|
-
|
|
3155
|
+
guard(access2);
|
|
3156
|
+
const refreshed = await active2.client.operation(active2.accountId, active2.operation.id);
|
|
3157
|
+
guard(access2);
|
|
3158
|
+
validateOperation(refreshed, active2.accountId, active2.operation.id);
|
|
3159
|
+
active2.operation = refreshed;
|
|
1846
3160
|
const state = active2.operation.state;
|
|
1847
|
-
|
|
1848
|
-
if (
|
|
3161
|
+
const result = { connected: state === "succeeded", state, operationId: active2.operation.id };
|
|
3162
|
+
if (state === "succeeded") return { ...result, message: "Native login succeeded" };
|
|
3163
|
+
if (terminal.has(state)) return { ...result, message: `Native login ${state}` };
|
|
3164
|
+
if (stopAtQr && state === "awaiting_approval") return { ...result, message: "Approve native login on your phone" };
|
|
1849
3165
|
if (stopAtQr && active2.operation.result?.qrAvailable === true) {
|
|
1850
3166
|
const generation = active2.operation.result?.qrGeneration;
|
|
1851
3167
|
const png = await active2.client.qr(active2.accountId, active2.operation.id, typeof generation === "number" ? generation : void 0);
|
|
1852
|
-
|
|
3168
|
+
guard(access2);
|
|
3169
|
+
return { ...result, qrDataUrl: `data:image/png;base64,${Buffer.from(png).toString("base64")}`, message: "Scan the white-background native QR and approve login" };
|
|
1853
3170
|
}
|
|
1854
|
-
|
|
1855
|
-
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
3171
|
+
await delay(Math.min(500, Math.max(0, deadline - Date.now())), void 0, { signal: access2.signal });
|
|
1856
3172
|
}
|
|
1857
|
-
|
|
3173
|
+
guard(access2);
|
|
3174
|
+
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" };
|
|
1858
3175
|
}
|
|
1859
|
-
async function sendNativeText(account,
|
|
3176
|
+
async function sendNativeText(account, threadId2, text3, key = randomUUID5()) {
|
|
1860
3177
|
const native = account.native;
|
|
1861
3178
|
const { client } = await ensureNativeHost(native);
|
|
1862
|
-
const send = await submitNativeText(client, native.accountId,
|
|
1863
|
-
return
|
|
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
|
+
);
|
|
1864
3187
|
}
|
|
1865
|
-
function createNativeLoginTool(account) {
|
|
3188
|
+
function createNativeLoginTool(account, dependencies = {}) {
|
|
3189
|
+
const actions = ["status", "start", "wait", "disconnect", "logout", "forget"];
|
|
3190
|
+
const configurationKey = nativeConfigurationKey(account.native);
|
|
1866
3191
|
return {
|
|
1867
3192
|
label: "WeChat Login",
|
|
1868
3193
|
name: "wechat_login",
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
3194
|
+
catalogMode: "direct-only",
|
|
3195
|
+
description: "Check WeChat status, start or resume native login, or wait for the same login operation. Show the returned QR image to the user to scan and approve on their phone; do not generate a replacement QR. Repeated start reuses an active operation. For a new operation, force uses QR instead of saved trust. timeoutMs bounds the wait. Disconnect retains saved trust. Logout reports its durable native outcome; it does not promise saved-device revocation. Forget requires confirm=true and removes local authentication while retaining history.",
|
|
3196
|
+
parameters: { type: "object", additionalProperties: false, properties: {
|
|
3197
|
+
action: { type: "string", enum: actions },
|
|
3198
|
+
force: { type: "boolean", description: "With start, use QR instead of saved trust for a new login. An active login is still reused." },
|
|
3199
|
+
timeoutMs: { type: "integer", minimum: 1e3, maximum: 3e5, description: "Wait bound in milliseconds; defaults to 30000. Start returns as soon as a QR is available." },
|
|
3200
|
+
confirm: { type: "boolean", description: "Required true for forget." }
|
|
3201
|
+
}, required: ["action"] },
|
|
3202
|
+
execute: async (_id, params, signal) => {
|
|
3203
|
+
if (!params || typeof params !== "object" || Array.isArray(params)) throw Error("Expected login arguments");
|
|
1872
3204
|
const args = params;
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
3205
|
+
if (Object.keys(args).some((key) => !["action", "force", "timeoutMs", "confirm"].includes(key)) || !actions.includes(args.action) || args.force !== void 0 && typeof args.force !== "boolean" || args.confirm !== void 0 && typeof args.confirm !== "boolean" || args.timeoutMs !== void 0 && (!Number.isSafeInteger(args.timeoutMs) || args.timeoutMs < 1e3 || args.timeoutMs > 3e5)) throw Error("Invalid native login arguments");
|
|
3206
|
+
if (args.action === "forget" && args.confirm !== true) throw Error("Forgetting native credentials requires confirm=true");
|
|
3207
|
+
const access2 = { host: dependencies.host, signal, assertCurrent: () => {
|
|
3208
|
+
dependencies.context?.assertInvocationCurrent?.();
|
|
3209
|
+
if (!dependencies.context) return;
|
|
3210
|
+
const context = dependencies.context;
|
|
3211
|
+
const config = context.getRuntimeConfig?.() ?? context.runtimeConfig ?? context.config;
|
|
3212
|
+
const current = config && resolveWeChatAccount(config);
|
|
3213
|
+
if (!current?.enabled || !current.native || nativeConfigurationKey(current.native) !== configurationKey) throw Error("Native login configuration changed; invoke the tool again");
|
|
3214
|
+
} };
|
|
3215
|
+
guard(access2);
|
|
3216
|
+
if (args.action === "start" || args.action === "wait") {
|
|
3217
|
+
const result2 = args.action === "start" ? await nativeLoginStart(account, { force: args.force, timeoutMs: args.timeoutMs }, access2) : await nativeLoginWait(account, args.timeoutMs, false, access2);
|
|
1877
3218
|
const content = [{ type: "text", text: result2.message }];
|
|
1878
3219
|
if (result2.qrDataUrl) content.push({ type: "image", data: result2.qrDataUrl.split(",")[1], mimeType: "image/png" });
|
|
1879
|
-
return { content, details: { connected: result2.connected } };
|
|
3220
|
+
return { content, details: { connected: result2.connected, state: result2.state, operationId: result2.operationId } };
|
|
1880
3221
|
}
|
|
3222
|
+
const native = account.native;
|
|
3223
|
+
const { client } = await (access2.host ?? ensureNativeHost)(native);
|
|
3224
|
+
guard(access2);
|
|
1881
3225
|
const result = args.action === "status" ? await client.account(native.accountId) : args.action === "disconnect" ? await client.disconnect(native.accountId) : args.action === "logout" ? await client.logout(native.accountId, randomUUID5()) : args.action === "forget" && args.confirm === true ? await client.forgetCredentials(native.accountId, randomUUID5(), true) : (() => {
|
|
1882
3226
|
throw new Error("Unknown native login action");
|
|
1883
3227
|
})();
|
|
3228
|
+
if (args.action !== "status") operations.delete(account.accountId);
|
|
3229
|
+
guard(access2);
|
|
1884
3230
|
return { content: [{ type: "text", text: JSON.stringify(result) }], details: result };
|
|
1885
3231
|
}
|
|
1886
3232
|
};
|
|
1887
3233
|
}
|
|
3234
|
+
function registerNativeLoginTool(api) {
|
|
3235
|
+
api.registerTool({ contextVersion: 2, create: (context) => {
|
|
3236
|
+
const config = context.getRuntimeConfig?.() ?? context.runtimeConfig ?? context.config;
|
|
3237
|
+
const account = config && resolveWeChatAccount(config);
|
|
3238
|
+
return account?.enabled && account.native ? [createNativeLoginTool(account, { context })] : [];
|
|
3239
|
+
} }, { names: ["wechat_login"] });
|
|
3240
|
+
}
|
|
1888
3241
|
|
|
1889
3242
|
// src/channel.ts
|
|
1890
|
-
async function sendWeChatText(cfg, to,
|
|
3243
|
+
async function sendWeChatText(cfg, to, text3) {
|
|
1891
3244
|
const account = resolveWeChatAccount(cfg);
|
|
1892
3245
|
if (!account?.serverUrl) throw new Error("No native daemon configured");
|
|
1893
|
-
return sendNativeText(account, to,
|
|
3246
|
+
return sendNativeText(account, to, text3);
|
|
1894
3247
|
}
|
|
3248
|
+
var mediaHandlers = createWeChatMediaHandlers();
|
|
1895
3249
|
var wechatMessageAdapter = createChannelMessageAdapterFromOutbound({
|
|
1896
3250
|
id: "agent-wechat",
|
|
1897
3251
|
capabilities: {
|
|
@@ -1900,14 +3254,11 @@ var wechatMessageAdapter = createChannelMessageAdapterFromOutbound({
|
|
|
1900
3254
|
messageSendingHooks: true
|
|
1901
3255
|
},
|
|
1902
3256
|
outbound: {
|
|
1903
|
-
sendText: async ({ cfg, to, text }) => ({
|
|
3257
|
+
sendText: async ({ cfg, to, text: text3 }) => ({
|
|
1904
3258
|
channel: "agent-wechat",
|
|
1905
|
-
|
|
3259
|
+
...await sendWeChatText(cfg, to, text3)
|
|
1906
3260
|
}),
|
|
1907
|
-
|
|
1908
|
-
channel: "agent-wechat",
|
|
1909
|
-
messageId: await sendWeChatMedia(cfg, to, text, mediaUrl, audioAsVoice)
|
|
1910
|
-
})
|
|
3261
|
+
...mediaHandlers
|
|
1911
3262
|
}
|
|
1912
3263
|
});
|
|
1913
3264
|
var meta = {
|
|
@@ -1931,6 +3282,7 @@ var wechatPlugin = {
|
|
|
1931
3282
|
tts: { voice: { synthesisTarget: "voice-note", transcodesAudio: true } }
|
|
1932
3283
|
},
|
|
1933
3284
|
reload: { configPrefixes: ["channels.agent-wechat"] },
|
|
3285
|
+
actions: wechatMediaActions,
|
|
1934
3286
|
configSchema: {
|
|
1935
3287
|
uiHints: { "native.token": { sensitive: true } },
|
|
1936
3288
|
schema: {
|
|
@@ -2029,7 +3381,7 @@ var wechatPlugin = {
|
|
|
2029
3381
|
},
|
|
2030
3382
|
// ---- Mention adapter ----
|
|
2031
3383
|
mentions: {
|
|
2032
|
-
stripMentions: ({ text, ctx }) => normalizeWeChatCommandBody(
|
|
3384
|
+
stripMentions: ({ text: text3, ctx }) => normalizeWeChatCommandBody(text3, {
|
|
2033
3385
|
isGroup: ctx.ChatType === "group",
|
|
2034
3386
|
wasMentioned: ctx.WasMentioned === true
|
|
2035
3387
|
})
|
|
@@ -2048,14 +3400,11 @@ var wechatPlugin = {
|
|
|
2048
3400
|
// ---- Outbound adapter for OpenClaw hosts using the outbound hook ----
|
|
2049
3401
|
outbound: {
|
|
2050
3402
|
deliveryMode: "direct",
|
|
2051
|
-
sendText: async ({ cfg, to, text }) => ({
|
|
3403
|
+
sendText: async ({ cfg, to, text: text3 }) => ({
|
|
2052
3404
|
channel: "agent-wechat",
|
|
2053
|
-
|
|
3405
|
+
...await sendWeChatText(cfg, to, text3)
|
|
2054
3406
|
}),
|
|
2055
|
-
|
|
2056
|
-
channel: "agent-wechat",
|
|
2057
|
-
messageId: await sendWeChatMedia(cfg, to, text, mediaUrl, audioAsVoice)
|
|
2058
|
-
})
|
|
3407
|
+
...mediaHandlers
|
|
2059
3408
|
},
|
|
2060
3409
|
message: wechatMessageAdapter,
|
|
2061
3410
|
gateway: {
|
|
@@ -2085,7 +3434,7 @@ var wechatPlugin = {
|
|
|
2085
3434
|
loginWithQrWait: async ({ accountId, timeoutMs }) => {
|
|
2086
3435
|
const account = resolveWeChatAccount(getWeChatRuntime().config.current(), accountId ?? void 0);
|
|
2087
3436
|
if (!account?.native) return { connected: false, message: "No native daemon configured" };
|
|
2088
|
-
return nativeLoginWait(account
|
|
3437
|
+
return nativeLoginWait(account, timeoutMs);
|
|
2089
3438
|
}
|
|
2090
3439
|
},
|
|
2091
3440
|
auth: {
|
|
@@ -2111,10 +3460,6 @@ var wechatPlugin = {
|
|
|
2111
3460
|
linked: runtime2?.linked ?? false
|
|
2112
3461
|
})
|
|
2113
3462
|
},
|
|
2114
|
-
agentTools: (({ cfg }) => {
|
|
2115
|
-
const account = resolveWeChatAccount(cfg);
|
|
2116
|
-
return account?.native ? [createNativeLoginTool(account)] : [];
|
|
2117
|
-
}),
|
|
2118
3463
|
directory: {
|
|
2119
3464
|
self: async ({ cfg }) => {
|
|
2120
3465
|
const account = resolveWeChatAccount(cfg);
|
|
@@ -2222,7 +3567,7 @@ function createNativeFacade(config, dependencies = {}) {
|
|
|
2222
3567
|
fail(res, 403, "facade_account_forbidden");
|
|
2223
3568
|
return true;
|
|
2224
3569
|
}
|
|
2225
|
-
if (!["GET", "HEAD", "POST", "PATCH", "DELETE"].includes(req.method ?? "")) {
|
|
3570
|
+
if (!["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"].includes(req.method ?? "")) {
|
|
2226
3571
|
fail(res, 405, "method_not_allowed");
|
|
2227
3572
|
return true;
|
|
2228
3573
|
}
|
|
@@ -2235,19 +3580,23 @@ function createNativeFacade(config, dependencies = {}) {
|
|
|
2235
3580
|
try {
|
|
2236
3581
|
const host2 = dependencies.endpoint ? void 0 : await ensureNativeHost(config);
|
|
2237
3582
|
const headers = new Headers();
|
|
2238
|
-
for (const
|
|
2239
|
-
const value = req.headers[
|
|
2240
|
-
if (typeof value === "string") headers.set(
|
|
3583
|
+
for (const name3 of ["content-type", "accept", "range", "if-none-match", "if-range", "last-event-id", "idempotency-key"]) {
|
|
3584
|
+
const value = req.headers[name3];
|
|
3585
|
+
if (typeof value === "string") headers.set(name3, value);
|
|
2241
3586
|
}
|
|
3587
|
+
const upload = pieces.length === 4 && pieces[3] === "uploads" && req.method === "POST";
|
|
3588
|
+
const mediaContent = pieces.length === 6 && pieces[3] === "media" && pieces[5] === "content" && parsed.searchParams.get("representation") !== "preview";
|
|
3589
|
+
const requestLimit = upload ? NATIVE_MAX_SOURCE_BYTES + 64 * 1024 : MAX_BODY;
|
|
3590
|
+
const responseLimit = mediaContent ? Math.max(MAX_BODY, NATIVE_MAX_SOURCE_BYTES) : MAX_BODY;
|
|
2242
3591
|
const length = req.headers["content-length"];
|
|
2243
|
-
if (length && (!/^\d+$/.test(length) || Number(length) >
|
|
3592
|
+
if (length && (!/^\d+$/.test(length) || Number(length) > requestLimit)) {
|
|
2244
3593
|
fail(res, 413, "payload_too_large");
|
|
2245
3594
|
return true;
|
|
2246
3595
|
}
|
|
2247
3596
|
let size = 0;
|
|
2248
3597
|
const body = ["GET", "HEAD"].includes(req.method ?? "") ? void 0 : Readable.toWeb(req).pipeThrough(new NodeTransformStream({ transform(chunk, controller) {
|
|
2249
3598
|
size += chunk.byteLength;
|
|
2250
|
-
if (size >
|
|
3599
|
+
if (size > requestLimit) {
|
|
2251
3600
|
tooLarge = true;
|
|
2252
3601
|
throw new Error("payload_too_large");
|
|
2253
3602
|
}
|
|
@@ -2260,10 +3609,16 @@ function createNativeFacade(config, dependencies = {}) {
|
|
|
2260
3609
|
headers.set("Authorization", `Bearer ${dependencies.token}`);
|
|
2261
3610
|
response = await (dependencies.fetch ?? fetch)(new URL(relative, dependencies.endpoint), init);
|
|
2262
3611
|
}
|
|
3612
|
+
const responseLength = response.headers.get("content-length");
|
|
3613
|
+
if (responseLength && (!/^\d+$/.test(responseLength) || Number(responseLength) > responseLimit)) {
|
|
3614
|
+
await response.body?.cancel();
|
|
3615
|
+
fail(res, 502, "native_facade_unavailable");
|
|
3616
|
+
return true;
|
|
3617
|
+
}
|
|
2263
3618
|
res.statusCode = response.status;
|
|
2264
|
-
for (const
|
|
2265
|
-
const value = response.headers.get(
|
|
2266
|
-
if (value) res.setHeader(
|
|
3619
|
+
for (const name3 of ["content-type", "content-length", "content-range", "accept-ranges", "etag", "cache-control", "content-disposition", "x-content-type-options"]) {
|
|
3620
|
+
const value = response.headers.get(name3);
|
|
3621
|
+
if (value) res.setHeader(name3, value);
|
|
2267
3622
|
}
|
|
2268
3623
|
res.setHeader("x-content-type-options", "nosniff");
|
|
2269
3624
|
const reader = response.body?.getReader();
|
|
@@ -2278,7 +3633,7 @@ function createNativeFacade(config, dependencies = {}) {
|
|
|
2278
3633
|
const { value, done } = await reader.read();
|
|
2279
3634
|
if (done) break;
|
|
2280
3635
|
emitted += value.length;
|
|
2281
|
-
if (!sse && emitted >
|
|
3636
|
+
if (!sse && emitted > responseLimit) throw new Error("upstream_response_too_large");
|
|
2282
3637
|
if (!res.write(value)) await drain(res, abort.signal);
|
|
2283
3638
|
}
|
|
2284
3639
|
} finally {
|
|
@@ -2310,6 +3665,588 @@ function registerNativeFacade(api, config) {
|
|
|
2310
3665
|
return handler.stop;
|
|
2311
3666
|
}
|
|
2312
3667
|
|
|
3668
|
+
// src/native-history-tools.ts
|
|
3669
|
+
import { resolveStableChannelMessageIngress as resolveStableChannelMessageIngress2 } from "openclaw/plugin-sdk/channel-ingress-runtime";
|
|
3670
|
+
import { imageResultFromFile } from "openclaw/plugin-sdk/channel-actions";
|
|
3671
|
+
var pageSchema = { limit: { type: "integer", minimum: 1, maximum: 50, default: 20 }, cursor: { type: "string", maxLength: 8192, description: "Opaque nextCursor from the same tool and query; do not invent one." } };
|
|
3672
|
+
var names = ["wechat_history", "wechat_search", "wechat_message", "wechat_media"];
|
|
3673
|
+
var archiveNames = ["wechat_archive_threads", "wechat_archive_search", "wechat_archive_history", "wechat_archive_message", "wechat_archive_media"];
|
|
3674
|
+
var messageIdSchema = { type: "string", minLength: 1, maxLength: 4096 };
|
|
3675
|
+
var qualities = ["best", "original", "standard", "thumbnail", "normal", "encoded"];
|
|
3676
|
+
function object(value) {
|
|
3677
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw Error("Expected tool arguments");
|
|
3678
|
+
return value;
|
|
3679
|
+
}
|
|
3680
|
+
function string(value, name3, max = 4096) {
|
|
3681
|
+
if (typeof value !== "string" || !value.trim() || value.length > max || /[\u0000-\u001f\u007f]/.test(value)) throw Error(`Invalid ${name3}`);
|
|
3682
|
+
return value.trim();
|
|
3683
|
+
}
|
|
3684
|
+
function threadId(value) {
|
|
3685
|
+
return string(string(value, "thread ID").replace(/^(?:agent-)?wechat:(?:group:)?/i, ""), "thread ID");
|
|
3686
|
+
}
|
|
3687
|
+
function messageResult(message, retrievalTool = "wechat_media", quotePermitted = false) {
|
|
3688
|
+
if (nativeRecallInfo(message)) return {
|
|
3689
|
+
id: message.id,
|
|
3690
|
+
threadId: message.threadId,
|
|
3691
|
+
serverId: message.serverId,
|
|
3692
|
+
direction: message.direction,
|
|
3693
|
+
type: 1e4,
|
|
3694
|
+
body: "[Message recalled]",
|
|
3695
|
+
status: "recalled",
|
|
3696
|
+
recall: nativeRecallInfo(message)
|
|
3697
|
+
};
|
|
3698
|
+
const isQuote = message.type === 49 && message.appMessageType === 57;
|
|
3699
|
+
const isForward = message.type === 49 && message.appMessageType === 19;
|
|
3700
|
+
const isLink = message.type === 49 && [3, 4, 5].includes(message.appMessageType ?? 0) && !!message.link;
|
|
3701
|
+
const kind2 = isQuote ? "quote" : isForward ? "forwarded_history" : isLink ? "link_preview" : message.type === 3 ? "image" : message.type === 47 ? "sticker" : message.type === 34 ? "voice" : message.type === 43 ? "video" : message.type === 49 && (message.appMessageType == null || message.appMessageType === 6) ? "file" : "unsupported";
|
|
3702
|
+
const body = message.type === 1 || isForward || isLink ? message.body ?? "" : isQuote ? renderEmbeddedQuote(message, quotePermitted).body : `[WeChat ${kind2} message; attachment content has not been retrieved by this tool]`;
|
|
3703
|
+
const quote = message.quote && {
|
|
3704
|
+
serverId: message.quote.serverId,
|
|
3705
|
+
type: message.quote.type,
|
|
3706
|
+
state: quotePermitted ? message.quote.state : "not permitted",
|
|
3707
|
+
senderId: message.quote.senderId,
|
|
3708
|
+
appMessageType: message.quote.appMessageType,
|
|
3709
|
+
embeddedImage: quotePermitted ? message.quote.embeddedImage : void 0
|
|
3710
|
+
};
|
|
3711
|
+
return {
|
|
3712
|
+
id: message.id,
|
|
3713
|
+
threadId: message.threadId,
|
|
3714
|
+
serverId: message.serverId,
|
|
3715
|
+
senderId: message.senderId,
|
|
3716
|
+
direction: message.direction,
|
|
3717
|
+
type: message.type,
|
|
3718
|
+
appMessageType: message.appMessageType,
|
|
3719
|
+
quote,
|
|
3720
|
+
link: isLink ? message.link : void 0,
|
|
3721
|
+
createdAt: message.createdAt,
|
|
3722
|
+
body: body.slice(0, 4e3),
|
|
3723
|
+
bodyTruncated: body.length > 4e3,
|
|
3724
|
+
attachment: message.type !== 1 && !isForward && kind2 !== "unsupported" ? { kind: kind2, retrievalTool, messageId: message.id } : void 0
|
|
3725
|
+
};
|
|
3726
|
+
}
|
|
3727
|
+
function createNativeHistoryTools(context, dependencies = {}) {
|
|
3728
|
+
return createLookupTools(context, dependencies, false);
|
|
3729
|
+
}
|
|
3730
|
+
function createNativeArchiveTools(context, dependencies = {}) {
|
|
3731
|
+
return createLookupTools(context, dependencies, true);
|
|
3732
|
+
}
|
|
3733
|
+
function createLookupTools(context, dependencies, archive) {
|
|
3734
|
+
const currentConfig = () => context.getRuntimeConfig?.() ?? context.runtimeConfig ?? context.config;
|
|
3735
|
+
if (!currentConfig()) return [];
|
|
3736
|
+
const selected = resolveWeChatAccount(currentConfig());
|
|
3737
|
+
if (!selected?.native || !selected.enabled) return [];
|
|
3738
|
+
const configurationKey = nativeConfigurationKey(selected.native);
|
|
3739
|
+
if (!archive && context.messageChannel !== "agent-wechat") return [];
|
|
3740
|
+
if (!archive && context.agentAccountId && context.agentAccountId !== selected.accountId) return [];
|
|
3741
|
+
if (!archive && context.deliveryContext?.channel === "agent-wechat" && context.deliveryContext.accountId && context.deliveryContext.accountId !== selected.accountId) return [];
|
|
3742
|
+
let currentThread;
|
|
3743
|
+
let requesterSenderId;
|
|
3744
|
+
const target = context.deliveryContext?.channel === "agent-wechat" ? context.deliveryContext.to : void 0;
|
|
3745
|
+
if (!archive) {
|
|
3746
|
+
try {
|
|
3747
|
+
if (context.nativeChannelId) currentThread = threadId(context.nativeChannelId);
|
|
3748
|
+
if (target) {
|
|
3749
|
+
const deliveryThread = threadId(target);
|
|
3750
|
+
if (currentThread && currentThread !== deliveryThread) return [];
|
|
3751
|
+
currentThread ??= deliveryThread;
|
|
3752
|
+
}
|
|
3753
|
+
requesterSenderId = string(context.requesterSenderId, "requester sender ID");
|
|
3754
|
+
} catch {
|
|
3755
|
+
return [];
|
|
3756
|
+
}
|
|
3757
|
+
if (!currentThread) return [];
|
|
3758
|
+
}
|
|
3759
|
+
const selectedId = selected.native.accountId;
|
|
3760
|
+
const tool = (name3, action, description, properties, required = []) => ({
|
|
3761
|
+
name: name3,
|
|
3762
|
+
label: name3.replaceAll("_", " "),
|
|
3763
|
+
description,
|
|
3764
|
+
// The pinned host's tool_call wrapper JSON-serializes image blocks. Its
|
|
3765
|
+
// public direct-only surface preserves actual image content for vision.
|
|
3766
|
+
...action === "media" ? { catalogMode: "direct-only" } : {},
|
|
3767
|
+
parameters: { type: "object", additionalProperties: false, properties, required },
|
|
3768
|
+
execute: async (_callId, input, signal) => {
|
|
3769
|
+
const args = object(input);
|
|
3770
|
+
const guard2 = () => {
|
|
3771
|
+
signal?.throwIfAborted();
|
|
3772
|
+
context.assertInvocationCurrent?.();
|
|
3773
|
+
const cfg2 = currentConfig();
|
|
3774
|
+
const account2 = resolveWeChatAccount(cfg2);
|
|
3775
|
+
if (!account2?.enabled || !account2.native || account2.native.accountId !== selectedId || account2.accountId !== selected.accountId || nativeConfigurationKey(account2.native) !== configurationKey) throw Error("WeChat account configuration changed; start a new turn");
|
|
3776
|
+
return { cfg: cfg2, account: account2, native: account2.native };
|
|
3777
|
+
};
|
|
3778
|
+
const { cfg, account, native } = guard2();
|
|
3779
|
+
if (Object.keys(args).some((key) => !Object.hasOwn(properties, key))) throw Error(archive ? "Unknown archive lookup argument" : "Unknown lookup argument; WeChat history is restricted to the current conversation");
|
|
3780
|
+
const limit = args.limit ?? 20;
|
|
3781
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 50) throw Error("limit must be 1\u201350");
|
|
3782
|
+
const cursor = args.cursor === void 0 ? void 0 : string(args.cursor, "cursor", 8192);
|
|
3783
|
+
const query = args.query === void 0 ? void 0 : string(args.query, "query", 256);
|
|
3784
|
+
if (query && Buffer.byteLength(query) > 256) throw Error("Search query exceeds 256 UTF-8 bytes");
|
|
3785
|
+
if (action === "search" && !query) throw Error("A non-empty search query is required");
|
|
3786
|
+
const conversation = archive ? args.threadId === void 0 ? void 0 : threadId(args.threadId) : currentThread;
|
|
3787
|
+
if (action === "history" && !conversation) throw Error("A thread ID is required");
|
|
3788
|
+
const messageId = Object.hasOwn(properties, "messageId") ? string(args.messageId, "message ID") : void 0;
|
|
3789
|
+
if (args.download !== void 0 && typeof args.download !== "boolean") throw Error("download must be a boolean");
|
|
3790
|
+
const quality = args.quality ?? "best";
|
|
3791
|
+
if (!qualities.includes(quality)) throw Error("Invalid media quality");
|
|
3792
|
+
const core = dependencies.core ?? getWeChatRuntime();
|
|
3793
|
+
const allowed = async (sender) => {
|
|
3794
|
+
if (archive) return true;
|
|
3795
|
+
const { cfg: cfg2, account: account2 } = guard2();
|
|
3796
|
+
const result2 = await resolveWeChatIngress({
|
|
3797
|
+
resolve: core.channel.inbound?.ingress?.resolveStable ?? resolveStableChannelMessageIngress2,
|
|
3798
|
+
cfg: cfg2,
|
|
3799
|
+
accountId: account2.accountId,
|
|
3800
|
+
policy: resolveWeChatPolicyContext({ account: account2, cfg: cfg2, chatId: conversation }),
|
|
3801
|
+
isGroup: conversation.endsWith("@chatroom"),
|
|
3802
|
+
chatId: conversation,
|
|
3803
|
+
senderId: sender,
|
|
3804
|
+
readStoreAllowFrom: async () => core.channel.pairing.readAllowFromStore({ channel: "agent-wechat", accountId: account2.accountId, env: process.env }).catch(() => [])
|
|
3805
|
+
});
|
|
3806
|
+
return result2.ingress.admission === "dispatch";
|
|
3807
|
+
};
|
|
3808
|
+
if (!await allowed(requesterSenderId)) throw Error("WeChat conversation access is no longer allowed");
|
|
3809
|
+
guard2();
|
|
3810
|
+
const { client } = await (dependencies.host ?? ensureNativeHost)(native);
|
|
3811
|
+
guard2();
|
|
3812
|
+
const accountId = native.accountId;
|
|
3813
|
+
const visibleMessage = async (message) => messageResult(
|
|
3814
|
+
message,
|
|
3815
|
+
archive ? "wechat_archive_media" : "wechat_media",
|
|
3816
|
+
!message.quote || archive || message.quote.direction === "outgoing" || !!message.quote.senderId && await allowed(message.quote.senderId)
|
|
3817
|
+
);
|
|
3818
|
+
let result;
|
|
3819
|
+
if (action === "threads") {
|
|
3820
|
+
const page = await client.threads(accountId, { limit, cursor, ...query ? { query } : {} });
|
|
3821
|
+
const items = [];
|
|
3822
|
+
for (const thread3 of page.items) {
|
|
3823
|
+
if (isNativeTombstone(thread3)) continue;
|
|
3824
|
+
if (thread3.accountId !== accountId) throw Error("Thread response crosses an account boundary");
|
|
3825
|
+
items.push({ id: thread3.id, peerId: thread3.peerId, kind: thread3.kind, displayName: thread3.displayName, unreadCount: thread3.unreadCount });
|
|
3826
|
+
}
|
|
3827
|
+
result = { ...page, items, scope: "local_profile", note: "Locally stored threads; coverage may be partial. This lookup does not mark threads read." };
|
|
3828
|
+
} else if (action === "message" || action === "media") {
|
|
3829
|
+
const message = await client.message(accountId, messageId);
|
|
3830
|
+
guard2();
|
|
3831
|
+
if (!await allowed(requesterSenderId)) throw Error("WeChat conversation access is no longer allowed");
|
|
3832
|
+
if (message.id !== messageId || message.accountId !== accountId || !archive && message.threadId !== conversation || message.direction !== "outgoing" && !await allowed(message.senderId ?? void 0)) throw Error("Message is outside the permitted conversation or sender policy");
|
|
3833
|
+
if (action === "message") result = await visibleMessage(message);
|
|
3834
|
+
if (action === "media") {
|
|
3835
|
+
const checkRecall = async () => {
|
|
3836
|
+
guard2();
|
|
3837
|
+
const latest = await client.message(accountId, messageId);
|
|
3838
|
+
guard2();
|
|
3839
|
+
if (latest.id !== message.id || latest.accountId !== accountId || latest.threadId !== message.threadId || latest.serverId !== message.serverId) throw Error("Native media message identity changed");
|
|
3840
|
+
if (nativeRecallInfo(latest)) throw new NativeApiError(410, "message_recalled", false);
|
|
3841
|
+
if (message.quote) {
|
|
3842
|
+
if (latest.quote?.state === "recalled") throw new NativeApiError(410, "message_recalled", false);
|
|
3843
|
+
if (!latest.quote || JSON.stringify(latest.quote) !== JSON.stringify(message.quote)) throw new NativeApiError(409, "media_source_changed", false);
|
|
3844
|
+
}
|
|
3845
|
+
};
|
|
3846
|
+
let prepared;
|
|
3847
|
+
try {
|
|
3848
|
+
prepared = await prepareNativeAttachment({
|
|
3849
|
+
client,
|
|
3850
|
+
account,
|
|
3851
|
+
message,
|
|
3852
|
+
core,
|
|
3853
|
+
cfg,
|
|
3854
|
+
quality,
|
|
3855
|
+
download: args.download !== false,
|
|
3856
|
+
waitMs: 2e3,
|
|
3857
|
+
signal,
|
|
3858
|
+
assertCurrent: guard2,
|
|
3859
|
+
allowQuotedMessage: async (original) => original.direction === "outgoing" || await allowed(original.senderId ?? void 0),
|
|
3860
|
+
beforeMediaAccess: async () => {
|
|
3861
|
+
if (!await allowed(requesterSenderId) || message.direction !== "outgoing" && !await allowed(message.senderId ?? void 0)) throw Error("WeChat conversation access is no longer allowed");
|
|
3862
|
+
await checkRecall();
|
|
3863
|
+
}
|
|
3864
|
+
});
|
|
3865
|
+
} catch (error) {
|
|
3866
|
+
guard2();
|
|
3867
|
+
if (!(error instanceof NativeApiError)) throw error;
|
|
3868
|
+
const details2 = {
|
|
3869
|
+
messageId: message.id,
|
|
3870
|
+
threadId: message.threadId,
|
|
3871
|
+
status: error.code === "message_recalled" ? "recalled" : error.retryable ? "pending" : ["unsupported_profile", "unsupported_media", "unsupported_media_variant"].includes(error.code) ? "unsupported" : "unavailable",
|
|
3872
|
+
retryable: error.retryable,
|
|
3873
|
+
reason: error.code
|
|
3874
|
+
};
|
|
3875
|
+
return { content: [{ type: "text", text: JSON.stringify(details2) }], details: details2 };
|
|
3876
|
+
}
|
|
3877
|
+
guard2();
|
|
3878
|
+
if (!await allowed(requesterSenderId) || message.direction !== "outgoing" && !await allowed(message.senderId ?? void 0)) throw Error("WeChat conversation access is no longer allowed");
|
|
3879
|
+
const details = {
|
|
3880
|
+
messageId: message.id,
|
|
3881
|
+
threadId: message.threadId,
|
|
3882
|
+
status: prepared.reason === "message_recalled" ? "recalled" : prepared.pending ? "pending" : prepared.attachment?.status ?? prepared.quote?.state ?? "unsupported",
|
|
3883
|
+
attachment: prepared.attachment,
|
|
3884
|
+
quote: prepared.quote,
|
|
3885
|
+
link: ["message_recalled", "media_identity_unavailable", "media_source_changed"].includes(prepared.reason ?? "") ? void 0 : message.link,
|
|
3886
|
+
variant: prepared.variant,
|
|
3887
|
+
jobId: prepared.jobId,
|
|
3888
|
+
retryable: prepared.retryable ?? false,
|
|
3889
|
+
reason: prepared.reason,
|
|
3890
|
+
body: prepared.body
|
|
3891
|
+
};
|
|
3892
|
+
const image = prepared.suppliedAssets?.find((asset) => asset.role === "model_image");
|
|
3893
|
+
const output = image ? await imageResultFromFile({ label: "WeChat attachment", path: image.path, extraText: JSON.stringify(details), details }) : { content: [{ type: "text", text: JSON.stringify(details) }], details };
|
|
3894
|
+
guard2();
|
|
3895
|
+
try {
|
|
3896
|
+
await checkRecall();
|
|
3897
|
+
} catch (error) {
|
|
3898
|
+
if (!(error instanceof NativeApiError) || error.code !== "message_recalled") throw error;
|
|
3899
|
+
const details2 = { messageId: message.id, threadId: message.threadId, status: "recalled", reason: "message_recalled", retryable: false };
|
|
3900
|
+
return { content: [{ type: "text", text: JSON.stringify(details2) }], details: details2 };
|
|
3901
|
+
}
|
|
3902
|
+
return output;
|
|
3903
|
+
}
|
|
3904
|
+
} else {
|
|
3905
|
+
const options = { limit, cursor, ...action === "search" ? { query } : {} };
|
|
3906
|
+
const page = conversation ? await client.messages(accountId, conversation, options) : await client.searchMessages(accountId, options);
|
|
3907
|
+
const items = [];
|
|
3908
|
+
for (const message of page.items) {
|
|
3909
|
+
if (isNativeTombstone(message)) continue;
|
|
3910
|
+
if (conversation && message.threadId !== conversation || message.accountId !== accountId) throw Error("WeChat history response crosses a conversation boundary");
|
|
3911
|
+
if (message.direction === "outgoing" || await allowed(message.senderId ?? void 0)) items.push(await visibleMessage(message));
|
|
3912
|
+
}
|
|
3913
|
+
result = {
|
|
3914
|
+
...page,
|
|
3915
|
+
items,
|
|
3916
|
+
scope: "local_profile",
|
|
3917
|
+
searchMode: action === "search" ? "case_insensitive_substring" : void 0,
|
|
3918
|
+
note: archive ? "Account-wide local history may be partial. These reads do not mark threads read or download attachments." : "Local history may be partial. A filtered page can be empty with a nextCursor. These reads do not mark a conversation read or download attachments."
|
|
3919
|
+
};
|
|
3920
|
+
}
|
|
3921
|
+
guard2();
|
|
3922
|
+
return { content: [{ type: "text", text: JSON.stringify(result) }], details: result };
|
|
3923
|
+
}
|
|
3924
|
+
});
|
|
3925
|
+
const querySchema = { type: "string", minLength: 1, maxLength: 256 };
|
|
3926
|
+
const mediaSchema = {
|
|
3927
|
+
messageId: messageIdSchema,
|
|
3928
|
+
download: { type: "boolean", default: true, description: "Set false to use cached media only without requesting a WeChat transfer." },
|
|
3929
|
+
quality: { type: "string", enum: qualities, default: "best", description: "best uses the best cached image, normal video or decoded voice. Explicit variants are strict and may be unavailable." }
|
|
3930
|
+
};
|
|
3931
|
+
if (archive) return [
|
|
3932
|
+
tool(archiveNames[0], "threads", "List or find locally stored threads across the configured WeChat account. Optional case-insensitive query matches thread IDs and display names. Includes groups and peers, with opaque pagination; no read marking.", { query: querySchema, ...pageSchema }),
|
|
3933
|
+
tool(archiveNames[1], "search", "Search locally stored messages across every thread in the configured WeChat account, including other senders. Optional threadId narrows the search. Follow nextCursor with the same query and thread selection; no remote backfill or read marking.", { query: querySchema, threadId: messageIdSchema, ...pageSchema }, ["query"]),
|
|
3934
|
+
tool(archiveNames[2], "history", "Read the locally stored history of any thread in the configured WeChat account, newest first, without sender filtering or read marking. Use wechat_archive_threads to find thread IDs.", { threadId: messageIdSchema, ...pageSchema }, ["threadId"]),
|
|
3935
|
+
tool(archiveNames[3], "message", "Look up a stored message in any thread of the configured WeChat account by its exact opaque message ID. Use wechat_archive_media to retrieve its attachment.", { messageId: messageIdSchema }, ["messageId"]),
|
|
3936
|
+
tool(archiveNames[4], "media", "Retrieve an attachment or quoted text/image/link from any thread in the configured WeChat account by its message ID. Use the parent quote message ID for quotes. Returns verified managed file paths and an image preview for vision. Cached bytes first; missing media requests a bounded server-owned download unless download=false. Preserve pending/expired/unavailable results and never automatically retry retryable=false. No sends or read marking.", mediaSchema, ["messageId"])
|
|
3937
|
+
];
|
|
3938
|
+
return [
|
|
3939
|
+
tool(names[0], "history", "Read the current WeChat conversation's locally stored messages, newest first, beyond the recent inbound buffer. Follow nextCursor for older history; no remote history backfill or read marking.", { ...pageSchema }),
|
|
3940
|
+
tool(names[1], "search", "Search the current WeChat conversation's locally stored message text by case-insensitive substring, beyond buffered messages. Follow nextCursor with the same query in this conversation.", { query: querySchema, ...pageSchema }, ["query"]),
|
|
3941
|
+
tool(names[2], "message", "Look up a stored message by its exact opaque message ID in the current WeChat conversation. Media is described without downloading it; use wechat_media to retrieve its attachment. Long text is bounded.", { messageId: messageIdSchema }, ["messageId"]),
|
|
3942
|
+
tool(names[3], "media", "Retrieve a message attachment or quoted text/image/link from the current WeChat conversation. Use the parent quote message ID for quotes. Returns a verified local file path and an image preview for vision when applicable. Uses cached bytes first; download defaults to true and requests a bounded server-owned transfer if missing. Pending results may be checked again; never automatically retry confirmed expiry or retryable=false. Does not send messages or mark the thread read.", mediaSchema, ["messageId"])
|
|
3943
|
+
];
|
|
3944
|
+
}
|
|
3945
|
+
function registerNativeHistoryTools(api) {
|
|
3946
|
+
api.registerTool({ contextVersion: 2, create: (context) => createNativeHistoryTools(context) }, { names });
|
|
3947
|
+
api.registerTool({ contextVersion: 2, create: (context) => createNativeArchiveTools(context) }, { names: archiveNames, optional: true });
|
|
3948
|
+
}
|
|
3949
|
+
|
|
3950
|
+
// src/native-share-tool.ts
|
|
3951
|
+
import { resolveStableChannelMessageIngress as resolveStableChannelMessageIngress3 } from "openclaw/plugin-sdk/channel-ingress-runtime";
|
|
3952
|
+
var name = "wechat_send_share";
|
|
3953
|
+
function text(value, label, max, multiline = false) {
|
|
3954
|
+
if (typeof value !== "string" || !value.trim() || Buffer.byteLength(value) > max || (multiline ? /[\u0000-\u0008\u000b-\u001f\u007f]/ : /[\u0000-\u001f\u007f]/).test(value)) throw Error(`Invalid ${label}`);
|
|
3955
|
+
return value;
|
|
3956
|
+
}
|
|
3957
|
+
function thread(value) {
|
|
3958
|
+
return text(text(value, "current conversation", 256).replace(/^(?:agent-)?wechat:(?:group:)?/i, "").trim(), "current conversation", 256);
|
|
3959
|
+
}
|
|
3960
|
+
function url(value, label) {
|
|
3961
|
+
const raw = text(value, label, 8192);
|
|
3962
|
+
const parsed = new URL(raw);
|
|
3963
|
+
if (!["https:", "http:"].includes(parsed.protocol) || !parsed.hostname || parsed.username || parsed.password) throw Error(`Invalid ${label}`);
|
|
3964
|
+
return raw;
|
|
3965
|
+
}
|
|
3966
|
+
function createNativeShareTools(context, dependencies = {}) {
|
|
3967
|
+
const currentConfig = () => context.getRuntimeConfig?.() ?? context.runtimeConfig ?? context.config;
|
|
3968
|
+
if (!currentConfig()) return [];
|
|
3969
|
+
const selected = resolveWeChatAccount(currentConfig());
|
|
3970
|
+
if (!selected?.enabled || !selected.native || context.messageChannel !== "agent-wechat" || context.agentAccountId && context.agentAccountId !== selected.accountId || context.deliveryContext?.channel === "agent-wechat" && context.deliveryContext.accountId && context.deliveryContext.accountId !== selected.accountId) return [];
|
|
3971
|
+
let conversation, requester;
|
|
3972
|
+
try {
|
|
3973
|
+
const native = context.nativeChannelId ? thread(context.nativeChannelId) : void 0;
|
|
3974
|
+
const delivery = context.deliveryContext?.channel === "agent-wechat" && context.deliveryContext.to ? thread(context.deliveryContext.to) : void 0;
|
|
3975
|
+
if (native && delivery && native !== delivery) return [];
|
|
3976
|
+
conversation = native ?? delivery;
|
|
3977
|
+
if (!conversation) return [];
|
|
3978
|
+
requester = text(context.requesterSenderId, "requester sender", 256);
|
|
3979
|
+
} catch {
|
|
3980
|
+
return [];
|
|
3981
|
+
}
|
|
3982
|
+
const configurationKey = nativeConfigurationKey(selected.native);
|
|
3983
|
+
const fields = ["title", "url", "description", "thumbnailUrl", "idempotencyKey"];
|
|
3984
|
+
return [{
|
|
3985
|
+
name,
|
|
3986
|
+
label: "Send WeChat share",
|
|
3987
|
+
description: "Send a URL share card to the current WeChat conversation, with an explicit title, URL, optional description and public thumbnail URL. Does not fetch or summarize the linked page. Use one idempotencyKey per intended share and reuse it after timeouts; never retry an uncertain send with a new key. Returns a durable send ID and state. Accepted means server acceptance; recipient rendering requires verification.",
|
|
3988
|
+
parameters: { type: "object", additionalProperties: false, required: ["title", "url", "idempotencyKey"], properties: {
|
|
3989
|
+
title: { type: "string", minLength: 1, maxLength: 16384 },
|
|
3990
|
+
url: { type: "string", minLength: 1, maxLength: 8192 },
|
|
3991
|
+
description: { type: "string", maxLength: 16384 },
|
|
3992
|
+
thumbnailUrl: { type: "string", minLength: 1, maxLength: 8192, description: "Public HTTP(S) image URL advertised as the card thumbnail; no upload or page scraping." },
|
|
3993
|
+
idempotencyKey: { type: "string", minLength: 1, maxLength: 200, description: "Stable unique key for this logical share. Reuse the same key and identical fields when inspecting/retrying this request." }
|
|
3994
|
+
} },
|
|
3995
|
+
execute: async (_callId, input, signal) => {
|
|
3996
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) throw Error("Expected share arguments");
|
|
3997
|
+
const args = input;
|
|
3998
|
+
if (Object.keys(args).some((key2) => !fields.includes(key2))) throw Error("Share sending is restricted to the current conversation");
|
|
3999
|
+
const key = text(args.idempotencyKey, "idempotency key", 200);
|
|
4000
|
+
const request = {
|
|
4001
|
+
kind: "share",
|
|
4002
|
+
threadId: conversation,
|
|
4003
|
+
title: text(args.title, "title", 16384, true),
|
|
4004
|
+
url: url(args.url, "URL"),
|
|
4005
|
+
...args.description !== void 0 ? { description: args.description === "" ? "" : text(args.description, "description", 16384, true) } : {},
|
|
4006
|
+
...args.thumbnailUrl !== void 0 ? { thumbnailUrl: url(args.thumbnailUrl, "thumbnail URL") } : {}
|
|
4007
|
+
};
|
|
4008
|
+
const guard2 = () => {
|
|
4009
|
+
signal?.throwIfAborted();
|
|
4010
|
+
context.assertInvocationCurrent?.();
|
|
4011
|
+
const cfg = currentConfig(), account = resolveWeChatAccount(cfg);
|
|
4012
|
+
if (!account?.enabled || !account.native || account.accountId !== selected.accountId || account.native.accountId !== selected.native.accountId || nativeConfigurationKey(account.native) !== configurationKey) throw Error("WeChat account configuration changed; start a new turn");
|
|
4013
|
+
return { cfg, account, native: account.native };
|
|
4014
|
+
};
|
|
4015
|
+
const core = dependencies.core ?? getWeChatRuntime();
|
|
4016
|
+
const authorize = async () => {
|
|
4017
|
+
const { cfg, account } = guard2();
|
|
4018
|
+
const result = await resolveWeChatIngress({
|
|
4019
|
+
resolve: core.channel.inbound?.ingress?.resolveStable ?? resolveStableChannelMessageIngress3,
|
|
4020
|
+
cfg,
|
|
4021
|
+
accountId: account.accountId,
|
|
4022
|
+
policy: resolveWeChatPolicyContext({ account, cfg, chatId: conversation }),
|
|
4023
|
+
isGroup: conversation.endsWith("@chatroom"),
|
|
4024
|
+
chatId: conversation,
|
|
4025
|
+
senderId: requester,
|
|
4026
|
+
readStoreAllowFrom: async () => core.channel.pairing.readAllowFromStore({ channel: "agent-wechat", accountId: account.accountId, env: process.env }).catch(() => [])
|
|
4027
|
+
});
|
|
4028
|
+
guard2();
|
|
4029
|
+
if (result.ingress.admission !== "dispatch") throw Error("WeChat conversation access is no longer allowed");
|
|
4030
|
+
};
|
|
4031
|
+
await authorize();
|
|
4032
|
+
const { native } = guard2();
|
|
4033
|
+
const { client } = await (dependencies.host ?? ensureNativeHost)(native);
|
|
4034
|
+
await authorize();
|
|
4035
|
+
let intent;
|
|
4036
|
+
try {
|
|
4037
|
+
intent = await client.sendShare(native.accountId, request, key, signal);
|
|
4038
|
+
} catch (error) {
|
|
4039
|
+
if (!(error instanceof NativeApiError) || error.status >= 500 || error.code === "timeout") {
|
|
4040
|
+
const details2 = { threadId: conversation, idempotencyKey: key, state: "submission_unknown", note: "Inspect the send by this idempotency key. Do not resend with a new key." };
|
|
4041
|
+
return { content: [{ type: "text", text: JSON.stringify(details2) }], details: details2, isError: true };
|
|
4042
|
+
}
|
|
4043
|
+
throw error;
|
|
4044
|
+
}
|
|
4045
|
+
if (intent.accountId !== native.accountId || intent.destination !== conversation || !intent.id) throw Error("Share receipt crosses an account or conversation boundary; inspect the original idempotency key before another send");
|
|
4046
|
+
const delivery = intent.state === "accepted" && intent.localMessageId && intent.serverId ? await nativeOutboundDelivery(client, native.accountId, conversation, [intent.localMessageId], { sendId: intent.id, state: intent.state, serverIds: [intent.serverId] }) : void 0;
|
|
4047
|
+
const details = {
|
|
4048
|
+
id: intent.id,
|
|
4049
|
+
threadId: conversation,
|
|
4050
|
+
idempotencyKey: key,
|
|
4051
|
+
state: intent.state,
|
|
4052
|
+
serverId: intent.serverId,
|
|
4053
|
+
messageId: delivery?.messageId || void 0,
|
|
4054
|
+
receiptState: delivery?.meta.receiptState,
|
|
4055
|
+
reason: intent.errorCode,
|
|
4056
|
+
note: ["accepted", "sent", "server_accepted"].includes(intent.state) ? "Server accepted; recipient rendering is not confirmed." : "Inspect this send ID or reuse the identical request/key. Do not send again with a new key."
|
|
4057
|
+
};
|
|
4058
|
+
return { content: [{ type: "text", text: JSON.stringify(details) }], details, isError: ["failed", "needs_review", "cancelled"].includes(intent.state) };
|
|
4059
|
+
}
|
|
4060
|
+
}];
|
|
4061
|
+
}
|
|
4062
|
+
function registerNativeShareTools(api) {
|
|
4063
|
+
api.registerTool({ contextVersion: 2, create: (context) => createNativeShareTools(context) }, { names: [name] });
|
|
4064
|
+
}
|
|
4065
|
+
|
|
4066
|
+
// src/native-recall-tools.ts
|
|
4067
|
+
import { createHash as createHash10 } from "node:crypto";
|
|
4068
|
+
import { resolveStableChannelMessageIngress as resolveStableChannelMessageIngress4 } from "openclaw/plugin-sdk/channel-ingress-runtime";
|
|
4069
|
+
var names2 = ["wechat_recall"];
|
|
4070
|
+
function text2(value, label) {
|
|
4071
|
+
if (typeof value !== "string" || !value.trim() || value.length > 4096 || /[\u0000-\u001f\u007f]/.test(value)) throw Error(`Invalid ${label}`);
|
|
4072
|
+
return value.trim();
|
|
4073
|
+
}
|
|
4074
|
+
function thread2(value) {
|
|
4075
|
+
return text2(text2(value, "conversation").replace(/^(?:agent-)?wechat:(?:group:)?/i, ""), "conversation");
|
|
4076
|
+
}
|
|
4077
|
+
function nativeRecallKey(accountId, threadId2, messageId, serverId) {
|
|
4078
|
+
return `openclaw-recall-${createHash10("sha256").update(JSON.stringify([accountId, threadId2, messageId, serverId])).digest("hex")}`;
|
|
4079
|
+
}
|
|
4080
|
+
function createNativeRecallTools(context, dependencies = {}) {
|
|
4081
|
+
const currentConfig = () => context.getRuntimeConfig?.() ?? context.runtimeConfig ?? context.config;
|
|
4082
|
+
if (!currentConfig()) return [];
|
|
4083
|
+
const selected = resolveWeChatAccount(currentConfig());
|
|
4084
|
+
if (!selected?.enabled || !selected.native || context.messageChannel !== "agent-wechat" || context.agentAccountId && context.agentAccountId !== selected.accountId || context.deliveryContext?.channel === "agent-wechat" && context.deliveryContext.accountId && context.deliveryContext.accountId !== selected.accountId) return [];
|
|
4085
|
+
let conversation, requester;
|
|
4086
|
+
try {
|
|
4087
|
+
const nativeThread = context.nativeChannelId ? thread2(context.nativeChannelId) : void 0;
|
|
4088
|
+
const delivered = context.deliveryContext?.channel === "agent-wechat" && context.deliveryContext.to ? thread2(context.deliveryContext.to) : void 0;
|
|
4089
|
+
if (nativeThread && delivered && nativeThread !== delivered) return [];
|
|
4090
|
+
conversation = text2(nativeThread ?? delivered, "conversation");
|
|
4091
|
+
requester = text2(context.requesterSenderId, "requester");
|
|
4092
|
+
} catch {
|
|
4093
|
+
return [];
|
|
4094
|
+
}
|
|
4095
|
+
const accountId = selected.native.accountId;
|
|
4096
|
+
const configurationKey = nativeConfigurationKey(selected.native);
|
|
4097
|
+
return [{
|
|
4098
|
+
name: names2[0],
|
|
4099
|
+
label: "WeChat Recall",
|
|
4100
|
+
description: "Recall one own sent message in the current WeChat conversation by its exact opaque message ID from a verified send receipt or wechat_history, or inspect a retained recalled placeholder without another native mutation. The daemon checks eligibility. Returns the durable operation and confirmed, rejected, pending or uncertain result. Never invent IDs or resubmit an uncertain action with a new key; prior model input and completed actions cannot be erased.",
|
|
4101
|
+
parameters: { type: "object", additionalProperties: false, properties: {
|
|
4102
|
+
messageId: { type: "string", minLength: 1, maxLength: 4096, description: "Exact stored message ID in this conversation; send/job/operation IDs are not message IDs." },
|
|
4103
|
+
serverId: { type: "string", pattern: "^[1-9][0-9]{0,19}$", description: "Exact decimal server ID from the same verified receipt or history entry. The stored local message ID alone may be reused." }
|
|
4104
|
+
}, required: ["messageId", "serverId"] },
|
|
4105
|
+
execute: async (_callId, input, signal) => {
|
|
4106
|
+
if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((key2) => !["messageId", "serverId"].includes(key2))) throw Error("Recall is restricted to a message ID in the current conversation");
|
|
4107
|
+
const messageId = text2(input.messageId, "message ID");
|
|
4108
|
+
const serverId = text2(input.serverId, "server ID");
|
|
4109
|
+
if (!/^[1-9]\d{0,19}$/.test(serverId) || BigInt(serverId) > 18446744073709551615n) throw Error("Invalid exact server message ID");
|
|
4110
|
+
const guard2 = () => {
|
|
4111
|
+
signal?.throwIfAborted();
|
|
4112
|
+
context.assertInvocationCurrent?.();
|
|
4113
|
+
const cfg = currentConfig(), account = resolveWeChatAccount(cfg);
|
|
4114
|
+
if (!account?.enabled || !account.native || account.accountId !== selected.accountId || account.native.accountId !== accountId || nativeConfigurationKey(account.native) !== configurationKey) throw Error("WeChat account configuration changed; start a new turn");
|
|
4115
|
+
return { cfg, account, native: account.native };
|
|
4116
|
+
};
|
|
4117
|
+
const allowed = async () => {
|
|
4118
|
+
const { cfg, account } = guard2();
|
|
4119
|
+
const core = dependencies.core ?? getWeChatRuntime();
|
|
4120
|
+
const ingress = await resolveWeChatIngress({
|
|
4121
|
+
resolve: core.channel.inbound?.ingress?.resolveStable ?? resolveStableChannelMessageIngress4,
|
|
4122
|
+
cfg,
|
|
4123
|
+
accountId: account.accountId,
|
|
4124
|
+
policy: resolveWeChatPolicyContext({ account, cfg, chatId: conversation }),
|
|
4125
|
+
isGroup: conversation.endsWith("@chatroom"),
|
|
4126
|
+
chatId: conversation,
|
|
4127
|
+
senderId: requester,
|
|
4128
|
+
readStoreAllowFrom: async () => core.channel.pairing.readAllowFromStore({ channel: "agent-wechat", accountId: account.accountId, env: process.env }).catch(() => [])
|
|
4129
|
+
});
|
|
4130
|
+
guard2();
|
|
4131
|
+
if (ingress.ingress.admission !== "dispatch") throw Error("WeChat conversation access is no longer allowed");
|
|
4132
|
+
};
|
|
4133
|
+
await allowed();
|
|
4134
|
+
const { native } = guard2();
|
|
4135
|
+
const { client } = await (dependencies.host ?? ensureNativeHost)(native);
|
|
4136
|
+
guard2();
|
|
4137
|
+
const message = await client.message(accountId, messageId);
|
|
4138
|
+
guard2();
|
|
4139
|
+
const retainedRecall = !!nativeRecallInfo(message);
|
|
4140
|
+
if (message.id !== messageId || message.accountId !== accountId || message.threadId !== conversation || message.direction !== "outgoing" && !retainedRecall) throw Error("Recall target is outside this conversation or was not sent by this account");
|
|
4141
|
+
if (message.serverId !== serverId) throw Error("The exact server identity does not match this receipt; the local message identity may have been reused");
|
|
4142
|
+
await allowed();
|
|
4143
|
+
guard2();
|
|
4144
|
+
const key = nativeRecallKey(accountId, conversation, messageId, serverId);
|
|
4145
|
+
let operation;
|
|
4146
|
+
let operationId;
|
|
4147
|
+
const result = (status2, extra = {}) => {
|
|
4148
|
+
const details = {
|
|
4149
|
+
messageId,
|
|
4150
|
+
serverId,
|
|
4151
|
+
threadId: conversation,
|
|
4152
|
+
accountId,
|
|
4153
|
+
action: retainedRecall ? "inspect_recalled" : "recall",
|
|
4154
|
+
idempotencyKey: key,
|
|
4155
|
+
operationId,
|
|
4156
|
+
operationState: operation?.state,
|
|
4157
|
+
status: status2,
|
|
4158
|
+
retryable: false,
|
|
4159
|
+
...extra
|
|
4160
|
+
};
|
|
4161
|
+
return { content: [{ type: "text", text: JSON.stringify(details) }], details };
|
|
4162
|
+
};
|
|
4163
|
+
try {
|
|
4164
|
+
operation = await client.recallMessage(accountId, messageId, serverId, key, signal);
|
|
4165
|
+
const checkOperation = (candidate) => {
|
|
4166
|
+
if (!candidate || typeof candidate.id !== "string" || !candidate.id || operationId && candidate.id !== operationId || candidate.accountId !== accountId || candidate.kind !== "message_recall") throw Error("Recall operation identity is invalid");
|
|
4167
|
+
};
|
|
4168
|
+
checkOperation(operation);
|
|
4169
|
+
operationId = operation.id;
|
|
4170
|
+
const deadline = Date.now() + Math.max(0, Math.min(dependencies.waitMs ?? 2e3, 1e4));
|
|
4171
|
+
while (["queued", "running", "submitting"].includes(operation.state) && Date.now() < deadline) {
|
|
4172
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(250, deadline - Date.now())));
|
|
4173
|
+
guard2();
|
|
4174
|
+
const remaining = Math.max(1, deadline - Date.now());
|
|
4175
|
+
const next = await client.operation(accountId, operation.id, signal ? AbortSignal.any([signal, AbortSignal.timeout(remaining)]) : AbortSignal.timeout(remaining));
|
|
4176
|
+
checkOperation(next);
|
|
4177
|
+
operation = next;
|
|
4178
|
+
}
|
|
4179
|
+
guard2();
|
|
4180
|
+
} catch (error) {
|
|
4181
|
+
const reason = error instanceof NativeApiError ? error.code : "recall_result_unavailable";
|
|
4182
|
+
return result("needs_review", { reason, note: "Inspect the existing operation or repeat only this same message with the same idempotency key. No automatic second submission was made." });
|
|
4183
|
+
}
|
|
4184
|
+
const receipt = operation.result && typeof operation.result === "object" ? operation.result : {};
|
|
4185
|
+
if (receipt.messageId !== void 0 && receipt.messageId !== messageId || receipt.threadId !== void 0 && receipt.threadId !== conversation || receipt.serverId !== void 0 && receipt.serverId !== serverId) throw Error("Recall operation target identity is invalid");
|
|
4186
|
+
const exactReceipt = receipt.messageId === messageId && receipt.threadId === conversation && receipt.serverId === serverId;
|
|
4187
|
+
const status = operation.state === "succeeded" && exactReceipt && ["recalled", "already_recalled"].includes(String(receipt.status)) ? String(receipt.status) : ["queued", "running", "submitting"].includes(operation.state) ? "pending" : operation.state === "failed" && exactReceipt && ["not_self", "not_eligible", "unavailable", "not_found"].includes(String(receipt.status)) ? String(receipt.status) : "needs_review";
|
|
4188
|
+
const boundedState = (value) => typeof value === "string" && /^[a-z0-9_]{1,80}$/.test(value) ? value : void 0;
|
|
4189
|
+
return result(status, {
|
|
4190
|
+
remoteOutcome: boundedState(receipt.remoteOutcome),
|
|
4191
|
+
profileProjection: boundedState(receipt.profileProjection),
|
|
4192
|
+
note: status === "pending" || status === "needs_review" ? "Inspect this durable operation; do not automatically submit a replacement recall." : void 0
|
|
4193
|
+
});
|
|
4194
|
+
}
|
|
4195
|
+
}];
|
|
4196
|
+
}
|
|
4197
|
+
function registerNativeRecallTools(api) {
|
|
4198
|
+
api.registerTool({ contextVersion: 2, create: (context) => createNativeRecallTools(context) }, { names: names2 });
|
|
4199
|
+
}
|
|
4200
|
+
|
|
4201
|
+
// src/native-group-tool.ts
|
|
4202
|
+
var name2 = "wechat_group_info";
|
|
4203
|
+
function createNativeGroupTools(context, dependencies = {}) {
|
|
4204
|
+
if (context.senderIsOwner !== true || typeof context.assertInvocationCurrent !== "function") return [];
|
|
4205
|
+
const currentConfig = () => context.getRuntimeConfig?.() ?? context.runtimeConfig ?? context.config;
|
|
4206
|
+
const selected = resolveWeChatAccount(currentConfig());
|
|
4207
|
+
if (!selected?.enabled || !selected.native || context.agentAccountId && context.agentAccountId !== selected.accountId || context.deliveryContext?.channel === "agent-wechat" && context.deliveryContext.accountId && context.deliveryContext.accountId !== selected.accountId) return [];
|
|
4208
|
+
const accountId = selected.native.accountId;
|
|
4209
|
+
const configurationKey = nativeConfigurationKey(selected.native);
|
|
4210
|
+
return [{
|
|
4211
|
+
name: name2,
|
|
4212
|
+
label: "WeChat Group Info",
|
|
4213
|
+
description: "Read cached group information and one page of members for the configured WeChat account. Available only to the trusted OpenClaw owner. Does not create groups, invite people or change settings. Cached member absence does not prove non-membership.",
|
|
4214
|
+
parameters: { type: "object", additionalProperties: false, properties: {
|
|
4215
|
+
groupId: { type: "string", minLength: 10, maxLength: 256, description: "Exact ordinary group username ending in @chatroom." },
|
|
4216
|
+
limit: { type: "integer", minimum: 1, maximum: 100 },
|
|
4217
|
+
cursor: { type: "string", maxLength: 8192 },
|
|
4218
|
+
username: { type: "string", minLength: 1, maxLength: 256, description: "Optionally inspect one exact member instead of listing a page." }
|
|
4219
|
+
}, required: ["groupId"] },
|
|
4220
|
+
execute: async (_callId, input, signal) => {
|
|
4221
|
+
if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((k) => !["groupId", "limit", "cursor", "username"].includes(k))) throw Error("Invalid group info request");
|
|
4222
|
+
const args = input;
|
|
4223
|
+
const identity = (value) => typeof value === "string" && value.length > 0 && value.length <= 256 && !/[\s\u0000-\u001f\u007f]/u.test(value);
|
|
4224
|
+
if (!identity(args.groupId) || !args.groupId.endsWith("@chatroom") || args.groupId.length <= 9 || args.limit != null && (!Number.isInteger(args.limit) || Number(args.limit) < 1 || Number(args.limit) > 100) || args.cursor != null && (typeof args.cursor !== "string" || args.cursor.length > 8192) || args.username != null && !identity(args.username) || args.username != null && (args.limit != null || args.cursor != null)) throw Error("Invalid group info selectors");
|
|
4225
|
+
const guard2 = () => {
|
|
4226
|
+
signal?.throwIfAborted();
|
|
4227
|
+
if (context.senderIsOwner !== true) throw Error("OpenClaw owner authorization is required");
|
|
4228
|
+
context.assertInvocationCurrent();
|
|
4229
|
+
const account = resolveWeChatAccount(currentConfig());
|
|
4230
|
+
if (!account?.enabled || !account.native || account.accountId !== selected.accountId || account.native.accountId !== accountId || nativeConfigurationKey(account.native) !== configurationKey) throw Error("WeChat account configuration changed; start a new turn");
|
|
4231
|
+
return account.native;
|
|
4232
|
+
};
|
|
4233
|
+
const native = guard2();
|
|
4234
|
+
const { client } = await (dependencies.host ?? ensureNativeHost)(native);
|
|
4235
|
+
guard2();
|
|
4236
|
+
const group = await client.group(accountId, args.groupId, signal);
|
|
4237
|
+
guard2();
|
|
4238
|
+
if (group.id !== args.groupId || group.roomId !== args.groupId) throw Error("Group identity is invalid");
|
|
4239
|
+
const members = typeof args.username === "string" ? await client.groupMember(accountId, args.groupId, args.username, signal) : await client.groupMembers(accountId, args.groupId, { limit: args.limit == null ? 50 : Number(args.limit), cursor: args.cursor }, signal);
|
|
4240
|
+
guard2();
|
|
4241
|
+
const details = { accountId, group, members, source: "cached", membershipAbsence: "unconfirmed" };
|
|
4242
|
+
return { content: [{ type: "text", text: JSON.stringify(details) }], details };
|
|
4243
|
+
}
|
|
4244
|
+
}];
|
|
4245
|
+
}
|
|
4246
|
+
function registerNativeGroupTools(api) {
|
|
4247
|
+
api.registerTool({ contextVersion: 2, create: (context) => createNativeGroupTools(context) }, { names: [name2] });
|
|
4248
|
+
}
|
|
4249
|
+
|
|
2313
4250
|
// index.ts
|
|
2314
4251
|
var plugin = {
|
|
2315
4252
|
id: "agent-wechat",
|
|
@@ -2320,9 +4257,15 @@ var plugin = {
|
|
|
2320
4257
|
setWeChatRuntime(api.runtime);
|
|
2321
4258
|
const selected = resolveWeChatAccount(api.config);
|
|
2322
4259
|
api.registerChannel({ plugin: wechatPlugin });
|
|
4260
|
+
registerNativeHistoryTools(api);
|
|
4261
|
+
registerNativeShareTools(api);
|
|
4262
|
+
registerNativeRecallTools(api);
|
|
4263
|
+
registerNativeGroupTools(api);
|
|
4264
|
+
registerNativeLoginTool(api);
|
|
2323
4265
|
const stopFacade = selected?.native ? registerNativeFacade(api, selected.native) : () => {
|
|
2324
4266
|
};
|
|
2325
|
-
const stopPreparedBoundary = registerNativePreparedBoundary(api)
|
|
4267
|
+
const stopPreparedBoundary = selected?.native?.readPolicy && selected.native.readPolicy !== "on_inbound" ? registerNativePreparedBoundary(api) : () => {
|
|
4268
|
+
};
|
|
2326
4269
|
api.registerService({
|
|
2327
4270
|
id: "agent-wechat-native",
|
|
2328
4271
|
reload: { configPrefixes: ["plugins.entries.agent-wechat.config", "channels.agent-wechat", "secrets"] },
|