rystem.playframework.client 0.1.2 → 0.1.4
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 +380 -1666
- package/lib/engine/PlayFrameworkClient.d.ts +19 -0
- package/lib/engine/PlayFrameworkClient.d.ts.map +1 -1
- package/lib/engine/PlayFrameworkClient.js +95 -7
- package/lib/index.d.ts +9 -0
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +9 -1
- package/lib/models/PlayFrameworkRequest.d.ts +10 -0
- package/lib/models/PlayFrameworkRequest.d.ts.map +1 -1
- package/lib/models/VoiceResponse.d.ts +39 -0
- package/lib/models/VoiceResponse.d.ts.map +1 -0
- package/lib/models/VoiceResponse.js +2 -0
- package/lib/utils/BrowserSpeechRecognizer.d.ts +128 -0
- package/lib/utils/BrowserSpeechRecognizer.d.ts.map +1 -0
- package/lib/utils/BrowserSpeechRecognizer.js +150 -0
- package/lib/utils/BrowserSpeechSynthesizer.d.ts +148 -0
- package/lib/utils/BrowserSpeechSynthesizer.d.ts.map +1 -0
- package/lib/utils/BrowserSpeechSynthesizer.js +400 -0
- package/lib/utils/BrowserVoiceClient.d.ts +142 -0
- package/lib/utils/BrowserVoiceClient.d.ts.map +1 -0
- package/lib/utils/BrowserVoiceClient.js +200 -0
- package/lib/utils/VoiceRecorder.d.ts +90 -0
- package/lib/utils/VoiceRecorder.d.ts.map +1 -0
- package/lib/utils/VoiceRecorder.js +195 -0
- package/package.json +1 -1
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { PlayFrameworkClient } from "../engine/PlayFrameworkClient";
|
|
2
|
+
import { AiSceneResponse } from "../models/AiSceneResponse";
|
|
3
|
+
import { PlayFrameworkRequest } from "../models/PlayFrameworkRequest";
|
|
4
|
+
import { BrowserSpeechRecognizer, BrowserSpeechRecognizerOptions } from "./BrowserSpeechRecognizer";
|
|
5
|
+
import { BrowserSpeechSynthesizer, BrowserSpeechSynthesizerOptions, BrowserSpeechSynthesizerCallbacks } from "./BrowserSpeechSynthesizer";
|
|
6
|
+
/**
|
|
7
|
+
* Streaming mode used for the text/LLM interaction.
|
|
8
|
+
*/
|
|
9
|
+
export type BrowserVoiceStreamingMode = 'stepByStep' | 'tokenStreaming';
|
|
10
|
+
/**
|
|
11
|
+
* Options for executeWithBrowserVoice.
|
|
12
|
+
*/
|
|
13
|
+
export interface BrowserVoiceOptions {
|
|
14
|
+
/**
|
|
15
|
+
* If provided, skip speech recognition and use this text directly as the user message.
|
|
16
|
+
* Useful when the caller already has the transcript (e.g. from an external recognizer).
|
|
17
|
+
*/
|
|
18
|
+
text?: string;
|
|
19
|
+
/**
|
|
20
|
+
* Streaming mode for the LLM interaction.
|
|
21
|
+
* - `'stepByStep'` — yields complete step responses (planning, actor actions, final message).
|
|
22
|
+
* - `'tokenStreaming'` — yields individual text tokens as they arrive.
|
|
23
|
+
* Default: `'stepByStep'`.
|
|
24
|
+
*/
|
|
25
|
+
streamingMode?: BrowserVoiceStreamingMode;
|
|
26
|
+
/**
|
|
27
|
+
* Base PlayFramework request properties (settings, metadata, conversationKey, etc.).
|
|
28
|
+
* The `message` field will be overwritten by the recognised speech text.
|
|
29
|
+
*/
|
|
30
|
+
request?: Partial<PlayFrameworkRequest>;
|
|
31
|
+
/** Timeout in ms for speech recognition (default: 15000). */
|
|
32
|
+
recognitionTimeoutMs?: number;
|
|
33
|
+
/** AbortSignal to cancel the entire voice flow. */
|
|
34
|
+
signal?: AbortSignal;
|
|
35
|
+
/**
|
|
36
|
+
* If `true`, the browser TTS will speak the LLM response as it arrives.
|
|
37
|
+
* Default: `true`.
|
|
38
|
+
*/
|
|
39
|
+
speakResponse?: boolean;
|
|
40
|
+
/**
|
|
41
|
+
* If `false`, disables the server-side voice-style system instruction
|
|
42
|
+
* that tells the LLM to respond conversationally (no tables, no markdown).
|
|
43
|
+
* Useful when you want voice I/O but still want rich formatted responses.
|
|
44
|
+
* Default: `true`.
|
|
45
|
+
*/
|
|
46
|
+
useVoiceStyle?: boolean;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Extra status information reported alongside `AiSceneResponse` events.
|
|
50
|
+
*/
|
|
51
|
+
export type BrowserVoiceStatus = 'recognizing' | 'recognized' | 'speaking' | 'speechComplete';
|
|
52
|
+
/**
|
|
53
|
+
* Event emitted by BrowserVoiceClient.executeWithBrowserVoice.
|
|
54
|
+
*/
|
|
55
|
+
export interface BrowserVoiceEvent {
|
|
56
|
+
/** The original AiSceneResponse from PlayFramework (null for voice-only status events). */
|
|
57
|
+
response: AiSceneResponse | null;
|
|
58
|
+
/** Voice pipeline status. */
|
|
59
|
+
voiceStatus?: BrowserVoiceStatus;
|
|
60
|
+
/** Recognised speech text (set when voiceStatus === 'recognized'). */
|
|
61
|
+
transcript?: string;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Orchestrates browser-native voice I/O with the PlayFrameworkClient.
|
|
65
|
+
*
|
|
66
|
+
* Flow:
|
|
67
|
+
* 1. **STT** — `BrowserSpeechRecognizer` captures user speech → text.
|
|
68
|
+
* 2. **LLM** — Text is sent to PlayFramework via step-by-step or token streaming.
|
|
69
|
+
* 3. **TTS** — `BrowserSpeechSynthesizer` speaks the LLM response in real-time.
|
|
70
|
+
*
|
|
71
|
+
* This gives a fully client-side voice experience (no server-side Whisper / TTS-1 needed).
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* ```ts
|
|
75
|
+
* const client = new PlayFrameworkClient(settings);
|
|
76
|
+
* const voice = new BrowserVoiceClient(client, { lang: 'it-IT' });
|
|
77
|
+
*
|
|
78
|
+
* for await (const event of voice.executeWithBrowserVoice()) {
|
|
79
|
+
* if (event.voiceStatus === 'recognized') {
|
|
80
|
+
* console.log('User said:', event.transcript);
|
|
81
|
+
* }
|
|
82
|
+
* if (event.response?.message) {
|
|
83
|
+
* console.log('AI:', event.response.message);
|
|
84
|
+
* }
|
|
85
|
+
* }
|
|
86
|
+
* ```
|
|
87
|
+
*/
|
|
88
|
+
export declare class BrowserVoiceClient {
|
|
89
|
+
private readonly client;
|
|
90
|
+
private readonly recognizer;
|
|
91
|
+
private readonly synthesizer;
|
|
92
|
+
/**
|
|
93
|
+
* Internal AbortController created for each `executeWithBrowserVoice()` invocation.
|
|
94
|
+
* Used by `cancelStream()` and `cancelAll()` to programmatically abort the HTTP/SSE stream.
|
|
95
|
+
* Set to `null` when no voice flow is in progress.
|
|
96
|
+
*/
|
|
97
|
+
private currentAbortController;
|
|
98
|
+
constructor(client: PlayFrameworkClient, recognizerOptions?: BrowserSpeechRecognizerOptions, synthesizerOptions?: BrowserSpeechSynthesizerOptions, synthesizerCallbacks?: BrowserSpeechSynthesizerCallbacks);
|
|
99
|
+
/** Returns `true` if the browser supports both Speech Recognition and Speech Synthesis. */
|
|
100
|
+
static isSupported(): boolean;
|
|
101
|
+
/** Access the underlying recognizer for advanced configuration. */
|
|
102
|
+
getRecognizer(): BrowserSpeechRecognizer;
|
|
103
|
+
/** Access the underlying synthesizer for advanced configuration. */
|
|
104
|
+
getSynthesizer(): BrowserSpeechSynthesizer;
|
|
105
|
+
/**
|
|
106
|
+
* Execute a complete voice interaction:
|
|
107
|
+
* Speech → Text → PlayFramework (streaming) → Text → Speech
|
|
108
|
+
*
|
|
109
|
+
* Yields `BrowserVoiceEvent` objects with both voice status and LLM responses.
|
|
110
|
+
*/
|
|
111
|
+
executeWithBrowserVoice(options?: BrowserVoiceOptions): AsyncIterableIterator<BrowserVoiceEvent>;
|
|
112
|
+
/**
|
|
113
|
+
* Execute a voice interaction using only browser TTS (no STT).
|
|
114
|
+
* Sends the provided text via PlayFramework and speaks the response.
|
|
115
|
+
*
|
|
116
|
+
* Shorthand for `executeWithBrowserVoice({ text, speakResponse: true, ... })`.
|
|
117
|
+
*/
|
|
118
|
+
speakResponse(text: string, streamingMode?: BrowserVoiceStreamingMode, request?: Partial<PlayFrameworkRequest>, signal?: AbortSignal): AsyncIterableIterator<BrowserVoiceEvent>;
|
|
119
|
+
/**
|
|
120
|
+
* Cancel only the audio (TTS). The HTTP/SSE text stream continues
|
|
121
|
+
* so you can still read the LLM response in your `for await` loop.
|
|
122
|
+
*/
|
|
123
|
+
cancelSpeech(): void;
|
|
124
|
+
/** Stop recognition if active. */
|
|
125
|
+
stopRecognition(): void;
|
|
126
|
+
/**
|
|
127
|
+
* Cancel the HTTP/SSE stream (abort the API call).
|
|
128
|
+
* The .NET server receives a cancelled `CancellationToken` and stops processing.
|
|
129
|
+
* TTS is also cancelled since no more text will arrive.
|
|
130
|
+
*/
|
|
131
|
+
cancelStream(): void;
|
|
132
|
+
/**
|
|
133
|
+
* Cancel everything: recognition + HTTP stream + audio.
|
|
134
|
+
* Equivalent to calling `stopRecognition()`, `cancelStream()`, and `cancelSpeech()` together.
|
|
135
|
+
*/
|
|
136
|
+
cancelAll(): void;
|
|
137
|
+
/**
|
|
138
|
+
* Whether a voice flow is currently in progress (stream is active).
|
|
139
|
+
*/
|
|
140
|
+
get isStreaming(): boolean;
|
|
141
|
+
}
|
|
142
|
+
//# sourceMappingURL=BrowserVoiceClient.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BrowserVoiceClient.d.ts","sourceRoot":"","sources":["../../src/utils/BrowserVoiceClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACpE,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAAE,uBAAuB,EAAE,8BAA8B,EAAE,MAAM,2BAA2B,CAAC;AACpG,OAAO,EAAE,wBAAwB,EAAE,+BAA+B,EAAE,iCAAiC,EAAE,MAAM,4BAA4B,CAAC;AAE1I;;GAEG;AACH,MAAM,MAAM,yBAAyB,GAAG,YAAY,GAAG,gBAAgB,CAAC;AAExE;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAChC;;;OAGG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IAEd;;;;;OAKG;IACH,aAAa,CAAC,EAAE,yBAAyB,CAAC;IAE1C;;;OAGG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC;IAExC,6DAA6D;IAC7D,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAE9B,mDAAmD;IACnD,MAAM,CAAC,EAAE,WAAW,CAAC;IAErB;;;OAGG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IAExB;;;;;OAKG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED;;GAEG;AACH,MAAM,MAAM,kBAAkB,GACxB,aAAa,GACb,YAAY,GACZ,UAAU,GACV,gBAAgB,CAAC;AAEvB;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAC9B,2FAA2F;IAC3F,QAAQ,EAAE,eAAe,GAAG,IAAI,CAAC;IAEjC,6BAA6B;IAC7B,WAAW,CAAC,EAAE,kBAAkB,CAAC;IAEjC,sEAAsE;IACtE,UAAU,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,qBAAa,kBAAkB;IAC3B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAsB;IAC7C,OAAO,CAAC,QAAQ,CAAC,UAAU,CAA0B;IACrD,OAAO,CAAC,QAAQ,CAAC,WAAW,CAA2B;IAEvD;;;;OAIG;IACH,OAAO,CAAC,sBAAsB,CAAgC;gBAG1D,MAAM,EAAE,mBAAmB,EAC3B,iBAAiB,CAAC,EAAE,8BAA8B,EAClD,kBAAkB,CAAC,EAAE,+BAA+B,EACpD,oBAAoB,CAAC,EAAE,iCAAiC;IAO5D,2FAA2F;IAC3F,MAAM,CAAC,WAAW,IAAI,OAAO;IAI7B,mEAAmE;IACnE,aAAa,IAAI,uBAAuB;IAIxC,oEAAoE;IACpE,cAAc,IAAI,wBAAwB;IAI1C;;;;;OAKG;IACI,uBAAuB,CAC1B,OAAO,CAAC,EAAE,mBAAmB,GAC9B,qBAAqB,CAAC,iBAAiB,CAAC;IAuG3C;;;;;OAKG;IACI,aAAa,CAChB,IAAI,EAAE,MAAM,EACZ,aAAa,GAAE,yBAAwC,EACvD,OAAO,CAAC,EAAE,OAAO,CAAC,oBAAoB,CAAC,EACvC,MAAM,CAAC,EAAE,WAAW,GACrB,qBAAqB,CAAC,iBAAiB,CAAC;IAU3C;;;OAGG;IACH,YAAY,IAAI,IAAI;IAIpB,kCAAkC;IAClC,eAAe,IAAI,IAAI;IAIvB;;;;OAIG;IACH,YAAY,IAAI,IAAI;IAOpB;;;OAGG;IACH,SAAS,IAAI,IAAI;IAKjB;;OAEG;IACH,IAAI,WAAW,IAAI,OAAO,CAEzB;CACJ"}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.BrowserVoiceClient = void 0;
|
|
4
|
+
const BrowserSpeechRecognizer_1 = require("./BrowserSpeechRecognizer");
|
|
5
|
+
const BrowserSpeechSynthesizer_1 = require("./BrowserSpeechSynthesizer");
|
|
6
|
+
/**
|
|
7
|
+
* Orchestrates browser-native voice I/O with the PlayFrameworkClient.
|
|
8
|
+
*
|
|
9
|
+
* Flow:
|
|
10
|
+
* 1. **STT** — `BrowserSpeechRecognizer` captures user speech → text.
|
|
11
|
+
* 2. **LLM** — Text is sent to PlayFramework via step-by-step or token streaming.
|
|
12
|
+
* 3. **TTS** — `BrowserSpeechSynthesizer` speaks the LLM response in real-time.
|
|
13
|
+
*
|
|
14
|
+
* This gives a fully client-side voice experience (no server-side Whisper / TTS-1 needed).
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```ts
|
|
18
|
+
* const client = new PlayFrameworkClient(settings);
|
|
19
|
+
* const voice = new BrowserVoiceClient(client, { lang: 'it-IT' });
|
|
20
|
+
*
|
|
21
|
+
* for await (const event of voice.executeWithBrowserVoice()) {
|
|
22
|
+
* if (event.voiceStatus === 'recognized') {
|
|
23
|
+
* console.log('User said:', event.transcript);
|
|
24
|
+
* }
|
|
25
|
+
* if (event.response?.message) {
|
|
26
|
+
* console.log('AI:', event.response.message);
|
|
27
|
+
* }
|
|
28
|
+
* }
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
class BrowserVoiceClient {
|
|
32
|
+
client;
|
|
33
|
+
recognizer;
|
|
34
|
+
synthesizer;
|
|
35
|
+
/**
|
|
36
|
+
* Internal AbortController created for each `executeWithBrowserVoice()` invocation.
|
|
37
|
+
* Used by `cancelStream()` and `cancelAll()` to programmatically abort the HTTP/SSE stream.
|
|
38
|
+
* Set to `null` when no voice flow is in progress.
|
|
39
|
+
*/
|
|
40
|
+
currentAbortController = null;
|
|
41
|
+
constructor(client, recognizerOptions, synthesizerOptions, synthesizerCallbacks) {
|
|
42
|
+
this.client = client;
|
|
43
|
+
this.recognizer = new BrowserSpeechRecognizer_1.BrowserSpeechRecognizer(recognizerOptions);
|
|
44
|
+
this.synthesizer = new BrowserSpeechSynthesizer_1.BrowserSpeechSynthesizer(synthesizerOptions, synthesizerCallbacks);
|
|
45
|
+
}
|
|
46
|
+
/** Returns `true` if the browser supports both Speech Recognition and Speech Synthesis. */
|
|
47
|
+
static isSupported() {
|
|
48
|
+
return BrowserSpeechRecognizer_1.BrowserSpeechRecognizer.isSupported() && BrowserSpeechSynthesizer_1.BrowserSpeechSynthesizer.isSupported();
|
|
49
|
+
}
|
|
50
|
+
/** Access the underlying recognizer for advanced configuration. */
|
|
51
|
+
getRecognizer() {
|
|
52
|
+
return this.recognizer;
|
|
53
|
+
}
|
|
54
|
+
/** Access the underlying synthesizer for advanced configuration. */
|
|
55
|
+
getSynthesizer() {
|
|
56
|
+
return this.synthesizer;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Execute a complete voice interaction:
|
|
60
|
+
* Speech → Text → PlayFramework (streaming) → Text → Speech
|
|
61
|
+
*
|
|
62
|
+
* Yields `BrowserVoiceEvent` objects with both voice status and LLM responses.
|
|
63
|
+
*/
|
|
64
|
+
async *executeWithBrowserVoice(options) {
|
|
65
|
+
const { text, streamingMode = 'stepByStep', request = {}, recognitionTimeoutMs = 15000, signal, speakResponse = true, useVoiceStyle = true, } = options ?? {};
|
|
66
|
+
// ── 0. Create internal AbortController for this invocation ─────
|
|
67
|
+
// Links to the user-provided signal so external abort propagates.
|
|
68
|
+
const controller = new AbortController();
|
|
69
|
+
this.currentAbortController = controller;
|
|
70
|
+
if (signal) {
|
|
71
|
+
if (signal.aborted) {
|
|
72
|
+
controller.abort(signal.reason);
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
signal.addEventListener('abort', () => controller.abort(signal.reason), { once: true });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const effectiveSignal = controller.signal;
|
|
79
|
+
try {
|
|
80
|
+
// ── 1. Speech Recognition (if no text provided) ────────────────
|
|
81
|
+
let transcript;
|
|
82
|
+
if (text != null) {
|
|
83
|
+
transcript = text;
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
yield { response: null, voiceStatus: 'recognizing' };
|
|
87
|
+
try {
|
|
88
|
+
transcript = await this.recognizer.listen(recognitionTimeoutMs);
|
|
89
|
+
}
|
|
90
|
+
catch (err) {
|
|
91
|
+
throw new Error(`Speech recognition failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
92
|
+
}
|
|
93
|
+
if (!transcript.trim()) {
|
|
94
|
+
// No speech detected
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
yield { response: null, voiceStatus: 'recognized', transcript };
|
|
99
|
+
// ── 2. Send text to PlayFramework via streaming ────────────────
|
|
100
|
+
const fullRequest = {
|
|
101
|
+
...request,
|
|
102
|
+
message: transcript,
|
|
103
|
+
settings: {
|
|
104
|
+
...request.settings,
|
|
105
|
+
isVoiceMode: useVoiceStyle,
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
const stream = streamingMode === 'tokenStreaming'
|
|
109
|
+
? this.client.executeTokenStreaming(fullRequest, effectiveSignal)
|
|
110
|
+
: this.client.executeStepByStep(fullRequest, effectiveSignal);
|
|
111
|
+
// ── 3. Stream responses and optionally speak them ──────────────
|
|
112
|
+
for await (const response of stream) {
|
|
113
|
+
// Forward the raw LLM event
|
|
114
|
+
yield { response };
|
|
115
|
+
if (!speakResponse)
|
|
116
|
+
continue;
|
|
117
|
+
// For token streaming, feed chunks incrementally
|
|
118
|
+
if (streamingMode === 'tokenStreaming' && response.streamingChunk) {
|
|
119
|
+
this.synthesizer.feedChunk(response.streamingChunk);
|
|
120
|
+
}
|
|
121
|
+
// For step-by-step, speak complete messages
|
|
122
|
+
if (streamingMode === 'stepByStep' && response.message) {
|
|
123
|
+
// Speak any status that carries meaningful text; skip system/noise statuses
|
|
124
|
+
const nonSpeakableStatuses = [
|
|
125
|
+
'initializing', 'loadingCache', 'savingCache', 'savingMemory',
|
|
126
|
+
'executingMainActors', 'executingScene', 'planning',
|
|
127
|
+
'functionRequest', 'functionCompleted', 'toolSkipped',
|
|
128
|
+
'awaitingClient', 'commandClient',
|
|
129
|
+
'directorDecision', 'summarizing', 'generatingFinalResponse',
|
|
130
|
+
'error', 'budgetExceeded', 'unauthorized',
|
|
131
|
+
];
|
|
132
|
+
if (!nonSpeakableStatuses.includes(response.status)) {
|
|
133
|
+
this.synthesizer.feedChunk(response.message);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
// ── 4. Flush remaining buffered text and wait for TTS to finish ─
|
|
138
|
+
if (speakResponse) {
|
|
139
|
+
yield { response: null, voiceStatus: 'speaking' };
|
|
140
|
+
await this.synthesizer.flushAndWait();
|
|
141
|
+
yield { response: null, voiceStatus: 'speechComplete' };
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
finally {
|
|
145
|
+
this.currentAbortController = null;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Execute a voice interaction using only browser TTS (no STT).
|
|
150
|
+
* Sends the provided text via PlayFramework and speaks the response.
|
|
151
|
+
*
|
|
152
|
+
* Shorthand for `executeWithBrowserVoice({ text, speakResponse: true, ... })`.
|
|
153
|
+
*/
|
|
154
|
+
async *speakResponse(text, streamingMode = 'stepByStep', request, signal) {
|
|
155
|
+
yield* this.executeWithBrowserVoice({
|
|
156
|
+
text,
|
|
157
|
+
streamingMode,
|
|
158
|
+
request,
|
|
159
|
+
signal,
|
|
160
|
+
speakResponse: true,
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Cancel only the audio (TTS). The HTTP/SSE text stream continues
|
|
165
|
+
* so you can still read the LLM response in your `for await` loop.
|
|
166
|
+
*/
|
|
167
|
+
cancelSpeech() {
|
|
168
|
+
this.synthesizer.cancel();
|
|
169
|
+
}
|
|
170
|
+
/** Stop recognition if active. */
|
|
171
|
+
stopRecognition() {
|
|
172
|
+
this.recognizer.stop();
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Cancel the HTTP/SSE stream (abort the API call).
|
|
176
|
+
* The .NET server receives a cancelled `CancellationToken` and stops processing.
|
|
177
|
+
* TTS is also cancelled since no more text will arrive.
|
|
178
|
+
*/
|
|
179
|
+
cancelStream() {
|
|
180
|
+
if (this.currentAbortController) {
|
|
181
|
+
this.currentAbortController.abort(new DOMException('The voice stream was cancelled', 'AbortError'));
|
|
182
|
+
}
|
|
183
|
+
this.synthesizer.cancel();
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Cancel everything: recognition + HTTP stream + audio.
|
|
187
|
+
* Equivalent to calling `stopRecognition()`, `cancelStream()`, and `cancelSpeech()` together.
|
|
188
|
+
*/
|
|
189
|
+
cancelAll() {
|
|
190
|
+
this.recognizer.abort();
|
|
191
|
+
this.cancelStream();
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Whether a voice flow is currently in progress (stream is active).
|
|
195
|
+
*/
|
|
196
|
+
get isStreaming() {
|
|
197
|
+
return this.currentAbortController !== null;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
exports.BrowserVoiceClient = BrowserVoiceClient;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Recording mode for VoiceRecorder.
|
|
3
|
+
* - `vad` — Voice Activity Detection: automatically stops when silence is detected.
|
|
4
|
+
* - `pushToTalk` — Press once to start, press again to stop & send.
|
|
5
|
+
* - `holdToTalk` — Hold button to record, release to stop & send.
|
|
6
|
+
*/
|
|
7
|
+
export type VoiceRecordingMode = 'vad' | 'pushToTalk' | 'holdToTalk';
|
|
8
|
+
/**
|
|
9
|
+
* Options for VoiceRecorder.
|
|
10
|
+
*/
|
|
11
|
+
export interface VoiceRecorderOptions {
|
|
12
|
+
/** Recording mode. Default: `'vad'`. */
|
|
13
|
+
mode?: VoiceRecordingMode;
|
|
14
|
+
/** Audio MIME type. Default: `'audio/webm'`. */
|
|
15
|
+
mimeType?: string;
|
|
16
|
+
/** Maximum recording duration in ms (safety cap). Default: `30000` (30s). */
|
|
17
|
+
maxDurationMs?: number;
|
|
18
|
+
/** Silence threshold (0-1). Audio level below this is "silence". Default: `0.01`. */
|
|
19
|
+
silenceThreshold?: number;
|
|
20
|
+
/** How long (ms) silence must last before auto-stopping. Default: `1500`. */
|
|
21
|
+
silenceDurationMs?: number;
|
|
22
|
+
/** Minimum recording duration in ms before VAD can trigger a stop. Default: `500`. */
|
|
23
|
+
minRecordingMs?: number;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Callbacks emitted by VoiceRecorder.
|
|
27
|
+
*/
|
|
28
|
+
export interface VoiceRecorderCallbacks {
|
|
29
|
+
/** Called when recording starts. */
|
|
30
|
+
onStart?: () => void;
|
|
31
|
+
/** Called every second with the elapsed seconds. */
|
|
32
|
+
onTick?: (seconds: number) => void;
|
|
33
|
+
/** Called with the recorded audio Blob when recording ends successfully. */
|
|
34
|
+
onRecorded?: (blob: Blob) => void;
|
|
35
|
+
/** Called when an error occurs. */
|
|
36
|
+
onError?: (error: Error) => void;
|
|
37
|
+
/** Called when recording stops (success or error). Always fires. */
|
|
38
|
+
onStop?: () => void;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Cross-browser voice recorder with support for VAD, push-to-talk, and hold-to-talk modes.
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* ```ts
|
|
45
|
+
* const recorder = new VoiceRecorder({ mode: 'vad', silenceDurationMs: 2000 });
|
|
46
|
+
*
|
|
47
|
+
* // Start recording — in VAD mode it stops automatically on silence
|
|
48
|
+
* recorder.start({
|
|
49
|
+
* onStart: () => console.log('Recording...'),
|
|
50
|
+
* onTick: (s) => console.log(`${s}s`),
|
|
51
|
+
* onRecorded: (blob) => sendToServer(blob),
|
|
52
|
+
* onStop: () => console.log('Done'),
|
|
53
|
+
* });
|
|
54
|
+
*
|
|
55
|
+
* // For pushToTalk: call recorder.stop() when user presses the button again.
|
|
56
|
+
* // For holdToTalk: call recorder.stop() on pointerup / mouseup.
|
|
57
|
+
* ```
|
|
58
|
+
*/
|
|
59
|
+
export declare class VoiceRecorder {
|
|
60
|
+
private _options;
|
|
61
|
+
private _mediaRecorder;
|
|
62
|
+
private _stream;
|
|
63
|
+
private _audioContext;
|
|
64
|
+
private _analyser;
|
|
65
|
+
private _vadIntervalId;
|
|
66
|
+
private _tickIntervalId;
|
|
67
|
+
private _maxTimeoutId;
|
|
68
|
+
private _recording;
|
|
69
|
+
private _startTime;
|
|
70
|
+
private _callbacks;
|
|
71
|
+
constructor(options?: VoiceRecorderOptions);
|
|
72
|
+
/** Whether the recorder is currently active. */
|
|
73
|
+
get isRecording(): boolean;
|
|
74
|
+
/** Current recording mode. */
|
|
75
|
+
get mode(): VoiceRecordingMode;
|
|
76
|
+
set mode(value: VoiceRecordingMode);
|
|
77
|
+
/**
|
|
78
|
+
* Start recording. In `vad` mode the recording stops automatically on silence.
|
|
79
|
+
* In `pushToTalk` and `holdToTalk` you must call `stop()` manually.
|
|
80
|
+
*/
|
|
81
|
+
start(callbacks?: VoiceRecorderCallbacks): Promise<void>;
|
|
82
|
+
/**
|
|
83
|
+
* Stop recording manually. Required for `pushToTalk` and `holdToTalk`,
|
|
84
|
+
* also works for `vad` (e.g. user wants to stop early).
|
|
85
|
+
*/
|
|
86
|
+
stop(): void;
|
|
87
|
+
private _setupVAD;
|
|
88
|
+
private _cleanup;
|
|
89
|
+
}
|
|
90
|
+
//# sourceMappingURL=VoiceRecorder.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"VoiceRecorder.d.ts","sourceRoot":"","sources":["../../src/utils/VoiceRecorder.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,MAAM,kBAAkB,GAAG,KAAK,GAAG,YAAY,GAAG,YAAY,CAAC;AAErE;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACjC,wCAAwC;IACxC,IAAI,CAAC,EAAE,kBAAkB,CAAC;IAC1B,gDAAgD;IAChD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,6EAA6E;IAC7E,aAAa,CAAC,EAAE,MAAM,CAAC;IAGvB,qFAAqF;IACrF,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,6EAA6E;IAC7E,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,sFAAsF;IACtF,cAAc,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACnC,oCAAoC;IACpC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,oDAAoD;IACpD,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IACnC,4EAA4E;IAC5E,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,IAAI,CAAC;IAClC,mCAAmC;IACnC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,oEAAoE;IACpE,MAAM,CAAC,EAAE,MAAM,IAAI,CAAC;CACvB;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,aAAa;IACtB,OAAO,CAAC,QAAQ,CAAiC;IACjD,OAAO,CAAC,cAAc,CAA8B;IACpD,OAAO,CAAC,OAAO,CAA4B;IAC3C,OAAO,CAAC,aAAa,CAA6B;IAClD,OAAO,CAAC,SAAS,CAA6B;IAC9C,OAAO,CAAC,cAAc,CAA+C;IACrE,OAAO,CAAC,eAAe,CAA+C;IACtE,OAAO,CAAC,aAAa,CAA8C;IACnE,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,UAAU,CAA8B;gBAEpC,OAAO,CAAC,EAAE,oBAAoB;IAW1C,gDAAgD;IAChD,IAAI,WAAW,IAAI,OAAO,CAEzB;IAED,8BAA8B;IAC9B,IAAI,IAAI,IAAI,kBAAkB,CAE7B;IAED,IAAI,IAAI,CAAC,KAAK,EAAE,kBAAkB,EAGjC;IAED;;;OAGG;IACG,KAAK,CAAC,SAAS,CAAC,EAAE,sBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC;IA2D9D;;;OAGG;IACH,IAAI,IAAI,IAAI;IAcZ,OAAO,CAAC,SAAS;IA6CjB,OAAO,CAAC,QAAQ;CA0BnB"}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.VoiceRecorder = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Cross-browser voice recorder with support for VAD, push-to-talk, and hold-to-talk modes.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```ts
|
|
9
|
+
* const recorder = new VoiceRecorder({ mode: 'vad', silenceDurationMs: 2000 });
|
|
10
|
+
*
|
|
11
|
+
* // Start recording — in VAD mode it stops automatically on silence
|
|
12
|
+
* recorder.start({
|
|
13
|
+
* onStart: () => console.log('Recording...'),
|
|
14
|
+
* onTick: (s) => console.log(`${s}s`),
|
|
15
|
+
* onRecorded: (blob) => sendToServer(blob),
|
|
16
|
+
* onStop: () => console.log('Done'),
|
|
17
|
+
* });
|
|
18
|
+
*
|
|
19
|
+
* // For pushToTalk: call recorder.stop() when user presses the button again.
|
|
20
|
+
* // For holdToTalk: call recorder.stop() on pointerup / mouseup.
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
class VoiceRecorder {
|
|
24
|
+
_options;
|
|
25
|
+
_mediaRecorder = null;
|
|
26
|
+
_stream = null;
|
|
27
|
+
_audioContext = null;
|
|
28
|
+
_analyser = null;
|
|
29
|
+
_vadIntervalId = null;
|
|
30
|
+
_tickIntervalId = null;
|
|
31
|
+
_maxTimeoutId = null;
|
|
32
|
+
_recording = false;
|
|
33
|
+
_startTime = 0;
|
|
34
|
+
_callbacks = {};
|
|
35
|
+
constructor(options) {
|
|
36
|
+
this._options = {
|
|
37
|
+
mode: options?.mode ?? 'vad',
|
|
38
|
+
mimeType: options?.mimeType ?? 'audio/webm',
|
|
39
|
+
maxDurationMs: options?.maxDurationMs ?? 30_000,
|
|
40
|
+
silenceThreshold: options?.silenceThreshold ?? 0.01,
|
|
41
|
+
silenceDurationMs: options?.silenceDurationMs ?? 1500,
|
|
42
|
+
minRecordingMs: options?.minRecordingMs ?? 500,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/** Whether the recorder is currently active. */
|
|
46
|
+
get isRecording() {
|
|
47
|
+
return this._recording;
|
|
48
|
+
}
|
|
49
|
+
/** Current recording mode. */
|
|
50
|
+
get mode() {
|
|
51
|
+
return this._options.mode;
|
|
52
|
+
}
|
|
53
|
+
set mode(value) {
|
|
54
|
+
if (this._recording)
|
|
55
|
+
throw new Error('Cannot change mode while recording');
|
|
56
|
+
this._options.mode = value;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Start recording. In `vad` mode the recording stops automatically on silence.
|
|
60
|
+
* In `pushToTalk` and `holdToTalk` you must call `stop()` manually.
|
|
61
|
+
*/
|
|
62
|
+
async start(callbacks) {
|
|
63
|
+
if (this._recording)
|
|
64
|
+
return;
|
|
65
|
+
this._callbacks = callbacks ?? {};
|
|
66
|
+
this._recording = true;
|
|
67
|
+
this._startTime = Date.now();
|
|
68
|
+
try {
|
|
69
|
+
this._stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
|
70
|
+
const recorder = new MediaRecorder(this._stream, { mimeType: this._options.mimeType });
|
|
71
|
+
this._mediaRecorder = recorder;
|
|
72
|
+
const chunks = [];
|
|
73
|
+
recorder.ondataavailable = (e) => {
|
|
74
|
+
if (e.data.size > 0)
|
|
75
|
+
chunks.push(e.data);
|
|
76
|
+
};
|
|
77
|
+
recorder.onstop = () => {
|
|
78
|
+
const blob = new Blob(chunks, { type: this._options.mimeType });
|
|
79
|
+
this._cleanup();
|
|
80
|
+
this._callbacks.onRecorded?.(blob);
|
|
81
|
+
this._callbacks.onStop?.();
|
|
82
|
+
};
|
|
83
|
+
recorder.onerror = () => {
|
|
84
|
+
this._cleanup();
|
|
85
|
+
this._callbacks.onError?.(new Error('MediaRecorder error'));
|
|
86
|
+
this._callbacks.onStop?.();
|
|
87
|
+
};
|
|
88
|
+
recorder.start();
|
|
89
|
+
this._callbacks.onStart?.();
|
|
90
|
+
// Tick timer (1s intervals)
|
|
91
|
+
let seconds = 0;
|
|
92
|
+
this._tickIntervalId = setInterval(() => {
|
|
93
|
+
seconds++;
|
|
94
|
+
this._callbacks.onTick?.(seconds);
|
|
95
|
+
}, 1000);
|
|
96
|
+
// Max duration safety cap
|
|
97
|
+
this._maxTimeoutId = setTimeout(() => {
|
|
98
|
+
this.stop();
|
|
99
|
+
}, this._options.maxDurationMs);
|
|
100
|
+
// VAD: set up silence detection
|
|
101
|
+
if (this._options.mode === 'vad') {
|
|
102
|
+
this._setupVAD();
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
catch (err) {
|
|
106
|
+
this._recording = false;
|
|
107
|
+
this._cleanup();
|
|
108
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
109
|
+
this._callbacks.onError?.(error);
|
|
110
|
+
this._callbacks.onStop?.();
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Stop recording manually. Required for `pushToTalk` and `holdToTalk`,
|
|
115
|
+
* also works for `vad` (e.g. user wants to stop early).
|
|
116
|
+
*/
|
|
117
|
+
stop() {
|
|
118
|
+
if (!this._recording)
|
|
119
|
+
return;
|
|
120
|
+
this._recording = false;
|
|
121
|
+
if (this._mediaRecorder && this._mediaRecorder.state !== 'inactive') {
|
|
122
|
+
this._mediaRecorder.stop(); // triggers onstop -> onRecorded -> onStop
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
this._cleanup();
|
|
126
|
+
this._callbacks.onStop?.();
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
// ── Private ──────────────────────────────────────────────────────
|
|
130
|
+
_setupVAD() {
|
|
131
|
+
if (!this._stream)
|
|
132
|
+
return;
|
|
133
|
+
this._audioContext = new AudioContext();
|
|
134
|
+
const source = this._audioContext.createMediaStreamSource(this._stream);
|
|
135
|
+
this._analyser = this._audioContext.createAnalyser();
|
|
136
|
+
this._analyser.fftSize = 2048;
|
|
137
|
+
source.connect(this._analyser);
|
|
138
|
+
const dataArray = new Uint8Array(this._analyser.fftSize);
|
|
139
|
+
let silenceStart = null;
|
|
140
|
+
this._vadIntervalId = setInterval(() => {
|
|
141
|
+
if (!this._analyser || !this._recording)
|
|
142
|
+
return;
|
|
143
|
+
this._analyser.getByteTimeDomainData(dataArray);
|
|
144
|
+
// Compute RMS (root mean square) level
|
|
145
|
+
let sum = 0;
|
|
146
|
+
for (let i = 0; i < dataArray.length; i++) {
|
|
147
|
+
const normalized = (dataArray[i] - 128) / 128; // -1..1
|
|
148
|
+
sum += normalized * normalized;
|
|
149
|
+
}
|
|
150
|
+
const rms = Math.sqrt(sum / dataArray.length);
|
|
151
|
+
const elapsed = Date.now() - this._startTime;
|
|
152
|
+
if (rms < this._options.silenceThreshold) {
|
|
153
|
+
// Below threshold — start or continue silence timer
|
|
154
|
+
if (silenceStart === null) {
|
|
155
|
+
silenceStart = Date.now();
|
|
156
|
+
}
|
|
157
|
+
else if (elapsed >= this._options.minRecordingMs &&
|
|
158
|
+
Date.now() - silenceStart >= this._options.silenceDurationMs) {
|
|
159
|
+
// Enough silence after minimum recording time → stop
|
|
160
|
+
this.stop();
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
// Audio detected — reset silence timer
|
|
165
|
+
silenceStart = null;
|
|
166
|
+
}
|
|
167
|
+
}, 100); // Check every 100ms
|
|
168
|
+
}
|
|
169
|
+
_cleanup() {
|
|
170
|
+
this._recording = false;
|
|
171
|
+
if (this._vadIntervalId !== null) {
|
|
172
|
+
clearInterval(this._vadIntervalId);
|
|
173
|
+
this._vadIntervalId = null;
|
|
174
|
+
}
|
|
175
|
+
if (this._tickIntervalId !== null) {
|
|
176
|
+
clearInterval(this._tickIntervalId);
|
|
177
|
+
this._tickIntervalId = null;
|
|
178
|
+
}
|
|
179
|
+
if (this._maxTimeoutId !== null) {
|
|
180
|
+
clearTimeout(this._maxTimeoutId);
|
|
181
|
+
this._maxTimeoutId = null;
|
|
182
|
+
}
|
|
183
|
+
if (this._audioContext) {
|
|
184
|
+
this._audioContext.close().catch(() => { });
|
|
185
|
+
this._audioContext = null;
|
|
186
|
+
this._analyser = null;
|
|
187
|
+
}
|
|
188
|
+
if (this._stream) {
|
|
189
|
+
this._stream.getTracks().forEach(t => t.stop());
|
|
190
|
+
this._stream = null;
|
|
191
|
+
}
|
|
192
|
+
this._mediaRecorder = null;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
exports.VoiceRecorder = VoiceRecorder;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "rystem.playframework.client",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
4
4
|
"author": "Alessandro Rapiti <alessandro.rapiti44@gmail.com>",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"description": "TypeScript client for Rystem PlayFramework HTTP API with step-by-step and token-level streaming support.",
|