rystem.playframework.client 0.1.1 → 0.1.3
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 +1617 -47
- package/lib/engine/ClientInteractionRegistry.d.ts +48 -1
- package/lib/engine/ClientInteractionRegistry.d.ts.map +1 -1
- package/lib/engine/ClientInteractionRegistry.js +84 -13
- package/lib/engine/PlayFrameworkClient.d.ts +58 -0
- package/lib/engine/PlayFrameworkClient.d.ts.map +1 -1
- package/lib/engine/PlayFrameworkClient.js +271 -24
- package/lib/index.d.ts +17 -1
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +15 -1
- package/lib/models/AiSceneResponse.d.ts +2 -2
- package/lib/models/AiSceneResponse.d.ts.map +1 -1
- package/lib/models/ClientInteractionRequest.d.ts +15 -0
- package/lib/models/ClientInteractionRequest.d.ts.map +1 -1
- package/lib/models/CommandResult.d.ts +31 -0
- package/lib/models/CommandResult.d.ts.map +1 -0
- package/lib/models/CommandResult.js +18 -0
- package/lib/models/ExecutionState.d.ts +35 -0
- package/lib/models/ExecutionState.d.ts.map +1 -0
- package/lib/models/ExecutionState.js +2 -0
- package/lib/models/PlayFrameworkRequest.d.ts +10 -0
- package/lib/models/PlayFrameworkRequest.d.ts.map +1 -1
- package/lib/models/StoredConversation.d.ts +88 -0
- package/lib/models/StoredConversation.d.ts.map +1 -0
- package/lib/models/StoredConversation.js +17 -0
- package/lib/models/StoredMessage.d.ts +30 -0
- package/lib/models/StoredMessage.d.ts.map +1 -0
- package/lib/models/StoredMessage.js +2 -0
- 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/ContentUrlConverter.d.ts +62 -0
- package/lib/utils/ContentUrlConverter.d.ts.map +1 -0
- package/lib/utils/ContentUrlConverter.js +151 -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,400 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.BrowserSpeechSynthesizer = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Wraps the browser Web Speech API `SpeechSynthesis` for text-to-speech,
|
|
6
|
+
* with built-in sentence accumulation for streaming scenarios.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* const synth = new BrowserSpeechSynthesizer({ lang: 'it-IT', rate: 1.1 });
|
|
11
|
+
*
|
|
12
|
+
* // Simple usage
|
|
13
|
+
* await synth.speak("Ciao, come stai?");
|
|
14
|
+
*
|
|
15
|
+
* // Streaming usage — feed text chunks as they arrive
|
|
16
|
+
* synth.feedChunk("Ciao, ");
|
|
17
|
+
* synth.feedChunk("come stai? ");
|
|
18
|
+
* synth.feedChunk("Tutto bene.");
|
|
19
|
+
* synth.flush(); // speak any remaining text
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
class BrowserSpeechSynthesizer {
|
|
23
|
+
options;
|
|
24
|
+
callbacks = {};
|
|
25
|
+
buffer = '';
|
|
26
|
+
_isSpeaking = false;
|
|
27
|
+
/** Number of utterances currently in the browser's native speech queue. */
|
|
28
|
+
_pendingCount = 0;
|
|
29
|
+
resolvedVoice = null;
|
|
30
|
+
voiceResolved = false;
|
|
31
|
+
warmedUp = false;
|
|
32
|
+
/** Chrome keepalive: periodic pause/resume to prevent auto-pause after ~15s. */
|
|
33
|
+
keepAliveTimer = null;
|
|
34
|
+
constructor(options, callbacks) {
|
|
35
|
+
this.options = {
|
|
36
|
+
lang: options?.lang ?? '',
|
|
37
|
+
rate: options?.rate ?? 1,
|
|
38
|
+
pitch: options?.pitch ?? 1,
|
|
39
|
+
volume: options?.volume ?? 1,
|
|
40
|
+
voiceName: options?.voiceName ?? '',
|
|
41
|
+
sentenceDelimiters: options?.sentenceDelimiters ?? ['.', '!', '?', '\n'],
|
|
42
|
+
minCharsBeforeSpeak: options?.minCharsBeforeSpeak ?? 20,
|
|
43
|
+
preferLocalVoice: options?.preferLocalVoice ?? true,
|
|
44
|
+
};
|
|
45
|
+
if (callbacks)
|
|
46
|
+
this.callbacks = callbacks;
|
|
47
|
+
// Pre-load voices (Chrome loads them asynchronously)
|
|
48
|
+
if (BrowserSpeechSynthesizer.isSupported()) {
|
|
49
|
+
window.speechSynthesis.getVoices(); // trigger async load
|
|
50
|
+
window.speechSynthesis.addEventListener?.('voiceschanged', () => {
|
|
51
|
+
// Only re-resolve if we haven't successfully found a voice yet.
|
|
52
|
+
// Chrome fires this event multiple times as network voices load
|
|
53
|
+
// incrementally; if we already have a match, keep it stable to
|
|
54
|
+
// avoid language flipping mid-stream.
|
|
55
|
+
if (!this.resolvedVoice) {
|
|
56
|
+
this.voiceResolved = false;
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** Whether speech is currently being synthesized. */
|
|
62
|
+
get isSpeaking() {
|
|
63
|
+
return this._isSpeaking;
|
|
64
|
+
}
|
|
65
|
+
/** Returns `true` if the browser supports the Web Speech Synthesis API. */
|
|
66
|
+
static isSupported() {
|
|
67
|
+
return typeof window !== 'undefined' && 'speechSynthesis' in window;
|
|
68
|
+
}
|
|
69
|
+
/** Set event callbacks. */
|
|
70
|
+
setCallbacks(callbacks) {
|
|
71
|
+
this.callbacks = callbacks;
|
|
72
|
+
}
|
|
73
|
+
/** Update language at runtime. Resets the resolved voice cache. */
|
|
74
|
+
setLang(lang) {
|
|
75
|
+
this.options.lang = lang;
|
|
76
|
+
this.voiceResolved = false;
|
|
77
|
+
this.resolvedVoice = null;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Get available voices. Due to browser async loading, you may need to call this
|
|
81
|
+
* after the `voiceschanged` event fires, or retry after a short delay.
|
|
82
|
+
*/
|
|
83
|
+
static getVoices() {
|
|
84
|
+
return typeof window !== 'undefined' && 'speechSynthesis' in window
|
|
85
|
+
? window.speechSynthesis.getVoices()
|
|
86
|
+
: [];
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Speak a complete text. Returns a Promise that resolves when the utterance finishes.
|
|
90
|
+
*/
|
|
91
|
+
speak(text) {
|
|
92
|
+
return new Promise((resolve, reject) => {
|
|
93
|
+
if (!BrowserSpeechSynthesizer.isSupported()) {
|
|
94
|
+
reject(new Error('SpeechSynthesis API is not supported in this browser.'));
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const trimmed = text.trim();
|
|
98
|
+
if (!trimmed) {
|
|
99
|
+
resolve();
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
// Chrome workaround: cancel any stale/paused state before first speak
|
|
103
|
+
if (!this.warmedUp) {
|
|
104
|
+
window.speechSynthesis.cancel();
|
|
105
|
+
this.warmedUp = true;
|
|
106
|
+
}
|
|
107
|
+
const utterance = this.createUtterance(trimmed);
|
|
108
|
+
utterance.onstart = () => {
|
|
109
|
+
this._isSpeaking = true;
|
|
110
|
+
this.callbacks.onSpeakStart?.(trimmed);
|
|
111
|
+
};
|
|
112
|
+
utterance.onend = () => {
|
|
113
|
+
this._isSpeaking = false;
|
|
114
|
+
this.callbacks.onSpeakEnd?.(trimmed);
|
|
115
|
+
resolve();
|
|
116
|
+
};
|
|
117
|
+
utterance.onerror = (event) => {
|
|
118
|
+
this._isSpeaking = false;
|
|
119
|
+
const err = new Error(`SpeechSynthesis error: ${event.error}`);
|
|
120
|
+
this.callbacks.onError?.(err);
|
|
121
|
+
reject(err);
|
|
122
|
+
};
|
|
123
|
+
window.speechSynthesis.speak(utterance);
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Feed a streaming text chunk. Text is accumulated until a sentence boundary is found,
|
|
128
|
+
* then the complete sentence is queued for speaking.
|
|
129
|
+
*/
|
|
130
|
+
feedChunk(chunk) {
|
|
131
|
+
// Pre-warm the TTS engine on the very first chunk so Chrome's internal
|
|
132
|
+
// pipeline is already initialised by the time the first real sentence is ready.
|
|
133
|
+
if (!this.warmedUp) {
|
|
134
|
+
this.preWarm();
|
|
135
|
+
}
|
|
136
|
+
this.buffer += chunk;
|
|
137
|
+
this.extractAndQueueSentences();
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Flush any remaining buffered text (e.g. at end of stream) and queue it for speaking.
|
|
141
|
+
*/
|
|
142
|
+
flush() {
|
|
143
|
+
const remaining = this.buffer.trim();
|
|
144
|
+
if (remaining) {
|
|
145
|
+
this.buffer = '';
|
|
146
|
+
this.enqueue(remaining);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Flush and wait for all queued sentences to finish speaking.
|
|
151
|
+
* Returns a Promise that resolves when the queue is empty and speech is done.
|
|
152
|
+
*/
|
|
153
|
+
async flushAndWait() {
|
|
154
|
+
this.flush();
|
|
155
|
+
if (this._pendingCount <= 0 && !this._isSpeaking)
|
|
156
|
+
return;
|
|
157
|
+
return new Promise((resolve) => {
|
|
158
|
+
const check = () => {
|
|
159
|
+
if (this._pendingCount <= 0 && !this._isSpeaking) {
|
|
160
|
+
resolve();
|
|
161
|
+
}
|
|
162
|
+
else {
|
|
163
|
+
setTimeout(check, 100);
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
check();
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
/** Cancel all speech and clear the queue. */
|
|
170
|
+
cancel() {
|
|
171
|
+
this.stopKeepAlive();
|
|
172
|
+
window.speechSynthesis.cancel();
|
|
173
|
+
this.buffer = '';
|
|
174
|
+
this._isSpeaking = false;
|
|
175
|
+
this._pendingCount = 0;
|
|
176
|
+
this.warmedUp = false; // reset so next speak/feedChunk re-warms
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Pre-warm Chrome's TTS engine by speaking a zero-volume silent utterance.
|
|
180
|
+
* This primes the internal synthesis pipeline (voice loading, audio context
|
|
181
|
+
* creation, etc.) so that the first real utterance starts faster.
|
|
182
|
+
*/
|
|
183
|
+
preWarm() {
|
|
184
|
+
if (this.warmedUp || !BrowserSpeechSynthesizer.isSupported())
|
|
185
|
+
return;
|
|
186
|
+
window.speechSynthesis.cancel(); // clear any stale state
|
|
187
|
+
const utterance = new SpeechSynthesisUtterance('');
|
|
188
|
+
utterance.volume = 0;
|
|
189
|
+
// Resolve and assign the voice now so the engine pre-loads it
|
|
190
|
+
const voice = this.resolveVoice();
|
|
191
|
+
if (voice) {
|
|
192
|
+
utterance.voice = voice;
|
|
193
|
+
utterance.lang = voice.lang;
|
|
194
|
+
}
|
|
195
|
+
else if (this.options.lang) {
|
|
196
|
+
utterance.lang = this.options.lang;
|
|
197
|
+
}
|
|
198
|
+
window.speechSynthesis.speak(utterance);
|
|
199
|
+
this.warmedUp = true;
|
|
200
|
+
}
|
|
201
|
+
/** Pause speech. */
|
|
202
|
+
pause() {
|
|
203
|
+
window.speechSynthesis.pause();
|
|
204
|
+
}
|
|
205
|
+
/** Resume speech. */
|
|
206
|
+
resume() {
|
|
207
|
+
window.speechSynthesis.resume();
|
|
208
|
+
}
|
|
209
|
+
// ── Private ────────────────────────────────────────────────
|
|
210
|
+
extractAndQueueSentences() {
|
|
211
|
+
const delimiters = this.options.sentenceDelimiters;
|
|
212
|
+
const minChars = this.options.minCharsBeforeSpeak;
|
|
213
|
+
let lastSplit = 0;
|
|
214
|
+
for (let i = 0; i < this.buffer.length; i++) {
|
|
215
|
+
if (delimiters.includes(this.buffer[i])) {
|
|
216
|
+
const sentence = this.buffer.substring(lastSplit, i + 1).trim();
|
|
217
|
+
if (sentence.length >= minChars) {
|
|
218
|
+
this.enqueue(sentence);
|
|
219
|
+
lastSplit = i + 1;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
// Keep un-split remainder in the buffer
|
|
224
|
+
if (lastSplit > 0) {
|
|
225
|
+
this.buffer = this.buffer.substring(lastSplit);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Submit a sentence directly to the browser's native speech queue.
|
|
230
|
+
* The browser pre-processes queued utterances so the next one starts
|
|
231
|
+
* immediately when the current one finishes — no gap between sentences.
|
|
232
|
+
*/
|
|
233
|
+
enqueue(text) {
|
|
234
|
+
if (!BrowserSpeechSynthesizer.isSupported())
|
|
235
|
+
return;
|
|
236
|
+
const trimmed = text.trim();
|
|
237
|
+
if (!trimmed)
|
|
238
|
+
return;
|
|
239
|
+
// Chrome workaround: cancel any stale/paused state before first speak
|
|
240
|
+
if (!this.warmedUp) {
|
|
241
|
+
window.speechSynthesis.cancel();
|
|
242
|
+
this.warmedUp = true;
|
|
243
|
+
}
|
|
244
|
+
const utterance = this.createUtterance(trimmed);
|
|
245
|
+
this._pendingCount++;
|
|
246
|
+
utterance.onstart = () => {
|
|
247
|
+
this._isSpeaking = true;
|
|
248
|
+
this.startKeepAlive();
|
|
249
|
+
this.callbacks.onSpeakStart?.(trimmed);
|
|
250
|
+
};
|
|
251
|
+
utterance.onend = () => {
|
|
252
|
+
this._pendingCount--;
|
|
253
|
+
this.callbacks.onSpeakEnd?.(trimmed);
|
|
254
|
+
if (this._pendingCount <= 0) {
|
|
255
|
+
this._pendingCount = 0;
|
|
256
|
+
this._isSpeaking = false;
|
|
257
|
+
this.stopKeepAlive();
|
|
258
|
+
this.callbacks.onQueueEmpty?.();
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
utterance.onerror = (event) => {
|
|
262
|
+
this._pendingCount--;
|
|
263
|
+
if (this._pendingCount <= 0) {
|
|
264
|
+
this._pendingCount = 0;
|
|
265
|
+
this._isSpeaking = false;
|
|
266
|
+
this.stopKeepAlive();
|
|
267
|
+
}
|
|
268
|
+
this.callbacks.onError?.(new Error(`SpeechSynthesis error: ${event.error}`));
|
|
269
|
+
};
|
|
270
|
+
window.speechSynthesis.speak(utterance);
|
|
271
|
+
}
|
|
272
|
+
createUtterance(text) {
|
|
273
|
+
const cleaned = BrowserSpeechSynthesizer.stripMarkdown(text);
|
|
274
|
+
const voice = this.resolveVoice();
|
|
275
|
+
const utterance = new SpeechSynthesisUtterance(cleaned);
|
|
276
|
+
// Set voice BEFORE lang — Chrome requires this order
|
|
277
|
+
if (voice) {
|
|
278
|
+
utterance.voice = voice;
|
|
279
|
+
utterance.lang = voice.lang; // use the voice's own lang tag for consistency
|
|
280
|
+
}
|
|
281
|
+
else if (this.options.lang) {
|
|
282
|
+
utterance.lang = this.options.lang;
|
|
283
|
+
}
|
|
284
|
+
utterance.rate = this.options.rate;
|
|
285
|
+
utterance.pitch = this.options.pitch;
|
|
286
|
+
utterance.volume = this.options.volume;
|
|
287
|
+
return utterance;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Normalize a BCP-47 lang code: lowercase and replace underscores with hyphens.
|
|
291
|
+
*/
|
|
292
|
+
static normalizeLang(lang) {
|
|
293
|
+
return lang.toLowerCase().replace(/_/g, '-');
|
|
294
|
+
}
|
|
295
|
+
resolveVoice() {
|
|
296
|
+
if (this.voiceResolved)
|
|
297
|
+
return this.resolvedVoice;
|
|
298
|
+
const voices = BrowserSpeechSynthesizer.getVoices();
|
|
299
|
+
if (voices.length === 0)
|
|
300
|
+
return null; // voices not loaded yet — do NOT cache, retry next time
|
|
301
|
+
// Try by exact name
|
|
302
|
+
if (this.options.voiceName) {
|
|
303
|
+
const byName = voices.find(v => v.name.toLowerCase().includes(this.options.voiceName.toLowerCase()));
|
|
304
|
+
if (byName) {
|
|
305
|
+
this.voiceResolved = true;
|
|
306
|
+
this.resolvedVoice = byName;
|
|
307
|
+
return byName;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
// Try by language (exact match, then base language match).
|
|
311
|
+
// When preferLocalVoice is true, search local voices first (no network latency).
|
|
312
|
+
if (this.options.lang) {
|
|
313
|
+
const targetLang = BrowserSpeechSynthesizer.normalizeLang(this.options.lang);
|
|
314
|
+
const targetBase = targetLang.split('-')[0];
|
|
315
|
+
const preferLocal = this.options.preferLocalVoice;
|
|
316
|
+
// Sort: local voices first when preferred
|
|
317
|
+
const sorted = preferLocal
|
|
318
|
+
? [...voices].sort((a, b) => (b.localService ? 1 : 0) - (a.localService ? 1 : 0))
|
|
319
|
+
: voices;
|
|
320
|
+
// Exact match: it-it === it-it
|
|
321
|
+
const exact = sorted.find(v => BrowserSpeechSynthesizer.normalizeLang(v.lang) === targetLang);
|
|
322
|
+
if (exact) {
|
|
323
|
+
this.voiceResolved = true;
|
|
324
|
+
this.resolvedVoice = exact;
|
|
325
|
+
return exact;
|
|
326
|
+
}
|
|
327
|
+
// Base language match: it-it starts with it, it-ch starts with it
|
|
328
|
+
const byBase = sorted.find(v => BrowserSpeechSynthesizer.normalizeLang(v.lang).startsWith(targetBase + '-')) ?? sorted.find(v => BrowserSpeechSynthesizer.normalizeLang(v.lang) === targetBase);
|
|
329
|
+
if (byBase) {
|
|
330
|
+
this.voiceResolved = true;
|
|
331
|
+
this.resolvedVoice = byBase;
|
|
332
|
+
return byBase;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
// Don't cache failure — voices may load later or lang may change
|
|
336
|
+
return null;
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Chrome workaround: keeps speech synthesis alive.
|
|
340
|
+
* Chrome auto-pauses `speechSynthesis` after ~15 seconds of continuous speech.
|
|
341
|
+
* Calling `pause()` then `resume()` periodically resets this internal timer.
|
|
342
|
+
*/
|
|
343
|
+
startKeepAlive() {
|
|
344
|
+
if (this.keepAliveTimer)
|
|
345
|
+
return; // already running
|
|
346
|
+
this.keepAliveTimer = setInterval(() => {
|
|
347
|
+
if (window.speechSynthesis.speaking && !window.speechSynthesis.paused) {
|
|
348
|
+
window.speechSynthesis.pause();
|
|
349
|
+
window.speechSynthesis.resume();
|
|
350
|
+
}
|
|
351
|
+
}, 10_000);
|
|
352
|
+
}
|
|
353
|
+
/** Stop the Chrome keepalive timer. */
|
|
354
|
+
stopKeepAlive() {
|
|
355
|
+
if (this.keepAliveTimer) {
|
|
356
|
+
clearInterval(this.keepAliveTimer);
|
|
357
|
+
this.keepAliveTimer = null;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Strip common Markdown formatting so TTS reads only the plain text.
|
|
362
|
+
* Handles: bold, italic, strikethrough, inline code, code blocks,
|
|
363
|
+
* headers, links, images, blockquotes, list markers, horizontal rules.
|
|
364
|
+
*/
|
|
365
|
+
static stripMarkdown(text) {
|
|
366
|
+
return text
|
|
367
|
+
// Code blocks (```...```)
|
|
368
|
+
.replace(/```[\s\S]*?```/g, '')
|
|
369
|
+
// Inline code (`...`)
|
|
370
|
+
.replace(/`([^`]+)`/g, '$1')
|
|
371
|
+
// Images 
|
|
372
|
+
.replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')
|
|
373
|
+
// Links [text](url)
|
|
374
|
+
.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
|
|
375
|
+
// Bold+Italic ***text*** or ___text___
|
|
376
|
+
.replace(/(\*{3}|_{3})(.+?)\1/g, '$2')
|
|
377
|
+
// Bold **text** or __text__
|
|
378
|
+
.replace(/(\*{2}|_{2})(.+?)\1/g, '$2')
|
|
379
|
+
// Italic *text* or _text_
|
|
380
|
+
.replace(/(\*|_)(.+?)\1/g, '$2')
|
|
381
|
+
// Strikethrough ~~text~~
|
|
382
|
+
.replace(/~~(.+?)~~/g, '$1')
|
|
383
|
+
// Headers # ... ######
|
|
384
|
+
.replace(/^#{1,6}\s+/gm, '')
|
|
385
|
+
// Blockquotes > text
|
|
386
|
+
.replace(/^>+\s?/gm, '')
|
|
387
|
+
// Unordered list markers (- * +)
|
|
388
|
+
.replace(/^[\s]*[-*+]\s+/gm, '')
|
|
389
|
+
// Ordered list markers (1. 2. etc.)
|
|
390
|
+
.replace(/^[\s]*\d+\.\s+/gm, '')
|
|
391
|
+
// Horizontal rules (---, ***, ___)
|
|
392
|
+
.replace(/^[-*_]{3,}\s*$/gm, '')
|
|
393
|
+
// HTML tags
|
|
394
|
+
.replace(/<[^>]+>/g, '')
|
|
395
|
+
// Collapse multiple newlines
|
|
396
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
397
|
+
.trim();
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
exports.BrowserSpeechSynthesizer = BrowserSpeechSynthesizer;
|
|
@@ -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"}
|