wechat-clawbot 1.3.3 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cordis.patch.yml +2 -1
- package/lib/bridge.d.ts +11 -0
- package/lib/bridge.d.ts.map +1 -1
- package/lib/bridge.js +89 -6
- package/lib/bridge.js.map +1 -1
- package/lib/claude-peer.d.ts +6 -0
- package/lib/claude-peer.d.ts.map +1 -1
- package/lib/claude-peer.js +21 -0
- package/lib/claude-peer.js.map +1 -1
- package/lib/client.js +22 -0
- package/lib/codex-rpc.js +1 -1
- package/lib/config.d.ts +30 -8
- package/lib/config.d.ts.map +1 -1
- package/lib/config.js +34 -1
- package/lib/config.js.map +1 -1
- package/lib/inbound.d.ts +22 -1
- package/lib/inbound.d.ts.map +1 -1
- package/lib/inbound.js +136 -13
- package/lib/inbound.js.map +1 -1
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +28 -6
- package/lib/index.js.map +1 -1
- package/lib/mcp-server.js +1 -1
- package/lib/monitor.d.ts +25 -0
- package/lib/monitor.d.ts.map +1 -1
- package/lib/monitor.js +107 -8
- package/lib/monitor.js.map +1 -1
- package/lib/onboarding.d.ts +71 -0
- package/lib/onboarding.d.ts.map +1 -0
- package/lib/onboarding.js +255 -0
- package/lib/onboarding.js.map +1 -0
- package/lib/prompt.d.ts +6 -2
- package/lib/prompt.d.ts.map +1 -1
- package/lib/prompt.js +67 -16
- package/lib/prompt.js.map +1 -1
- package/lib/schedule-migrate.d.ts +97 -7
- package/lib/schedule-migrate.d.ts.map +1 -1
- package/lib/schedule-migrate.js +96 -16
- package/lib/schedule-migrate.js.map +1 -1
- package/lib/voice-setup.d.ts +90 -0
- package/lib/voice-setup.d.ts.map +1 -0
- package/lib/voice-setup.js +289 -0
- package/lib/voice-setup.js.map +1 -0
- package/lib/voice.d.ts +182 -0
- package/lib/voice.d.ts.map +1 -0
- package/lib/voice.js +639 -0
- package/lib/voice.js.map +1 -0
- package/native/macos-speech/main.swift +198 -0
- package/package.json +5 -2
- package/wechat-clawbot-INSTALL.md +57 -14
package/lib/voice.js
ADDED
|
@@ -0,0 +1,639 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Voice messages that arrive without WeChat's transcript.
|
|
3
|
+
*
|
|
4
|
+
* WeChat transcribes a voice message itself and sends the text along with the
|
|
5
|
+
* audio (`voice_item.text`); that text is all this plugin ever read. Some
|
|
6
|
+
* evenings the text is simply not there — the item carries the audio and its
|
|
7
|
+
* length, nothing else — and the message used to fall through to "unsupported".
|
|
8
|
+
*
|
|
9
|
+
* On a Mac the plugin now makes the transcript itself: download and decrypt
|
|
10
|
+
* the audio, decode it, and hand a WAV to `clawbot-speech`
|
|
11
|
+
* (native/macos-speech/main.swift), which runs the system's on-device speech
|
|
12
|
+
* models. The audio stays on the machine, macOS asks for no permission, and
|
|
13
|
+
* the WAV is deleted as soon as it has been read.
|
|
14
|
+
*
|
|
15
|
+
* Two things can do the transcribing, tried in this order:
|
|
16
|
+
* 1. DSH's own speech recognition (`ctx.speechToText`, the experimental
|
|
17
|
+
* 语音输入 bundle: a local SenseVoice model), when the owner has switched
|
|
18
|
+
* it on and its model is on disk. The same on macOS, Windows and Linux,
|
|
19
|
+
* which is what makes voice work alike for everyone.
|
|
20
|
+
* 2. This Mac's on-device models, through `clawbot-speech`: nothing to set
|
|
21
|
+
* up, macOS 26 and later only.
|
|
22
|
+
* With neither, the owner is told how to switch the first one on (the bot can
|
|
23
|
+
* do it for them: voice-setup.ts).
|
|
24
|
+
*
|
|
25
|
+
* WeChat voice comes in two encodings. For years it was SILK (`silk-wasm`).
|
|
26
|
+
* The messages that arrive without a transcript are the newer one: Opus
|
|
27
|
+
* packets in a small container of WeChat's own, `#!OPUS_RAW_V1` (`opusscript`).
|
|
28
|
+
*
|
|
29
|
+
* Everything here answers with an outcome instead of throwing: a voice message
|
|
30
|
+
* that cannot be transcribed is still a message the owner sent, and the router
|
|
31
|
+
* tells them so in plain words.
|
|
32
|
+
*/
|
|
33
|
+
import { execFile } from "node:child_process";
|
|
34
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
35
|
+
import fs from "node:fs";
|
|
36
|
+
import os from "node:os";
|
|
37
|
+
import path from "node:path";
|
|
38
|
+
import { fileURLToPath } from "node:url";
|
|
39
|
+
import { downloadAndDecryptBuffer, downloadPlainCdnBuffer } from "./ilink/cdn/pic-decrypt.js";
|
|
40
|
+
import { MessageItemType } from "./ilink/api/types.js";
|
|
41
|
+
import { resolveStateDir } from "./ilink/storage/state-dir.js";
|
|
42
|
+
import { logger } from "./ilink/util/logger.js";
|
|
43
|
+
/** Read DSH's speech recognition without trusting it to be there or to be the version this was written against. */
|
|
44
|
+
export function hostSpeechStatus(speech) {
|
|
45
|
+
if (speech === undefined || speech === null || typeof speech.snapshot !== "function")
|
|
46
|
+
return { state: "absent" };
|
|
47
|
+
try {
|
|
48
|
+
const snap = speech.snapshot();
|
|
49
|
+
const wanted = snap.selection?.providerId;
|
|
50
|
+
const provider = snap.providers.find((p) => p.id === wanted) ?? (wanted === undefined ? snap.providers[0] : undefined);
|
|
51
|
+
if (provider === undefined)
|
|
52
|
+
return { state: "absent" };
|
|
53
|
+
const phase = String(provider.preparation?.phase ?? "ready");
|
|
54
|
+
const state = phase === "ready" || phase === "standby" || phase === "waking"
|
|
55
|
+
? "ready"
|
|
56
|
+
: phase === "downloading" || phase === "checking" || phase === "loading"
|
|
57
|
+
? "preparing"
|
|
58
|
+
: phase === "failed" ? "failed" : "unprepared";
|
|
59
|
+
return {
|
|
60
|
+
state,
|
|
61
|
+
providerId: String(provider.id),
|
|
62
|
+
name: typeof provider.name === "string" && provider.name !== "" ? provider.name : String(provider.id),
|
|
63
|
+
phase,
|
|
64
|
+
local: provider.location !== "cloud",
|
|
65
|
+
...(typeof provider.preparation?.message === "string" ? { message: provider.preparation.message.slice(0, 200) } : {}),
|
|
66
|
+
...(typeof provider.preparation?.completedBytes === "number" ? { completedBytes: provider.preparation.completedBytes } : {}),
|
|
67
|
+
...(typeof provider.preparation?.totalBytes === "number" ? { totalBytes: provider.preparation.totalBytes } : {}),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
logger.warn(`voice: could not read DSH's speech recognition: ${String(err.message ?? err).slice(0, 160)}`);
|
|
72
|
+
return { state: "absent" };
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const HELPER_NAME = "clawbot-speech";
|
|
76
|
+
/** A failed build is not retried on every voice message. */
|
|
77
|
+
const BUILD_RETRY_MS = 10 * 60_000;
|
|
78
|
+
/** WeChat voice runs to a minute; anything far past that is not a voice message. */
|
|
79
|
+
const VOICE_MAX_BYTES = 20 * 1024 * 1024;
|
|
80
|
+
/** The message loop waits on a voice message this long for its audio, and this long for its text, at most. */
|
|
81
|
+
const DOWNLOAD_TIMEOUT_MS = 30_000;
|
|
82
|
+
const TRANSCRIBE_TIMEOUT_MS = 40_000;
|
|
83
|
+
/**
|
|
84
|
+
* Voice is decoded to 16 kHz mono, whatever it was recorded at: what speech
|
|
85
|
+
* models are trained on, and the one form DSH's recognizer accepts. Both
|
|
86
|
+
* decoders resample to the rate they are asked for.
|
|
87
|
+
*/
|
|
88
|
+
const PCM_SAMPLE_RATE = 16_000;
|
|
89
|
+
/** DSH's recognizer gets this long for one voice message. */
|
|
90
|
+
const HOST_TRANSCRIBE_TIMEOUT_MS = 60_000;
|
|
91
|
+
/**
|
|
92
|
+
* WeChat's Opus voice container: this marker, one byte for the sample rate (an
|
|
93
|
+
* index into OPUS_RAW_RATES), one for the channel count, one zero byte; then
|
|
94
|
+
* the packets, each behind its length as a little-endian 16-bit number. A
|
|
95
|
+
* length of zero stands for a packet that was lost.
|
|
96
|
+
*/
|
|
97
|
+
const OPUS_RAW_MAGIC = "#!OPUS_RAW_V1";
|
|
98
|
+
const OPUS_RAW_HEADER_BYTES = 16;
|
|
99
|
+
const OPUS_RAW_RATES = [8000, 12000, 16000, 24000, 48000];
|
|
100
|
+
/** The most one Opus packet can be (three 1276-byte frames). */
|
|
101
|
+
const OPUS_MAX_PACKET_BYTES = 3828;
|
|
102
|
+
/** Five minutes of audio is far past any voice message. */
|
|
103
|
+
const VOICE_MAX_SECONDS = 300;
|
|
104
|
+
/** macOS 26 is Darwin 25: the first with the on-device speech models. */
|
|
105
|
+
const MIN_DARWIN_MAJOR = 25;
|
|
106
|
+
class HelperError extends Error {
|
|
107
|
+
reason;
|
|
108
|
+
constructor(reason, message) {
|
|
109
|
+
super(message);
|
|
110
|
+
this.reason = reason;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
function execFileP(file, args, timeoutMs) {
|
|
114
|
+
return new Promise((resolve, reject) => {
|
|
115
|
+
execFile(file, [...args], { timeout: timeoutMs, maxBuffer: 4 << 20 }, (err, stdout, stderr) => {
|
|
116
|
+
if (err === null)
|
|
117
|
+
resolve({ stdout, stderr });
|
|
118
|
+
else
|
|
119
|
+
reject(Object.assign(err, { stdout, stderr }));
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
/** True for a voice item WeChat sent without its transcript. */
|
|
124
|
+
export function voiceLacksTranscript(item) {
|
|
125
|
+
return !!item && item.type === MessageItemType.VOICE && !item.voice_item?.text?.trim();
|
|
126
|
+
}
|
|
127
|
+
/** Whether this machine can transcribe at all (a Mac on macOS 26 or later). */
|
|
128
|
+
export function voicePlatformSupported(platform = process.platform, release = os.release()) {
|
|
129
|
+
if (platform !== "darwin")
|
|
130
|
+
return false;
|
|
131
|
+
const major = Number.parseInt(release.split(".")[0] ?? "", 10);
|
|
132
|
+
return Number.isFinite(major) && major >= MIN_DARWIN_MAJOR;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* A transcript as a person would have typed it. The newer speech model sets
|
|
136
|
+
* Chinese apart with spaces of its own ("下午 3:00提醒我 ,然后"); none belongs
|
|
137
|
+
* next to a Chinese character or Chinese punctuation. Spaces between words in
|
|
138
|
+
* another script are left alone.
|
|
139
|
+
*/
|
|
140
|
+
export function tidyTranscript(text) {
|
|
141
|
+
return text
|
|
142
|
+
.replace(/\s+/g, " ")
|
|
143
|
+
.replace(/(?<=[\p{Script=Han},。!?;:、)》」』])\s+|\s+(?=[\p{Script=Han},。!?;:、(《「『])/gu, "")
|
|
144
|
+
.trim();
|
|
145
|
+
}
|
|
146
|
+
/** 16-bit little-endian PCM (mono unless told otherwise) in a WAV container. */
|
|
147
|
+
export function pcmToWav(pcm, sampleRate, channels = 1) {
|
|
148
|
+
const header = Buffer.alloc(44);
|
|
149
|
+
header.write("RIFF", 0, "ascii");
|
|
150
|
+
header.writeUInt32LE(36 + pcm.byteLength, 4);
|
|
151
|
+
header.write("WAVE", 8, "ascii");
|
|
152
|
+
header.write("fmt ", 12, "ascii");
|
|
153
|
+
header.writeUInt32LE(16, 16);
|
|
154
|
+
header.writeUInt16LE(1, 20); // PCM
|
|
155
|
+
header.writeUInt16LE(channels, 22);
|
|
156
|
+
header.writeUInt32LE(sampleRate, 24);
|
|
157
|
+
header.writeUInt32LE(sampleRate * channels * 2, 28);
|
|
158
|
+
header.writeUInt16LE(channels * 2, 32);
|
|
159
|
+
header.writeUInt16LE(16, 34);
|
|
160
|
+
header.write("data", 36, "ascii");
|
|
161
|
+
header.writeUInt32LE(pcm.byteLength, 40);
|
|
162
|
+
return Buffer.concat([header, Buffer.from(pcm.buffer, pcm.byteOffset, pcm.byteLength)]);
|
|
163
|
+
}
|
|
164
|
+
/** What the downloaded bytes are, by their first bytes (the item's encode_type is not always filled in). */
|
|
165
|
+
export function sniffAudio(buf) {
|
|
166
|
+
const ascii = (start, length) => buf.subarray(start, start + length).toString("latin1");
|
|
167
|
+
// Tencent's SILK starts with one 0x02 byte before the standard marker.
|
|
168
|
+
if (ascii(0, 9) === "#!SILK_V3" || (buf[0] === 0x02 && ascii(1, 9) === "#!SILK_V3"))
|
|
169
|
+
return "silk";
|
|
170
|
+
if (ascii(0, OPUS_RAW_MAGIC.length) === OPUS_RAW_MAGIC)
|
|
171
|
+
return "opus-raw";
|
|
172
|
+
if (ascii(0, 4) === "RIFF" && ascii(8, 4) === "WAVE")
|
|
173
|
+
return "wav";
|
|
174
|
+
if (ascii(0, 5) === "#!AMR")
|
|
175
|
+
return "amr";
|
|
176
|
+
if (ascii(4, 4) === "ftyp")
|
|
177
|
+
return "m4a";
|
|
178
|
+
if (ascii(0, 3) === "ID3" || (buf.length > 1 && buf[0] === 0xff && (buf[1] & 0xe0) === 0xe0))
|
|
179
|
+
return "mp3";
|
|
180
|
+
return "unknown";
|
|
181
|
+
}
|
|
182
|
+
/** silk-wasm, loaded on first use: a plugin without it still starts, and only voice goes without. */
|
|
183
|
+
async function loadSilk() {
|
|
184
|
+
const loaded = (await import("silk-wasm"));
|
|
185
|
+
const decode = loaded.decode ?? loaded.default?.decode;
|
|
186
|
+
if (typeof decode !== "function")
|
|
187
|
+
throw new Error("silk-wasm has no decode()");
|
|
188
|
+
return { decode };
|
|
189
|
+
}
|
|
190
|
+
/** opusscript (libopus compiled to WebAssembly), loaded on first use like silk-wasm. */
|
|
191
|
+
async function loadOpus() {
|
|
192
|
+
const loaded = (await import("opusscript"));
|
|
193
|
+
const ctor = typeof loaded.default === "function" ? loaded.default : loaded;
|
|
194
|
+
if (typeof ctor !== "function")
|
|
195
|
+
throw new Error("opusscript did not load");
|
|
196
|
+
return ctor;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* WeChat's `#!OPUS_RAW_V1` voice as 16-bit PCM with the channel count its
|
|
200
|
+
* header names, at `outputRate` (Opus decodes to any of its rates; default:
|
|
201
|
+
* the rate the header names).
|
|
202
|
+
*/
|
|
203
|
+
export async function decodeOpusRaw(buf, outputRate) {
|
|
204
|
+
if (buf.length < OPUS_RAW_HEADER_BYTES || buf.subarray(0, OPUS_RAW_MAGIC.length).toString("latin1") !== OPUS_RAW_MAGIC) {
|
|
205
|
+
throw new Error("not an OPUS_RAW_V1 file");
|
|
206
|
+
}
|
|
207
|
+
const recordedRate = OPUS_RAW_RATES[buf[13]];
|
|
208
|
+
const channels = buf[14];
|
|
209
|
+
if (recordedRate === undefined || (channels !== 1 && channels !== 2) || buf[15] !== 0) {
|
|
210
|
+
throw new Error(`an OPUS_RAW_V1 header this version does not know (rate ${buf[13]}, channels ${buf[14]}, then ${buf[15]})`);
|
|
211
|
+
}
|
|
212
|
+
const sampleRate = outputRate ?? recordedRate;
|
|
213
|
+
if (!OPUS_RAW_RATES.includes(sampleRate))
|
|
214
|
+
throw new Error(`Opus does not decode to ${sampleRate} Hz`);
|
|
215
|
+
const Opus = await loadOpus();
|
|
216
|
+
const decoder = new Opus(sampleRate, channels);
|
|
217
|
+
const bytesPerSecond = sampleRate * channels * 2;
|
|
218
|
+
// A packet that never arrived: 20 ms of silence where it would have been.
|
|
219
|
+
const lost = Buffer.alloc(bytesPerSecond / 50);
|
|
220
|
+
const pieces = [];
|
|
221
|
+
let total = 0;
|
|
222
|
+
try {
|
|
223
|
+
let pos = OPUS_RAW_HEADER_BYTES;
|
|
224
|
+
while (pos + 2 <= buf.length) {
|
|
225
|
+
const length = buf.readUInt16LE(pos);
|
|
226
|
+
pos += 2;
|
|
227
|
+
if (length > OPUS_MAX_PACKET_BYTES)
|
|
228
|
+
throw new Error(`an Opus packet of ${length} bytes`);
|
|
229
|
+
if (length > buf.length - pos) {
|
|
230
|
+
// Cut off mid-packet: what was decoded before it still counts.
|
|
231
|
+
if (total === 0)
|
|
232
|
+
throw new Error("the first Opus packet is cut off");
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
const piece = length === 0 ? lost : decoder.decode(buf.subarray(pos, pos + length));
|
|
236
|
+
pos += length;
|
|
237
|
+
if (piece.length === 0)
|
|
238
|
+
throw new Error("an Opus packet decoded to nothing");
|
|
239
|
+
total += piece.length;
|
|
240
|
+
if (total > bytesPerSecond * VOICE_MAX_SECONDS)
|
|
241
|
+
throw new Error(`more than ${VOICE_MAX_SECONDS} s of audio`);
|
|
242
|
+
pieces.push(piece);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
finally {
|
|
246
|
+
decoder.delete();
|
|
247
|
+
}
|
|
248
|
+
if (total === 0)
|
|
249
|
+
throw new Error("no Opus packets in the file");
|
|
250
|
+
return { pcm: Buffer.concat(pieces), sampleRate, channels };
|
|
251
|
+
}
|
|
252
|
+
/** Two interleaved 16-bit channels averaged into one. */
|
|
253
|
+
export function stereoToMono(pcm) {
|
|
254
|
+
const mono = Buffer.alloc(Math.floor(pcm.length / 4) * 2);
|
|
255
|
+
for (let i = 0; i + 3 < pcm.length; i += 4) {
|
|
256
|
+
mono.writeInt16LE(Math.round((pcm.readInt16LE(i) + pcm.readInt16LE(i + 2)) / 2), i / 2);
|
|
257
|
+
}
|
|
258
|
+
return mono;
|
|
259
|
+
}
|
|
260
|
+
/** True for exactly the WAV DSH's recognizer takes: a 44-byte header, PCM, mono, 16 kHz, 16-bit, lengths that add up. */
|
|
261
|
+
export function isCanonicalWav(buf) {
|
|
262
|
+
return buf.length > 44
|
|
263
|
+
&& buf.subarray(0, 4).toString("latin1") === "RIFF" && buf.subarray(8, 16).toString("latin1") === "WAVEfmt "
|
|
264
|
+
&& buf.readUInt32LE(4) === buf.length - 8 && buf.readUInt32LE(16) === 16
|
|
265
|
+
&& buf.readUInt16LE(20) === 1 && buf.readUInt16LE(22) === 1 && buf.readUInt32LE(24) === PCM_SAMPLE_RATE
|
|
266
|
+
&& buf.readUInt16LE(34) === 16 && buf.subarray(36, 40).toString("latin1") === "data"
|
|
267
|
+
&& buf.readUInt32LE(40) === buf.length - 44;
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* The audio as a file a speech model can open: its bytes, the extension to
|
|
271
|
+
* save them under, and whether it is the canonical WAV (16 kHz, mono, 16-bit)
|
|
272
|
+
* that DSH's recognizer takes. WeChat's own two formats always come out that way.
|
|
273
|
+
*/
|
|
274
|
+
export async function playableAudio(buf) {
|
|
275
|
+
const kind = sniffAudio(buf);
|
|
276
|
+
if (kind === "wav")
|
|
277
|
+
return { bytes: buf, ext: ".wav", canonical: isCanonicalWav(buf) };
|
|
278
|
+
if (kind === "mp3" || kind === "m4a" || kind === "amr")
|
|
279
|
+
return { bytes: buf, ext: `.${kind}`, canonical: false };
|
|
280
|
+
if (kind === "opus-raw") {
|
|
281
|
+
const decoded = await decodeOpusRaw(buf, PCM_SAMPLE_RATE);
|
|
282
|
+
const mono = decoded.channels === 2 ? stereoToMono(decoded.pcm) : decoded.pcm;
|
|
283
|
+
return { bytes: pcmToWav(mono, PCM_SAMPLE_RATE), ext: ".wav", canonical: true };
|
|
284
|
+
}
|
|
285
|
+
if (buf.subarray(0, 6).toString("latin1") === "#!OPUS") {
|
|
286
|
+
throw new Error("an Opus container this version does not know");
|
|
287
|
+
}
|
|
288
|
+
// SILK, or something unnamed that WeChat only ever means SILK by.
|
|
289
|
+
const silk = await loadSilk();
|
|
290
|
+
const decoded = await silk.decode(buf, PCM_SAMPLE_RATE);
|
|
291
|
+
if (decoded.data.byteLength === 0)
|
|
292
|
+
throw new Error("the audio decoded to nothing");
|
|
293
|
+
return { bytes: pcmToWav(decoded.data, PCM_SAMPLE_RATE), ext: ".wav", canonical: true };
|
|
294
|
+
}
|
|
295
|
+
/** Builds `clawbot-speech` on first use and runs it. */
|
|
296
|
+
export class SpeechHelper {
|
|
297
|
+
root;
|
|
298
|
+
source;
|
|
299
|
+
building = null;
|
|
300
|
+
buildFailure = null;
|
|
301
|
+
constructor(root = path.join(resolveStateDir(), "speech-helper"), source = fileURLToPath(new URL("../native/macos-speech/main.swift", import.meta.url))) {
|
|
302
|
+
this.root = root;
|
|
303
|
+
this.source = source;
|
|
304
|
+
}
|
|
305
|
+
get exePath() {
|
|
306
|
+
return path.join(this.root, HELPER_NAME);
|
|
307
|
+
}
|
|
308
|
+
fingerprint() {
|
|
309
|
+
return createHash("sha256").update(fs.readFileSync(this.source)).digest("hex");
|
|
310
|
+
}
|
|
311
|
+
/** Whether the helper exists and was built from the current source. */
|
|
312
|
+
isBuilt() {
|
|
313
|
+
try {
|
|
314
|
+
return fs.existsSync(this.exePath)
|
|
315
|
+
&& fs.readFileSync(path.join(this.root, "source.sha256"), "utf-8").trim() === this.fingerprint();
|
|
316
|
+
}
|
|
317
|
+
catch {
|
|
318
|
+
return false;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Compile the helper when it is missing or the plugin's Swift source changed.
|
|
323
|
+
* No permission hangs on this binary, so a stale one is simply replaced; when
|
|
324
|
+
* the rebuild fails, the old one goes on working.
|
|
325
|
+
*/
|
|
326
|
+
async ensureBuilt() {
|
|
327
|
+
while (this.building !== null)
|
|
328
|
+
await this.building.catch(() => undefined);
|
|
329
|
+
if (this.isBuilt())
|
|
330
|
+
return;
|
|
331
|
+
let print;
|
|
332
|
+
try {
|
|
333
|
+
print = this.fingerprint();
|
|
334
|
+
}
|
|
335
|
+
catch (err) {
|
|
336
|
+
throw new HelperError("build", `转写小程序的源码读不到:${String(err.message ?? err).slice(0, 200)}`);
|
|
337
|
+
}
|
|
338
|
+
const failed = this.buildFailure;
|
|
339
|
+
if (failed !== null && failed.fingerprint === print && Date.now() - failed.at < BUILD_RETRY_MS) {
|
|
340
|
+
if (fs.existsSync(this.exePath))
|
|
341
|
+
return;
|
|
342
|
+
throw failed.error;
|
|
343
|
+
}
|
|
344
|
+
this.building = this.build(print)
|
|
345
|
+
.then(() => { this.buildFailure = null; })
|
|
346
|
+
.catch((err) => {
|
|
347
|
+
const error = err instanceof HelperError ? err : new HelperError("build", String(err.message ?? err));
|
|
348
|
+
this.buildFailure = { fingerprint: print, at: Date.now(), error };
|
|
349
|
+
if (fs.existsSync(this.exePath)) {
|
|
350
|
+
logger.warn(`voice: could not rebuild ${HELPER_NAME} (${error.message}); the older build stays in use`);
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
throw error;
|
|
354
|
+
})
|
|
355
|
+
.finally(() => { this.building = null; });
|
|
356
|
+
return this.building;
|
|
357
|
+
}
|
|
358
|
+
async build(print) {
|
|
359
|
+
// Ask where the tools are before calling one: with none installed, the
|
|
360
|
+
// stand-ins in /usr/bin put macOS's "install the command line tools" dialog
|
|
361
|
+
// up, and nobody asked for a dialog by sending a voice message.
|
|
362
|
+
let developerDir = "";
|
|
363
|
+
try {
|
|
364
|
+
developerDir = (await execFileP("/usr/bin/xcode-select", ["-p"], 10_000)).stdout.trim();
|
|
365
|
+
}
|
|
366
|
+
catch {
|
|
367
|
+
developerDir = "";
|
|
368
|
+
}
|
|
369
|
+
if (developerDir === "" || !fs.existsSync(developerDir)) {
|
|
370
|
+
throw new HelperError("tools", "电脑上没有 Xcode 命令行工具(终端运行 xcode-select --install 可以装)");
|
|
371
|
+
}
|
|
372
|
+
fs.mkdirSync(this.root, { recursive: true, mode: 0o700 });
|
|
373
|
+
const staging = path.join(this.root, `.build-${process.pid}-${randomUUID().slice(0, 8)}`);
|
|
374
|
+
fs.mkdirSync(staging, { recursive: true, mode: 0o700 });
|
|
375
|
+
const exe = path.join(staging, HELPER_NAME);
|
|
376
|
+
logger.info(`voice: building ${HELPER_NAME} (first use, or the plugin's Swift source changed)`);
|
|
377
|
+
try {
|
|
378
|
+
try {
|
|
379
|
+
await execFileP("/usr/bin/xcrun", ["swiftc", "-O", this.source, "-o", exe], 600_000);
|
|
380
|
+
}
|
|
381
|
+
catch (err) {
|
|
382
|
+
const e = err;
|
|
383
|
+
if (e.code === "ENOENT" || /xcrun: error|no developer tools|CommandLineTools/i.test(String(e.stderr ?? ""))) {
|
|
384
|
+
throw new HelperError("tools", "电脑上的 Xcode 命令行工具用不了(终端运行 xcode-select --install 重装)");
|
|
385
|
+
}
|
|
386
|
+
throw new HelperError("build", `转写小程序没编译成:${String(e.stderr ?? err).trim().slice(-300)}`);
|
|
387
|
+
}
|
|
388
|
+
fs.renameSync(exe, this.exePath);
|
|
389
|
+
fs.writeFileSync(path.join(this.root, "source.sha256"), print, { mode: 0o600 });
|
|
390
|
+
}
|
|
391
|
+
finally {
|
|
392
|
+
fs.rmSync(staging, { recursive: true, force: true });
|
|
393
|
+
}
|
|
394
|
+
logger.info(`voice: built ${this.exePath}`);
|
|
395
|
+
}
|
|
396
|
+
/** Run one helper command and read its JSON answer. */
|
|
397
|
+
async run(args, timeoutMs) {
|
|
398
|
+
await this.ensureBuilt();
|
|
399
|
+
let stdout = "";
|
|
400
|
+
try {
|
|
401
|
+
stdout = (await execFileP(this.exePath, args, timeoutMs)).stdout;
|
|
402
|
+
}
|
|
403
|
+
catch (err) {
|
|
404
|
+
const e = err;
|
|
405
|
+
if (e.killed === true)
|
|
406
|
+
throw new HelperError("failed", `转写超过 ${Math.round(timeoutMs / 1000)} 秒没出结果`);
|
|
407
|
+
stdout = typeof e.stdout === "string" ? e.stdout : "";
|
|
408
|
+
if (stdout.trim() === "")
|
|
409
|
+
throw new HelperError("failed", `转写小程序没跑起来:${String(e.message ?? err).slice(0, 200)}`);
|
|
410
|
+
}
|
|
411
|
+
const line = stdout.trim().split("\n").pop() ?? "";
|
|
412
|
+
try {
|
|
413
|
+
const parsed = JSON.parse(line);
|
|
414
|
+
if (parsed !== null && typeof parsed === "object")
|
|
415
|
+
return parsed;
|
|
416
|
+
}
|
|
417
|
+
catch {
|
|
418
|
+
// fall through
|
|
419
|
+
}
|
|
420
|
+
throw new HelperError("failed", "转写小程序的回答读不懂");
|
|
421
|
+
}
|
|
422
|
+
/** What this Mac can transcribe `language` with, without transcribing anything. */
|
|
423
|
+
status(language) {
|
|
424
|
+
return this.run(["status", language], 30_000);
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Have macOS download the newer speech model's pack for `language` (a few
|
|
428
|
+
* hundred megabytes from Apple). Only ever on the owner's word; transcribing
|
|
429
|
+
* never calls this.
|
|
430
|
+
*/
|
|
431
|
+
install(language) {
|
|
432
|
+
return this.run(["install", language], 60 * 60_000);
|
|
433
|
+
}
|
|
434
|
+
/** Transcribe one audio file. */
|
|
435
|
+
async transcribe(file, language, timeoutMs = TRANSCRIBE_TIMEOUT_MS) {
|
|
436
|
+
const res = await this.run(["transcribe", language, file], timeoutMs);
|
|
437
|
+
if (res.ok === true) {
|
|
438
|
+
const text = typeof res.text === "string" ? tidyTranscript(res.text) : "";
|
|
439
|
+
if (text === "")
|
|
440
|
+
return { ok: false, reason: "empty" };
|
|
441
|
+
return { ok: true, text, engine: typeof res.engine === "string" ? res.engine : "speech" };
|
|
442
|
+
}
|
|
443
|
+
const code = typeof res.code === "string" ? res.code : "";
|
|
444
|
+
const detail = typeof res.error === "string" ? res.error.slice(0, 300) : undefined;
|
|
445
|
+
if (code === "unsupported_os")
|
|
446
|
+
return { ok: false, reason: "no-engine", detail };
|
|
447
|
+
if (code === "unsupported_language" || code === "model_missing")
|
|
448
|
+
return { ok: false, reason: "language", detail };
|
|
449
|
+
return { ok: false, reason: "failed", detail };
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
/** One helper for the process: a rebuilt listener keeps its build, and its memory of a failed one. */
|
|
453
|
+
let shared = null;
|
|
454
|
+
export function sharedSpeechHelper() {
|
|
455
|
+
return (shared ??= new SpeechHelper());
|
|
456
|
+
}
|
|
457
|
+
let warmed = false;
|
|
458
|
+
/**
|
|
459
|
+
* Compile the helper ahead of the first voice message that needs it, so that
|
|
460
|
+
* message waits for a transcript and not for a compiler. Once per process, a
|
|
461
|
+
* little after start, and quietly: a Mac without the tools just goes without.
|
|
462
|
+
*/
|
|
463
|
+
export function prewarmSpeechHelper(delayMs = 30_000) {
|
|
464
|
+
if (warmed || !voicePlatformSupported())
|
|
465
|
+
return;
|
|
466
|
+
warmed = true;
|
|
467
|
+
const timer = setTimeout(() => {
|
|
468
|
+
const helper = sharedSpeechHelper();
|
|
469
|
+
if (helper.isBuilt())
|
|
470
|
+
return;
|
|
471
|
+
void helper.ensureBuilt().catch((err) => {
|
|
472
|
+
logger.info(`voice: on-device transcription is not set up (${String(err.message ?? err).slice(0, 200)})`);
|
|
473
|
+
});
|
|
474
|
+
}, delayMs);
|
|
475
|
+
timer.unref?.();
|
|
476
|
+
}
|
|
477
|
+
/** One recording through DSH's recognizer. Throws when it does. */
|
|
478
|
+
async function transcribeWithHost(speech, wav) {
|
|
479
|
+
const controller = new AbortController();
|
|
480
|
+
const timer = setTimeout(() => controller.abort(new Error(`no transcript after ${HOST_TRANSCRIBE_TIMEOUT_MS / 1000} s`)), HOST_TRANSCRIBE_TIMEOUT_MS);
|
|
481
|
+
try {
|
|
482
|
+
const result = await speech.transcribe(speech.resolve({ audio: wav }), controller.signal);
|
|
483
|
+
return typeof result?.text === "string" ? tidyTranscript(result.text) : "";
|
|
484
|
+
}
|
|
485
|
+
finally {
|
|
486
|
+
clearTimeout(timer);
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
async function downloadVoice(item, cdnBaseUrl) {
|
|
490
|
+
const media = item.voice_item?.media;
|
|
491
|
+
if (!media)
|
|
492
|
+
throw new Error("no media");
|
|
493
|
+
return media.aes_key
|
|
494
|
+
? downloadAndDecryptBuffer(media.encrypt_query_param ?? "", media.aes_key, cdnBaseUrl, "inbound voice", media.full_url)
|
|
495
|
+
: downloadPlainCdnBuffer(media.encrypt_query_param ?? "", cdnBaseUrl, "inbound voice-plain", media.full_url);
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* Transcribe a voice item on this machine: DSH's speech recognition when it is
|
|
499
|
+
* ready, else this Mac's own. Never throws. For the Mac's helper the audio is
|
|
500
|
+
* written to a private temporary folder and removed afterwards; DSH's
|
|
501
|
+
* recognizer takes it from memory.
|
|
502
|
+
*/
|
|
503
|
+
export async function transcribeVoiceItem(item, deps) {
|
|
504
|
+
let speech;
|
|
505
|
+
try {
|
|
506
|
+
speech = deps.hostSpeech?.();
|
|
507
|
+
}
|
|
508
|
+
catch {
|
|
509
|
+
speech = undefined;
|
|
510
|
+
}
|
|
511
|
+
const host = hostSpeechStatus(speech);
|
|
512
|
+
const mac = (deps.platformSupported ?? voicePlatformSupported)();
|
|
513
|
+
// Nothing here can transcribe: say so before fetching anything.
|
|
514
|
+
if (host.state !== "ready" && !mac) {
|
|
515
|
+
return { ok: false, reason: host.state === "absent" ? "no-engine" : "host-unprepared", host: host.state };
|
|
516
|
+
}
|
|
517
|
+
const media = item.voice_item?.media;
|
|
518
|
+
if (!media?.encrypt_query_param && !media?.full_url)
|
|
519
|
+
return { ok: false, reason: "no-media" };
|
|
520
|
+
const started = Date.now();
|
|
521
|
+
const seconds = () => ((Date.now() - started) / 1000).toFixed(1);
|
|
522
|
+
let raw;
|
|
523
|
+
let timer;
|
|
524
|
+
try {
|
|
525
|
+
// The CDN fetch has no time limit of its own, and the next message waits behind this one.
|
|
526
|
+
raw = await Promise.race([
|
|
527
|
+
(deps.download ?? ((it) => downloadVoice(it, deps.cdnBaseUrl)))(item),
|
|
528
|
+
new Promise((_, reject) => {
|
|
529
|
+
timer = setTimeout(() => reject(new Error(`no audio after ${DOWNLOAD_TIMEOUT_MS / 1000} s`)), deps.downloadTimeoutMs ?? DOWNLOAD_TIMEOUT_MS);
|
|
530
|
+
}),
|
|
531
|
+
]);
|
|
532
|
+
}
|
|
533
|
+
catch (err) {
|
|
534
|
+
clearTimeout(timer);
|
|
535
|
+
logger.warn(`voice: download failed: ${String(err.message ?? err).slice(0, 200)}`);
|
|
536
|
+
return { ok: false, reason: "download" };
|
|
537
|
+
}
|
|
538
|
+
clearTimeout(timer);
|
|
539
|
+
if (raw.length === 0 || raw.length > VOICE_MAX_BYTES) {
|
|
540
|
+
logger.warn(`voice: ${raw.length} bytes of audio is not a voice message`);
|
|
541
|
+
return { ok: false, reason: "download" };
|
|
542
|
+
}
|
|
543
|
+
let audio;
|
|
544
|
+
try {
|
|
545
|
+
audio = await playableAudio(raw);
|
|
546
|
+
}
|
|
547
|
+
catch (err) {
|
|
548
|
+
// The first bytes name the format (a header, a length); they say nothing of what was said.
|
|
549
|
+
logger.warn(`voice: could not decode ${raw.length} bytes (starts ${raw.subarray(0, 24).toString("hex")}, encode_type=${String(item.voice_item?.encode_type ?? "?")}): `
|
|
550
|
+
+ String(err.message ?? err).slice(0, 200));
|
|
551
|
+
return { ok: false, reason: "decode" };
|
|
552
|
+
}
|
|
553
|
+
// 1. DSH's own speech recognition: the same on every platform.
|
|
554
|
+
let hostFailure;
|
|
555
|
+
if (host.state === "ready" && speech !== undefined && audio.canonical) {
|
|
556
|
+
try {
|
|
557
|
+
const text = await transcribeWithHost(speech, audio.bytes);
|
|
558
|
+
if (text === "") {
|
|
559
|
+
logger.info(`voice: WeChat sent no transcript; DSH's ${host.name} heard nothing in it (${seconds()}s)`);
|
|
560
|
+
return { ok: false, reason: "empty" };
|
|
561
|
+
}
|
|
562
|
+
// Length only: the log is not the place for what the owner said.
|
|
563
|
+
logger.info(`voice: WeChat sent no transcript; transcribed by DSH's ${host.name} (${seconds()}s) -> ${[...text].length} chars`);
|
|
564
|
+
return { ok: true, text, engine: host.providerId };
|
|
565
|
+
}
|
|
566
|
+
catch (err) {
|
|
567
|
+
hostFailure = String(err.message ?? err).slice(0, 200);
|
|
568
|
+
logger.warn(`voice: DSH's ${host.name} failed (${hostFailure})${mac ? "; trying this Mac's own" : ""}`);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
if (!mac) {
|
|
572
|
+
return hostFailure === undefined
|
|
573
|
+
? { ok: false, reason: "no-engine", host: host.state }
|
|
574
|
+
: { ok: false, reason: "failed", detail: hostFailure, host: host.state };
|
|
575
|
+
}
|
|
576
|
+
// 2. This Mac's on-device models.
|
|
577
|
+
let dir = "";
|
|
578
|
+
try {
|
|
579
|
+
dir = fs.mkdtempSync(path.join(os.tmpdir(), "clawbot-voice-"));
|
|
580
|
+
const file = path.join(dir, `voice${audio.ext}`);
|
|
581
|
+
fs.writeFileSync(file, audio.bytes, { mode: 0o600 });
|
|
582
|
+
const outcome = await deps.helper.transcribe(file, deps.language);
|
|
583
|
+
if (outcome.ok) {
|
|
584
|
+
logger.info(`voice: WeChat sent no transcript; transcribed by this Mac (${outcome.engine}, ${deps.language}, ${seconds()}s) -> ${[...outcome.text].length} chars`);
|
|
585
|
+
return outcome;
|
|
586
|
+
}
|
|
587
|
+
logger.warn(`voice: WeChat sent no transcript and this Mac made none (${outcome.reason}${outcome.detail ? `: ${outcome.detail}` : ""}, ${seconds()}s)`);
|
|
588
|
+
return { ...outcome, host: host.state };
|
|
589
|
+
}
|
|
590
|
+
catch (err) {
|
|
591
|
+
const reason = err instanceof HelperError ? err.reason : "failed";
|
|
592
|
+
const detail = String(err.message ?? err).slice(0, 300);
|
|
593
|
+
logger.warn(`voice: WeChat sent no transcript and this Mac made none (${reason}: ${detail})`);
|
|
594
|
+
return { ok: false, reason, detail, host: host.state };
|
|
595
|
+
}
|
|
596
|
+
finally {
|
|
597
|
+
if (dir !== "")
|
|
598
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
/** What the bot answers to when asked to switch DSH's speech recognition on (voice-setup.ts). */
|
|
602
|
+
export const VOICE_SETUP_PHRASE = "打开语音输入";
|
|
603
|
+
/**
|
|
604
|
+
* What to tell the sender when a voice message has no transcript from either
|
|
605
|
+
* side. Says it is a voice message (it used to be called a video), why there
|
|
606
|
+
* is no text, and what to do — above all how to get voice working: DSH's own
|
|
607
|
+
* 语音输入, which the bot can switch on for the owner.
|
|
608
|
+
*/
|
|
609
|
+
export function voiceNotice(outcome) {
|
|
610
|
+
const head = "[DSH] 这条语音微信没有附上转写的文字,";
|
|
611
|
+
const typeIt = "这条麻烦先打字发给我。";
|
|
612
|
+
const retry = "麻烦打字发给我,或者再发一次。";
|
|
613
|
+
const how = `DSH 自带一个「语音输入」插件,打开后语音就在这台电脑上转成文字。回我「${VOICE_SETUP_PHRASE}」我来替你开,或者自己在电脑的 DSH 网页里点「插件」→「语音输入」。`;
|
|
614
|
+
if (outcome === undefined || outcome.ok)
|
|
615
|
+
return `${head}我听不了语音。${retry}`;
|
|
616
|
+
switch (outcome.reason) {
|
|
617
|
+
case "off":
|
|
618
|
+
return `${head}我听不了语音。${retry}`;
|
|
619
|
+
case "empty":
|
|
620
|
+
return `${head}电脑转写也没听出内容。${retry}`;
|
|
621
|
+
case "host-unprepared":
|
|
622
|
+
return outcome.host === "preparing"
|
|
623
|
+
? `${head}电脑上的语音识别模型还在下载,好了我会告诉你。${typeIt}`
|
|
624
|
+
: `${head}DSH 的「语音输入」开着,但语音识别模型还没下载。回我「${VOICE_SETUP_PHRASE}」我来接着下载,或者在电脑的 DSH 网页里点「插件」→「语音输入」→「下载并准备」。${typeIt}`;
|
|
625
|
+
case "no-engine":
|
|
626
|
+
case "tools":
|
|
627
|
+
case "build":
|
|
628
|
+
case "language":
|
|
629
|
+
return `${head}电脑上也还没有语音识别,所以我没听到内容。${how}${typeIt}`;
|
|
630
|
+
case "no-media":
|
|
631
|
+
case "download":
|
|
632
|
+
return `${head}语音本身也没能下载下来。${retry}`;
|
|
633
|
+
case "decode":
|
|
634
|
+
return `${head}电脑也没认出这条语音的格式(微信可能又换了格式)。${typeIt}`;
|
|
635
|
+
default:
|
|
636
|
+
return `${head}电脑这边也没转写成。${retry}`;
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
//# sourceMappingURL=voice.js.map
|