@agent-wechat/agent-wechat 1.3.2 → 1.4.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -2
- package/dist/index.js +1483 -44
- package/openclaw.plugin.json +356 -6
- package/package.json +163 -3
package/dist/index.js
CHANGED
|
@@ -1,3 +1,112 @@
|
|
|
1
|
+
// src/calls-secrets.ts
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { resolveConfiguredSecretInputString } from "openclaw/plugin-sdk/secret-input-runtime";
|
|
4
|
+
var secrets = /* @__PURE__ */ new WeakMap();
|
|
5
|
+
function bindCallVoiceSecret(config, value) {
|
|
6
|
+
secrets.set(config, value);
|
|
7
|
+
return config;
|
|
8
|
+
}
|
|
9
|
+
function callsConfigurationKey(config) {
|
|
10
|
+
return createHash("sha256").update(JSON.stringify([config, config.voice && secrets.get(config.voice)])).digest("hex");
|
|
11
|
+
}
|
|
12
|
+
async function resolveCallVoiceApiKey(config, cfg, env = process.env) {
|
|
13
|
+
const value = secrets.get(config);
|
|
14
|
+
if (value === void 0) return void 0;
|
|
15
|
+
try {
|
|
16
|
+
const resolved = await resolveConfiguredSecretInputString({
|
|
17
|
+
config: cfg ?? {},
|
|
18
|
+
env,
|
|
19
|
+
value,
|
|
20
|
+
path: "calls.voice.realtime.providers.openai.apiKey",
|
|
21
|
+
unresolvedReasonStyle: "generic"
|
|
22
|
+
});
|
|
23
|
+
if (resolved.unresolvedRefReason || !resolved.value || resolved.value.length > 8192 || !/^[\x21-\x7e]+$/.test(resolved.value)) throw Error("unresolved");
|
|
24
|
+
return resolved.value;
|
|
25
|
+
} catch {
|
|
26
|
+
throw Error("Calling OpenAI API key could not be resolved; check OpenClaw secret configuration");
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// src/calls-config.ts
|
|
31
|
+
var identifier = (value) => typeof value === "string" && value.length > 0 && value.length <= 200 && !/[\u0000-\u001f\u007f]/.test(value);
|
|
32
|
+
var object = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
33
|
+
function names(value) {
|
|
34
|
+
if (value === void 0) return [];
|
|
35
|
+
if (!Array.isArray(value) || value.length > 128 || value.some((name3) => !identifier(name3) || name3 === "*")) throw Error("Invalid calling allowlist");
|
|
36
|
+
return [...new Set(value)];
|
|
37
|
+
}
|
|
38
|
+
function voiceConfig(value) {
|
|
39
|
+
if (!value || value.enabled !== true) return void 0;
|
|
40
|
+
const realtime = value.realtime;
|
|
41
|
+
const consultation = value.consultation ?? {};
|
|
42
|
+
if (!object(realtime) || !identifier(realtime.provider) || !identifier(value.agentId) || ![void 0, "disabled", "allowlist"].includes(value.inboundPolicy) || ![void 0, "disabled", "allowlist"].includes(value.outboundPolicy) || ![void 0, "none", "safe-read-only"].includes(value.toolPolicy) || [realtime.model, realtime.voice, consultation.model].some((item) => item !== void 0 && !identifier(item)) || consultation.model !== void 0 && !/^[^/]+\/.+$/.test(consultation.model) || realtime.instructions !== void 0 && (typeof realtime.instructions !== "string" || realtime.instructions.length > 4e3 || /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(realtime.instructions))) throw Error("Invalid calling configuration");
|
|
43
|
+
const maxDurationSeconds = value.maxDurationSeconds ?? 300;
|
|
44
|
+
const timeoutMs = consultation.timeoutMs ?? 3e4;
|
|
45
|
+
if (!Number.isInteger(maxDurationSeconds) || maxDurationSeconds < 30 || maxDurationSeconds > 3600) throw Error("Invalid calling duration");
|
|
46
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1e3 || timeoutMs > 12e4) throw Error("Invalid calling consultation timeout");
|
|
47
|
+
if (value.toolPolicy === "safe-read-only" && value.allowConsultSessionPersistence !== true) throw Error("Calling consultation requires opting in to host session persistence");
|
|
48
|
+
return bindCallVoiceSecret({
|
|
49
|
+
enabled: true,
|
|
50
|
+
inboundPolicy: value.inboundPolicy ?? "disabled",
|
|
51
|
+
inboundAllowFrom: names(value.inboundAllowFrom),
|
|
52
|
+
outboundPolicy: value.outboundPolicy ?? "disabled",
|
|
53
|
+
outboundAllowTo: names(value.outboundAllowTo),
|
|
54
|
+
outboundToolAllowFrom: names(value.outboundToolAllowFrom),
|
|
55
|
+
agentId: value.agentId,
|
|
56
|
+
realtime: { provider: realtime.provider, model: realtime.model, voice: realtime.voice, instructions: realtime.instructions },
|
|
57
|
+
toolPolicy: value.toolPolicy ?? "none",
|
|
58
|
+
allowConsultSessionPersistence: value.allowConsultSessionPersistence === true,
|
|
59
|
+
consultation: { model: consultation.model, timeoutMs },
|
|
60
|
+
maxDurationSeconds
|
|
61
|
+
}, realtime.providers?.openai?.apiKey);
|
|
62
|
+
}
|
|
63
|
+
function resolveWeChatCallsConfig(value) {
|
|
64
|
+
if (!value) return void 0;
|
|
65
|
+
if (!object(value) || Object.keys(value).some((key) => !["voice", "video"].includes(key)) || [value.voice, value.video].some((item) => item !== void 0 && (!object(item) || item.enabled !== void 0 && typeof item.enabled !== "boolean"))) throw Error("Invalid calling configuration; use calls.voice.enabled and calls.video.enabled");
|
|
66
|
+
const voice = voiceConfig(value.voice);
|
|
67
|
+
const video = { enabled: value.video?.enabled === true };
|
|
68
|
+
return voice || video.enabled ? { voice, video } : void 0;
|
|
69
|
+
}
|
|
70
|
+
var nameSchema = { type: "string", minLength: 1, maxLength: 200 };
|
|
71
|
+
var allowlistSchema = { type: "array", maxItems: 128, items: nameSchema };
|
|
72
|
+
var callsConfigSchema = {
|
|
73
|
+
type: "object",
|
|
74
|
+
additionalProperties: false,
|
|
75
|
+
description: "Independent voice and video permissions. Both default off; the current backend supports direct voice only.",
|
|
76
|
+
properties: {
|
|
77
|
+
voice: { type: "object", additionalProperties: false, properties: {
|
|
78
|
+
enabled: { type: "boolean", default: false, description: "Enable direct voice calling. Disabled voice calls are ignored without answering or declining." },
|
|
79
|
+
inboundPolicy: { type: "string", enum: ["disabled", "allowlist"] },
|
|
80
|
+
inboundAllowFrom: allowlistSchema,
|
|
81
|
+
outboundPolicy: { type: "string", enum: ["disabled", "allowlist"] },
|
|
82
|
+
outboundAllowTo: allowlistSchema,
|
|
83
|
+
outboundToolAllowFrom: allowlistSchema,
|
|
84
|
+
agentId: nameSchema,
|
|
85
|
+
realtime: { type: "object", additionalProperties: false, properties: {
|
|
86
|
+
provider: { ...nameSchema, description: "Use openai. Other providers and continuous-output models fail preflight without fallback." },
|
|
87
|
+
model: { ...nameSchema, description: "Realtime speech model; omitted uses the selected provider's default." },
|
|
88
|
+
voice: { ...nameSchema, description: "Spoken voice; omitted uses the selected provider's default." },
|
|
89
|
+
instructions: { type: "string", maxLength: 4e3, description: "Additional conversation guidance; does not grant tool or account-owner authority." },
|
|
90
|
+
providers: { type: "object", additionalProperties: false, properties: {
|
|
91
|
+
openai: { type: "object", additionalProperties: false, properties: {
|
|
92
|
+
apiKey: { description: "Optional OpenClaw SecretRef or API-key string. Omitted uses the selected agent's OpenAI auth profile or Gateway environment." }
|
|
93
|
+
} }
|
|
94
|
+
} }
|
|
95
|
+
} },
|
|
96
|
+
toolPolicy: { type: "string", enum: ["none", "safe-read-only"], default: "none" },
|
|
97
|
+
allowConsultSessionPersistence: { type: "boolean", default: false, description: "Required for safe-read-only consultation: OpenClaw creates a separate per-call agent session which can persist. This adapter does not store transcripts or recordings." },
|
|
98
|
+
consultation: { type: "object", additionalProperties: false, properties: {
|
|
99
|
+
model: { ...nameSchema, pattern: "^[^/]+/.+$", description: "Agent-consult provider/model override; omitted uses the selected agent's model." },
|
|
100
|
+
timeoutMs: { type: "integer", minimum: 1e3, maximum: 12e4, default: 3e4 }
|
|
101
|
+
} },
|
|
102
|
+
maxDurationSeconds: { type: "integer", minimum: 30, maximum: 3600, default: 300 }
|
|
103
|
+
} },
|
|
104
|
+
video: { type: "object", additionalProperties: false, properties: {
|
|
105
|
+
enabled: { type: "boolean", default: false, description: "Allow video independently of voice. Current video capability is unavailable; permission alone never answers a video call or routes it as voice." }
|
|
106
|
+
} }
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
|
|
1
110
|
// src/native-config.ts
|
|
2
111
|
var nativeConfigSchema = {
|
|
3
112
|
type: "object",
|
|
@@ -29,12 +138,12 @@ var nativeConfigSchema = {
|
|
|
29
138
|
var nativePluginConfigSchema = {
|
|
30
139
|
type: "object",
|
|
31
140
|
additionalProperties: false,
|
|
32
|
-
properties: { backend: { type: "string", enum: ["native"] }, native: nativeConfigSchema }
|
|
141
|
+
properties: { backend: { type: "string", enum: ["native"] }, native: nativeConfigSchema, calls: callsConfigSchema }
|
|
33
142
|
};
|
|
34
143
|
|
|
35
144
|
// src/native-secrets.ts
|
|
36
|
-
import { createHash } from "node:crypto";
|
|
37
|
-
import { resolveConfiguredSecretInputString } from "openclaw/plugin-sdk/secret-input-runtime";
|
|
145
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
146
|
+
import { resolveConfiguredSecretInputString as resolveConfiguredSecretInputString2 } from "openclaw/plugin-sdk/secret-input-runtime";
|
|
38
147
|
var contexts = /* @__PURE__ */ new WeakMap();
|
|
39
148
|
function bindNativeSecretContext(native, config, path) {
|
|
40
149
|
if ("tokenFile" in native) throw new Error("native.tokenFile has been removed; use native.token with an OpenClaw SecretRef or environment reference");
|
|
@@ -43,14 +152,14 @@ function bindNativeSecretContext(native, config, path) {
|
|
|
43
152
|
return copy;
|
|
44
153
|
}
|
|
45
154
|
function nativeConfigurationKey(native) {
|
|
46
|
-
return
|
|
155
|
+
return createHash2("sha256").update(JSON.stringify({ native, providers: contexts.get(native)?.config.secrets })).digest("hex");
|
|
47
156
|
}
|
|
48
157
|
async function resolveNativeToken(native, env = process.env) {
|
|
49
158
|
if ("tokenFile" in native) throw new Error("native.tokenFile has been removed; use native.token with an OpenClaw SecretRef or environment reference");
|
|
50
159
|
const context = contexts.get(native);
|
|
51
160
|
let value;
|
|
52
161
|
try {
|
|
53
|
-
const result = await
|
|
162
|
+
const result = await resolveConfiguredSecretInputString2({
|
|
54
163
|
config: context?.config ?? {},
|
|
55
164
|
env,
|
|
56
165
|
value: native.token,
|
|
@@ -90,6 +199,7 @@ function resolveWeChatAccount(cfg, accountId) {
|
|
|
90
199
|
const serverUrl = native.mode === "external" ? native.endpoint ?? "" : `http://${native.listen ?? "127.0.0.1:6174"}`;
|
|
91
200
|
if (!serverUrl) return null;
|
|
92
201
|
return {
|
|
202
|
+
calls: resolveWeChatCallsConfig(wechat?.calls ?? plugin2?.calls),
|
|
93
203
|
backend: "native",
|
|
94
204
|
native,
|
|
95
205
|
accountId: accountId ?? DEFAULT_ACCOUNT_ID,
|
|
@@ -105,7 +215,7 @@ function resolveWeChatAccount(cfg, accountId) {
|
|
|
105
215
|
}
|
|
106
216
|
|
|
107
217
|
// src/native-host.ts
|
|
108
|
-
import { createHash as
|
|
218
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
109
219
|
import { constants } from "node:fs";
|
|
110
220
|
import { access, lstat, readFile, realpath } from "node:fs/promises";
|
|
111
221
|
import { spawn, execFile } from "node:child_process";
|
|
@@ -113,6 +223,576 @@ import { promisify } from "node:util";
|
|
|
113
223
|
import { delimiter, dirname, isAbsolute, join, toNamespacedPath } from "node:path";
|
|
114
224
|
import { createConnection } from "node:net";
|
|
115
225
|
|
|
226
|
+
// ../shared/dist/native-calls.js
|
|
227
|
+
var NATIVE_CALL_MAX_FRAME_BYTES = 64 * 1024;
|
|
228
|
+
function pcmBytes(format) {
|
|
229
|
+
if (![8e3, 12e3, 16e3, 24e3, 48e3].includes(format.sampleRate) || ![1, 2].includes(format.channels) || ![10, 20, 40, 60].includes(format.frameMs))
|
|
230
|
+
throw new Error("Invalid call PCM format");
|
|
231
|
+
return format.sampleRate * format.frameMs / 1e3 * format.channels * 2;
|
|
232
|
+
}
|
|
233
|
+
var NativeCallError = class extends Error {
|
|
234
|
+
code;
|
|
235
|
+
outcomeUnknown;
|
|
236
|
+
constructor(code, outcomeUnknown = false) {
|
|
237
|
+
super(`Native call operation failed (${code})`);
|
|
238
|
+
this.name = "NativeCallError";
|
|
239
|
+
this.code = code;
|
|
240
|
+
this.outcomeUnknown = outcomeUnknown;
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
function resourceId(value) {
|
|
244
|
+
if (!value || value === "." || value === ".." || value.length > 200 || /[\u0000-\u001f\u007f]/.test(value))
|
|
245
|
+
throw new Error("Invalid call resource ID");
|
|
246
|
+
return encodeURIComponent(value);
|
|
247
|
+
}
|
|
248
|
+
function callSocketUrl(baseUrl, accountId, suffix) {
|
|
249
|
+
const url2 = new URL(`v1/accounts/${resourceId(accountId)}/calls/${suffix}`, validateNativeBaseUrl(baseUrl));
|
|
250
|
+
url2.protocol = url2.protocol === "https:" ? "wss:" : "ws:";
|
|
251
|
+
return url2.toString();
|
|
252
|
+
}
|
|
253
|
+
var EventQueue = class {
|
|
254
|
+
values = [];
|
|
255
|
+
waiter;
|
|
256
|
+
ended = false;
|
|
257
|
+
failure;
|
|
258
|
+
consumed = false;
|
|
259
|
+
limit;
|
|
260
|
+
constructor(limit) {
|
|
261
|
+
this.limit = limit;
|
|
262
|
+
}
|
|
263
|
+
push(value) {
|
|
264
|
+
if (this.ended)
|
|
265
|
+
return false;
|
|
266
|
+
if (this.waiter) {
|
|
267
|
+
const waiter = this.waiter;
|
|
268
|
+
this.waiter = void 0;
|
|
269
|
+
waiter.resolve({ value, done: false });
|
|
270
|
+
return true;
|
|
271
|
+
}
|
|
272
|
+
if (this.values.length >= this.limit)
|
|
273
|
+
return false;
|
|
274
|
+
this.values.push(value);
|
|
275
|
+
return true;
|
|
276
|
+
}
|
|
277
|
+
clear() {
|
|
278
|
+
this.values = [];
|
|
279
|
+
}
|
|
280
|
+
close(failure) {
|
|
281
|
+
this.ended = true;
|
|
282
|
+
this.failure = failure;
|
|
283
|
+
this.values = [];
|
|
284
|
+
if (this.waiter) {
|
|
285
|
+
const waiter = this.waiter;
|
|
286
|
+
this.waiter = void 0;
|
|
287
|
+
if (failure)
|
|
288
|
+
waiter.reject(failure);
|
|
289
|
+
else
|
|
290
|
+
waiter.resolve({ value: void 0, done: true });
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
[Symbol.asyncIterator]() {
|
|
294
|
+
if (this.consumed)
|
|
295
|
+
throw new Error("Call event stream already has a consumer");
|
|
296
|
+
this.consumed = true;
|
|
297
|
+
return { next: () => {
|
|
298
|
+
const value = this.values.shift();
|
|
299
|
+
if (value !== void 0)
|
|
300
|
+
return Promise.resolve({ value, done: false });
|
|
301
|
+
if (this.failure)
|
|
302
|
+
return Promise.reject(this.failure);
|
|
303
|
+
if (this.ended)
|
|
304
|
+
return Promise.resolve({ value: void 0, done: true });
|
|
305
|
+
if (this.waiter)
|
|
306
|
+
return Promise.reject(new Error("Concurrent call event reads are unsupported"));
|
|
307
|
+
return new Promise((resolve, reject) => {
|
|
308
|
+
this.waiter = { resolve, reject };
|
|
309
|
+
});
|
|
310
|
+
} };
|
|
311
|
+
}
|
|
312
|
+
};
|
|
313
|
+
function binaryBytes(value) {
|
|
314
|
+
if (value instanceof Uint8Array)
|
|
315
|
+
return value;
|
|
316
|
+
if (value instanceof ArrayBuffer)
|
|
317
|
+
return new Uint8Array(value);
|
|
318
|
+
return void 0;
|
|
319
|
+
}
|
|
320
|
+
var CONTROL_BYTES = 16 * 1024;
|
|
321
|
+
function object2(value) {
|
|
322
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
323
|
+
}
|
|
324
|
+
function idValue(value) {
|
|
325
|
+
return typeof value === "string" && value.length > 0 && value.length <= 200 && !/[\u0000-\u001f\u007f]/.test(value);
|
|
326
|
+
}
|
|
327
|
+
function uint32(value) {
|
|
328
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 4294967295;
|
|
329
|
+
}
|
|
330
|
+
function formatValue(value) {
|
|
331
|
+
if (!object2(value))
|
|
332
|
+
return false;
|
|
333
|
+
try {
|
|
334
|
+
pcmBytes(value);
|
|
335
|
+
return true;
|
|
336
|
+
} catch {
|
|
337
|
+
return false;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
function trackValue(value) {
|
|
341
|
+
return object2(value) && uint32(value.id) && value.id > 0 && uint32(value.generation) && value.generation > 0 && ["send", "receive"].includes(String(value.direction)) && formatValue(value.format);
|
|
342
|
+
}
|
|
343
|
+
function availabilityValue(value) {
|
|
344
|
+
return object2(value) && typeof value.busy === "boolean" && typeof value.ownedByThisClient === "boolean";
|
|
345
|
+
}
|
|
346
|
+
function participantControlValue(value) {
|
|
347
|
+
return object2(value) && idValue(value.participantId) && object2(value.control) && value.control.kind === "microphone" && typeof value.control.muted === "boolean";
|
|
348
|
+
}
|
|
349
|
+
function callValue(value) {
|
|
350
|
+
return object2(value) && idValue(value.callId) && uint32(value.revision) && ["direct", "conference"].includes(String(value.kind)) && ["voice", "video"].includes(String(value.callType)) && ["incoming", "outgoing"].includes(String(value.direction)) && ["offered", "dialing", "ringing", "connecting", "connected", "ending", "ended", "uncertain"].includes(String(value.state)) && typeof value.ownedByThisClient === "boolean" && (value.controls === void 0 || Array.isArray(value.controls) && value.controls.length <= 16 && value.controls.every(participantControlValue));
|
|
351
|
+
}
|
|
352
|
+
function offerValue(value) {
|
|
353
|
+
return object2(value) && idValue(value.callId) && uint32(value.revision) && idValue(value.callerId) && ["direct", "conference"].includes(String(value.kind)) && ["voice", "video"].includes(String(value.callType));
|
|
354
|
+
}
|
|
355
|
+
function pendingOfferValue(value) {
|
|
356
|
+
return offerValue(value) && object2(value) && ["waiting_for_ready", "preparing"].includes(String(value.phase));
|
|
357
|
+
}
|
|
358
|
+
function errorCode(value) {
|
|
359
|
+
return typeof value === "string" && ["invalid_request", "busy", "already_claimed", "offer_expired", "not_owner", "unsupported", "media_not_ready", "outcome_unknown", "capacity", "stale", "forbidden", "closed"].includes(value);
|
|
360
|
+
}
|
|
361
|
+
function parseCallEvent(data) {
|
|
362
|
+
if (typeof data !== "string" || new TextEncoder().encode(data).byteLength > CONTROL_BYTES)
|
|
363
|
+
throw new NativeCallError("invalid_event");
|
|
364
|
+
let value;
|
|
365
|
+
try {
|
|
366
|
+
value = JSON.parse(data);
|
|
367
|
+
} catch {
|
|
368
|
+
throw new NativeCallError("invalid_event");
|
|
369
|
+
}
|
|
370
|
+
if (!object2(value))
|
|
371
|
+
throw new NativeCallError("invalid_event");
|
|
372
|
+
let valid = false;
|
|
373
|
+
switch (value.type) {
|
|
374
|
+
case "hello":
|
|
375
|
+
if (value.currentPendingOffer === void 0)
|
|
376
|
+
value.currentPendingOffer = null;
|
|
377
|
+
valid = value.protocolVersion === 1 && idValue(value.clientId) && object2(value.capabilities) && Object.entries(value.capabilities).every(([key, enabled2]) => idValue(key) && typeof enabled2 === "boolean") && availabilityValue(value.availability) && (value.currentOffer === null || offerValue(value.currentOffer)) && (value.currentPendingOffer === null || pendingOfferValue(value.currentPendingOffer)) && (value.currentCall === null || callValue(value.currentCall)) && formatValue(value.audioFormat);
|
|
378
|
+
break;
|
|
379
|
+
case "command.result":
|
|
380
|
+
valid = idValue(value.requestId) && ["accepted", "replayed", "error"].includes(String(value.status)) && (value.callId === null || idValue(value.callId)) && (value.ownerToken === null || idValue(value.ownerToken)) && (value.code === null || errorCode(value.code));
|
|
381
|
+
break;
|
|
382
|
+
case "call.offered":
|
|
383
|
+
valid = offerValue(value.offer);
|
|
384
|
+
break;
|
|
385
|
+
case "call.pending":
|
|
386
|
+
valid = value.offer === null || pendingOfferValue(value.offer);
|
|
387
|
+
break;
|
|
388
|
+
case "call.state":
|
|
389
|
+
valid = callValue(value.call);
|
|
390
|
+
break;
|
|
391
|
+
case "call.control":
|
|
392
|
+
valid = idValue(value.callId) && participantControlValue(value);
|
|
393
|
+
break;
|
|
394
|
+
case "calls.availability":
|
|
395
|
+
valid = availabilityValue(value.availability);
|
|
396
|
+
break;
|
|
397
|
+
case "track.added":
|
|
398
|
+
case "track.updated":
|
|
399
|
+
valid = idValue(value.callId) && trackValue(value.track);
|
|
400
|
+
break;
|
|
401
|
+
case "media.ready":
|
|
402
|
+
valid = trackValue(value.sendTrack) && trackValue(value.receiveTrack) && value.sendTrack.direction === "send" && value.receiveTrack.direction === "receive" && value.sendTrack.id !== value.receiveTrack.id;
|
|
403
|
+
break;
|
|
404
|
+
case "call.error":
|
|
405
|
+
valid = errorCode(value.code);
|
|
406
|
+
break;
|
|
407
|
+
}
|
|
408
|
+
if (!valid)
|
|
409
|
+
throw new NativeCallError("invalid_event");
|
|
410
|
+
return value;
|
|
411
|
+
}
|
|
412
|
+
var NativeCallsClient = class {
|
|
413
|
+
options;
|
|
414
|
+
queue;
|
|
415
|
+
pending = /* @__PURE__ */ new Map();
|
|
416
|
+
socket;
|
|
417
|
+
opening;
|
|
418
|
+
openResolve;
|
|
419
|
+
openReject;
|
|
420
|
+
handshakeTimer;
|
|
421
|
+
hello;
|
|
422
|
+
closed = false;
|
|
423
|
+
owner;
|
|
424
|
+
media = /* @__PURE__ */ new Map();
|
|
425
|
+
constructor(options) {
|
|
426
|
+
const url2 = validateNativeBaseUrl(options.baseUrl);
|
|
427
|
+
const env = globalThis.process?.env;
|
|
428
|
+
if (url2.protocol === "https:" && env?.NODE_TLS_REJECT_UNAUTHORIZED === "0")
|
|
429
|
+
throw new Error("Call API requires TLS verification");
|
|
430
|
+
if (typeof options.token !== "string" || !options.token || /[\r\n]/.test(options.token))
|
|
431
|
+
throw new Error("Call API bearer token is required");
|
|
432
|
+
resourceId(options.accountId);
|
|
433
|
+
for (const value of [options.handshakeTimeoutMs ?? 1e4, options.commandTimeoutMs ?? 3e4])
|
|
434
|
+
if (!Number.isInteger(value) || value < 1 || value > 3e5)
|
|
435
|
+
throw new Error("Invalid call timeout");
|
|
436
|
+
const maxEvents = options.maxEvents ?? 64;
|
|
437
|
+
const maxBufferedBytes = options.maxBufferedBytes ?? 64 * 1024;
|
|
438
|
+
if (!Number.isInteger(maxEvents) || maxEvents < 1 || maxEvents > 256 || !Number.isInteger(maxBufferedBytes) || maxBufferedBytes < 1024 || maxBufferedBytes > 1024 * 1024)
|
|
439
|
+
throw new Error("Invalid call queue bound");
|
|
440
|
+
this.options = { ...options, maxEvents, maxBufferedBytes };
|
|
441
|
+
this.queue = new EventQueue(maxEvents);
|
|
442
|
+
}
|
|
443
|
+
connect() {
|
|
444
|
+
if (this.closed)
|
|
445
|
+
return Promise.reject(new NativeCallError("closed"));
|
|
446
|
+
if (this.opening)
|
|
447
|
+
return this.opening;
|
|
448
|
+
this.opening = new Promise((resolve, reject) => {
|
|
449
|
+
this.openResolve = resolve;
|
|
450
|
+
this.openReject = reject;
|
|
451
|
+
});
|
|
452
|
+
this.handshakeTimer = setTimeout(() => this.fail(new NativeCallError("handshake_timeout")), this.options.handshakeTimeoutMs ?? 1e4);
|
|
453
|
+
try {
|
|
454
|
+
const socket = this.options.webSocketFactory(callSocketUrl(this.options.baseUrl, this.options.accountId, "socket"), { headers: { Authorization: `Bearer ${this.options.token}` }, maxPayload: CONTROL_BYTES });
|
|
455
|
+
this.socket = socket;
|
|
456
|
+
socket.binaryType = "arraybuffer";
|
|
457
|
+
socket.onmessage = (event) => {
|
|
458
|
+
try {
|
|
459
|
+
this.receive(parseCallEvent(event.data));
|
|
460
|
+
} catch {
|
|
461
|
+
this.fail(new NativeCallError("invalid_event"));
|
|
462
|
+
}
|
|
463
|
+
};
|
|
464
|
+
socket.onerror = () => this.fail(new NativeCallError("connection_failed", this.pending.size > 0));
|
|
465
|
+
socket.onclose = () => this.fail(new NativeCallError("closed", this.pending.size > 0));
|
|
466
|
+
} catch {
|
|
467
|
+
this.fail(new NativeCallError("connection_failed"));
|
|
468
|
+
}
|
|
469
|
+
return this.opening;
|
|
470
|
+
}
|
|
471
|
+
events() {
|
|
472
|
+
return this.queue;
|
|
473
|
+
}
|
|
474
|
+
receive(event) {
|
|
475
|
+
if (this.closed)
|
|
476
|
+
return;
|
|
477
|
+
if (!this.hello && event.type !== "hello")
|
|
478
|
+
throw new NativeCallError("missing_hello");
|
|
479
|
+
if (event.type === "hello") {
|
|
480
|
+
if (this.hello)
|
|
481
|
+
throw new NativeCallError("duplicate_hello");
|
|
482
|
+
this.hello = event;
|
|
483
|
+
clearTimeout(this.handshakeTimer);
|
|
484
|
+
}
|
|
485
|
+
if (!this.queue.push(event)) {
|
|
486
|
+
this.fail(new NativeCallError("event_backpressure"));
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
if (event.type === "hello") {
|
|
490
|
+
this.openResolve?.(event);
|
|
491
|
+
this.openResolve = void 0;
|
|
492
|
+
this.openReject = void 0;
|
|
493
|
+
}
|
|
494
|
+
if (event.type === "command.result") {
|
|
495
|
+
const pending2 = this.pending.get(event.requestId);
|
|
496
|
+
if (!pending2)
|
|
497
|
+
return;
|
|
498
|
+
clearTimeout(pending2.timer);
|
|
499
|
+
this.pending.delete(event.requestId);
|
|
500
|
+
if (event.status === "error")
|
|
501
|
+
pending2.reject(new NativeCallError(event.code ?? "invalid_request", event.code === "outcome_unknown"));
|
|
502
|
+
else {
|
|
503
|
+
if (event.callId && event.ownerToken)
|
|
504
|
+
this.owner = { callId: event.callId, token: event.ownerToken };
|
|
505
|
+
pending2.resolve(event);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
if (event.type === "track.updated" || event.type === "track.added")
|
|
509
|
+
this.media.get(event.callId)?.updateTrack(event.track);
|
|
510
|
+
if (event.type === "call.state") {
|
|
511
|
+
if (!event.call.ownedByThisClient || ["ended", "uncertain"].includes(event.call.state))
|
|
512
|
+
this.dropMedia(event.call.callId);
|
|
513
|
+
else if (event.call.state === "ending")
|
|
514
|
+
this.media.get(event.call.callId)?.stopAudio();
|
|
515
|
+
}
|
|
516
|
+
if (event.type === "calls.availability" && (!event.availability.busy || !event.availability.ownedByThisClient)) {
|
|
517
|
+
for (const callId of this.media.keys())
|
|
518
|
+
this.dropMedia(callId);
|
|
519
|
+
this.owner = void 0;
|
|
520
|
+
}
|
|
521
|
+
if (event.type === "call.error" && ["forbidden", "closed"].includes(event.code))
|
|
522
|
+
this.fail(new NativeCallError(event.code));
|
|
523
|
+
}
|
|
524
|
+
command(command) {
|
|
525
|
+
if (!this.hello || this.closed || this.socket?.readyState !== 1)
|
|
526
|
+
return Promise.reject(new NativeCallError("not_connected"));
|
|
527
|
+
if (!idValue(command.requestId))
|
|
528
|
+
return Promise.reject(new NativeCallError("invalid_request"));
|
|
529
|
+
const encoded = JSON.stringify(command);
|
|
530
|
+
const encodedBytes = new TextEncoder().encode(encoded).byteLength;
|
|
531
|
+
if (encodedBytes > CONTROL_BYTES)
|
|
532
|
+
return Promise.reject(new NativeCallError("invalid_request"));
|
|
533
|
+
const prior = this.pending.get(command.requestId);
|
|
534
|
+
if (prior)
|
|
535
|
+
return prior.command === encoded ? prior.promise : Promise.reject(new NativeCallError("idempotency_conflict"));
|
|
536
|
+
if (this.pending.size >= 64 || this.socket.bufferedAmount + encodedBytes > this.options.maxBufferedBytes)
|
|
537
|
+
return Promise.reject(new NativeCallError("control_backpressure"));
|
|
538
|
+
let resolve;
|
|
539
|
+
let reject;
|
|
540
|
+
const promise = new Promise((yes, no) => {
|
|
541
|
+
resolve = yes;
|
|
542
|
+
reject = no;
|
|
543
|
+
});
|
|
544
|
+
const timer = setTimeout(() => {
|
|
545
|
+
this.pending.delete(command.requestId);
|
|
546
|
+
reject(new NativeCallError("command_timeout", true));
|
|
547
|
+
}, this.options.commandTimeoutMs ?? 3e4);
|
|
548
|
+
this.pending.set(command.requestId, { command: encoded, promise, resolve, reject, timer });
|
|
549
|
+
try {
|
|
550
|
+
this.socket.send(encoded);
|
|
551
|
+
} catch {
|
|
552
|
+
this.fail(new NativeCallError("send_failed", true));
|
|
553
|
+
}
|
|
554
|
+
return promise;
|
|
555
|
+
}
|
|
556
|
+
ready(requestId, ready, format = this.hello?.audioFormat, scope) {
|
|
557
|
+
if (!format)
|
|
558
|
+
return Promise.reject(new NativeCallError("not_connected"));
|
|
559
|
+
pcmBytes(format);
|
|
560
|
+
return this.command({ type: "call.ready", requestId, ready, format, ...scope ? { scope } : {} });
|
|
561
|
+
}
|
|
562
|
+
dial(requestId, contactId) {
|
|
563
|
+
return this.command({ type: "call.dial", requestId, target: { kind: "direct", contactId }, callType: "voice" });
|
|
564
|
+
}
|
|
565
|
+
answer(requestId, callId, expectedRevision) {
|
|
566
|
+
return this.command({ type: "call.answer", requestId, callId, expectedRevision });
|
|
567
|
+
}
|
|
568
|
+
/** Acceptance starts termination. Retain control and media transports until
|
|
569
|
+
* the terminal call.state event; a lost confirmation leaves an unknown outcome. */
|
|
570
|
+
end(type, requestId, callId, expectedRevision) {
|
|
571
|
+
return this.command({ type, requestId, callId, expectedRevision });
|
|
572
|
+
}
|
|
573
|
+
clearAudio(requestId, callId) {
|
|
574
|
+
return this.command({ type: "call.clear_audio", requestId, callId });
|
|
575
|
+
}
|
|
576
|
+
async attachMedia(callId) {
|
|
577
|
+
if (!this.hello || this.closed || this.owner?.callId !== callId)
|
|
578
|
+
throw new NativeCallError("not_owner");
|
|
579
|
+
if (this.media.has(callId))
|
|
580
|
+
throw new NativeCallError("media_already_attached");
|
|
581
|
+
const attachment = { type: "media.attach", clientId: this.hello.clientId, ownerToken: this.owner.token };
|
|
582
|
+
const media = new NativeCallMediaClient(this.options, callId, attachment);
|
|
583
|
+
this.media.set(callId, media);
|
|
584
|
+
try {
|
|
585
|
+
await media.connect();
|
|
586
|
+
return media;
|
|
587
|
+
} catch (error) {
|
|
588
|
+
this.media.delete(callId);
|
|
589
|
+
throw error;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
dropMedia(callId) {
|
|
593
|
+
this.media.get(callId)?.close();
|
|
594
|
+
this.media.delete(callId);
|
|
595
|
+
if (this.owner?.callId === callId)
|
|
596
|
+
this.owner = void 0;
|
|
597
|
+
}
|
|
598
|
+
fail(error) {
|
|
599
|
+
if (this.closed)
|
|
600
|
+
return;
|
|
601
|
+
this.closed = true;
|
|
602
|
+
clearTimeout(this.handshakeTimer);
|
|
603
|
+
this.openReject?.(error);
|
|
604
|
+
this.openReject = void 0;
|
|
605
|
+
for (const pending2 of this.pending.values()) {
|
|
606
|
+
clearTimeout(pending2.timer);
|
|
607
|
+
pending2.reject(new NativeCallError(error.code, true));
|
|
608
|
+
}
|
|
609
|
+
this.pending.clear();
|
|
610
|
+
for (const media of this.media.values())
|
|
611
|
+
media.close();
|
|
612
|
+
this.media.clear();
|
|
613
|
+
this.owner = void 0;
|
|
614
|
+
this.queue.close(error);
|
|
615
|
+
try {
|
|
616
|
+
this.socket?.close(1e3, "call client stopped");
|
|
617
|
+
} catch {
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
close() {
|
|
621
|
+
this.fail(new NativeCallError("closed"));
|
|
622
|
+
}
|
|
623
|
+
};
|
|
624
|
+
var NativeCallMediaClient = class {
|
|
625
|
+
options;
|
|
626
|
+
callId;
|
|
627
|
+
attachment;
|
|
628
|
+
queue = new EventQueue(16);
|
|
629
|
+
socket;
|
|
630
|
+
opening;
|
|
631
|
+
openResolve;
|
|
632
|
+
openReject;
|
|
633
|
+
timer;
|
|
634
|
+
readyEvent;
|
|
635
|
+
sendGeneration;
|
|
636
|
+
ending = false;
|
|
637
|
+
closed = false;
|
|
638
|
+
constructor(options, callId, attachment) {
|
|
639
|
+
const url2 = validateNativeBaseUrl(options.baseUrl);
|
|
640
|
+
resourceId(callId);
|
|
641
|
+
const env = globalThis.process?.env;
|
|
642
|
+
if (url2.protocol === "https:" && env?.NODE_TLS_REJECT_UNAUTHORIZED === "0")
|
|
643
|
+
throw new Error("Call API requires TLS verification");
|
|
644
|
+
if (typeof options.token !== "string" || !options.token || /[\r\n]/.test(options.token))
|
|
645
|
+
throw new Error("Call API bearer token is required");
|
|
646
|
+
this.options = options;
|
|
647
|
+
this.callId = callId;
|
|
648
|
+
this.attachment = attachment;
|
|
649
|
+
}
|
|
650
|
+
connect() {
|
|
651
|
+
if (this.closed)
|
|
652
|
+
return Promise.reject(new NativeCallError("closed"));
|
|
653
|
+
if (this.opening)
|
|
654
|
+
return this.opening;
|
|
655
|
+
this.opening = new Promise((resolve, reject) => {
|
|
656
|
+
this.openResolve = resolve;
|
|
657
|
+
this.openReject = reject;
|
|
658
|
+
});
|
|
659
|
+
this.timer = setTimeout(() => this.fail(new NativeCallError("media_handshake_timeout")), this.options.handshakeTimeoutMs ?? 1e4);
|
|
660
|
+
try {
|
|
661
|
+
const socket = this.options.webSocketFactory(callSocketUrl(this.options.baseUrl, this.options.accountId, `${resourceId(this.callId)}/media`), { headers: { Authorization: `Bearer ${this.options.token}` }, maxPayload: NATIVE_CALL_MAX_FRAME_BYTES });
|
|
662
|
+
this.socket = socket;
|
|
663
|
+
socket.binaryType = "arraybuffer";
|
|
664
|
+
socket.onopen = () => {
|
|
665
|
+
try {
|
|
666
|
+
socket.send(JSON.stringify(this.attachment));
|
|
667
|
+
} catch {
|
|
668
|
+
this.fail(new NativeCallError("media_attach_failed"));
|
|
669
|
+
}
|
|
670
|
+
};
|
|
671
|
+
socket.onmessage = (event) => {
|
|
672
|
+
try {
|
|
673
|
+
this.receive(event.data);
|
|
674
|
+
} catch {
|
|
675
|
+
this.fail(new NativeCallError("invalid_media"));
|
|
676
|
+
}
|
|
677
|
+
};
|
|
678
|
+
socket.onerror = () => this.fail(new NativeCallError("media_connection_failed"));
|
|
679
|
+
socket.onclose = () => this.fail(new NativeCallError("media_closed"));
|
|
680
|
+
} catch {
|
|
681
|
+
this.fail(new NativeCallError("media_connection_failed"));
|
|
682
|
+
}
|
|
683
|
+
return this.opening;
|
|
684
|
+
}
|
|
685
|
+
frames() {
|
|
686
|
+
return this.queue;
|
|
687
|
+
}
|
|
688
|
+
tracks() {
|
|
689
|
+
if (!this.readyEvent)
|
|
690
|
+
throw new NativeCallError("media_not_ready");
|
|
691
|
+
return { sendTrack: structuredClone(this.readyEvent.sendTrack), receiveTrack: structuredClone(this.readyEvent.receiveTrack) };
|
|
692
|
+
}
|
|
693
|
+
receive(data) {
|
|
694
|
+
if (this.closed)
|
|
695
|
+
return;
|
|
696
|
+
if (typeof data === "string") {
|
|
697
|
+
const event = parseCallEvent(data);
|
|
698
|
+
if (event.type === "call.error") {
|
|
699
|
+
this.fail(new NativeCallError(event.code));
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
if (event.type === "track.updated" || event.type === "track.added") {
|
|
703
|
+
if (event.callId !== this.callId)
|
|
704
|
+
throw new Error("Wrong media call");
|
|
705
|
+
this.updateTrack(event.track);
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
if (event.type !== "media.ready" || this.readyEvent)
|
|
709
|
+
throw new Error("Unexpected media event");
|
|
710
|
+
this.readyEvent = structuredClone(event);
|
|
711
|
+
clearTimeout(this.timer);
|
|
712
|
+
this.openResolve?.(structuredClone(event));
|
|
713
|
+
this.openResolve = void 0;
|
|
714
|
+
this.openReject = void 0;
|
|
715
|
+
return;
|
|
716
|
+
}
|
|
717
|
+
const bytes = binaryBytes(data);
|
|
718
|
+
if (!bytes || !this.readyEvent)
|
|
719
|
+
throw new Error("Unattached media");
|
|
720
|
+
if (this.ending)
|
|
721
|
+
return;
|
|
722
|
+
if (bytes.byteLength === 0 || bytes.byteLength > NATIVE_CALL_MAX_FRAME_BYTES || bytes.byteLength % (this.readyEvent.receiveTrack.format.channels * 2) !== 0)
|
|
723
|
+
throw new Error("Invalid PCM samples");
|
|
724
|
+
if (!this.queue.push({ payload: bytes }))
|
|
725
|
+
this.fail(new NativeCallError("media_backpressure"));
|
|
726
|
+
}
|
|
727
|
+
/** Called from authenticated control track updates as well as this socket. */
|
|
728
|
+
updateTrack(track) {
|
|
729
|
+
if (!this.readyEvent || this.closed)
|
|
730
|
+
return;
|
|
731
|
+
const key = track.direction === "send" ? "sendTrack" : "receiveTrack";
|
|
732
|
+
const prior = this.readyEvent[key];
|
|
733
|
+
if (track.id !== prior.id || track.generation < prior.generation || JSON.stringify(track.format) !== JSON.stringify(prior.format)) {
|
|
734
|
+
this.fail(new NativeCallError("invalid_track_update"));
|
|
735
|
+
return;
|
|
736
|
+
}
|
|
737
|
+
if (track.generation === prior.generation)
|
|
738
|
+
return;
|
|
739
|
+
if (track.direction === "receive")
|
|
740
|
+
this.queue.clear();
|
|
741
|
+
this.readyEvent[key] = structuredClone(track);
|
|
742
|
+
}
|
|
743
|
+
/** Stop audio immediately without detaching the owner before termination. */
|
|
744
|
+
stopAudio() {
|
|
745
|
+
this.ending = true;
|
|
746
|
+
this.queue.clear();
|
|
747
|
+
}
|
|
748
|
+
/** Send PCM chunks, with the generation captured for this producer. The daemon
|
|
749
|
+
* buffers, frames and clocks the samples. An old producer cannot silently
|
|
750
|
+
* adopt the new generation after clearAudio. */
|
|
751
|
+
sendPcm(samples, generation) {
|
|
752
|
+
if (this.closed || !this.readyEvent || this.socket?.readyState !== 1)
|
|
753
|
+
throw new NativeCallError("media_not_ready");
|
|
754
|
+
if (this.ending)
|
|
755
|
+
throw new NativeCallError("call_ending");
|
|
756
|
+
if (generation !== this.readyEvent.sendTrack.generation)
|
|
757
|
+
throw new NativeCallError("stale");
|
|
758
|
+
if (!(samples instanceof Int16Array) || samples.length === 0 || samples.length % this.readyEvent.sendTrack.format.channels !== 0 || samples.byteLength > NATIVE_CALL_MAX_FRAME_BYTES)
|
|
759
|
+
throw new NativeCallError("invalid_pcm");
|
|
760
|
+
const start = this.sendGeneration === generation ? void 0 : JSON.stringify({ type: "audio.start", generation });
|
|
761
|
+
if (this.socket.bufferedAmount + samples.byteLength + (start?.length ?? 0) > (this.options.maxBufferedBytes ?? 65536))
|
|
762
|
+
throw new NativeCallError("media_backpressure");
|
|
763
|
+
const bytes = new Uint8Array(samples.byteLength);
|
|
764
|
+
const view = new DataView(bytes.buffer);
|
|
765
|
+
for (let i = 0; i < samples.length; i++)
|
|
766
|
+
view.setInt16(i * 2, samples[i], true);
|
|
767
|
+
try {
|
|
768
|
+
if (start) {
|
|
769
|
+
this.socket.send(start);
|
|
770
|
+
this.sendGeneration = generation;
|
|
771
|
+
}
|
|
772
|
+
this.socket.send(bytes);
|
|
773
|
+
} catch {
|
|
774
|
+
this.fail(new NativeCallError("media_send_failed", true));
|
|
775
|
+
throw new NativeCallError("media_send_failed", true);
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
fail(error) {
|
|
779
|
+
if (this.closed)
|
|
780
|
+
return;
|
|
781
|
+
this.closed = true;
|
|
782
|
+
clearTimeout(this.timer);
|
|
783
|
+
this.openReject?.(error);
|
|
784
|
+
this.openReject = void 0;
|
|
785
|
+
this.queue.close(error);
|
|
786
|
+
try {
|
|
787
|
+
this.socket?.close(1e3, "call media stopped");
|
|
788
|
+
} catch {
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
close() {
|
|
792
|
+
this.fail(new NativeCallError("media_closed"));
|
|
793
|
+
}
|
|
794
|
+
};
|
|
795
|
+
|
|
116
796
|
// ../shared/dist/native.generated.js
|
|
117
797
|
var NATIVE_MAX_SOURCE_BYTES = 536870912;
|
|
118
798
|
var NATIVE_MAX_ORDINARY_SOURCE_BYTES = 26214383;
|
|
@@ -265,6 +945,9 @@ var NativeWeChatClient = class {
|
|
|
265
945
|
return void 0;
|
|
266
946
|
return JSON.parse(new TextDecoder().decode(await this.readBounded(response)));
|
|
267
947
|
}
|
|
948
|
+
calls(accountId, webSocketFactory, options = {}) {
|
|
949
|
+
return new NativeCallsClient({ baseUrl: this.baseUrl.toString(), token: this.token, accountId, webSocketFactory, ...options });
|
|
950
|
+
}
|
|
268
951
|
status() {
|
|
269
952
|
return this.request("v1/status");
|
|
270
953
|
}
|
|
@@ -714,7 +1397,7 @@ var NativeWeChatClient = class {
|
|
|
714
1397
|
async *watch(accountId, after = "0", signal, options = {}) {
|
|
715
1398
|
const connection = new AbortController();
|
|
716
1399
|
const streamSignal = signal ? AbortSignal.any([signal, connection.signal]) : connection.signal;
|
|
717
|
-
const
|
|
1400
|
+
const bounded2 = async (work, milliseconds, reason) => {
|
|
718
1401
|
if (streamSignal.aborted)
|
|
719
1402
|
throw streamSignal.reason;
|
|
720
1403
|
let timer;
|
|
@@ -740,7 +1423,7 @@ var NativeWeChatClient = class {
|
|
|
740
1423
|
let eventCursor = "";
|
|
741
1424
|
let eventType = "";
|
|
742
1425
|
try {
|
|
743
|
-
const response = await
|
|
1426
|
+
const response = await bounded2(() => 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");
|
|
744
1427
|
if (!response.headers.get("content-type")?.startsWith("text/event-stream")) {
|
|
745
1428
|
await response.body?.cancel();
|
|
746
1429
|
throw new Error("Expected native SSE response");
|
|
@@ -750,7 +1433,7 @@ var NativeWeChatClient = class {
|
|
|
750
1433
|
throw new Error("Native SSE has no body");
|
|
751
1434
|
while (true) {
|
|
752
1435
|
const activeReader = reader;
|
|
753
|
-
const { value, done } = await
|
|
1436
|
+
const { value, done } = await bounded2(() => activeReader.read(), this.streamIdleTimeoutMs, "Native SSE idle timeout");
|
|
754
1437
|
if (done)
|
|
755
1438
|
break;
|
|
756
1439
|
options.onActivity?.();
|
|
@@ -870,7 +1553,7 @@ async function resolveNativeExecutable(explicit, path = process.env.PATH ?? "",
|
|
|
870
1553
|
if (manifest.version !== pkg.version || !asset || !/^[a-f0-9]{64}$/.test(asset.sha256)) throw new Error("Native CLI manifest is incompatible");
|
|
871
1554
|
candidate = await realpath(join(root, "native", pkg.version, target.key, target.executable));
|
|
872
1555
|
const bytes = await readFile(candidate);
|
|
873
|
-
if (bytes.length !== asset.bytes ||
|
|
1556
|
+
if (bytes.length !== asset.bytes || createHash3("sha256").update(bytes).digest("hex") !== asset.sha256) throw new Error("Installed native executable checksum mismatch");
|
|
874
1557
|
}
|
|
875
1558
|
const stat = await lstat(candidate);
|
|
876
1559
|
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("Native executable must be a regular file");
|
|
@@ -1256,11 +1939,11 @@ function resolveWeChatIngress(params) {
|
|
|
1256
1939
|
}
|
|
1257
1940
|
|
|
1258
1941
|
// src/outbound-media.ts
|
|
1259
|
-
import { createHash as
|
|
1942
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
1260
1943
|
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
1261
1944
|
|
|
1262
1945
|
// src/native-media.ts
|
|
1263
|
-
import { createHash as
|
|
1946
|
+
import { createHash as createHash5, randomUUID } from "node:crypto";
|
|
1264
1947
|
import { openAsBlob } from "node:fs";
|
|
1265
1948
|
import { mkdtemp, open, rm } from "node:fs/promises";
|
|
1266
1949
|
import { tmpdir } from "node:os";
|
|
@@ -1269,7 +1952,7 @@ import { getImageMetadata, resizeToJpeg, IMAGE_REDUCE_QUALITY_STEPS } from "open
|
|
|
1269
1952
|
import { saveMediaStream } from "openclaw/plugin-sdk/media-store";
|
|
1270
1953
|
|
|
1271
1954
|
// src/attachment-store.ts
|
|
1272
|
-
import { createHash as
|
|
1955
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
1273
1956
|
var AttachmentTooLargeError = class extends Error {
|
|
1274
1957
|
};
|
|
1275
1958
|
function decodedSize(base64) {
|
|
@@ -1292,7 +1975,7 @@ async function saveManagedAttachmentBytes(params) {
|
|
|
1292
1975
|
const size = params.bytes.byteLength;
|
|
1293
1976
|
if (size > params.maxBytes) throw new AttachmentTooLargeError(`Attachment exceeds configured ${params.maxBytes} byte limit`);
|
|
1294
1977
|
const buffer = Buffer.from(params.bytes.buffer, params.bytes.byteOffset, size);
|
|
1295
|
-
const sha256 =
|
|
1978
|
+
const sha256 = createHash4("sha256").update(buffer).digest("hex");
|
|
1296
1979
|
const saved = await params.saveMediaBuffer(
|
|
1297
1980
|
buffer,
|
|
1298
1981
|
params.mime,
|
|
@@ -1305,7 +1988,7 @@ async function saveManagedAttachmentBytes(params) {
|
|
|
1305
1988
|
async function saveVerifiedManagedAttachmentStream(params) {
|
|
1306
1989
|
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");
|
|
1307
1990
|
let size = 0, finished = false;
|
|
1308
|
-
const digest2 =
|
|
1991
|
+
const digest2 = createHash4("sha256");
|
|
1309
1992
|
const stream = (async function* () {
|
|
1310
1993
|
for await (const chunk of params.stream) {
|
|
1311
1994
|
params.assertCurrent();
|
|
@@ -1861,7 +2544,7 @@ async function prepareNativeAttachmentInput(params) {
|
|
|
1861
2544
|
if (!asset && job && ["queued", "running"].includes(job.state)) return { body: `[${attachmentKind} pending]`, pending: true, jobId: job.id, retryable: true };
|
|
1862
2545
|
}
|
|
1863
2546
|
const candidate = transferCandidate();
|
|
1864
|
-
const filename = basename(asset?.filename ?? candidate?.filename ?? `message-${
|
|
2547
|
+
const filename = basename(asset?.filename ?? candidate?.filename ?? `message-${createHash5("sha256").update(message.id).digest("hex").slice(0, 12)}.bin`).replace(/[\r\n\0]/g, "_");
|
|
1865
2548
|
if (!asset) {
|
|
1866
2549
|
if (candidate?.state === "recalled" || transferError?.code === "message_recalled") return { body: "[Message recalled]", pending: false, retryable: false, reason: "message_recalled" };
|
|
1867
2550
|
const state = candidate?.state === "expired" ? "expired" : candidate?.state === "unsupported" ? "unsupported" : "unavailable";
|
|
@@ -1933,7 +2616,7 @@ async function prepareNativeAttachmentInput(params) {
|
|
|
1933
2616
|
guard2();
|
|
1934
2617
|
const mime = content.contentType.split(";", 1)[0].trim().toLowerCase();
|
|
1935
2618
|
if (!/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/.test(mime)) throw Error("Native attachment MIME type is unsupported");
|
|
1936
|
-
const hash =
|
|
2619
|
+
const hash = createHash5("sha256").update(content.bytes).digest("hex");
|
|
1937
2620
|
if (!asset.sha256 || hash !== asset.sha256 || asset.byteLength != null && asset.byteLength !== content.bytes.length) throw new Error("Native attachment integrity did not verify");
|
|
1938
2621
|
await authorize();
|
|
1939
2622
|
const saved = await saveManagedAttachmentBytes({ bytes: content.bytes, mime, filename, maxBytes, saveMediaBuffer: core.channel.media.saveMediaBuffer });
|
|
@@ -1958,7 +2641,7 @@ async function prepareNativeAttachmentInput(params) {
|
|
|
1958
2641
|
const derived = await client.mediaContent(accountId, asset.id, { maxBytes: preview.byteLength, representation: "preview", signal: params.signal });
|
|
1959
2642
|
guard2();
|
|
1960
2643
|
const derivedMime = derived.contentType.split(";", 1)[0].trim().toLowerCase();
|
|
1961
|
-
if (derived.sourceSha256 !== hash || derivedMime !== preview.contentType || derived.bytes.length !== preview.byteLength ||
|
|
2644
|
+
if (derived.sourceSha256 !== hash || derivedMime !== preview.contentType || derived.bytes.length !== preview.byteLength || createHash5("sha256").update(derived.bytes).digest("hex") !== preview.sha256) throw Error("Native WXGF preview integrity did not verify");
|
|
1962
2645
|
imageBytes = Buffer.from(derived.bytes);
|
|
1963
2646
|
imageMime = derivedMime;
|
|
1964
2647
|
}
|
|
@@ -2123,11 +2806,11 @@ async function sendNativeAttachment(client, account, threadId2, mediaUrl, audioA
|
|
|
2123
2806
|
}
|
|
2124
2807
|
|
|
2125
2808
|
// src/native-prepared-boundary.ts
|
|
2126
|
-
import { createHash as
|
|
2809
|
+
import { createHash as createHash6, randomUUID as randomUUID2 } from "node:crypto";
|
|
2127
2810
|
import { basename as basename2, isAbsolute as isAbsolute2 } from "node:path";
|
|
2128
2811
|
var pending = /* @__PURE__ */ new Map();
|
|
2129
2812
|
var enabled = false;
|
|
2130
|
-
var digest = (value) =>
|
|
2813
|
+
var digest = (value) => createHash6("sha256").update(value).digest("hex");
|
|
2131
2814
|
function prune() {
|
|
2132
2815
|
for (const [id2, item] of pending) if (item.expires < Date.now()) pending.delete(id2);
|
|
2133
2816
|
}
|
|
@@ -2180,7 +2863,7 @@ function nativeDispatchManifest(params) {
|
|
|
2180
2863
|
}))) } : {},
|
|
2181
2864
|
assets,
|
|
2182
2865
|
policySha256: digest(JSON.stringify(params.policy ?? null)),
|
|
2183
|
-
// Exact source-turn identity of OpenClaw 2026.10.2 through 2026.10.
|
|
2866
|
+
// Exact source-turn identity of OpenClaw 2026.10.2 through 2026.10.9. Requiring it in the later
|
|
2184
2867
|
// snapshot prevents an identical older image/body from proving this input.
|
|
2185
2868
|
hostSourceTurnId: `channel-user:v1:${digest(JSON.stringify(["agent-wechat", params.channelAccountId, `wechat:${params.message.threadId}`, messageSid]))}`
|
|
2186
2869
|
};
|
|
@@ -2370,15 +3053,15 @@ async function sendWeChatMedia(cfg, to, text3, mediaUrl, audioAsVoice = false, i
|
|
|
2370
3053
|
const result = await sendNativeAttachment(client, account, to, mediaUrl, audioAsVoice, key, beforeSend, options);
|
|
2371
3054
|
if (text3) {
|
|
2372
3055
|
await beforeSend?.();
|
|
2373
|
-
await submitNativeText(client, account.native.accountId, to, text3,
|
|
3056
|
+
await submitNativeText(client, account.native.accountId, to, text3, createHash7("sha256").update(`${key}\0caption`).digest("hex"));
|
|
2374
3057
|
}
|
|
2375
3058
|
return result;
|
|
2376
3059
|
}
|
|
2377
3060
|
|
|
2378
3061
|
// src/native-send-key.ts
|
|
2379
|
-
import { createHash as
|
|
3062
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
2380
3063
|
function nativeOutboundKey(queueId, partIndex = 0, attachmentIndex = 0) {
|
|
2381
|
-
return
|
|
3064
|
+
return createHash8("sha256").update(JSON.stringify(["wechat-media", queueId, partIndex, attachmentIndex])).digest("hex");
|
|
2382
3065
|
}
|
|
2383
3066
|
|
|
2384
3067
|
// src/outbound-options.ts
|
|
@@ -2505,12 +3188,12 @@ function createWeChatMediaHandlers(send = sendWeChatMedia) {
|
|
|
2505
3188
|
}
|
|
2506
3189
|
|
|
2507
3190
|
// src/native-monitor.ts
|
|
2508
|
-
import { createHash as
|
|
3191
|
+
import { createHash as createHash10 } from "node:crypto";
|
|
2509
3192
|
import { createChannelMessageReplyPipeline } from "openclaw/plugin-sdk/channel-outbound";
|
|
2510
3193
|
import { resolveStableChannelMessageIngress } from "openclaw/plugin-sdk/channel-ingress-runtime";
|
|
2511
3194
|
|
|
2512
3195
|
// src/native-consumer-state.ts
|
|
2513
|
-
import { createHash as
|
|
3196
|
+
import { createHash as createHash9, randomUUID as randomUUID4 } from "node:crypto";
|
|
2514
3197
|
import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2515
3198
|
import { dirname as dirname2, isAbsolute as isAbsolute3, join as join3 } from "node:path";
|
|
2516
3199
|
var NativeConsumerState = class {
|
|
@@ -2518,7 +3201,7 @@ var NativeConsumerState = class {
|
|
|
2518
3201
|
value;
|
|
2519
3202
|
constructor(directory, serverId, accountId) {
|
|
2520
3203
|
if (!isAbsolute3(directory) || !serverId || !accountId) throw new Error("Native consumer state requires absolute storage and bound server/account identities");
|
|
2521
|
-
this.file = join3(directory, `${
|
|
3204
|
+
this.file = join3(directory, `${createHash9("sha256").update(`${serverId}\0${accountId}`).digest("hex")}.json`);
|
|
2522
3205
|
this.value = { schemaVersion: 1, serverId, accountId, cursor: "0", items: {} };
|
|
2523
3206
|
if (existsSync(this.file)) {
|
|
2524
3207
|
const stat = lstatSync(this.file);
|
|
@@ -2737,7 +3420,7 @@ var NativeConsumerState = class {
|
|
|
2737
3420
|
});
|
|
2738
3421
|
const revisions = items.map((item) => item.revision);
|
|
2739
3422
|
if (new Set(items.map((item) => item.message.threadId)).size !== 1) throw new Error("Prepared input manifest crosses threads");
|
|
2740
|
-
const manifestHash =
|
|
3423
|
+
const manifestHash = createHash9("sha256").update(JSON.stringify({
|
|
2741
3424
|
accountId: this.value.accountId,
|
|
2742
3425
|
messageIds: exact,
|
|
2743
3426
|
dispatchManifests: items.map((item) => item.dispatchManifest ?? null)
|
|
@@ -2746,7 +3429,7 @@ var NativeConsumerState = class {
|
|
|
2746
3429
|
const runId = typeof args[0] === "string" ? args[0] : args[0]?.runId;
|
|
2747
3430
|
if (typeof runId !== "string" || !runId || runId.length > 256) throw new Error("Prepared run callback has no valid runId");
|
|
2748
3431
|
this.mutate(() => {
|
|
2749
|
-
const currentHash =
|
|
3432
|
+
const currentHash = createHash9("sha256").update(JSON.stringify({
|
|
2750
3433
|
accountId: this.value.accountId,
|
|
2751
3434
|
messageIds: exact,
|
|
2752
3435
|
dispatchManifests: exact.map((id2) => this.value.items[id2]?.dispatchManifest ?? null)
|
|
@@ -3116,12 +3799,12 @@ async function dispatchNativeMessageInput(params, revision) {
|
|
|
3116
3799
|
if (urls.length > 16) throw new Error("Native reply media count exceeds its bound");
|
|
3117
3800
|
if (payload.audioAsVoice && !urls.length) throw new Error("Native voice reply requires an audio attachment");
|
|
3118
3801
|
for (const url2 of urls) {
|
|
3119
|
-
const key =
|
|
3802
|
+
const key = createHash10("sha256").update(`${dispatchManifest.messageSid}\0${delivery++}`).digest("hex");
|
|
3120
3803
|
await sendNativeAttachment(client, account, message.threadId, url2, payload.audioAsVoice === true, key, beforeSend);
|
|
3121
3804
|
}
|
|
3122
3805
|
if (payload.text) {
|
|
3123
3806
|
await beforeSend();
|
|
3124
|
-
const key =
|
|
3807
|
+
const key = createHash10("sha256").update(`${dispatchManifest.messageSid}\0${delivery++}`).digest("hex");
|
|
3125
3808
|
await submitNativeText(client, account.native.accountId, message.threadId, payload.text, key, { mentions: options.mentions, quote });
|
|
3126
3809
|
}
|
|
3127
3810
|
if (urls.length || payload.text) params.onDelivered?.();
|
|
@@ -3952,11 +4635,11 @@ function registerNativeFacade(api, config) {
|
|
|
3952
4635
|
import { resolveStableChannelMessageIngress as resolveStableChannelMessageIngress2 } from "openclaw/plugin-sdk/channel-ingress-runtime";
|
|
3953
4636
|
import { imageResultFromFile } from "openclaw/plugin-sdk/channel-actions";
|
|
3954
4637
|
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." } };
|
|
3955
|
-
var
|
|
4638
|
+
var names2 = ["wechat_history", "wechat_search", "wechat_message", "wechat_media"];
|
|
3956
4639
|
var archiveNames = ["wechat_archive_threads", "wechat_archive_search", "wechat_archive_history", "wechat_archive_message", "wechat_archive_media"];
|
|
3957
4640
|
var messageIdSchema = { type: "string", minLength: 1, maxLength: 4096 };
|
|
3958
4641
|
var qualities = ["best", "original", "standard", "thumbnail", "normal", "encoded"];
|
|
3959
|
-
function
|
|
4642
|
+
function object3(value) {
|
|
3960
4643
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw Error("Expected tool arguments");
|
|
3961
4644
|
return value;
|
|
3962
4645
|
}
|
|
@@ -4049,7 +4732,7 @@ function createLookupTools(context, dependencies, archive) {
|
|
|
4049
4732
|
...action === "media" ? { catalogMode: "direct-only" } : {},
|
|
4050
4733
|
parameters: { type: "object", additionalProperties: false, properties, required },
|
|
4051
4734
|
execute: async (_callId, input, signal) => {
|
|
4052
|
-
const args =
|
|
4735
|
+
const args = object3(input);
|
|
4053
4736
|
const guard2 = () => {
|
|
4054
4737
|
signal?.throwIfAborted();
|
|
4055
4738
|
context.assertInvocationCurrent?.();
|
|
@@ -4219,14 +4902,14 @@ function createLookupTools(context, dependencies, archive) {
|
|
|
4219
4902
|
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"])
|
|
4220
4903
|
];
|
|
4221
4904
|
return [
|
|
4222
|
-
tool(
|
|
4223
|
-
tool(
|
|
4224
|
-
tool(
|
|
4225
|
-
tool(
|
|
4905
|
+
tool(names2[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 }),
|
|
4906
|
+
tool(names2[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"]),
|
|
4907
|
+
tool(names2[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"]),
|
|
4908
|
+
tool(names2[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"])
|
|
4226
4909
|
];
|
|
4227
4910
|
}
|
|
4228
4911
|
function registerNativeHistoryTools(api) {
|
|
4229
|
-
api.registerTool({ contextVersion: 2, create: (context) => createNativeHistoryTools(context) }, { names });
|
|
4912
|
+
api.registerTool({ contextVersion: 2, create: (context) => createNativeHistoryTools(context) }, { names: names2 });
|
|
4230
4913
|
api.registerTool({ contextVersion: 2, create: (context) => createNativeArchiveTools(context) }, { names: archiveNames, optional: true });
|
|
4231
4914
|
}
|
|
4232
4915
|
|
|
@@ -4347,9 +5030,9 @@ function registerNativeShareTools(api) {
|
|
|
4347
5030
|
}
|
|
4348
5031
|
|
|
4349
5032
|
// src/native-recall-tools.ts
|
|
4350
|
-
import { createHash as
|
|
5033
|
+
import { createHash as createHash11 } from "node:crypto";
|
|
4351
5034
|
import { resolveStableChannelMessageIngress as resolveStableChannelMessageIngress4 } from "openclaw/plugin-sdk/channel-ingress-runtime";
|
|
4352
|
-
var
|
|
5035
|
+
var names3 = ["wechat_recall"];
|
|
4353
5036
|
function text2(value, label) {
|
|
4354
5037
|
if (typeof value !== "string" || !value.trim() || value.length > 4096 || /[\u0000-\u001f\u007f]/.test(value)) throw Error(`Invalid ${label}`);
|
|
4355
5038
|
return value.trim();
|
|
@@ -4358,7 +5041,7 @@ function thread2(value) {
|
|
|
4358
5041
|
return text2(text2(value, "conversation").replace(/^(?:agent-)?wechat:(?:group:)?/i, ""), "conversation");
|
|
4359
5042
|
}
|
|
4360
5043
|
function nativeRecallKey(accountId, threadId2, messageId, serverId) {
|
|
4361
|
-
return `openclaw-recall-${
|
|
5044
|
+
return `openclaw-recall-${createHash11("sha256").update(JSON.stringify([accountId, threadId2, messageId, serverId])).digest("hex")}`;
|
|
4362
5045
|
}
|
|
4363
5046
|
function createNativeRecallTools(context, dependencies = {}) {
|
|
4364
5047
|
const currentConfig = () => context.getRuntimeConfig?.() ?? context.runtimeConfig ?? context.config;
|
|
@@ -4378,7 +5061,7 @@ function createNativeRecallTools(context, dependencies = {}) {
|
|
|
4378
5061
|
const accountId = selected.native.accountId;
|
|
4379
5062
|
const configurationKey = nativeConfigurationKey(selected.native);
|
|
4380
5063
|
return [{
|
|
4381
|
-
name:
|
|
5064
|
+
name: names3[0],
|
|
4382
5065
|
label: "WeChat Recall",
|
|
4383
5066
|
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.",
|
|
4384
5067
|
parameters: { type: "object", additionalProperties: false, properties: {
|
|
@@ -4478,7 +5161,7 @@ function createNativeRecallTools(context, dependencies = {}) {
|
|
|
4478
5161
|
}];
|
|
4479
5162
|
}
|
|
4480
5163
|
function registerNativeRecallTools(api) {
|
|
4481
|
-
api.registerTool({ contextVersion: 2, create: (context) => createNativeRecallTools(context) }, { names:
|
|
5164
|
+
api.registerTool({ contextVersion: 2, create: (context) => createNativeRecallTools(context) }, { names: names3 });
|
|
4482
5165
|
}
|
|
4483
5166
|
|
|
4484
5167
|
// src/native-group-tool.ts
|
|
@@ -4530,6 +5213,753 @@ function registerNativeGroupTools(api) {
|
|
|
4530
5213
|
api.registerTool({ contextVersion: 2, create: (context) => createNativeGroupTools(context) }, { names: [name2] });
|
|
4531
5214
|
}
|
|
4532
5215
|
|
|
5216
|
+
// src/calls-service.ts
|
|
5217
|
+
import { randomUUID as randomUUID8 } from "node:crypto";
|
|
5218
|
+
|
|
5219
|
+
// src/calls-voice.ts
|
|
5220
|
+
import { randomUUID as randomUUID7 } from "node:crypto";
|
|
5221
|
+
var PCM = { encoding: "pcm16", sampleRateHz: 24e3, channels: 1 };
|
|
5222
|
+
var fits = (formats) => formats?.some((format) => format.encoding === PCM.encoding && format.sampleRateHz === PCM.sampleRateHz && format.channels === 1) === true;
|
|
5223
|
+
async function prepareOpenClawCallVoice(config, cfg, runtime2, dependencies) {
|
|
5224
|
+
const voicePath = "openclaw/plugin-sdk/realtime-voice";
|
|
5225
|
+
const audioPath = "openclaw/plugin-sdk/realtime-voice-provider";
|
|
5226
|
+
const [sdk, audioSdk] = dependencies ? [dependencies.voiceSdk, dependencies.audioSdk] : await Promise.all([import(voicePath), import(audioPath)]);
|
|
5227
|
+
for (const name3 of ["createRealtimeVoiceBridgeSession", "resolveConfiguredRealtimeVoiceProvider", "resolveRealtimeVoiceAgentConsultTools", "resolveRealtimeVoiceAgentConsultToolsAllow"]) {
|
|
5228
|
+
if (typeof sdk[name3] !== "function") throw Error("Calling realtime SDK unavailable");
|
|
5229
|
+
}
|
|
5230
|
+
if (typeof audioSdk.createStreamingPcmResampler !== "function") throw Error("Calling streaming resampler unavailable");
|
|
5231
|
+
if (config.toolPolicy !== "none" && (typeof sdk.consultRealtimeVoiceAgent !== "function" || !runtime2.agent?.runEmbeddedAgent || !config.allowConsultSessionPersistence)) throw Error("Calling consultation unavailable");
|
|
5232
|
+
const apiKey = await resolveCallVoiceApiKey(config, cfg);
|
|
5233
|
+
let selected;
|
|
5234
|
+
try {
|
|
5235
|
+
selected = sdk.resolveConfiguredRealtimeVoiceProvider({
|
|
5236
|
+
cfg,
|
|
5237
|
+
configuredProviderId: config.realtime.provider,
|
|
5238
|
+
agentId: config.agentId,
|
|
5239
|
+
surface: "bridge",
|
|
5240
|
+
providerConfigs: apiKey === void 0 ? void 0 : { openai: { apiKey } },
|
|
5241
|
+
providerConfigOverrides: { ...config.realtime.model ? { model: config.realtime.model } : {}, ...config.realtime.voice ? { voice: config.realtime.voice } : {} },
|
|
5242
|
+
useProviderDefaultModel: true,
|
|
5243
|
+
autoRespondToAudio: true
|
|
5244
|
+
});
|
|
5245
|
+
} catch {
|
|
5246
|
+
throw Error("Calling realtime provider configuration unavailable");
|
|
5247
|
+
}
|
|
5248
|
+
const capabilities = selected.capabilities;
|
|
5249
|
+
if (selected.provider?.id !== "openai") throw Error("Calling provider unsupported");
|
|
5250
|
+
if (!capabilities || !fits(capabilities.inputAudioFormats) || !fits(capabilities.outputAudioFormats) || capabilities.supportsBargeIn !== true || typeof selected.provider?.createBridge !== "function" || config.toolPolicy !== "none" && capabilities.supportsToolCalls !== true) throw Error("Calling provider capabilities unavailable");
|
|
5251
|
+
return {
|
|
5252
|
+
sampleRate: PCM.sampleRateHz,
|
|
5253
|
+
resampler: (inputRate, outputRate) => audioSdk.createStreamingPcmResampler(inputRate, outputRate),
|
|
5254
|
+
async open(callbacks, context) {
|
|
5255
|
+
let session;
|
|
5256
|
+
let closed = false;
|
|
5257
|
+
let ready = false;
|
|
5258
|
+
let resolveReady;
|
|
5259
|
+
let rejectReady;
|
|
5260
|
+
const admission = new Promise((resolve, reject) => {
|
|
5261
|
+
resolveReady = resolve;
|
|
5262
|
+
rejectReady = reject;
|
|
5263
|
+
});
|
|
5264
|
+
void admission.catch(() => {
|
|
5265
|
+
});
|
|
5266
|
+
const consults = /* @__PURE__ */ new Map();
|
|
5267
|
+
const signal = context.signal;
|
|
5268
|
+
const fail2 = () => {
|
|
5269
|
+
if (!closed) {
|
|
5270
|
+
rejectReady(Error("Calling provider failed"));
|
|
5271
|
+
callbacks.failed();
|
|
5272
|
+
}
|
|
5273
|
+
};
|
|
5274
|
+
const abort = () => {
|
|
5275
|
+
closed = true;
|
|
5276
|
+
rejectReady(Error("Calling provider stopped"));
|
|
5277
|
+
void Promise.resolve(session?.close()).catch(() => {
|
|
5278
|
+
});
|
|
5279
|
+
};
|
|
5280
|
+
signal.throwIfAborted();
|
|
5281
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
5282
|
+
const consultModel = config.consultation.model?.split(/\/(.*)/s);
|
|
5283
|
+
const sessionKey = `agent:${config.agentId}:wechat-call:${randomUUID7()}`;
|
|
5284
|
+
let consulting = false;
|
|
5285
|
+
const consult = async (question, requestSignal) => {
|
|
5286
|
+
if (closed || signal.aborted || !ready || config.toolPolicy === "none" || consulting || question.length > 4e3 || !question.trim()) throw Error("Calling consultation not admitted");
|
|
5287
|
+
consulting = true;
|
|
5288
|
+
try {
|
|
5289
|
+
return await sdk.consultRealtimeVoiceAgent({
|
|
5290
|
+
cfg,
|
|
5291
|
+
agentRuntime: runtime2.agent,
|
|
5292
|
+
agentId: config.agentId,
|
|
5293
|
+
sessionKey,
|
|
5294
|
+
contextMode: "isolated",
|
|
5295
|
+
senderId: context.senderId,
|
|
5296
|
+
senderIsOwner: false,
|
|
5297
|
+
messageProvider: "agent-wechat",
|
|
5298
|
+
toolsAllow: sdk.resolveRealtimeVoiceAgentConsultToolsAllow(config.toolPolicy),
|
|
5299
|
+
transcript: [],
|
|
5300
|
+
args: { question },
|
|
5301
|
+
surface: "a WeChat voice call",
|
|
5302
|
+
userLabel: "Caller",
|
|
5303
|
+
assistantLabel: "Assistant",
|
|
5304
|
+
runIdPrefix: "wechat-call",
|
|
5305
|
+
lane: "wechat-call",
|
|
5306
|
+
timeoutMs: config.consultation.timeoutMs,
|
|
5307
|
+
...consultModel ? { provider: consultModel[0], model: consultModel[1] } : {},
|
|
5308
|
+
abortSignal: requestSignal ? AbortSignal.any([signal, requestSignal]) : signal,
|
|
5309
|
+
logger: { info() {
|
|
5310
|
+
}, warn() {
|
|
5311
|
+
}, error() {
|
|
5312
|
+
} }
|
|
5313
|
+
});
|
|
5314
|
+
} finally {
|
|
5315
|
+
consulting = false;
|
|
5316
|
+
}
|
|
5317
|
+
};
|
|
5318
|
+
try {
|
|
5319
|
+
session = sdk.createRealtimeVoiceBridgeSession({
|
|
5320
|
+
cfg,
|
|
5321
|
+
agentId: config.agentId,
|
|
5322
|
+
provider: selected.provider,
|
|
5323
|
+
providerConfig: selected.providerConfig,
|
|
5324
|
+
capabilities,
|
|
5325
|
+
audioFormat: PCM,
|
|
5326
|
+
autoRespondToAudio: true,
|
|
5327
|
+
interruptResponseOnInputAudio: true,
|
|
5328
|
+
instructions: ["Speak concisely with the caller. Calling permission does not grant account-owner authority. Do not claim to perform actions unless a permitted tool confirms them.", config.realtime.instructions].filter(Boolean).join("\n\n"),
|
|
5329
|
+
tools: sdk.resolveRealtimeVoiceAgentConsultTools(config.toolPolicy),
|
|
5330
|
+
triggerGreetingOnReady: false,
|
|
5331
|
+
markStrategy: "ignore",
|
|
5332
|
+
audioSink: { isOpen: () => ready && !closed && !signal.aborted, sendAudio: callbacks.audio, clearAudio: callbacks.clear },
|
|
5333
|
+
onReady: () => {
|
|
5334
|
+
if (!closed && !signal.aborted) {
|
|
5335
|
+
ready = true;
|
|
5336
|
+
resolveReady();
|
|
5337
|
+
}
|
|
5338
|
+
},
|
|
5339
|
+
onClose: fail2,
|
|
5340
|
+
onError: fail2,
|
|
5341
|
+
...config.toolPolicy !== "none" ? { runAgentConsult: (request) => consult(request.prompt, request.signal) } : {},
|
|
5342
|
+
onToolCall: async (event) => {
|
|
5343
|
+
if (closed || signal.aborted || !session) return;
|
|
5344
|
+
if (typeof event.callId !== "string" || !event.callId || event.callId.length > 200) throw Error("Invalid call consultation identity");
|
|
5345
|
+
if (event.name !== sdk.REALTIME_VOICE_AGENT_CONSULT_TOOL_NAME || config.toolPolicy === "none") {
|
|
5346
|
+
await session.submitToolResult(event.callId, { error: "Tool is not permitted for this call" });
|
|
5347
|
+
return;
|
|
5348
|
+
}
|
|
5349
|
+
if (consults.size >= 32 && !consults.has(event.callId)) throw Error("Calling consultation limit reached");
|
|
5350
|
+
let result = consults.get(event.callId);
|
|
5351
|
+
if (!result) {
|
|
5352
|
+
const question = event.args && typeof event.args === "object" ? event.args.question : void 0;
|
|
5353
|
+
result = (typeof question === "string" ? consult(question) : Promise.reject(Error("Question required"))).then((value) => ({ text: value.text.slice(0, 8e3) }), () => ({ error: "Call consultation failed" }));
|
|
5354
|
+
consults.set(event.callId, result);
|
|
5355
|
+
}
|
|
5356
|
+
const answer = await result;
|
|
5357
|
+
if (!closed && !signal.aborted) await session.submitToolResult(event.callId, answer);
|
|
5358
|
+
}
|
|
5359
|
+
});
|
|
5360
|
+
if (!session || typeof session.connect !== "function" || typeof session.sendAudio !== "function" || typeof session.close !== "function" || typeof session.setMediaTimestamp !== "function" || session.bridge?.outputAudioMode === "continuous") throw Error("Calling bridge contract unavailable");
|
|
5361
|
+
signal.throwIfAborted();
|
|
5362
|
+
if (closed) throw Error("Calling provider stopped");
|
|
5363
|
+
await session.connect();
|
|
5364
|
+
await admission;
|
|
5365
|
+
signal.throwIfAborted();
|
|
5366
|
+
if (!session.bridge.isConnected()) throw Error("Calling provider not connected");
|
|
5367
|
+
return {
|
|
5368
|
+
sendAudio: (audio) => {
|
|
5369
|
+
if (!closed && !signal.aborted) session.sendAudio(audio);
|
|
5370
|
+
},
|
|
5371
|
+
setMediaTimestamp: (ms) => {
|
|
5372
|
+
if (!closed && !signal.aborted) session.setMediaTimestamp(ms);
|
|
5373
|
+
},
|
|
5374
|
+
close: async () => {
|
|
5375
|
+
if (closed) return;
|
|
5376
|
+
closed = true;
|
|
5377
|
+
ready = false;
|
|
5378
|
+
signal.removeEventListener("abort", abort);
|
|
5379
|
+
consults.clear();
|
|
5380
|
+
await session.close();
|
|
5381
|
+
}
|
|
5382
|
+
};
|
|
5383
|
+
} catch {
|
|
5384
|
+
closed = true;
|
|
5385
|
+
signal.removeEventListener("abort", abort);
|
|
5386
|
+
void Promise.resolve(session?.close()).catch(() => {
|
|
5387
|
+
});
|
|
5388
|
+
throw Error("Calling provider unavailable");
|
|
5389
|
+
}
|
|
5390
|
+
}
|
|
5391
|
+
};
|
|
5392
|
+
}
|
|
5393
|
+
|
|
5394
|
+
// src/calls-audio.ts
|
|
5395
|
+
var CallPcmOutput = class {
|
|
5396
|
+
pending = Buffer.alloc(0);
|
|
5397
|
+
resampler;
|
|
5398
|
+
items = /* @__PURE__ */ new Set();
|
|
5399
|
+
revokedItems = /* @__PURE__ */ new Set();
|
|
5400
|
+
closed = false;
|
|
5401
|
+
paused = false;
|
|
5402
|
+
clearEpoch = 0;
|
|
5403
|
+
maxBytes;
|
|
5404
|
+
media;
|
|
5405
|
+
format;
|
|
5406
|
+
voice;
|
|
5407
|
+
clearRemote;
|
|
5408
|
+
failed;
|
|
5409
|
+
constructor(media, format, voice, clearRemote, failed) {
|
|
5410
|
+
this.media = media;
|
|
5411
|
+
this.format = format;
|
|
5412
|
+
this.voice = voice;
|
|
5413
|
+
this.clearRemote = clearRemote;
|
|
5414
|
+
this.failed = failed;
|
|
5415
|
+
if (format.channels !== 1 || format.frameMs !== 20 || ![8e3, 12e3, 16e3, 24e3, 48e3].includes(format.sampleRate)) throw Error("Calling PCM format unsupported");
|
|
5416
|
+
this.maxBytes = format.sampleRate * 2 * 8;
|
|
5417
|
+
this.resampler = voice.resampler(voice.sampleRate, format.sampleRate);
|
|
5418
|
+
}
|
|
5419
|
+
enqueue(audio, metadata) {
|
|
5420
|
+
if (this.closed) return;
|
|
5421
|
+
const epoch = this.clearEpoch;
|
|
5422
|
+
const item = metadata?.itemId;
|
|
5423
|
+
if (!item || item.length > 200 || audio.length % 2 !== 0 || audio.length > this.voice.sampleRate * 4) return this.fail();
|
|
5424
|
+
if (this.revokedItems.has(item)) return;
|
|
5425
|
+
if (!this.items.has(item) && this.items.size >= 256) return this.fail();
|
|
5426
|
+
this.items.add(item);
|
|
5427
|
+
let converted;
|
|
5428
|
+
try {
|
|
5429
|
+
converted = this.resampler.process(audio);
|
|
5430
|
+
} catch {
|
|
5431
|
+
if (epoch === this.clearEpoch) this.fail();
|
|
5432
|
+
return;
|
|
5433
|
+
}
|
|
5434
|
+
if (this.closed || epoch !== this.clearEpoch || this.revokedItems.has(item)) return;
|
|
5435
|
+
if (converted.length % 2 !== 0 || this.pending.length + converted.length > this.maxBytes) return this.fail();
|
|
5436
|
+
this.pending = Buffer.concat([this.pending, converted]);
|
|
5437
|
+
if (!this.paused) this.flush();
|
|
5438
|
+
}
|
|
5439
|
+
async clear() {
|
|
5440
|
+
if (this.closed) return;
|
|
5441
|
+
const epoch = ++this.clearEpoch;
|
|
5442
|
+
this.paused = true;
|
|
5443
|
+
this.pending = Buffer.alloc(0);
|
|
5444
|
+
for (const item of this.items) this.revokedItems.add(item);
|
|
5445
|
+
try {
|
|
5446
|
+
const resampler = this.voice.resampler(this.voice.sampleRate, this.format.sampleRate);
|
|
5447
|
+
if (this.closed || epoch !== this.clearEpoch) return;
|
|
5448
|
+
this.resampler = resampler;
|
|
5449
|
+
await this.clearRemote();
|
|
5450
|
+
if (!this.closed && epoch === this.clearEpoch) {
|
|
5451
|
+
this.paused = false;
|
|
5452
|
+
this.flush();
|
|
5453
|
+
}
|
|
5454
|
+
} catch {
|
|
5455
|
+
if (epoch === this.clearEpoch) this.fail();
|
|
5456
|
+
}
|
|
5457
|
+
}
|
|
5458
|
+
flush() {
|
|
5459
|
+
if (this.closed || this.paused || this.pending.length === 0) return;
|
|
5460
|
+
try {
|
|
5461
|
+
const generation = this.media.tracks().sendTrack.generation;
|
|
5462
|
+
while (this.pending.length > 0) {
|
|
5463
|
+
const chunk = this.pending.subarray(0, 16 * 1024);
|
|
5464
|
+
const samples = new Int16Array(chunk.length / 2);
|
|
5465
|
+
for (let i = 0; i < samples.length; i++) samples[i] = chunk.readInt16LE(i * 2);
|
|
5466
|
+
this.media.sendPcm(samples, generation);
|
|
5467
|
+
this.pending = this.pending.subarray(chunk.length);
|
|
5468
|
+
}
|
|
5469
|
+
} catch {
|
|
5470
|
+
this.fail();
|
|
5471
|
+
}
|
|
5472
|
+
}
|
|
5473
|
+
fail() {
|
|
5474
|
+
if (!this.closed) {
|
|
5475
|
+
this.close();
|
|
5476
|
+
this.failed();
|
|
5477
|
+
}
|
|
5478
|
+
}
|
|
5479
|
+
close() {
|
|
5480
|
+
this.closed = true;
|
|
5481
|
+
this.pending = Buffer.alloc(0);
|
|
5482
|
+
this.items.clear();
|
|
5483
|
+
this.revokedItems.clear();
|
|
5484
|
+
}
|
|
5485
|
+
};
|
|
5486
|
+
|
|
5487
|
+
// src/calls-service.ts
|
|
5488
|
+
var TERMINAL_WAIT_MS = 3e4;
|
|
5489
|
+
var bounded = async (promise, ms) => {
|
|
5490
|
+
let timer;
|
|
5491
|
+
try {
|
|
5492
|
+
return await Promise.race([promise, new Promise((_, reject) => {
|
|
5493
|
+
timer = setTimeout(() => reject(Error("Calling operation timed out")), ms);
|
|
5494
|
+
})]);
|
|
5495
|
+
} finally {
|
|
5496
|
+
clearTimeout(timer);
|
|
5497
|
+
}
|
|
5498
|
+
};
|
|
5499
|
+
async function nativeCallSocketFactory() {
|
|
5500
|
+
const wsPath = "ws";
|
|
5501
|
+
const module = await import(wsPath);
|
|
5502
|
+
const WebSocket = module.default;
|
|
5503
|
+
if (typeof WebSocket !== "function") throw Error("Calling WebSocket transport unavailable");
|
|
5504
|
+
return (url2, options) => new WebSocket(url2, { ...options, followRedirects: false, perMessageDeflate: false });
|
|
5505
|
+
}
|
|
5506
|
+
var NativeCallService = class {
|
|
5507
|
+
client;
|
|
5508
|
+
prepared;
|
|
5509
|
+
format;
|
|
5510
|
+
active;
|
|
5511
|
+
stopped = false;
|
|
5512
|
+
busy = false;
|
|
5513
|
+
unconfirmedCallId;
|
|
5514
|
+
seen = /* @__PURE__ */ new Set();
|
|
5515
|
+
loop;
|
|
5516
|
+
state = "disabled";
|
|
5517
|
+
config;
|
|
5518
|
+
account;
|
|
5519
|
+
cfg;
|
|
5520
|
+
runtime;
|
|
5521
|
+
dependencies;
|
|
5522
|
+
constructor(account, cfg, runtime2, dependencies = {}) {
|
|
5523
|
+
this.account = account;
|
|
5524
|
+
this.cfg = cfg;
|
|
5525
|
+
this.runtime = runtime2;
|
|
5526
|
+
this.dependencies = dependencies;
|
|
5527
|
+
this.config = account.calls?.voice;
|
|
5528
|
+
if (!this.config && account.calls?.video.enabled) this.state = "unavailable";
|
|
5529
|
+
}
|
|
5530
|
+
status() {
|
|
5531
|
+
return { state: this.state, owned: this.active?.claimed === true, ...this.active?.claimed && this.active.callId ? { callId: this.active.callId } : {} };
|
|
5532
|
+
}
|
|
5533
|
+
async start() {
|
|
5534
|
+
if (!this.config || !this.account.enabled || this.stopped || this.state !== "disabled") return;
|
|
5535
|
+
this.state = "starting";
|
|
5536
|
+
try {
|
|
5537
|
+
this.prepared = await bounded((this.dependencies.prepareVoice ?? prepareOpenClawCallVoice)(this.config, this.cfg, this.runtime), 1e4);
|
|
5538
|
+
if (this.stopped) return;
|
|
5539
|
+
if (this.dependencies.client) this.client = this.dependencies.client;
|
|
5540
|
+
else {
|
|
5541
|
+
const native = this.account.native;
|
|
5542
|
+
if (!native) throw Error("Native calling configuration unavailable");
|
|
5543
|
+
const host2 = await (this.dependencies.host ?? ensureNativeHost)(native);
|
|
5544
|
+
this.client = host2.client.calls(native.accountId, this.dependencies.socketFactory ?? await nativeCallSocketFactory());
|
|
5545
|
+
}
|
|
5546
|
+
if (this.stopped) {
|
|
5547
|
+
this.client.close();
|
|
5548
|
+
return;
|
|
5549
|
+
}
|
|
5550
|
+
const hello = await this.client.connect();
|
|
5551
|
+
if (this.stopped) {
|
|
5552
|
+
this.client.close();
|
|
5553
|
+
return;
|
|
5554
|
+
}
|
|
5555
|
+
if (!hello.capabilities.directAudio || hello.audioFormat.channels !== 1 || hello.audioFormat.frameMs !== 20) throw Error("Native direct voice unavailable");
|
|
5556
|
+
this.format = hello.audioFormat;
|
|
5557
|
+
this.busy = hello.availability.busy;
|
|
5558
|
+
this.state = this.busy ? "busy" : "available";
|
|
5559
|
+
this.loop = this.consume();
|
|
5560
|
+
} catch {
|
|
5561
|
+
this.state = this.stopped ? "stopped" : "unavailable";
|
|
5562
|
+
this.client?.close();
|
|
5563
|
+
}
|
|
5564
|
+
}
|
|
5565
|
+
current(owned) {
|
|
5566
|
+
return !this.stopped && this.active === owned && !owned.retired && !owned.abort.signal.aborted;
|
|
5567
|
+
}
|
|
5568
|
+
async consume() {
|
|
5569
|
+
try {
|
|
5570
|
+
for await (const event of this.client.events()) {
|
|
5571
|
+
if (this.stopped) break;
|
|
5572
|
+
if (event.type === "hello") {
|
|
5573
|
+
if (event.currentOffer) this.offer(event.currentOffer);
|
|
5574
|
+
else if (event.currentPendingOffer) this.pending(event.currentPendingOffer);
|
|
5575
|
+
} else if (event.type === "call.pending" && event.offer) this.pending(event.offer);
|
|
5576
|
+
else if (event.type === "call.offered") this.offer(event.offer);
|
|
5577
|
+
else if (event.type === "call.state") {
|
|
5578
|
+
if (event.call.state === "ended" && this.unconfirmedCallId === event.call.callId && !this.active) {
|
|
5579
|
+
this.unconfirmedCallId = void 0;
|
|
5580
|
+
this.state = this.busy ? "busy" : "available";
|
|
5581
|
+
}
|
|
5582
|
+
const active2 = this.active;
|
|
5583
|
+
if (!active2 || active2.callId && active2.callId !== event.call.callId) continue;
|
|
5584
|
+
if (event.call.kind !== "direct" || event.call.callType !== "voice") {
|
|
5585
|
+
this.state = "needs_review";
|
|
5586
|
+
await this.retire(active2);
|
|
5587
|
+
this.client?.close();
|
|
5588
|
+
continue;
|
|
5589
|
+
}
|
|
5590
|
+
if (!event.call.ownedByThisClient) {
|
|
5591
|
+
if (active2.callId === event.call.callId && event.call.state !== "offered") {
|
|
5592
|
+
await this.retire(active2);
|
|
5593
|
+
this.state = event.call.state === "ended" ? "available" : "busy";
|
|
5594
|
+
}
|
|
5595
|
+
continue;
|
|
5596
|
+
}
|
|
5597
|
+
active2.callId = event.call.callId;
|
|
5598
|
+
active2.call = event.call;
|
|
5599
|
+
if (["ending", "ended", "uncertain"].includes(event.call.state)) {
|
|
5600
|
+
active2.output?.close();
|
|
5601
|
+
active2.media?.stopAudio();
|
|
5602
|
+
this.stopVoice(active2);
|
|
5603
|
+
if (event.call.state === "ending") {
|
|
5604
|
+
active2.endStarted = true;
|
|
5605
|
+
this.armTerminalWait(active2);
|
|
5606
|
+
} else {
|
|
5607
|
+
this.state = event.call.state === "uncertain" ? "needs_review" : "available";
|
|
5608
|
+
this.unconfirmedCallId = event.call.state === "uncertain" ? event.call.callId : void 0;
|
|
5609
|
+
await this.retire(active2);
|
|
5610
|
+
}
|
|
5611
|
+
} else if (event.call.state === "connected" && active2.claimed) void this.attach(active2);
|
|
5612
|
+
} else if (event.type === "calls.availability") {
|
|
5613
|
+
this.busy = event.availability.busy;
|
|
5614
|
+
if (this.active?.claimed && !event.availability.ownedByThisClient) await this.retire(this.active);
|
|
5615
|
+
if (event.availability.busy && !this.active && this.state !== "needs_review") this.state = "busy";
|
|
5616
|
+
if (!event.availability.busy) {
|
|
5617
|
+
if (this.active?.claimed) await this.retire(this.active);
|
|
5618
|
+
if (this.state !== "needs_review") this.state = "available";
|
|
5619
|
+
}
|
|
5620
|
+
} else if (event.type === "call.error" && ["outcome_unknown", "forbidden", "closed"].includes(event.code)) {
|
|
5621
|
+
this.state = "needs_review";
|
|
5622
|
+
if (this.active) await this.retire(this.active);
|
|
5623
|
+
this.client?.close();
|
|
5624
|
+
break;
|
|
5625
|
+
}
|
|
5626
|
+
}
|
|
5627
|
+
} catch {
|
|
5628
|
+
if (!this.stopped) {
|
|
5629
|
+
this.state = "needs_review";
|
|
5630
|
+
if (this.active) await this.retire(this.active);
|
|
5631
|
+
this.client?.close();
|
|
5632
|
+
}
|
|
5633
|
+
}
|
|
5634
|
+
}
|
|
5635
|
+
offer(offer) {
|
|
5636
|
+
if (!this.allowedIncoming(offer)) return;
|
|
5637
|
+
const existing = this.active;
|
|
5638
|
+
if (existing?.callId === offer.callId && existing.peer === offer.callerId && !existing.claimed) {
|
|
5639
|
+
existing.offered = offer;
|
|
5640
|
+
existing.candidateRevision = offer.revision;
|
|
5641
|
+
if (existing.ready && existing.voice) void this.claim(existing, offer);
|
|
5642
|
+
return;
|
|
5643
|
+
}
|
|
5644
|
+
if (existing || this.seen.has(offer.callId) || this.state === "needs_review") return;
|
|
5645
|
+
const active2 = this.incoming(offer);
|
|
5646
|
+
active2.offered = offer;
|
|
5647
|
+
void this.prepareIncoming(active2);
|
|
5648
|
+
}
|
|
5649
|
+
allowedIncoming(offer) {
|
|
5650
|
+
return !!this.config && this.config.inboundPolicy === "allowlist" && this.config.inboundAllowFrom.includes(offer.callerId) && offer.kind === "direct" && offer.callType === "voice";
|
|
5651
|
+
}
|
|
5652
|
+
pending(offer) {
|
|
5653
|
+
if (!this.allowedIncoming(offer)) return;
|
|
5654
|
+
if (this.active?.callId === offer.callId && this.active.peer === offer.callerId && !this.active.submitted) {
|
|
5655
|
+
this.active.candidateRevision = offer.revision;
|
|
5656
|
+
return;
|
|
5657
|
+
}
|
|
5658
|
+
if (this.active || this.seen.has(offer.callId) || this.state === "needs_review") return;
|
|
5659
|
+
void this.prepareIncoming(this.incoming(offer));
|
|
5660
|
+
}
|
|
5661
|
+
incoming(offer) {
|
|
5662
|
+
if (this.seen.size >= 128) this.seen.delete(this.seen.values().next().value);
|
|
5663
|
+
this.seen.add(offer.callId);
|
|
5664
|
+
const active2 = this.reserve(offer.callerId, offer.callId);
|
|
5665
|
+
active2.candidateRevision = offer.revision;
|
|
5666
|
+
active2.timer = setTimeout(() => {
|
|
5667
|
+
if (this.current(active2) && !active2.claimed) void this.fail(active2);
|
|
5668
|
+
}, 2e4);
|
|
5669
|
+
active2.timer.unref?.();
|
|
5670
|
+
return active2;
|
|
5671
|
+
}
|
|
5672
|
+
async prepareIncoming(active2) {
|
|
5673
|
+
try {
|
|
5674
|
+
await this.openVoice(active2);
|
|
5675
|
+
if (!this.current(active2)) return;
|
|
5676
|
+
active2.incomingReadinessAttempted = true;
|
|
5677
|
+
await this.client.ready(randomUUID8(), true, this.format, { kind: "offer", callId: active2.callId, expectedRevision: active2.candidateRevision });
|
|
5678
|
+
if (!this.current(active2)) return;
|
|
5679
|
+
active2.ready = true;
|
|
5680
|
+
if (active2.offered) void this.claim(active2, active2.offered);
|
|
5681
|
+
} catch (error) {
|
|
5682
|
+
await this.claimFailed(active2, error);
|
|
5683
|
+
}
|
|
5684
|
+
}
|
|
5685
|
+
reserve(peer, callId) {
|
|
5686
|
+
const active2 = { key: randomUUID8(), peer, callId, claimed: false, submitted: false, ready: false, incomingReadinessAttempted: false, claiming: false, abort: new AbortController(), retired: false, attaching: false, endStarted: false };
|
|
5687
|
+
this.active = active2;
|
|
5688
|
+
this.state = "preparing";
|
|
5689
|
+
return active2;
|
|
5690
|
+
}
|
|
5691
|
+
async openVoice(active2) {
|
|
5692
|
+
const opening = this.prepared.open(
|
|
5693
|
+
{
|
|
5694
|
+
audio: (audio, metadata) => {
|
|
5695
|
+
if (this.current(active2)) active2.output?.enqueue(audio, metadata);
|
|
5696
|
+
},
|
|
5697
|
+
clear: () => {
|
|
5698
|
+
if (this.current(active2)) void active2.output?.clear();
|
|
5699
|
+
},
|
|
5700
|
+
failed: () => {
|
|
5701
|
+
if (this.current(active2)) void this.fail(active2);
|
|
5702
|
+
}
|
|
5703
|
+
},
|
|
5704
|
+
{ senderId: active2.peer, signal: active2.abort.signal }
|
|
5705
|
+
);
|
|
5706
|
+
void opening.then((voice) => {
|
|
5707
|
+
if (!this.current(active2)) void Promise.resolve(voice.close()).catch(() => {
|
|
5708
|
+
});
|
|
5709
|
+
}, () => {
|
|
5710
|
+
});
|
|
5711
|
+
active2.voice = await bounded(opening, 1e4);
|
|
5712
|
+
if (!this.current(active2)) throw Error("Calling preflight superseded");
|
|
5713
|
+
}
|
|
5714
|
+
async claim(active2, offer) {
|
|
5715
|
+
if (!this.current(active2) || active2.claiming || active2.claimed || !active2.ready || !active2.voice) return;
|
|
5716
|
+
active2.claiming = true;
|
|
5717
|
+
try {
|
|
5718
|
+
active2.submitted = true;
|
|
5719
|
+
const result = await this.client.answer(randomUUID8(), offer.callId, offer.revision);
|
|
5720
|
+
if (!this.current(active2)) return;
|
|
5721
|
+
if (result.callId !== offer.callId || !result.ownerToken) throw Error("Calling claim not admitted");
|
|
5722
|
+
active2.claimed = true;
|
|
5723
|
+
this.armDuration(active2);
|
|
5724
|
+
this.state = "busy";
|
|
5725
|
+
if (active2.call?.state === "connected") void this.attach(active2);
|
|
5726
|
+
} catch (error) {
|
|
5727
|
+
await this.claimFailed(active2, error);
|
|
5728
|
+
}
|
|
5729
|
+
}
|
|
5730
|
+
async claimFailed(active2, error) {
|
|
5731
|
+
if (this.current(active2)) {
|
|
5732
|
+
const knownLoss = error instanceof NativeCallError && ["already_claimed", "offer_expired", "stale", "busy", "unsupported"].includes(error.code) && !error.outcomeUnknown;
|
|
5733
|
+
this.state = knownLoss ? this.busy ? "busy" : "available" : active2.submitted || active2.incomingReadinessAttempted ? "needs_review" : "unavailable";
|
|
5734
|
+
await this.retire(active2);
|
|
5735
|
+
if (!knownLoss) this.client?.close();
|
|
5736
|
+
}
|
|
5737
|
+
}
|
|
5738
|
+
async dial(peer, access2) {
|
|
5739
|
+
access2.signal?.throwIfAborted();
|
|
5740
|
+
access2.assertCurrent();
|
|
5741
|
+
if (!this.config || this.config.outboundPolicy !== "allowlist" || !this.config.outboundAllowTo.includes(peer) || peer.endsWith("@chatroom")) throw Error("Calling destination not permitted");
|
|
5742
|
+
if (this.stopped || this.state !== "available" || this.active || this.busy || !this.prepared || !this.client) throw Error("Calling service is not available");
|
|
5743
|
+
const active2 = this.reserve(peer);
|
|
5744
|
+
const aborted = () => {
|
|
5745
|
+
if (this.current(active2) && !active2.claimed) void this.fail(active2);
|
|
5746
|
+
};
|
|
5747
|
+
access2.signal?.addEventListener("abort", aborted, { once: true });
|
|
5748
|
+
try {
|
|
5749
|
+
await this.openVoice(active2);
|
|
5750
|
+
access2.signal?.throwIfAborted();
|
|
5751
|
+
access2.assertCurrent();
|
|
5752
|
+
if (!this.current(active2)) throw Error("Calling preflight superseded");
|
|
5753
|
+
await this.client.ready(randomUUID8(), true, this.format, { kind: "outgoing" });
|
|
5754
|
+
access2.signal?.throwIfAborted();
|
|
5755
|
+
access2.assertCurrent();
|
|
5756
|
+
if (!this.current(active2)) throw Error("Calling preflight superseded");
|
|
5757
|
+
active2.submitted = true;
|
|
5758
|
+
const result = await this.client.dial(randomUUID8(), peer);
|
|
5759
|
+
if (!this.current(active2) || !result.callId || !result.ownerToken) throw Error("Calling dial outcome not admitted");
|
|
5760
|
+
active2.callId = result.callId;
|
|
5761
|
+
active2.claimed = true;
|
|
5762
|
+
this.state = "busy";
|
|
5763
|
+
this.armDuration(active2);
|
|
5764
|
+
if (active2.call?.state === "connected") void this.attach(active2);
|
|
5765
|
+
return { callId: result.callId };
|
|
5766
|
+
} catch (error) {
|
|
5767
|
+
const unknown = active2.submitted && (!(error instanceof NativeCallError) || error.outcomeUnknown);
|
|
5768
|
+
if (this.current(active2)) {
|
|
5769
|
+
this.state = unknown ? "needs_review" : active2.submitted ? "available" : "unavailable";
|
|
5770
|
+
await this.retire(active2);
|
|
5771
|
+
if (unknown || !active2.submitted) this.client.close();
|
|
5772
|
+
}
|
|
5773
|
+
throw Error(unknown ? "Call outcome needs review; no automatic redial" : "Call was not admitted");
|
|
5774
|
+
} finally {
|
|
5775
|
+
access2.signal?.removeEventListener("abort", aborted);
|
|
5776
|
+
}
|
|
5777
|
+
}
|
|
5778
|
+
armDuration(active2) {
|
|
5779
|
+
clearTimeout(active2.timer);
|
|
5780
|
+
active2.timer = setTimeout(() => {
|
|
5781
|
+
if (this.current(active2)) void this.end().catch(() => {
|
|
5782
|
+
});
|
|
5783
|
+
}, this.config.maxDurationSeconds * 1e3);
|
|
5784
|
+
active2.timer.unref?.();
|
|
5785
|
+
}
|
|
5786
|
+
async attach(active2) {
|
|
5787
|
+
if (!this.current(active2) || !active2.claimed || active2.attaching || active2.media || !active2.callId || active2.endStarted) return;
|
|
5788
|
+
active2.attaching = true;
|
|
5789
|
+
try {
|
|
5790
|
+
const media = await this.client.attachMedia(active2.callId);
|
|
5791
|
+
if (this.stopped || this.active !== active2 || active2.retired) {
|
|
5792
|
+
media.close();
|
|
5793
|
+
return;
|
|
5794
|
+
}
|
|
5795
|
+
active2.media = media;
|
|
5796
|
+
if (active2.endStarted) {
|
|
5797
|
+
media.stopAudio();
|
|
5798
|
+
this.armTerminalWait(active2);
|
|
5799
|
+
return;
|
|
5800
|
+
}
|
|
5801
|
+
if (!this.current(active2)) {
|
|
5802
|
+
media.close();
|
|
5803
|
+
return;
|
|
5804
|
+
}
|
|
5805
|
+
const tracks = media.tracks();
|
|
5806
|
+
if (JSON.stringify(tracks.sendTrack.format) !== JSON.stringify(this.format) || JSON.stringify(tracks.receiveTrack.format) !== JSON.stringify(this.format)) throw Error("Calling PCM changed");
|
|
5807
|
+
active2.output = new CallPcmOutput(media, this.format, this.prepared, () => this.client.clearAudio(randomUUID8(), active2.callId), () => {
|
|
5808
|
+
void this.fail(active2);
|
|
5809
|
+
});
|
|
5810
|
+
const resampler = this.prepared.resampler(this.format.sampleRate, this.prepared.sampleRate);
|
|
5811
|
+
void (async () => {
|
|
5812
|
+
let receivedMs = 0;
|
|
5813
|
+
try {
|
|
5814
|
+
for await (const frame of media.frames()) {
|
|
5815
|
+
if (!this.current(active2) || active2.endStarted) break;
|
|
5816
|
+
const audio = resampler.process(Buffer.from(frame.payload));
|
|
5817
|
+
if (audio.length > this.prepared.sampleRate * 2 || !Number.isFinite(receivedMs) || receivedMs > Number.MAX_SAFE_INTEGER) throw Error("Calling input budget exceeded");
|
|
5818
|
+
active2.voice.setMediaTimestamp(receivedMs);
|
|
5819
|
+
receivedMs += frame.payload.byteLength * 1e3 / (this.format.sampleRate * this.format.channels * 2);
|
|
5820
|
+
active2.voice.sendAudio(audio);
|
|
5821
|
+
}
|
|
5822
|
+
} catch {
|
|
5823
|
+
if (this.current(active2) && !active2.endStarted) await this.fail(active2);
|
|
5824
|
+
}
|
|
5825
|
+
})();
|
|
5826
|
+
} catch {
|
|
5827
|
+
if (this.current(active2)) await this.fail(active2);
|
|
5828
|
+
} finally {
|
|
5829
|
+
active2.attaching = false;
|
|
5830
|
+
}
|
|
5831
|
+
}
|
|
5832
|
+
async end() {
|
|
5833
|
+
const active2 = this.active;
|
|
5834
|
+
if (!active2?.claimed || !active2.callId || !active2.call || !this.client || active2.endStarted) throw Error("No owned call can be ended");
|
|
5835
|
+
if (!["dialing", "ringing", "connecting", "connected"].includes(active2.call.state)) throw Error("Call cannot be ended in this state");
|
|
5836
|
+
active2.endStarted = true;
|
|
5837
|
+
active2.output?.close();
|
|
5838
|
+
active2.media?.stopAudio();
|
|
5839
|
+
this.stopVoice(active2);
|
|
5840
|
+
this.armTerminalWait(active2);
|
|
5841
|
+
try {
|
|
5842
|
+
await this.client.end(["dialing", "ringing"].includes(active2.call.state) ? "call.cancel" : "call.hangup", randomUUID8(), active2.callId, active2.call.revision);
|
|
5843
|
+
} catch {
|
|
5844
|
+
this.state = "needs_review";
|
|
5845
|
+
this.client.close();
|
|
5846
|
+
await this.retire(active2);
|
|
5847
|
+
throw Error("Call end outcome needs review");
|
|
5848
|
+
}
|
|
5849
|
+
}
|
|
5850
|
+
async fail(active2) {
|
|
5851
|
+
if (active2.endStarted && !this.stopped && this.active === active2 && !active2.retired) {
|
|
5852
|
+
active2.output?.close();
|
|
5853
|
+
active2.media?.stopAudio();
|
|
5854
|
+
this.stopVoice(active2);
|
|
5855
|
+
this.armTerminalWait(active2);
|
|
5856
|
+
return;
|
|
5857
|
+
}
|
|
5858
|
+
if (!this.current(active2)) return;
|
|
5859
|
+
active2.output?.close();
|
|
5860
|
+
if (active2.claimed && active2.call && !active2.endStarted) {
|
|
5861
|
+
try {
|
|
5862
|
+
await bounded(this.end(), 2e3);
|
|
5863
|
+
return;
|
|
5864
|
+
} catch {
|
|
5865
|
+
}
|
|
5866
|
+
}
|
|
5867
|
+
this.state = active2.submitted || active2.incomingReadinessAttempted ? "needs_review" : "unavailable";
|
|
5868
|
+
await this.retire(active2);
|
|
5869
|
+
this.client?.close();
|
|
5870
|
+
}
|
|
5871
|
+
stopVoice(active2) {
|
|
5872
|
+
active2.abort.abort();
|
|
5873
|
+
const voice = active2.voice;
|
|
5874
|
+
if (!voice) return;
|
|
5875
|
+
active2.voice = void 0;
|
|
5876
|
+
active2.voiceClosing = bounded(Promise.resolve().then(() => voice.close()), 1e3).then(() => {
|
|
5877
|
+
}, () => {
|
|
5878
|
+
});
|
|
5879
|
+
}
|
|
5880
|
+
armTerminalWait(active2) {
|
|
5881
|
+
clearTimeout(active2.timer);
|
|
5882
|
+
if (active2.endTimer) return;
|
|
5883
|
+
active2.endTimer = setTimeout(() => {
|
|
5884
|
+
if (this.stopped || this.active !== active2 || active2.retired) return;
|
|
5885
|
+
this.state = "needs_review";
|
|
5886
|
+
this.client?.close();
|
|
5887
|
+
void this.retire(active2);
|
|
5888
|
+
}, TERMINAL_WAIT_MS);
|
|
5889
|
+
active2.endTimer.unref?.();
|
|
5890
|
+
}
|
|
5891
|
+
async retire(active2) {
|
|
5892
|
+
if (active2.retired) return;
|
|
5893
|
+
active2.retired = true;
|
|
5894
|
+
clearTimeout(active2.timer);
|
|
5895
|
+
clearTimeout(active2.endTimer);
|
|
5896
|
+
active2.output?.close();
|
|
5897
|
+
active2.media?.close();
|
|
5898
|
+
this.stopVoice(active2);
|
|
5899
|
+
if (this.active === active2) this.active = void 0;
|
|
5900
|
+
await active2.voiceClosing;
|
|
5901
|
+
}
|
|
5902
|
+
async stop() {
|
|
5903
|
+
if (this.stopped) return;
|
|
5904
|
+
this.stopped = true;
|
|
5905
|
+
if (this.active?.claimed && !this.active.endStarted) {
|
|
5906
|
+
try {
|
|
5907
|
+
await bounded(this.end(), 2e3);
|
|
5908
|
+
} catch {
|
|
5909
|
+
}
|
|
5910
|
+
}
|
|
5911
|
+
this.client?.close();
|
|
5912
|
+
if (this.active) await this.retire(this.active);
|
|
5913
|
+
this.state = "stopped";
|
|
5914
|
+
if (this.loop) {
|
|
5915
|
+
try {
|
|
5916
|
+
await bounded(this.loop, 1e3);
|
|
5917
|
+
} catch {
|
|
5918
|
+
}
|
|
5919
|
+
}
|
|
5920
|
+
}
|
|
5921
|
+
};
|
|
5922
|
+
|
|
5923
|
+
// src/calls-tool.ts
|
|
5924
|
+
function registerNativeCallTool(api, service) {
|
|
5925
|
+
api.registerTool({ contextVersion: 2, create: (context) => {
|
|
5926
|
+
const cfg = context.getRuntimeConfig?.() ?? context.runtimeConfig ?? context.config;
|
|
5927
|
+
const account = cfg && resolveWeChatAccount(cfg);
|
|
5928
|
+
if (!account?.enabled || !account.calls?.voice || !account.native) return [];
|
|
5929
|
+
const configurationKey = nativeConfigurationKey(account.native);
|
|
5930
|
+
const callConfiguration = callsConfigurationKey(account.calls);
|
|
5931
|
+
const check = () => assertCallingToolAccess(context, configurationKey, callConfiguration);
|
|
5932
|
+
return [{
|
|
5933
|
+
name: "wechat_call",
|
|
5934
|
+
label: "WeChat Call",
|
|
5935
|
+
catalogMode: "direct-only",
|
|
5936
|
+
description: "Check this plugin's voice-call status, initiate one authorized direct voice call, or end its owned call. Calls require separate calling allowlists and provider readiness. Never retry an uncertain dial or call without the user's request. This tool does not open a computer microphone, record calls, or grant caller owner privileges.",
|
|
5937
|
+
parameters: { type: "object", additionalProperties: false, required: ["action"], properties: {
|
|
5938
|
+
action: { type: "string", enum: ["status", "dial", "hangup"] },
|
|
5939
|
+
contactId: { type: "string", minLength: 1, maxLength: 200 }
|
|
5940
|
+
} },
|
|
5941
|
+
execute: async (_id, args, signal) => {
|
|
5942
|
+
if (!args || typeof args !== "object" || Array.isArray(args)) throw Error("Invalid calling arguments");
|
|
5943
|
+
const value = args;
|
|
5944
|
+
if (Object.keys(value).some((key) => !["action", "contactId"].includes(key)) || !["status", "dial", "hangup"].includes(value.action) || (value.action === "dial" ? typeof value.contactId !== "string" || !value.contactId || value.contactId.length > 200 : value.contactId !== void 0)) throw Error("Invalid calling arguments");
|
|
5945
|
+
signal?.throwIfAborted();
|
|
5946
|
+
check();
|
|
5947
|
+
const current = service();
|
|
5948
|
+
if (!current) throw Error("Calling service unavailable");
|
|
5949
|
+
const result = value.action === "status" ? current.status() : value.action === "dial" ? await current.dial(value.contactId, { signal, assertCurrent: check }) : await current.end();
|
|
5950
|
+
return { content: [{ type: "text", text: JSON.stringify(result ?? { requested: true }) }], details: result ?? { requested: true } };
|
|
5951
|
+
}
|
|
5952
|
+
}];
|
|
5953
|
+
} }, { names: ["wechat_call"], optional: true });
|
|
5954
|
+
}
|
|
5955
|
+
function assertCallingToolAccess(context, configurationKey, callConfiguration) {
|
|
5956
|
+
if (!context.assertInvocationCurrent) throw Error("Calling tool invocation authority unavailable");
|
|
5957
|
+
context.assertInvocationCurrent();
|
|
5958
|
+
const cfg = context.getRuntimeConfig?.() ?? context.runtimeConfig ?? context.config;
|
|
5959
|
+
const current = cfg && resolveWeChatAccount(cfg);
|
|
5960
|
+
if (!current?.enabled || !current.native || !current.calls?.voice || nativeConfigurationKey(current.native) !== configurationKey || callsConfigurationKey(current.calls) !== callConfiguration || context.agentId !== current.calls.voice.agentId || context.senderIsOwner !== true || !context.requesterSenderId || !current.calls.voice.outboundToolAllowFrom.includes(context.requesterSenderId)) throw Error("Calling tool is not permitted for this requester");
|
|
5961
|
+
}
|
|
5962
|
+
|
|
4533
5963
|
// index.ts
|
|
4534
5964
|
var plugin = {
|
|
4535
5965
|
id: "agent-wechat",
|
|
@@ -4545,6 +5975,8 @@ var plugin = {
|
|
|
4545
5975
|
registerNativeRecallTools(api);
|
|
4546
5976
|
registerNativeGroupTools(api);
|
|
4547
5977
|
registerNativeLoginTool(api);
|
|
5978
|
+
let calls;
|
|
5979
|
+
registerNativeCallTool(api, () => calls);
|
|
4548
5980
|
const stopFacade = selected?.native ? registerNativeFacade(api, selected.native) : () => {
|
|
4549
5981
|
};
|
|
4550
5982
|
const stopPreparedBoundary = selected?.native?.readPolicy && selected.native.readPolicy !== "on_inbound" ? registerNativePreparedBoundary(api) : () => {
|
|
@@ -4555,8 +5987,15 @@ var plugin = {
|
|
|
4555
5987
|
start: async (context) => {
|
|
4556
5988
|
const account = resolveWeChatAccount(context.config);
|
|
4557
5989
|
if (account?.native && account.enabled) await ensureNativeHost(account.native);
|
|
5990
|
+
if (account?.native && account.enabled && account.calls) {
|
|
5991
|
+
calls = new NativeCallService(account, context.config, api.runtime);
|
|
5992
|
+
await calls.start();
|
|
5993
|
+
if (calls.status().state === "unavailable") context.logger.warn("WeChat calling unavailable; messaging remains active");
|
|
5994
|
+
}
|
|
4558
5995
|
},
|
|
4559
5996
|
stop: async () => {
|
|
5997
|
+
await calls?.stop();
|
|
5998
|
+
calls = void 0;
|
|
4560
5999
|
stopFacade();
|
|
4561
6000
|
stopPreparedBoundary();
|
|
4562
6001
|
await stopNativeHost();
|