@jskit-ai/assistant-voice 0.2.87 → 0.2.89
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 +92 -13
- package/examples/conversation/README.md +2 -2
- package/examples/conversation/package.json +9 -9
- package/package.json +10 -5
- package/src/client/ConversationDialog.vue +4 -1
- package/src/client/browser.js +4 -3
- package/src/client/voiceLauncher.js +27 -8
- package/src/server/index.js +7 -2
- package/src/server/standInSpeechEngine.js +116 -0
- package/src/server/voiceCredentials.js +220 -0
- package/src/server/voiceDaemon.js +286 -243
- package/src/server/voiceDaemonHttp.js +24 -0
- package/src/server/voiceProxy.js +31 -7
- package/src/server/voiceProxyConfig.js +25 -23
- package/src/server/voiceSpeechQueue.js +68 -0
- package/src/shared/protocol.js +212 -12
- package/src/server/voiceAccessToken.js +0 -82
package/README.md
CHANGED
|
@@ -179,19 +179,98 @@ registerVoiceProxyRoute(fastify, {
|
|
|
179
179
|
```
|
|
180
180
|
|
|
181
181
|
The route's authorization is mandatory and runs before upstream connection.
|
|
182
|
-
Keep endpoint and token
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
The
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
182
|
+
Keep the endpoint and token server-side: `resolveVoiceProxyConfig` takes the
|
|
183
|
+
token as `accessTokenFile` (a protected file) or as `accessToken` (its value, for
|
|
184
|
+
example from a secret environment variable), one or the other. The token grants
|
|
185
|
+
speech-service use, not access to a conversation or permission to run an agent.
|
|
186
|
+
Browsers need a secure origin (HTTPS or a browser-recognized localhost origin)
|
|
187
|
+
and microphone permission.
|
|
188
|
+
|
|
189
|
+
## Speech service
|
|
190
|
+
|
|
191
|
+
The speech service is a service like a database: its host runs it, and each
|
|
192
|
+
application is a client of it with its own token. `createVoiceDaemon({ engine,
|
|
193
|
+
credentialsFile, ... })` runs the bounded protocol service on a speech engine
|
|
194
|
+
(`@jskit-ai/assistant-voice-sherpa`'s, or a stand-in). Its routes:
|
|
195
|
+
|
|
196
|
+
| Route | Token | Answers |
|
|
197
|
+
| --- | --- | --- |
|
|
198
|
+
| `GET /health` | none | `ok`, `connections`, `queueDepth`, `startedAt`, `protocolVersion`, `versions` (package and native runtime versions by name) and `credentialsSha256` |
|
|
199
|
+
| `GET /v1/catalogue` | yes | `protocolVersion`, `inputSampleRate`, `outputSampleRate`, `recognitionModels` (`id`, `hotwords`), `voices` and `defaultVoice` |
|
|
200
|
+
| `GET /voices` | yes | `voices` and `defaultVoice` |
|
|
201
|
+
| `/v1/voice` WebSocket | yes | the voice protocol; the voice is chosen per reply |
|
|
202
|
+
|
|
203
|
+
A client sends `Authorization: Bearer <token>`. The protocol only gains fields;
|
|
204
|
+
a change that breaks a client would be `/v2`. `readVoiceServiceCatalogue(config)`
|
|
205
|
+
and `readVoiceCatalogue(config)` read the two catalogues with a client's
|
|
206
|
+
`resolveVoiceProxyConfig` result.
|
|
207
|
+
|
|
208
|
+
### Credentials file
|
|
209
|
+
|
|
210
|
+
The host writes the clients it admits to a JSON file; the service holds only
|
|
211
|
+
each token's SHA-256 and never sees a token it did not receive:
|
|
212
|
+
|
|
213
|
+
```json
|
|
214
|
+
{
|
|
215
|
+
"schema": "jskit.assistant-voice.credentials.v1",
|
|
216
|
+
"clients": {
|
|
217
|
+
"crd_mercbot": { "tokenSha256": ["<64 lowercase hex>"] },
|
|
218
|
+
"lnk_ws-12": { "tokenSha256": ["<hex>", "<hex>"], "maximumConnections": 6 }
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
- A client name is 1 to 64 lowercase letters, digits, dots, dashes or
|
|
224
|
+
underscores, starting and ending with a letter or digit.
|
|
225
|
+
- `tokenSha256` lists 1 to 8 hashes, so a token can be rotated: add the new
|
|
226
|
+
hash, move the client, then remove the old one. A hash is the lowercase hex
|
|
227
|
+
SHA-256 of the token's UTF-8 bytes (`voiceTokenSha256(token)`), and appears
|
|
228
|
+
once in the file. A token is an RFC 6750 bearer token of 32 to 1024
|
|
229
|
+
characters; `createVoiceClientToken()` makes one of 32 random bytes.
|
|
230
|
+
- `maximumConnections` replaces the service's per-client limit for that client.
|
|
231
|
+
A client's tokens share one limit.
|
|
232
|
+
- Unknown fields are refused (`parseVoiceCredentials(document)` checks a
|
|
233
|
+
document), as are more than 10,000 clients or 4 MiB.
|
|
234
|
+
|
|
235
|
+
The service checks the file every second (`credentialsPollMs`). Write it
|
|
236
|
+
atomically, to a temporary file renamed over it. A change takes effect at once:
|
|
237
|
+
a removed token's open sessions are cancelled and closed with
|
|
238
|
+
`voice_access_revoked` (1008), and an added client connects without a restart.
|
|
239
|
+
`/health`'s `credentialsSha256` is the SHA-256 of the file bytes in use, and
|
|
240
|
+
changes only after the revoked sessions have ended, so a host knows the service
|
|
241
|
+
runs exactly what it wrote. A rewrite that is not a valid file leaves the last
|
|
242
|
+
valid credentials in use; a missing file admits no one (`credentialsSha256` is
|
|
243
|
+
`null`). The service does not start without a valid file.
|
|
244
|
+
|
|
245
|
+
### Access log
|
|
246
|
+
|
|
247
|
+
`accessLog(record)` receives, by default as one JSON line on standard output:
|
|
248
|
+
|
|
249
|
+
- one `voice.connection` record per connection: `client`, `startedAt`,
|
|
250
|
+
`endedAt`, `audioSecondsHeard`, `charactersSpoken`, `closed` (`client`,
|
|
251
|
+
`idle`, `revoked`, `shutdown`, `protocol` or `error`) and `closeCode`. A
|
|
252
|
+
refused connection has its record at once, with `closed` `unauthorized`
|
|
253
|
+
(`client` `null`) or `capacity` and nothing heard or spoken. It never holds
|
|
254
|
+
audio or words;
|
|
255
|
+
- one `voice.credentials` record when the credentials load, at start and at each
|
|
256
|
+
change: `credentialsSha256`, `clients` and the `clientsAdded`,
|
|
257
|
+
`clientsRemoved` and `clientsChanged` (tokens or limit), and `sessionsEnded`;
|
|
258
|
+
- a `voice.credentials.refused` record with the `reason` when a changed file
|
|
259
|
+
cannot be used, and the `credentialsSha256` still in use.
|
|
260
|
+
|
|
261
|
+
### Capacity
|
|
262
|
+
|
|
263
|
+
An engine says how many recognitions and syntheses it runs at once
|
|
264
|
+
(`engine.concurrency`, default one each). The service synthesizes that many
|
|
265
|
+
phrases at once, one per connection at a time, and sizes its limits from it:
|
|
266
|
+
`maximumConnections` 8 per recognition worker, `maximumConnectionsPerClient` 2
|
|
267
|
+
per recognition worker and `maximumQueuedSpeech` 4 per synthesis worker, each
|
|
268
|
+
replaceable. Past them a connection gets 429 and a phrase `busy`.
|
|
269
|
+
|
|
270
|
+
`@jskit-ai/assistant-voice/stand-in`'s `createStandInSpeechEngine()` is an
|
|
271
|
+
engine with no model for tests and catalogue proofs: it hears any audio as
|
|
272
|
+
`recognizedText` and speaks silence. Its `versions` name it, so `/health`
|
|
273
|
+
shows a stand-in runs.
|
|
195
274
|
|
|
196
275
|
## Example and testing
|
|
197
276
|
|
|
@@ -21,8 +21,8 @@ dependency scanning and shared client dependencies.
|
|
|
21
21
|
in the server environment using your secret manager or protected shell session.
|
|
22
22
|
Keep the key out of JSON configuration and browser environment variables.
|
|
23
23
|
3. For voice, prepare a speech service using the assistant-voice-sherpa README,
|
|
24
|
-
or obtain a speech endpoint and
|
|
25
|
-
|
|
24
|
+
or obtain a speech endpoint and client token from its operator. Supply its
|
|
25
|
+
endpoint and protected token file to this example's server.
|
|
26
26
|
4. Start the server with your protected configuration paths:
|
|
27
27
|
|
|
28
28
|
```sh
|
|
@@ -9,15 +9,15 @@
|
|
|
9
9
|
},
|
|
10
10
|
"dependencies": {
|
|
11
11
|
"@fastify/websocket": "^11.2.0",
|
|
12
|
-
"@jskit-ai/assistant-core": "0.2.
|
|
13
|
-
"@jskit-ai/assistant-runtime": "0.2.
|
|
14
|
-
"@jskit-ai/assistant-voice": "0.2.
|
|
15
|
-
"@jskit-ai/connectors-catalog": "0.2.
|
|
16
|
-
"@jskit-ai/http-runtime": "0.2.
|
|
17
|
-
"@jskit-ai/kernel": "0.2.
|
|
18
|
-
"@jskit-ai/material-web": "0.1.
|
|
19
|
-
"@jskit-ai/realtime": "0.2.
|
|
20
|
-
"@jskit-ai/shell-web": "0.2.
|
|
12
|
+
"@jskit-ai/assistant-core": "0.2.83",
|
|
13
|
+
"@jskit-ai/assistant-runtime": "0.2.89",
|
|
14
|
+
"@jskit-ai/assistant-voice": "0.2.89",
|
|
15
|
+
"@jskit-ai/connectors-catalog": "0.2.55",
|
|
16
|
+
"@jskit-ai/http-runtime": "0.2.35",
|
|
17
|
+
"@jskit-ai/kernel": "0.2.34",
|
|
18
|
+
"@jskit-ai/material-web": "0.1.10",
|
|
19
|
+
"@jskit-ai/realtime": "0.2.54",
|
|
20
|
+
"@jskit-ai/shell-web": "0.2.51",
|
|
21
21
|
"@tanstack/vue-query": "^5.90.5",
|
|
22
22
|
"fastify": "^5.12.7",
|
|
23
23
|
"pinia": "^4.0.3",
|
package/package.json
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/assistant-voice",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.89",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"description": "Duplex voice conversations with application-owned targets
|
|
5
|
+
"description": "Duplex voice conversations with application-owned targets and authorization, and the speech service engine with its client.",
|
|
6
6
|
"scripts": {
|
|
7
7
|
"test": "jskit test"
|
|
8
8
|
},
|
|
9
9
|
"exports": {
|
|
10
10
|
"./client": "./src/client/index.js",
|
|
11
11
|
"./server": "./src/server/index.js",
|
|
12
|
+
"./stand-in": "./src/server/standInSpeechEngine.js",
|
|
12
13
|
"./shared/protocol": "./src/shared/protocol.js",
|
|
13
14
|
"./shared/visemes": "./src/shared/visemes.js",
|
|
14
15
|
"./locales/en.json": "./locales/en.json"
|
|
@@ -20,7 +21,7 @@
|
|
|
20
21
|
"examples"
|
|
21
22
|
],
|
|
22
23
|
"dependencies": {
|
|
23
|
-
"@jskit-ai/assistant-core": "0.2.
|
|
24
|
+
"@jskit-ai/assistant-core": "0.2.83",
|
|
24
25
|
"ws": "^8.20.1"
|
|
25
26
|
},
|
|
26
27
|
"jskit": {
|
|
@@ -46,7 +47,11 @@
|
|
|
46
47
|
},
|
|
47
48
|
{
|
|
48
49
|
"subpath": "./server",
|
|
49
|
-
"summary": "Authorized WebSocket proxy,
|
|
50
|
+
"summary": "Authorized WebSocket proxy and catalogue client, the speech service daemon with its credentials file, access log and catalogue, and client tokens."
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
"subpath": "./stand-in",
|
|
54
|
+
"summary": "A speech engine with no model, for tests and catalogue proofs of a voice service."
|
|
50
55
|
},
|
|
51
56
|
{
|
|
52
57
|
"subpath": "./shared/protocol",
|
|
@@ -62,7 +67,7 @@
|
|
|
62
67
|
}
|
|
63
68
|
},
|
|
64
69
|
"peerDependencies": {
|
|
65
|
-
"@jskit-ai/kernel": "0.2.
|
|
70
|
+
"@jskit-ai/kernel": "0.2.34",
|
|
66
71
|
"vue": "^3.5.13",
|
|
67
72
|
"vuetify": "^4.3.0"
|
|
68
73
|
},
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
<script setup>
|
|
2
2
|
import { useDisplay } from "vuetify";
|
|
3
|
-
|
|
3
|
+
// Each from its own entry: "vuetify/components" would load every Vuetify component wherever this file's source is
|
|
4
|
+
// loaded as it is, as an app's tests do.
|
|
5
|
+
import { VCard } from "vuetify/components/VCard";
|
|
6
|
+
import { VDialog } from "vuetify/components/VDialog";
|
|
4
7
|
import { computed } from "vue";
|
|
5
8
|
import { useJskitText } from "./i18n.js";
|
|
6
9
|
|
package/src/client/browser.js
CHANGED
|
@@ -15,15 +15,16 @@ function audioContextConstructor() {
|
|
|
15
15
|
* Listens to an event of the page until the returned function is called.
|
|
16
16
|
* @param {string} type
|
|
17
17
|
* @param {EventListener} listener
|
|
18
|
+
* @param {AddEventListenerOptions} [options] Such as `{ capture: true }`, to hear the event before its target does.
|
|
18
19
|
* @returns {() => void} Stops listening.
|
|
19
20
|
*/
|
|
20
|
-
function listenToPage(type, listener) {
|
|
21
|
+
function listenToPage(type, listener, options) {
|
|
21
22
|
const page = globalThis.window;
|
|
22
23
|
// readable-check: allow optional-call - platform object: outside a browser there is no window to listen to
|
|
23
|
-
page?.addEventListener?.(type, listener);
|
|
24
|
+
page?.addEventListener?.(type, listener, options);
|
|
24
25
|
return () => {
|
|
25
26
|
// readable-check: allow optional-call - platform object: outside a browser there is no window to listen to
|
|
26
|
-
page?.removeEventListener?.(type, listener);
|
|
27
|
+
page?.removeEventListener?.(type, listener, options);
|
|
27
28
|
};
|
|
28
29
|
}
|
|
29
30
|
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { onScopeDispose, ref, toValue } from "vue";
|
|
2
|
+
import { listenToPage } from "./browser.js";
|
|
2
3
|
|
|
3
4
|
/** Reports nothing when an application leaves out onError. */
|
|
4
5
|
function ignoreLauncherError() {}
|
|
@@ -18,12 +19,30 @@ export function useVoiceLauncher({ open, enabled = true, onTap, onError = ignore
|
|
|
18
19
|
const holding = ref(false);
|
|
19
20
|
let input = null;
|
|
20
21
|
let timer;
|
|
21
|
-
let suppressClick = false;
|
|
22
22
|
let revision = 0;
|
|
23
23
|
let session;
|
|
24
|
+
let stopSwallowing = () => {};
|
|
24
25
|
function report(operation) { Promise.resolve(operation).catch(onError); }
|
|
26
|
+
// A pointer hold ends with the browser's click wherever the pointer lifts, and the hold may have opened something over
|
|
27
|
+
// the launcher there, such as a full-screen conversation's Close. That click is the hold's, so it does nothing. The
|
|
28
|
+
// next press ends the watch, as does a keyboard or assistive click (detail 0), which a release never makes.
|
|
29
|
+
function swallowReleaseClick() {
|
|
30
|
+
stopSwallowing();
|
|
31
|
+
const stops = [
|
|
32
|
+
listenToPage("click", event => {
|
|
33
|
+
stopSwallowing();
|
|
34
|
+
if (event.detail === 0) return;
|
|
35
|
+
event.preventDefault();
|
|
36
|
+
event.stopImmediatePropagation();
|
|
37
|
+
}, { capture: true }),
|
|
38
|
+
listenToPage("pointerdown", () => stopSwallowing(), { capture: true })
|
|
39
|
+
];
|
|
40
|
+
stopSwallowing = () => {
|
|
41
|
+
for (const stop of stops) stop();
|
|
42
|
+
stopSwallowing = () => {};
|
|
43
|
+
};
|
|
44
|
+
}
|
|
25
45
|
function begin(identity, delay) {
|
|
26
|
-
suppressClick = false;
|
|
27
46
|
input = identity;
|
|
28
47
|
const expected = ++revision;
|
|
29
48
|
timer = setTimeout(() => {
|
|
@@ -55,7 +74,7 @@ export function useVoiceLauncher({ open, enabled = true, onTap, onError = ignore
|
|
|
55
74
|
return;
|
|
56
75
|
}
|
|
57
76
|
holding.value = false;
|
|
58
|
-
|
|
77
|
+
if (!keyboard) swallowReleaseClick();
|
|
59
78
|
if (session) report(discard ? session.discardHeldRecording() : session.finishHeldRecording());
|
|
60
79
|
session = null;
|
|
61
80
|
}
|
|
@@ -65,12 +84,12 @@ export function useVoiceLauncher({ open, enabled = true, onTap, onError = ignore
|
|
|
65
84
|
if (event?.pointerId !== undefined && event.pointerId !== input) return;
|
|
66
85
|
finish(true);
|
|
67
86
|
}
|
|
68
|
-
function click(
|
|
69
|
-
const suppressed = suppressClick && event.detail !== 0;
|
|
70
|
-
suppressClick = false;
|
|
71
|
-
if (suppressed) { event.preventDefault(); event.stopImmediatePropagation(); return; }
|
|
87
|
+
function click() {
|
|
72
88
|
if (toValue(enabled) && tappable) report(onTap());
|
|
73
89
|
}
|
|
74
|
-
onScopeDispose(
|
|
90
|
+
onScopeDispose(() => {
|
|
91
|
+
cancel();
|
|
92
|
+
stopSwallowing();
|
|
93
|
+
});
|
|
75
94
|
return { holding, pointerDown, pointerUp, keyDown, keyUp, cancel, click };
|
|
76
95
|
}
|
package/src/server/index.js
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
export { createVoiceDaemon } from "./voiceDaemon.js";
|
|
2
|
-
export { registerVoiceProxyRoute, readVoiceCatalogue } from "./voiceProxy.js";
|
|
2
|
+
export { registerVoiceProxyRoute, readVoiceCatalogue, readVoiceServiceCatalogue } from "./voiceProxy.js";
|
|
3
3
|
export { resolveVoiceProxyConfig, readVoiceAccessToken, voiceEndpoint } from "./voiceProxyConfig.js";
|
|
4
|
-
export {
|
|
4
|
+
export {
|
|
5
|
+
VOICE_CREDENTIALS_SCHEMA,
|
|
6
|
+
createVoiceClientToken,
|
|
7
|
+
parseVoiceCredentials,
|
|
8
|
+
voiceTokenSha256
|
|
9
|
+
} from "./voiceCredentials.js";
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
3
|
+
import { normalizeRecognizedText, recognitionHotwords, recognitionSpellingCount, recognitionSpellings } from "../shared/protocol.js";
|
|
4
|
+
|
|
5
|
+
const PACKAGE_VERSION = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
|
|
6
|
+
|
|
7
|
+
/** A listener that does not follow the recognized words ignores them. */
|
|
8
|
+
function ignoreRecognizedText() {}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* A speech engine with no model, for tests and catalogue proofs of a voice
|
|
12
|
+
* service: it hears any audio as `recognizedText` and speaks each phrase as
|
|
13
|
+
* silence, a tenth of a second per word. Its versions name it, so a service's
|
|
14
|
+
* /health shows that a stand-in runs.
|
|
15
|
+
* @param {object} [options]
|
|
16
|
+
* @param {string} [options.recognizedText] Heard as the native engine hears it: an all-uppercase text is
|
|
17
|
+
* written with JSKIT's spellings and `spellings`.
|
|
18
|
+
* @param {{ id: string, label: string, language?: string }[]} [options.voices]
|
|
19
|
+
* @param {string} [options.defaultVoice]
|
|
20
|
+
* @param {number} [options.sampleRate]
|
|
21
|
+
* @param {number} [options.synthesisMs] How long each phrase's synthesis takes.
|
|
22
|
+
* @param {string[]} [options.hotwords] Checked and counted in its recognition model, as the native engine checks and counts a host's additions.
|
|
23
|
+
* @param {Record<string, string>} [options.spellings] A host's spellings, checked and applied as the native engine applies them.
|
|
24
|
+
* @param {number} [options.recognitionWorkers]
|
|
25
|
+
* @param {number} [options.synthesisWorkers]
|
|
26
|
+
*/
|
|
27
|
+
function createStandInSpeechEngine({
|
|
28
|
+
recognizedText = "Hello world",
|
|
29
|
+
voices = [{ id: "stand-in", label: "Stand-in voice", language: "en" }],
|
|
30
|
+
defaultVoice = voices[0]?.id || "",
|
|
31
|
+
sampleRate = 22_050,
|
|
32
|
+
synthesisMs = 0,
|
|
33
|
+
hotwords = [],
|
|
34
|
+
spellings = {},
|
|
35
|
+
recognitionWorkers = 1,
|
|
36
|
+
synthesisWorkers = 1
|
|
37
|
+
} = {}) {
|
|
38
|
+
let closed = false;
|
|
39
|
+
const addedHotwords = recognitionHotwords(hotwords);
|
|
40
|
+
const vocabulary = recognitionSpellings(spellings);
|
|
41
|
+
const heard = normalizeRecognizedText(recognizedText, vocabulary);
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* One recording, heard as the stand-in's text once any audio arrives.
|
|
45
|
+
* @param {{ onPartial?: (text: string) => void, onEndpoint?: (text: string) => void, continuous?: boolean }} [options]
|
|
46
|
+
*/
|
|
47
|
+
function createListeningSession({ onPartial = ignoreRecognizedText, onEndpoint = ignoreRecognizedText, continuous = false } = {}) {
|
|
48
|
+
let acceptedSamples = 0;
|
|
49
|
+
let ended = false;
|
|
50
|
+
function acceptPcm(frame) {
|
|
51
|
+
if (ended) return acceptedSamples ? heard : "";
|
|
52
|
+
const first = !acceptedSamples;
|
|
53
|
+
acceptedSamples += frame.byteLength / 2;
|
|
54
|
+
if (first) onPartial(heard);
|
|
55
|
+
if (continuous && first) onEndpoint(heard);
|
|
56
|
+
return heard;
|
|
57
|
+
}
|
|
58
|
+
function finish() {
|
|
59
|
+
ended = true;
|
|
60
|
+
return acceptedSamples ? heard : "";
|
|
61
|
+
}
|
|
62
|
+
function reset() {
|
|
63
|
+
const text = acceptedSamples ? heard : "";
|
|
64
|
+
acceptedSamples = 0;
|
|
65
|
+
return text;
|
|
66
|
+
}
|
|
67
|
+
function isEndpoint() {
|
|
68
|
+
return !ended && acceptedSamples > 0;
|
|
69
|
+
}
|
|
70
|
+
function cancel() {
|
|
71
|
+
ended = true;
|
|
72
|
+
}
|
|
73
|
+
return Object.freeze({
|
|
74
|
+
acceptPcm,
|
|
75
|
+
cancel,
|
|
76
|
+
finish,
|
|
77
|
+
isEndpoint,
|
|
78
|
+
reset,
|
|
79
|
+
get acceptedSamples() { return acceptedSamples; }
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function synthesize(text, { onAudio = () => null, signal = null, voiceId = defaultVoice } = {}) {
|
|
84
|
+
if (closed) throw new Error("Speech engine is closed.");
|
|
85
|
+
if (!voices.some(voice => voice.id === voiceId)) throw new Error("The selected voice is not available.");
|
|
86
|
+
if (synthesisMs > 0) await delay(synthesisMs, undefined, { signal }).catch(() => null);
|
|
87
|
+
if (signal?.aborted) return { cancelled: true, sampleRate, samples: 0 };
|
|
88
|
+
const words = String(text || "").trim().split(/\s+/u).filter(Boolean).length;
|
|
89
|
+
const samples = Math.round(words * sampleRate / 10);
|
|
90
|
+
if (samples) onAudio(Buffer.alloc(samples * 2));
|
|
91
|
+
return { cancelled: false, sampleRate, samples };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function warmup() {}
|
|
95
|
+
|
|
96
|
+
async function close() {
|
|
97
|
+
closed = true;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return Object.freeze({
|
|
101
|
+
concurrency: Object.freeze({ recognition: recognitionWorkers, synthesis: synthesisWorkers }),
|
|
102
|
+
createListeningSession,
|
|
103
|
+
defaultVoice,
|
|
104
|
+
recognitionModels: Object.freeze([Object.freeze({
|
|
105
|
+
id: "stand-in", hotwords: addedHotwords.length, spellings: recognitionSpellingCount(vocabulary)
|
|
106
|
+
})]),
|
|
107
|
+
sampleRate,
|
|
108
|
+
synthesize,
|
|
109
|
+
versions: Object.freeze({ "@jskit-ai/assistant-voice/stand-in": PACKAGE_VERSION }),
|
|
110
|
+
voices: Object.freeze(voices.map(voice => Object.freeze({ ...voice }))),
|
|
111
|
+
warmup,
|
|
112
|
+
close
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export { createStandInSpeechEngine };
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import { readFileSync, statSync } from "node:fs";
|
|
3
|
+
|
|
4
|
+
// The host writes this file; the voice service holds only each token's SHA-256.
|
|
5
|
+
const VOICE_CREDENTIALS_SCHEMA = "jskit.assistant-voice.credentials.v1";
|
|
6
|
+
const VOICE_CLIENT_PATTERN = /^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/u;
|
|
7
|
+
const SHA256_PATTERN = /^[a-f0-9]{64}$/u;
|
|
8
|
+
// RFC 6750's b64token, at least 32 characters, so a token is a real secret.
|
|
9
|
+
const VOICE_TOKEN_PATTERN = /^[A-Za-z0-9._~+/-]{32,1024}=*$/u;
|
|
10
|
+
const MAXIMUM_CLIENTS = 10_000;
|
|
11
|
+
const MAXIMUM_TOKENS_PER_CLIENT = 8;
|
|
12
|
+
const MAXIMUM_CREDENTIALS_BYTES = 4 * 1024 * 1024;
|
|
13
|
+
const CLIENT_FIELDS = new Set(["tokenSha256", "maximumConnections"]);
|
|
14
|
+
|
|
15
|
+
function credentialsError(message) {
|
|
16
|
+
return Object.assign(new Error(`Voice credentials: ${message}`), { code: "voice_credentials_invalid" });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** A client token's SHA-256, as the credentials file lists it: lowercase hex of its UTF-8 bytes. */
|
|
20
|
+
function voiceTokenSha256(token = "") {
|
|
21
|
+
return crypto.createHash("sha256").update(String(token), "utf8").digest("hex");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** A new random client token (32 bytes, base64url). */
|
|
25
|
+
function createVoiceClientToken() {
|
|
26
|
+
return crypto.randomBytes(32).toString("base64url");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function isVoiceClientToken(token = "") {
|
|
30
|
+
return VOICE_TOKEN_PATTERN.test(String(token));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function bearerVoiceAccessToken(headers = {}) {
|
|
34
|
+
const value = String(headers.authorization || "").trim();
|
|
35
|
+
const match = /^Bearer\s+([^\s]+)$/iu.exec(value);
|
|
36
|
+
return match ? match[1] : "";
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Checks a credentials document and answers its clients by token hash.
|
|
41
|
+
* @param {unknown} document
|
|
42
|
+
* @returns {Map<string, { client: string, maximumConnections?: number }>} Each token hash's client.
|
|
43
|
+
*/
|
|
44
|
+
function parseVoiceCredentials(document) {
|
|
45
|
+
if (!document || typeof document !== "object" || Array.isArray(document)) throw credentialsError("the file must hold a JSON object.");
|
|
46
|
+
if (document.schema !== VOICE_CREDENTIALS_SCHEMA) throw credentialsError(`schema must be ${VOICE_CREDENTIALS_SCHEMA}.`);
|
|
47
|
+
const unknown = Object.keys(document).filter(key => !["schema", "clients"].includes(key));
|
|
48
|
+
if (unknown.length) throw credentialsError(`unknown field ${unknown[0]}.`);
|
|
49
|
+
const { clients } = document;
|
|
50
|
+
if (!clients || typeof clients !== "object" || Array.isArray(clients)) throw credentialsError("clients must be an object keyed by client name.");
|
|
51
|
+
const names = Object.keys(clients);
|
|
52
|
+
if (names.length > MAXIMUM_CLIENTS) throw credentialsError(`at most ${MAXIMUM_CLIENTS} clients.`);
|
|
53
|
+
const byHash = new Map();
|
|
54
|
+
for (const client of names) {
|
|
55
|
+
if (!VOICE_CLIENT_PATTERN.test(client)) throw credentialsError(`client name ${JSON.stringify(client.slice(0, 80))} must be 1 to 64 lowercase letters, digits, dots, dashes or underscores.`);
|
|
56
|
+
const entry = clients[client];
|
|
57
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) throw credentialsError(`client ${client} must be an object.`);
|
|
58
|
+
const extra = Object.keys(entry).find(key => !CLIENT_FIELDS.has(key));
|
|
59
|
+
if (extra) throw credentialsError(`client ${client} has an unknown field ${extra}.`);
|
|
60
|
+
const hashes = entry.tokenSha256;
|
|
61
|
+
if (!Array.isArray(hashes) || !hashes.length || hashes.length > MAXIMUM_TOKENS_PER_CLIENT) {
|
|
62
|
+
throw credentialsError(`client ${client} needs tokenSha256: 1 to ${MAXIMUM_TOKENS_PER_CLIENT} token hashes.`);
|
|
63
|
+
}
|
|
64
|
+
const { maximumConnections } = entry;
|
|
65
|
+
if (maximumConnections !== undefined && (!Number.isSafeInteger(maximumConnections) || maximumConnections < 1)) {
|
|
66
|
+
throw credentialsError(`client ${client}'s maximumConnections must be a positive whole number.`);
|
|
67
|
+
}
|
|
68
|
+
for (const hash of hashes) {
|
|
69
|
+
if (typeof hash !== "string" || !SHA256_PATTERN.test(hash)) throw credentialsError(`client ${client} has a token hash that is not 64 lowercase hex digits.`);
|
|
70
|
+
if (byHash.has(hash)) throw credentialsError(`a token hash is listed twice (client ${client}).`);
|
|
71
|
+
byHash.set(hash, Object.freeze({ client, ...(maximumConnections ? { maximumConnections } : {}) }));
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return byHash;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function fileIdentity(file) {
|
|
78
|
+
const metadata = statSync(file);
|
|
79
|
+
if (!metadata.isFile()) throw credentialsError(`${file} is not a file.`);
|
|
80
|
+
if (metadata.size > MAXIMUM_CREDENTIALS_BYTES) throw credentialsError("the file is larger than 4 MiB.");
|
|
81
|
+
return `${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeMs}:${metadata.ctimeMs}`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function readCredentialsFile(file) {
|
|
85
|
+
let bytes;
|
|
86
|
+
let document;
|
|
87
|
+
try {
|
|
88
|
+
bytes = readFileSync(file);
|
|
89
|
+
document = JSON.parse(bytes.toString("utf8"));
|
|
90
|
+
} catch (error) {
|
|
91
|
+
throw credentialsError(`${file} could not be read as JSON (${error?.code || error?.name}).`);
|
|
92
|
+
}
|
|
93
|
+
return Object.freeze({
|
|
94
|
+
byHash: parseVoiceCredentials(document),
|
|
95
|
+
sha256: crypto.createHash("sha256").update(bytes).digest("hex")
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const NO_CREDENTIALS = Object.freeze({ byHash: new Map(), sha256: null });
|
|
100
|
+
|
|
101
|
+
// Each client's tokens and limit, to tell which clients a reload added, removed or changed.
|
|
102
|
+
function clientTerms(byHash) {
|
|
103
|
+
const terms = new Map();
|
|
104
|
+
for (const [hash, { client, maximumConnections }] of byHash) {
|
|
105
|
+
const entry = terms.get(client) || { hashes: [], maximumConnections };
|
|
106
|
+
entry.hashes.push(hash);
|
|
107
|
+
terms.set(client, entry);
|
|
108
|
+
}
|
|
109
|
+
return new Map([...terms].map(([client, { hashes, maximumConnections }]) => [client, `${hashes.sort().join(",")}/${maximumConnections ?? ""}`]));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* What a reload changed: the clients it added, removed or changed (tokens or limit).
|
|
114
|
+
* @returns {{ clients: number, clientsAdded: string[], clientsRemoved: string[], clientsChanged: string[] }}
|
|
115
|
+
*/
|
|
116
|
+
function credentialChanges(previous, next) {
|
|
117
|
+
const before = clientTerms(previous.byHash);
|
|
118
|
+
const after = clientTerms(next.byHash);
|
|
119
|
+
return {
|
|
120
|
+
clients: after.size,
|
|
121
|
+
clientsAdded: [...after.keys()].filter(client => !before.has(client)).sort(),
|
|
122
|
+
clientsRemoved: [...before.keys()].filter(client => !after.has(client)).sort(),
|
|
123
|
+
clientsChanged: [...after].filter(([client, terms]) => before.has(client) && before.get(client) !== terms).map(([client]) => client).sort()
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* The credentials a voice service accepts, read from the host's file and read
|
|
129
|
+
* again whenever the file changes. A file that becomes invalid keeps the last
|
|
130
|
+
* valid credentials and is reported; a file that disappears accepts no one.
|
|
131
|
+
* @param {object} options
|
|
132
|
+
* @param {string} options.file
|
|
133
|
+
* @param {number} [options.pollIntervalMs]
|
|
134
|
+
* @param {(reason: string) => void} options.onRefused Called when a changed file cannot be used.
|
|
135
|
+
* @param {(changes: ReturnType<typeof credentialChanges>) => void} options.onChange Called once the accepted credentials changed, at start too.
|
|
136
|
+
*/
|
|
137
|
+
function createVoiceCredentialStore({ file, pollIntervalMs = 1000, onRefused, onChange }) {
|
|
138
|
+
const path = String(file || "").trim();
|
|
139
|
+
if (!path) throw new TypeError("A voice service needs its credentials file.");
|
|
140
|
+
let current = NO_CREDENTIALS;
|
|
141
|
+
let identity = "";
|
|
142
|
+
let timer = null;
|
|
143
|
+
|
|
144
|
+
function apply(next) {
|
|
145
|
+
const previous = current;
|
|
146
|
+
current = next;
|
|
147
|
+
onChange(credentialChanges(previous, next));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function poll() {
|
|
151
|
+
let next;
|
|
152
|
+
try {
|
|
153
|
+
next = fileIdentity(path);
|
|
154
|
+
} catch (error) {
|
|
155
|
+
if (error?.code !== "ENOENT") {
|
|
156
|
+
if (identity !== "unreadable") onRefused(error.message);
|
|
157
|
+
identity = "unreadable";
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
if (identity === "missing") return;
|
|
161
|
+
identity = "missing";
|
|
162
|
+
apply(NO_CREDENTIALS);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
if (next === identity) return;
|
|
166
|
+
identity = next;
|
|
167
|
+
let credentials;
|
|
168
|
+
try {
|
|
169
|
+
credentials = readCredentialsFile(path);
|
|
170
|
+
} catch (error) {
|
|
171
|
+
onRefused(error.message);
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
apply(credentials);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function start() {
|
|
178
|
+
identity = fileIdentity(path);
|
|
179
|
+
apply(readCredentialsFile(path));
|
|
180
|
+
timer = setInterval(poll, pollIntervalMs);
|
|
181
|
+
timer.unref();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function stop() {
|
|
185
|
+
clearInterval(timer);
|
|
186
|
+
timer = null;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** The client a bearer token names, with the token's hash, or null. */
|
|
190
|
+
function principalFor(token = "") {
|
|
191
|
+
if (!isVoiceClientToken(token)) return null;
|
|
192
|
+
const tokenSha256 = voiceTokenSha256(token);
|
|
193
|
+
const credential = current.byHash.get(tokenSha256);
|
|
194
|
+
return credential ? { ...credential, tokenSha256 } : null;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Whether a token hash still names the same client. */
|
|
198
|
+
function accepts(tokenSha256, client) {
|
|
199
|
+
return current.byHash.get(tokenSha256)?.client === client;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
return Object.freeze({
|
|
203
|
+
accepts,
|
|
204
|
+
principalFor,
|
|
205
|
+
start,
|
|
206
|
+
stop,
|
|
207
|
+
/** The SHA-256 of the file bytes in use, or null when the file is missing. */
|
|
208
|
+
get sha256() { return current.sha256; }
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export {
|
|
213
|
+
VOICE_CREDENTIALS_SCHEMA,
|
|
214
|
+
bearerVoiceAccessToken,
|
|
215
|
+
createVoiceClientToken,
|
|
216
|
+
createVoiceCredentialStore,
|
|
217
|
+
isVoiceClientToken,
|
|
218
|
+
parseVoiceCredentials,
|
|
219
|
+
voiceTokenSha256
|
|
220
|
+
};
|