@miles-huang/cove 0.1.3 → 0.1.5
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/.env.example +7 -3
- package/README.md +17 -9
- package/bin/cove.js +220 -9
- package/package.json +1 -1
- package/server/agent/messages.js +213 -4
- package/server/agent/runtime.js +1 -1
- package/server/agent/session-hub.js +305 -22
- package/server/app.js +21 -4
- package/server/auth.js +40 -29
- package/server/cli.js +207 -28
- package/server/config.js +6 -5
- package/server/credentials.js +174 -0
- package/server/index.js +3 -0
- package/server/routes/meta.js +4 -2
- package/server/routes/sessions.js +30 -0
- package/server/routes/update.js +36 -0
- package/server/routes/uploads.js +100 -0
- package/server/routes/voice.js +95 -0
- package/server/server.js +114 -14
- package/server/updater.js +484 -0
- package/server/voice.js +618 -0
- package/shared/protocol.js +8 -0
- package/web/assets/{abnfDiagram-VCTEODGH-BvfDeUDt.js → abnfDiagram-VCTEODGH-CzbWgcsF.js} +1 -1
- package/web/assets/{architectureDiagram-5GKGNRK7-B6x-Vdta.js → architectureDiagram-5GKGNRK7-jpqUHglp.js} +1 -1
- package/web/assets/{blockDiagram-I7D4REHJ-DSdow19J.js → blockDiagram-I7D4REHJ-CaDKtZbM.js} +1 -1
- package/web/assets/{c4Diagram-7LVT6UL2-DNANA_BY.js → c4Diagram-7LVT6UL2-DSzOjXhU.js} +1 -1
- package/web/assets/channel-CyiORw9T.js +1 -0
- package/web/assets/{chunk-2Q5K7J3B-DQhKxJim.js → chunk-2Q5K7J3B-jC1KoHVE.js} +1 -1
- package/web/assets/{chunk-5VM5RSS4-CxYuf8nJ.js → chunk-5VM5RSS4-D6X5RslJ.js} +1 -1
- package/web/assets/{chunk-F27PBJKO-pm7TdZp3.js → chunk-F27PBJKO-BbRLxBSh.js} +1 -1
- package/web/assets/{chunk-IMKFNOWR-BOUFtEzN.js → chunk-IMKFNOWR-y223YRpm.js} +1 -1
- package/web/assets/{chunk-JWPE2WC7-AmPhkmIF.js → chunk-JWPE2WC7-s-_Lm4OD.js} +1 -1
- package/web/assets/{chunk-POPQ4Y6H-DAjm7eYi.js → chunk-POPQ4Y6H-FAjR47qb.js} +1 -1
- package/web/assets/{chunk-SVP7TREG-CPIhAIng.js → chunk-SVP7TREG-V3BsTVSS.js} +1 -1
- package/web/assets/{chunk-TICWLB2K-zdUNYXIa.js → chunk-TICWLB2K-BHXaSfO0.js} +1 -1
- package/web/assets/{chunk-XXDRQBXY-HxMWsKyb.js → chunk-XXDRQBXY-uzA700bf.js} +1 -1
- package/web/assets/classDiagram-ZZMXUADV-gyexRBgY.js +1 -0
- package/web/assets/classDiagram-v2-VYDZK3BY-Bc9eynfM.js +1 -0
- package/web/assets/{cose-bilkent-JH36ORCC-lYmJLW2h.js → cose-bilkent-JH36ORCC-B6XhcmxK.js} +1 -1
- package/web/assets/{cynefin-OW5HDTMX-C8UcJePz.js → cynefin-OW5HDTMX-CCabvWFn.js} +1 -1
- package/web/assets/{cynefinDiagram-5FMLGOSQ-Dt1tZqyf.js → cynefinDiagram-5FMLGOSQ-D3FXPxq1.js} +1 -1
- package/web/assets/{dagre-GXQ25YYZ-Y0qiXkMO.js → dagre-GXQ25YYZ-eitZh1b1.js} +1 -1
- package/web/assets/{diagram-S7CK7UJ4-BtcdW_SA.js → diagram-S7CK7UJ4-B_523Ard.js} +1 -1
- package/web/assets/{diagram-UQ7AKVKN-DMwC8JNI.js → diagram-UQ7AKVKN-DLK2D1Lf.js} +1 -1
- package/web/assets/{diagram-VSXAHHWV-BVU0Bm6u.js → diagram-VSXAHHWV-IqWaTga0.js} +1 -1
- package/web/assets/{diagram-VX7I27RA-BYlx-nH2.js → diagram-VX7I27RA-D42Xhhqj.js} +1 -1
- package/web/assets/{diagram-Z3DM3KII-C_oAUIPq.js → diagram-Z3DM3KII-B38ZR6s3.js} +1 -1
- package/web/assets/{ebnfDiagram-PWID7BFC-D9eTa0_d.js → ebnfDiagram-PWID7BFC-Bto2hjgy.js} +1 -1
- package/web/assets/{erDiagram-RLTQ6QDP-Cn00lD_I.js → erDiagram-RLTQ6QDP-BbrcgCtr.js} +1 -1
- package/web/assets/{flowDiagram-HODETNUW-CBjFObVm.js → flowDiagram-HODETNUW-BccX2IC1.js} +1 -1
- package/web/assets/{ganttDiagram-EL5Y4UJY-BrJFpYUI.js → ganttDiagram-EL5Y4UJY-CIVhLWAs.js} +1 -1
- package/web/assets/{gitGraphDiagram-WWUBYQGX-CgDCGY4x.js → gitGraphDiagram-WWUBYQGX-CiQgydKF.js} +1 -1
- package/web/assets/{highlighted-body-6RAV4W6J-BaouqEZW.js → highlighted-body-6RAV4W6J-eKTYB7cG.js} +1 -1
- package/web/assets/index-8rrMUwb2.css +1 -0
- package/web/assets/index-DFKPpT1o.js +1289 -0
- package/web/assets/{infoDiagram-27XIBGKW-4GAuy2r7.js → infoDiagram-27XIBGKW-C3mfF7LW.js} +1 -1
- package/web/assets/{ishikawaDiagram-5VMMS53U-CDZ9dPA6.js → ishikawaDiagram-5VMMS53U-XWdz8N0o.js} +1 -1
- package/web/assets/{journeyDiagram-3NMN7TZE-D0uXeMh-.js → journeyDiagram-3NMN7TZE-CtvvC10N.js} +1 -1
- package/web/assets/{kanban-definition-UXKFOSKX-C4H7MD6w.js → kanban-definition-UXKFOSKX-uhxTqXnW.js} +1 -1
- package/web/assets/{layout-BFfV8fTs.js → layout-BQ419s8Q.js} +1 -1
- package/web/assets/{mindmap-definition-YA3MSWOX-Dd7Obl6F.js → mindmap-definition-YA3MSWOX-Cg7HolUO.js} +1 -1
- package/web/assets/{pegDiagram-XKGWAZYB-nDep-Xjv.js → pegDiagram-XKGWAZYB-Ca_T_k1c.js} +1 -1
- package/web/assets/{pieDiagram-E7YTZNPT-C8783QQe.js → pieDiagram-E7YTZNPT-Cqu0K07s.js} +1 -1
- package/web/assets/{quadrantDiagram-AXDQQJYC-CH5o8mIt.js → quadrantDiagram-AXDQQJYC-wK7kSaZg.js} +1 -1
- package/web/assets/{railroadDiagram-O6MQD6OU-QPxQi08o.js → railroadDiagram-O6MQD6OU-Yt2QDvBQ.js} +1 -1
- package/web/assets/{requirementDiagram-BXWQKSXE-DVr0s9y9.js → requirementDiagram-BXWQKSXE-BnUkaWq7.js} +1 -1
- package/web/assets/{sankeyDiagram-P5KCCOFB-Bq3TJeq8.js → sankeyDiagram-P5KCCOFB-M_ig6yCr.js} +1 -1
- package/web/assets/{sequenceDiagram-WJ2MYXX4-VWpvqhZf.js → sequenceDiagram-WJ2MYXX4-BZsd1fkB.js} +1 -1
- package/web/assets/{sizeCapture-INFHLROL-1n-6h_CN.js → sizeCapture-INFHLROL-QGHTzTuy.js} +1 -1
- package/web/assets/{stateDiagram-D77RDMKH-cmZfkPUb.js → stateDiagram-D77RDMKH-B-fkTedS.js} +1 -1
- package/web/assets/stateDiagram-v2-MP3YSRHH-BUXoRLIu.js +1 -0
- package/web/assets/{swimlanes-42K2YHIH-BqTB27WF.js → swimlanes-42K2YHIH-BP-raAm4.js} +1 -1
- package/web/assets/swimlanesDiagram-VR7AAH4N-ClyXkjH5.js +8 -0
- package/web/assets/{timeline-definition-24CTP7MA--BCgTKxF.js → timeline-definition-24CTP7MA-CDTB4Ri6.js} +1 -1
- package/web/assets/{vennDiagram-4TSXK5OY-BJaPku01.js → vennDiagram-4TSXK5OY-DFmr7Hbu.js} +1 -1
- package/web/assets/{wardleyDiagram-VM6X3IG4-n2YbPRWQ.js → wardleyDiagram-VM6X3IG4-DrhRjyVy.js} +1 -1
- package/web/assets/{xychartDiagram-S5SC5T6Z-CQpktgwa.js → xychartDiagram-S5SC5T6Z-CvH_0Dcr.js} +1 -1
- package/web/index.html +2 -2
- package/web/assets/channel-CyEPAFBz.js +0 -1
- package/web/assets/classDiagram-ZZMXUADV-DqTY3X0j.js +0 -1
- package/web/assets/classDiagram-v2-VYDZK3BY-BSxiMdF_.js +0 -1
- package/web/assets/index-4qPcqjHt.js +0 -1259
- package/web/assets/index-5AGKaJhL.css +0 -1
- package/web/assets/stateDiagram-v2-MP3YSRHH-wEaM0KsS.js +0 -1
- package/web/assets/swimlanesDiagram-VR7AAH4N-CjIKX5n2.js +0 -8
package/server/voice.js
ADDED
|
@@ -0,0 +1,618 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { existsSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { isAbsolute, join, relative, sep } from "node:path";
|
|
4
|
+
import { isVoiceProtocol, } from "../shared/protocol.js";
|
|
5
|
+
import { FileCredentialStore } from "./agent/provider-store.js";
|
|
6
|
+
export const VOICE_AUTH_KEY = "__voice__";
|
|
7
|
+
export const MAX_VOICE_AUDIO_BYTES = 10 * 1024 * 1024;
|
|
8
|
+
const VOICE_TIMEOUT_MS = 30_000;
|
|
9
|
+
const DASHSCOPE_WS_CHUNK_BYTES = 3200;
|
|
10
|
+
export const DEFAULT_VOICE_PROTOCOL = "dashscope-asr-ws";
|
|
11
|
+
export const DEFAULT_VOICE_BASE_URL = "wss://cn-beijing.maas.qianwenaiapi.com/api-ws/v1/inference";
|
|
12
|
+
export const DEFAULT_VOICE_MODEL = "qwen-audio-3.1-asr-flash-message";
|
|
13
|
+
export class VoiceServiceError extends Error {
|
|
14
|
+
status;
|
|
15
|
+
code;
|
|
16
|
+
constructor(status, code, message) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.status = status;
|
|
19
|
+
this.code = code;
|
|
20
|
+
this.name = "VoiceServiceError";
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function isContainedIn(root, target) {
|
|
24
|
+
const rel = relative(root, target);
|
|
25
|
+
return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
|
|
26
|
+
}
|
|
27
|
+
function assertValidVoiceBaseUrl(raw, protocol) {
|
|
28
|
+
if (typeof raw !== "string" || !raw.trim()) {
|
|
29
|
+
throw new VoiceServiceError(400, "INVALID_BASE_URL", "请输入有效的语音接口地址。");
|
|
30
|
+
}
|
|
31
|
+
const trimmed = raw.trim().replace(/\/+$/, "");
|
|
32
|
+
let parsed;
|
|
33
|
+
try {
|
|
34
|
+
parsed = new URL(trimmed);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
throw new VoiceServiceError(400, "INVALID_BASE_URL", "语音接口地址格式无效。");
|
|
38
|
+
}
|
|
39
|
+
if (protocol === "dashscope-asr-ws") {
|
|
40
|
+
if (parsed.protocol !== "wss:" && parsed.protocol !== "ws:") {
|
|
41
|
+
throw new VoiceServiceError(400, "INVALID_BASE_URL", "DashScope WebSocket 协议必须使用 ws 或 wss 地址。");
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
else if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
45
|
+
throw new VoiceServiceError(400, "INVALID_BASE_URL", "语音接口地址必须使用 http 或 https 协议。");
|
|
46
|
+
}
|
|
47
|
+
return trimmed;
|
|
48
|
+
}
|
|
49
|
+
function detectDashScopeAudioParams(audioBuffer, mimeType, filename) {
|
|
50
|
+
if (audioBuffer.byteLength >= 44 &&
|
|
51
|
+
audioBuffer.toString("ascii", 0, 4) === "RIFF" &&
|
|
52
|
+
audioBuffer.toString("ascii", 8, 12) === "WAVE") {
|
|
53
|
+
const rawRate = audioBuffer.readUInt32LE(24);
|
|
54
|
+
const sampleRate = rawRate >= 8000 && rawRate <= 48000 ? rawRate : 16_000;
|
|
55
|
+
return { format: "wav", sampleRate };
|
|
56
|
+
}
|
|
57
|
+
const lowerMime = mimeType.split(";")[0]?.trim().toLowerCase() ?? "";
|
|
58
|
+
const lowerName = filename.trim().toLowerCase();
|
|
59
|
+
if (lowerMime === "audio/mpeg" || lowerMime === "audio/mp3" || lowerName.endsWith(".mp3")) {
|
|
60
|
+
return { format: "mp3", sampleRate: 16_000 };
|
|
61
|
+
}
|
|
62
|
+
if (lowerMime === "audio/ogg" || lowerName.endsWith(".ogg") || lowerName.endsWith(".opus")) {
|
|
63
|
+
return { format: "opus", sampleRate: 16_000 };
|
|
64
|
+
}
|
|
65
|
+
if (lowerMime === "audio/mp4" ||
|
|
66
|
+
lowerMime === "audio/m4a" ||
|
|
67
|
+
lowerMime === "audio/x-m4a" ||
|
|
68
|
+
lowerMime === "audio/aac" ||
|
|
69
|
+
lowerName.endsWith(".m4a") ||
|
|
70
|
+
lowerName.endsWith(".aac")) {
|
|
71
|
+
return { format: "aac", sampleRate: 16_000 };
|
|
72
|
+
}
|
|
73
|
+
return { format: "wav", sampleRate: 16_000 };
|
|
74
|
+
}
|
|
75
|
+
function joinRecognizedSegments(segments) {
|
|
76
|
+
let out = "";
|
|
77
|
+
for (const raw of segments) {
|
|
78
|
+
const seg = raw.trim();
|
|
79
|
+
if (!seg)
|
|
80
|
+
continue;
|
|
81
|
+
if (!out) {
|
|
82
|
+
out = seg;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
const prevLast = out[out.length - 1] ?? "";
|
|
86
|
+
const nextFirst = seg[0] ?? "";
|
|
87
|
+
const needsSpace = /[A-Za-z0-9]/.test(prevLast) && /[A-Za-z0-9]/.test(nextFirst);
|
|
88
|
+
out += needsSpace ? ` ${seg}` : seg;
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
function decodeWsMessageData(data) {
|
|
93
|
+
if (typeof data === "string")
|
|
94
|
+
return data;
|
|
95
|
+
if (data instanceof ArrayBuffer) {
|
|
96
|
+
return Buffer.from(data).toString("utf-8");
|
|
97
|
+
}
|
|
98
|
+
if (ArrayBuffer.isView(data)) {
|
|
99
|
+
return Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString("utf-8");
|
|
100
|
+
}
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
function assertValidVoiceModel(raw) {
|
|
104
|
+
if (typeof raw !== "string" || !raw.trim()) {
|
|
105
|
+
throw new VoiceServiceError(400, "INVALID_VOICE_MODEL", "请输入语音识别模型名称。");
|
|
106
|
+
}
|
|
107
|
+
return raw.trim().slice(0, 120);
|
|
108
|
+
}
|
|
109
|
+
function assertValidVoiceLanguage(raw) {
|
|
110
|
+
if (typeof raw !== "string") {
|
|
111
|
+
throw new VoiceServiceError(400, "INVALID_VOICE_LANGUAGE", "语音识别语言格式无效。");
|
|
112
|
+
}
|
|
113
|
+
return raw.trim().slice(0, 32);
|
|
114
|
+
}
|
|
115
|
+
function normalizeQwenAudioMime(mimeType) {
|
|
116
|
+
const base = mimeType.split(";")[0]?.trim().toLowerCase() ?? "";
|
|
117
|
+
switch (base) {
|
|
118
|
+
case "audio/wav":
|
|
119
|
+
case "audio/x-wav":
|
|
120
|
+
case "audio/wave":
|
|
121
|
+
return "audio/wav";
|
|
122
|
+
case "audio/mpeg":
|
|
123
|
+
case "audio/mp3":
|
|
124
|
+
return "audio/mpeg";
|
|
125
|
+
case "audio/webm":
|
|
126
|
+
return "audio/webm";
|
|
127
|
+
case "audio/ogg":
|
|
128
|
+
return "audio/ogg";
|
|
129
|
+
case "audio/mp4":
|
|
130
|
+
case "audio/m4a":
|
|
131
|
+
case "audio/x-m4a":
|
|
132
|
+
return "audio/mp4";
|
|
133
|
+
default:
|
|
134
|
+
return "audio/wav";
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
function extractChatContentText(content) {
|
|
138
|
+
if (typeof content === "string")
|
|
139
|
+
return content;
|
|
140
|
+
if (!Array.isArray(content))
|
|
141
|
+
return "";
|
|
142
|
+
return content
|
|
143
|
+
.map((part) => {
|
|
144
|
+
if (part && typeof part === "object" && part.type === "text") {
|
|
145
|
+
const text = part.text;
|
|
146
|
+
return typeof text === "string" ? text : "";
|
|
147
|
+
}
|
|
148
|
+
return "";
|
|
149
|
+
})
|
|
150
|
+
.join("")
|
|
151
|
+
.trim();
|
|
152
|
+
}
|
|
153
|
+
async function readUpstreamError(response) {
|
|
154
|
+
try {
|
|
155
|
+
const raw = await response.text();
|
|
156
|
+
if (!raw.trim())
|
|
157
|
+
return `HTTP ${response.status}`;
|
|
158
|
+
try {
|
|
159
|
+
const parsed = JSON.parse(raw);
|
|
160
|
+
const msg = typeof parsed?.error?.message === "string"
|
|
161
|
+
? parsed.error.message
|
|
162
|
+
: typeof parsed?.message === "string"
|
|
163
|
+
? parsed.message
|
|
164
|
+
: raw;
|
|
165
|
+
return `HTTP ${response.status}: ${msg.trim().slice(0, 200)}`;
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
return `HTTP ${response.status}: ${raw.trim().slice(0, 200)}`;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
return `HTTP ${response.status}`;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
function defaultVoiceFile() {
|
|
176
|
+
return {
|
|
177
|
+
version: 1,
|
|
178
|
+
protocol: DEFAULT_VOICE_PROTOCOL,
|
|
179
|
+
baseUrl: DEFAULT_VOICE_BASE_URL,
|
|
180
|
+
model: DEFAULT_VOICE_MODEL,
|
|
181
|
+
language: "",
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
export class VoiceStore {
|
|
185
|
+
realAgentDir;
|
|
186
|
+
voicePath;
|
|
187
|
+
authStorage;
|
|
188
|
+
fetchImpl;
|
|
189
|
+
constructor(config, fetchImpl = globalThis.fetch, authStorage) {
|
|
190
|
+
this.realAgentDir = realpathSync(config.agentDir);
|
|
191
|
+
this.voicePath = join(config.agentDir, "voice.json");
|
|
192
|
+
this.authStorage = authStorage ?? new FileCredentialStore(join(config.agentDir, "auth.json"));
|
|
193
|
+
this.fetchImpl = fetchImpl;
|
|
194
|
+
}
|
|
195
|
+
async getConfig() {
|
|
196
|
+
const stored = this.loadFromDisk();
|
|
197
|
+
const hasApiKey = await this.hasStoredApiKey();
|
|
198
|
+
return {
|
|
199
|
+
enabled: Boolean(hasApiKey && stored.baseUrl && stored.model),
|
|
200
|
+
protocol: stored.protocol,
|
|
201
|
+
baseUrl: stored.baseUrl,
|
|
202
|
+
model: stored.model,
|
|
203
|
+
language: stored.language,
|
|
204
|
+
hasApiKey,
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
async updateConfig(req) {
|
|
208
|
+
const current = this.loadFromDisk();
|
|
209
|
+
const next = { ...current };
|
|
210
|
+
if (req.protocol !== undefined) {
|
|
211
|
+
if (!isVoiceProtocol(req.protocol)) {
|
|
212
|
+
throw new VoiceServiceError(400, "INVALID_VOICE_PROTOCOL", "不支持的语音识别协议。");
|
|
213
|
+
}
|
|
214
|
+
next.protocol = req.protocol;
|
|
215
|
+
}
|
|
216
|
+
next.baseUrl = assertValidVoiceBaseUrl(req.baseUrl !== undefined ? req.baseUrl : next.baseUrl, next.protocol);
|
|
217
|
+
if (req.model !== undefined) {
|
|
218
|
+
next.model = assertValidVoiceModel(req.model);
|
|
219
|
+
}
|
|
220
|
+
if (req.language !== undefined) {
|
|
221
|
+
next.language = assertValidVoiceLanguage(req.language);
|
|
222
|
+
}
|
|
223
|
+
if (req.apiKey !== undefined) {
|
|
224
|
+
if (typeof req.apiKey !== "string") {
|
|
225
|
+
throw new VoiceServiceError(400, "INVALID_API_KEY", "API 密钥格式无效。");
|
|
226
|
+
}
|
|
227
|
+
const trimmedKey = req.apiKey.trim();
|
|
228
|
+
if (trimmedKey) {
|
|
229
|
+
await this.authStorage.modify(VOICE_AUTH_KEY, async () => ({ type: "api_key", key: trimmedKey }));
|
|
230
|
+
}
|
|
231
|
+
else {
|
|
232
|
+
await this.authStorage.delete(VOICE_AUTH_KEY);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
this.saveToDisk(next);
|
|
236
|
+
return this.getConfig();
|
|
237
|
+
}
|
|
238
|
+
async transcribe(audioBuffer, mimeType = "audio/wav", filename = "recording.wav") {
|
|
239
|
+
if (audioBuffer.byteLength === 0) {
|
|
240
|
+
throw new VoiceServiceError(400, "INVALID_AUDIO", "音频内容为空。");
|
|
241
|
+
}
|
|
242
|
+
if (audioBuffer.byteLength > MAX_VOICE_AUDIO_BYTES) {
|
|
243
|
+
throw new VoiceServiceError(413, "AUDIO_TOO_LARGE", "音频文件过大(单次录音上限 10 MB)。");
|
|
244
|
+
}
|
|
245
|
+
const stored = this.loadFromDisk();
|
|
246
|
+
const apiKey = await this.readStoredApiKey();
|
|
247
|
+
if (!apiKey || !stored.baseUrl || !stored.model) {
|
|
248
|
+
throw new VoiceServiceError(400, "VOICE_NOT_CONFIGURED", "尚未配置语音识别服务,请先在「设置 → 通用 → 语音输入」中配置千问或兼容 API 密钥。");
|
|
249
|
+
}
|
|
250
|
+
if (stored.protocol === "dashscope-asr-ws") {
|
|
251
|
+
return this.transcribeDashScopeAsrWs(stored, apiKey, audioBuffer, mimeType, filename);
|
|
252
|
+
}
|
|
253
|
+
if (stored.protocol === "qwen-chat-audio") {
|
|
254
|
+
return this.transcribeQwenChatAudio(stored, apiKey, audioBuffer, mimeType);
|
|
255
|
+
}
|
|
256
|
+
return this.transcribeOpenAiMultipart(stored, apiKey, audioBuffer, mimeType, filename);
|
|
257
|
+
}
|
|
258
|
+
async transcribeDashScopeAsrWs(stored, apiKey, audioBuffer, mimeType, filename) {
|
|
259
|
+
const taskId = randomUUID().replace(/-/g, "");
|
|
260
|
+
const { format, sampleRate } = detectDashScopeAudioParams(audioBuffer, mimeType, filename);
|
|
261
|
+
const languageHints = stored.language
|
|
262
|
+
? stored.language
|
|
263
|
+
.split(/[\s,,]+/)
|
|
264
|
+
.map((item) => item.trim())
|
|
265
|
+
.filter(Boolean)
|
|
266
|
+
: [];
|
|
267
|
+
return new Promise((resolve, reject) => {
|
|
268
|
+
let settled = false;
|
|
269
|
+
let audioSent = false;
|
|
270
|
+
const finalizedSegments = [];
|
|
271
|
+
let pendingText = "";
|
|
272
|
+
const NodeWebSocket = globalThis.WebSocket;
|
|
273
|
+
const ws = new NodeWebSocket(stored.baseUrl, {
|
|
274
|
+
headers: {
|
|
275
|
+
Authorization: `Bearer ${apiKey}`,
|
|
276
|
+
},
|
|
277
|
+
});
|
|
278
|
+
ws.binaryType = "arraybuffer";
|
|
279
|
+
const cleanup = () => {
|
|
280
|
+
clearTimeout(timer);
|
|
281
|
+
ws.removeEventListener("open", onOpen);
|
|
282
|
+
ws.removeEventListener("message", onMessage);
|
|
283
|
+
ws.removeEventListener("error", onError);
|
|
284
|
+
ws.removeEventListener("close", onClose);
|
|
285
|
+
};
|
|
286
|
+
const closeSocket = (normal) => {
|
|
287
|
+
try {
|
|
288
|
+
if (ws.readyState === ws.OPEN || ws.readyState === ws.CONNECTING) {
|
|
289
|
+
if (normal) {
|
|
290
|
+
ws.close(1000);
|
|
291
|
+
}
|
|
292
|
+
else {
|
|
293
|
+
ws.close();
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
catch {
|
|
298
|
+
// ignore close failures
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
const finishSuccess = (text) => {
|
|
302
|
+
if (settled)
|
|
303
|
+
return;
|
|
304
|
+
settled = true;
|
|
305
|
+
cleanup();
|
|
306
|
+
closeSocket(true);
|
|
307
|
+
resolve({ text });
|
|
308
|
+
};
|
|
309
|
+
const finishError = (err) => {
|
|
310
|
+
if (settled)
|
|
311
|
+
return;
|
|
312
|
+
settled = true;
|
|
313
|
+
cleanup();
|
|
314
|
+
closeSocket(false);
|
|
315
|
+
reject(err);
|
|
316
|
+
};
|
|
317
|
+
const timer = setTimeout(() => {
|
|
318
|
+
finishError(new VoiceServiceError(502, "VOICE_TRANSCRIBE_FAILED", "语音识别 WebSocket 连接超时。"));
|
|
319
|
+
}, VOICE_TIMEOUT_MS);
|
|
320
|
+
const collectOutput = (output) => {
|
|
321
|
+
if (!output || typeof output !== "object")
|
|
322
|
+
return;
|
|
323
|
+
const record = output;
|
|
324
|
+
const rawSentence = record.sentence;
|
|
325
|
+
if (rawSentence !== undefined && rawSentence !== null) {
|
|
326
|
+
const items = Array.isArray(rawSentence) ? rawSentence : [rawSentence];
|
|
327
|
+
for (const item of items) {
|
|
328
|
+
if (!item || typeof item !== "object")
|
|
329
|
+
continue;
|
|
330
|
+
const sentence = item;
|
|
331
|
+
if (sentence.heartbeat === true)
|
|
332
|
+
continue;
|
|
333
|
+
const text = typeof sentence.text === "string" ? sentence.text.trim() : "";
|
|
334
|
+
const isEnd = sentence.sentence_end === true ||
|
|
335
|
+
(sentence.sentence_end !== false &&
|
|
336
|
+
typeof sentence.end_time === "number" &&
|
|
337
|
+
Number.isFinite(sentence.end_time));
|
|
338
|
+
if (isEnd) {
|
|
339
|
+
if (text)
|
|
340
|
+
finalizedSegments.push(text);
|
|
341
|
+
pendingText = "";
|
|
342
|
+
}
|
|
343
|
+
else if (text) {
|
|
344
|
+
pendingText = text;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
if (typeof record.text === "string" && record.text.trim()) {
|
|
350
|
+
pendingText = record.text.trim();
|
|
351
|
+
}
|
|
352
|
+
};
|
|
353
|
+
const onOpen = () => {
|
|
354
|
+
if (settled)
|
|
355
|
+
return;
|
|
356
|
+
const parameters = {
|
|
357
|
+
format,
|
|
358
|
+
sample_rate: sampleRate,
|
|
359
|
+
};
|
|
360
|
+
if (languageHints.length > 0) {
|
|
361
|
+
parameters.language_hints = languageHints;
|
|
362
|
+
}
|
|
363
|
+
try {
|
|
364
|
+
ws.send(JSON.stringify({
|
|
365
|
+
header: {
|
|
366
|
+
action: "run-task",
|
|
367
|
+
task_id: taskId,
|
|
368
|
+
streaming: "duplex",
|
|
369
|
+
},
|
|
370
|
+
payload: {
|
|
371
|
+
task_group: "audio",
|
|
372
|
+
task: "asr",
|
|
373
|
+
function: "recognition",
|
|
374
|
+
model: stored.model,
|
|
375
|
+
parameters,
|
|
376
|
+
input: {},
|
|
377
|
+
},
|
|
378
|
+
}));
|
|
379
|
+
}
|
|
380
|
+
catch (error) {
|
|
381
|
+
const msg = error instanceof Error ? error.message : "发送初始化指令失败";
|
|
382
|
+
finishError(new VoiceServiceError(502, "VOICE_TRANSCRIBE_FAILED", `语音识别任务启动失败(${msg})。`));
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
const onMessage = (event) => {
|
|
386
|
+
if (settled)
|
|
387
|
+
return;
|
|
388
|
+
const rawText = decodeWsMessageData(event.data);
|
|
389
|
+
if (!rawText)
|
|
390
|
+
return;
|
|
391
|
+
let parsed;
|
|
392
|
+
try {
|
|
393
|
+
parsed = JSON.parse(rawText);
|
|
394
|
+
}
|
|
395
|
+
catch {
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
const eventName = parsed?.header?.event;
|
|
399
|
+
if (eventName === "task-started") {
|
|
400
|
+
if (!audioSent) {
|
|
401
|
+
audioSent = true;
|
|
402
|
+
try {
|
|
403
|
+
for (let offset = 0; offset < audioBuffer.byteLength; offset += DASHSCOPE_WS_CHUNK_BYTES) {
|
|
404
|
+
const end = Math.min(offset + DASHSCOPE_WS_CHUNK_BYTES, audioBuffer.byteLength);
|
|
405
|
+
ws.send(audioBuffer.subarray(offset, end));
|
|
406
|
+
}
|
|
407
|
+
ws.send(JSON.stringify({
|
|
408
|
+
header: {
|
|
409
|
+
action: "finish-task",
|
|
410
|
+
task_id: taskId,
|
|
411
|
+
streaming: "duplex",
|
|
412
|
+
},
|
|
413
|
+
payload: {
|
|
414
|
+
input: {},
|
|
415
|
+
},
|
|
416
|
+
}));
|
|
417
|
+
}
|
|
418
|
+
catch (error) {
|
|
419
|
+
const msg = error instanceof Error ? error.message : "音频流发送失败";
|
|
420
|
+
finishError(new VoiceServiceError(502, "VOICE_TRANSCRIBE_FAILED", `语音识别音频发送失败(${msg})。`));
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
if (eventName === "result-generated") {
|
|
426
|
+
collectOutput(parsed?.payload?.output);
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
if (eventName === "task-finished") {
|
|
430
|
+
collectOutput(parsed?.payload?.output);
|
|
431
|
+
if (pendingText) {
|
|
432
|
+
finalizedSegments.push(pendingText);
|
|
433
|
+
pendingText = "";
|
|
434
|
+
}
|
|
435
|
+
finishSuccess(joinRecognizedSegments(finalizedSegments));
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
if (eventName === "task-failed") {
|
|
439
|
+
const code = typeof parsed?.header?.error_code === "string" ? parsed.header.error_code.trim() : "";
|
|
440
|
+
const errMsg = typeof parsed?.header?.error_message === "string"
|
|
441
|
+
? parsed.header.error_message.trim()
|
|
442
|
+
: typeof parsed?.payload?.message === "string"
|
|
443
|
+
? parsed.payload.message.trim()
|
|
444
|
+
: "";
|
|
445
|
+
const detail = [code, errMsg].filter(Boolean).join(": ") || "服务端返回任务失败";
|
|
446
|
+
finishError(new VoiceServiceError(502, "VOICE_TRANSCRIBE_FAILED", `语音识别失败(${detail})。`));
|
|
447
|
+
}
|
|
448
|
+
};
|
|
449
|
+
const onError = (event) => {
|
|
450
|
+
const errObj = event;
|
|
451
|
+
const msg = errObj.error instanceof Error
|
|
452
|
+
? errObj.error.message
|
|
453
|
+
: typeof errObj.message === "string" && errObj.message.trim()
|
|
454
|
+
? errObj.message.trim()
|
|
455
|
+
: "连接异常";
|
|
456
|
+
finishError(new VoiceServiceError(502, "VOICE_TRANSCRIBE_FAILED", `语音识别 WebSocket 连接失败(${msg})。`));
|
|
457
|
+
};
|
|
458
|
+
const onClose = (event) => {
|
|
459
|
+
if (settled)
|
|
460
|
+
return;
|
|
461
|
+
const segments = pendingText ? [...finalizedSegments, pendingText] : [...finalizedSegments];
|
|
462
|
+
const text = joinRecognizedSegments(segments);
|
|
463
|
+
if (audioSent && event.code === 1000 && text) {
|
|
464
|
+
finishSuccess(text);
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
467
|
+
const reason = typeof event.reason === "string" ? event.reason.trim() : "";
|
|
468
|
+
finishError(new VoiceServiceError(502, "VOICE_TRANSCRIBE_FAILED", `语音识别连接异常关闭(code ${event.code}${reason ? `: ${reason}` : ""})。`));
|
|
469
|
+
};
|
|
470
|
+
ws.addEventListener("open", onOpen);
|
|
471
|
+
ws.addEventListener("message", onMessage);
|
|
472
|
+
ws.addEventListener("error", onError);
|
|
473
|
+
ws.addEventListener("close", onClose);
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
async transcribeQwenChatAudio(stored, apiKey, audioBuffer, mimeType) {
|
|
477
|
+
const normalizedMime = normalizeQwenAudioMime(mimeType);
|
|
478
|
+
const dataUri = `data:${normalizedMime};base64,${audioBuffer.toString("base64")}`;
|
|
479
|
+
let response;
|
|
480
|
+
try {
|
|
481
|
+
response = await this.fetchImpl(`${stored.baseUrl}/chat/completions`, {
|
|
482
|
+
method: "POST",
|
|
483
|
+
headers: {
|
|
484
|
+
Authorization: `Bearer ${apiKey}`,
|
|
485
|
+
"Content-Type": "application/json",
|
|
486
|
+
},
|
|
487
|
+
body: JSON.stringify({
|
|
488
|
+
model: stored.model,
|
|
489
|
+
stream: false,
|
|
490
|
+
messages: [
|
|
491
|
+
{
|
|
492
|
+
role: "user",
|
|
493
|
+
content: [
|
|
494
|
+
{
|
|
495
|
+
type: "input_audio",
|
|
496
|
+
input_audio: { data: dataUri },
|
|
497
|
+
},
|
|
498
|
+
],
|
|
499
|
+
},
|
|
500
|
+
],
|
|
501
|
+
asr_options: {
|
|
502
|
+
enable_itn: true,
|
|
503
|
+
...(stored.language ? { language: stored.language } : {}),
|
|
504
|
+
},
|
|
505
|
+
}),
|
|
506
|
+
signal: AbortSignal.timeout(VOICE_TIMEOUT_MS),
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
catch (error) {
|
|
510
|
+
const msg = error instanceof Error ? error.message : "网络请求失败";
|
|
511
|
+
throw new VoiceServiceError(502, "VOICE_TRANSCRIBE_FAILED", `语音识别接口连接失败(${msg})。`);
|
|
512
|
+
}
|
|
513
|
+
if (!response.ok) {
|
|
514
|
+
const detail = await readUpstreamError(response);
|
|
515
|
+
throw new VoiceServiceError(502, "VOICE_TRANSCRIBE_FAILED", `语音识别失败(${detail})。`);
|
|
516
|
+
}
|
|
517
|
+
let payload;
|
|
518
|
+
try {
|
|
519
|
+
payload = await response.json();
|
|
520
|
+
}
|
|
521
|
+
catch {
|
|
522
|
+
throw new VoiceServiceError(502, "VOICE_TRANSCRIBE_FAILED", "语音识别接口返回了无效的 JSON 响应。");
|
|
523
|
+
}
|
|
524
|
+
const choices = payload?.choices;
|
|
525
|
+
const first = Array.isArray(choices) ? choices[0] : undefined;
|
|
526
|
+
const text = extractChatContentText(first?.message?.content).trim();
|
|
527
|
+
return { text };
|
|
528
|
+
}
|
|
529
|
+
async transcribeOpenAiMultipart(stored, apiKey, audioBuffer, mimeType, filename) {
|
|
530
|
+
const formData = new FormData();
|
|
531
|
+
formData.append("file", new Blob([new Uint8Array(audioBuffer)], { type: mimeType || "audio/wav" }), filename || "recording.wav");
|
|
532
|
+
formData.append("model", stored.model);
|
|
533
|
+
if (stored.language) {
|
|
534
|
+
formData.append("language", stored.language);
|
|
535
|
+
}
|
|
536
|
+
let response;
|
|
537
|
+
try {
|
|
538
|
+
response = await this.fetchImpl(`${stored.baseUrl}/audio/transcriptions`, {
|
|
539
|
+
method: "POST",
|
|
540
|
+
headers: {
|
|
541
|
+
Authorization: `Bearer ${apiKey}`,
|
|
542
|
+
},
|
|
543
|
+
body: formData,
|
|
544
|
+
signal: AbortSignal.timeout(VOICE_TIMEOUT_MS),
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
catch (error) {
|
|
548
|
+
const msg = error instanceof Error ? error.message : "网络请求失败";
|
|
549
|
+
throw new VoiceServiceError(502, "VOICE_TRANSCRIBE_FAILED", `语音识别接口连接失败(${msg})。`);
|
|
550
|
+
}
|
|
551
|
+
if (!response.ok) {
|
|
552
|
+
const detail = await readUpstreamError(response);
|
|
553
|
+
throw new VoiceServiceError(502, "VOICE_TRANSCRIBE_FAILED", `语音识别失败(${detail})。`);
|
|
554
|
+
}
|
|
555
|
+
const contentType = response.headers.get("content-type")?.toLowerCase() ?? "";
|
|
556
|
+
if (contentType.includes("text/plain")) {
|
|
557
|
+
const plain = await response.text();
|
|
558
|
+
return { text: plain.trim() };
|
|
559
|
+
}
|
|
560
|
+
let payload;
|
|
561
|
+
try {
|
|
562
|
+
payload = await response.json();
|
|
563
|
+
}
|
|
564
|
+
catch {
|
|
565
|
+
throw new VoiceServiceError(502, "VOICE_TRANSCRIBE_FAILED", "语音识别接口返回了无效的 JSON 响应。");
|
|
566
|
+
}
|
|
567
|
+
const rawText = payload?.text;
|
|
568
|
+
return { text: typeof rawText === "string" ? rawText.trim() : "" };
|
|
569
|
+
}
|
|
570
|
+
async readStoredApiKey() {
|
|
571
|
+
const cred = await this.authStorage.read(VOICE_AUTH_KEY);
|
|
572
|
+
if (cred?.type === "api_key" && typeof cred.key === "string" && cred.key.trim().length > 0) {
|
|
573
|
+
return cred.key.trim();
|
|
574
|
+
}
|
|
575
|
+
return undefined;
|
|
576
|
+
}
|
|
577
|
+
async hasStoredApiKey() {
|
|
578
|
+
return (await this.readStoredApiKey()) !== undefined;
|
|
579
|
+
}
|
|
580
|
+
assertContainedPath(target) {
|
|
581
|
+
const resolved = realpathSync(join(target, ".."));
|
|
582
|
+
if (resolved !== this.realAgentDir && !isContainedIn(this.realAgentDir, resolved)) {
|
|
583
|
+
throw new Error(`Voice configuration escapes agentDir: ${target}`);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
loadFromDisk() {
|
|
587
|
+
this.assertContainedPath(this.voicePath);
|
|
588
|
+
const defaults = defaultVoiceFile();
|
|
589
|
+
if (!existsSync(this.voicePath)) {
|
|
590
|
+
return defaults;
|
|
591
|
+
}
|
|
592
|
+
try {
|
|
593
|
+
const raw = readFileSync(this.voicePath, "utf-8");
|
|
594
|
+
const parsed = JSON.parse(raw);
|
|
595
|
+
return {
|
|
596
|
+
version: 1,
|
|
597
|
+
protocol: isVoiceProtocol(parsed.protocol) ? parsed.protocol : defaults.protocol,
|
|
598
|
+
baseUrl: typeof parsed.baseUrl === "string" && parsed.baseUrl.trim()
|
|
599
|
+
? parsed.baseUrl.trim().replace(/\/+$/, "")
|
|
600
|
+
: defaults.baseUrl,
|
|
601
|
+
model: typeof parsed.model === "string" && parsed.model.trim()
|
|
602
|
+
? parsed.model.trim().slice(0, 120)
|
|
603
|
+
: defaults.model,
|
|
604
|
+
language: typeof parsed.language === "string" ? parsed.language.trim().slice(0, 32) : "",
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
catch {
|
|
608
|
+
return defaults;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
saveToDisk(data) {
|
|
612
|
+
this.assertContainedPath(this.voicePath);
|
|
613
|
+
writeFileSync(this.voicePath, `${JSON.stringify(data, null, 2)}\n`, {
|
|
614
|
+
encoding: "utf-8",
|
|
615
|
+
mode: 0o600,
|
|
616
|
+
});
|
|
617
|
+
}
|
|
618
|
+
}
|
package/shared/protocol.js
CHANGED
|
@@ -41,4 +41,12 @@ export function clampThinkingLevelForDescriptor(descriptor, level) {
|
|
|
41
41
|
export function clampThinkingLevelForModel(modelId, level, models, providerId) {
|
|
42
42
|
return clampThinkingLevelForDescriptor(getModelDescriptor(modelId, models, providerId), level);
|
|
43
43
|
}
|
|
44
|
+
export const VOICE_PROTOCOLS = [
|
|
45
|
+
{ id: "dashscope-asr-ws", label: "千问语音识别 WebSocket(DashScope Recognition)" },
|
|
46
|
+
{ id: "qwen-chat-audio", label: "通义千问 HTTP(qwen3-asr-flash / input_audio)" },
|
|
47
|
+
{ id: "openai-transcriptions", label: "OpenAI 兼容(/audio/transcriptions)" },
|
|
48
|
+
];
|
|
49
|
+
export function isVoiceProtocol(value) {
|
|
50
|
+
return value === "dashscope-asr-ws" || value === "qwen-chat-audio" || value === "openai-transcriptions";
|
|
51
|
+
}
|
|
44
52
|
//# sourceMappingURL=protocol.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{g as p,r as u,d as a}from"./chunk-SVP7TREG-
|
|
1
|
+
import{g as p,r as u,d as a}from"./chunk-SVP7TREG-V3BsTVSS.js";import{p as f}from"./chunk-JWPE2WC7-s-_Lm4OD.js";import{c as n,l as o}from"./index-DFKPpT1o.js";import{M as c,b as d}from"./cynefin-OW5HDTMX-CCabvWFn.js";var v=d().RailroadAbnf.parser.LangiumParser,l=n(e=>{const r=e.alternatives.map(g);return r.length===1?r[0]:{type:"choice",alternatives:r}},"transformAlternation"),g=n(e=>{const r=e.elements.map(y);return r.length===1?r[0]:{type:"sequence",elements:r}},"transformConcatenation"),b=n(e=>{if(e.includes("*")){const[t,s]=e.split("*"),i=t?parseInt(t,10):0,m=s?parseInt(s,10):1/0;return{min:i,max:m}}const r=parseInt(e,10);return{min:r,max:r}},"parseRepeat"),y=n(e=>{const r=A(e.primary);if(!e.repeat)return r;const{min:t,max:s}=b(e.repeat);return t===0&&s===1?{type:"optional",element:r}:{type:"repetition",element:r,min:t,max:s}},"transformElement"),A=n(e=>{switch(e.$type){case"AbnfStringLiteral":return{type:"terminal",value:e.value};case"AbnfNumVal":return{type:"terminal",value:e.value};case"AbnfRuleName":return{type:"nonterminal",name:e.name};case"AbnfGroup":return l(e.element);case"AbnfOptionalGroup":return{type:"optional",element:l(e.element)};default:throw new Error(`Unsupported ABNF primary node: ${e.$type}`)}},"transformPrimary"),P=n(e=>({name:e.name,definition:l(e.definition)}),"transformRule"),h=n(e=>{f(e,a),e.title&&a.setTitle(e.title),e.rules.map(r=>a.addRule(P(r)))},"populateDb"),R={parse:n(e=>{a.clear(),o.debug("[ABNF Parser] Starting Langium parse");const r=v.parse(e);if(r.lexerErrors.length>0||r.parserErrors.length>0)throw new c(r);const t=r.value;o.debug("[ABNF Parser] Parsed rules:",t.rules.length),h(t),o.debug("[ABNF Parser] Parse complete")},"parse"),parser:{yy:a}},w={parser:R,db:a,renderer:u,styles:p};export{w as diagram};
|