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.
@@ -3,6 +3,7 @@ import { AiSceneResponse } from "../models/AiSceneResponse";
3
3
  import { PlayFrameworkSettings } from "../servicecollection/PlayFrameworkSettings";
4
4
  import { ClientInteractionRegistry } from "./ClientInteractionRegistry";
5
5
  import type { StoredConversation, ConversationQueryParameters } from "../models/StoredConversation";
6
+ import type { VoiceEvent, VoiceRequestOptions } from "../models/VoiceResponse";
6
7
  /**
7
8
  * PlayFramework HTTP client with step-by-step and token-level streaming support.
8
9
  * Supports client-side tool execution with continuation tokens.
@@ -81,5 +82,23 @@ export declare class PlayFrameworkClient {
81
82
  * Helper to build query string from parameters.
82
83
  */
83
84
  private buildQueryString;
85
+ /**
86
+ * Execute the voice pipeline: audio → STT → PlayFramework → TTS → audio streaming.
87
+ * Sends audio as multipart/form-data, receives SSE stream of VoiceEvent.
88
+ *
89
+ * @param options - Voice request options (audio blob, conversationKey, metadata).
90
+ * @returns AsyncIterableIterator of VoiceEvent (transcription, audio chunks, scene events, completion).
91
+ *
92
+ * @example
93
+ * ```ts
94
+ * const audioBlob = await recordAudio();
95
+ * for await (const event of client.executeVoice({ audio: audioBlob })) {
96
+ * if (event.type === 'transcription') console.log('User said:', event.text);
97
+ * if (event.type === 'audio') playAudioBase64(event.audio!);
98
+ * if (event.type === 'scene') console.log('Scene:', event.status, event.message);
99
+ * }
100
+ * ```
101
+ */
102
+ executeVoice(options: VoiceRequestOptions): AsyncIterableIterator<VoiceEvent>;
84
103
  }
85
104
  //# sourceMappingURL=PlayFrameworkClient.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"PlayFrameworkClient.d.ts","sourceRoot":"","sources":["../../src/engine/PlayFrameworkClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAAE,eAAe,EAA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OG;IACU,eAAe,CACxB,eAAe,EAAE,MAAM,EACvB,eAAe,GAAE,OAAe,EAChC,MAAM,CAAC,EAAE,WAAW,GACrB,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;IAuBrC;;;;;;OAMG;IACU,kBAAkB,CAC3B,eAAe,EAAE,MAAM,EACvB,MAAM,CAAC,EAAE,WAAW,GACrB,OAAO,CAAC,IAAI,CAAC;IAgBhB;;;;;;;OAOG;IACU,4BAA4B,CACrC,eAAe,EAAE,MAAM,EACvB,QAAQ,EAAE,OAAO,EACjB,MAAM,CAAC,EAAE,WAAW,GACrB,OAAO,CAAC,kBAAkB,CAAC;IAoB9B;;OAEG;IACH,OAAO,CAAC,gBAAgB;IAoCxB;;;;;;;;;;;;;;;;OAgBG;IACW,YAAY,CACtB,OAAO,EAAE,mBAAmB,GAC7B,qBAAqB,CAAC,UAAU,CAAC;CAgFvC"}
@@ -139,7 +139,7 @@ class PlayFrameworkClient {
139
139
  if (event.status === "awaitingClient" || event.status === "commandClient") {
140
140
  const interactionResponse = event;
141
141
  const isCommand = event.status === "commandClient";
142
- console.log(isCommand ? '🔥 [PlayFrameworkClient] Received CommandClient (fire-and-forget)' : '⏸️ [PlayFrameworkClient] Received AwaitingClient', ', tool:', interactionResponse.clientInteractionRequest?.toolName);
142
+ console.log(isCommand ? '[PlayFrameworkClient] Received CommandClient (fire-and-forget)' : '[PlayFrameworkClient] Received AwaitingClient', ', tool:', interactionResponse.clientInteractionRequest?.toolName);
143
143
  // Capture conversationKey from the response (server sets it for resume)
144
144
  if (interactionResponse.conversationKey) {
145
145
  capturedConversationKey = interactionResponse.conversationKey;
@@ -164,7 +164,7 @@ class PlayFrameworkClient {
164
164
  shouldRetry = false; // Success, no retry
165
165
  // Handle client interactions if any were received during this stream
166
166
  if (shouldContinue && pendingInteractions.length > 0) {
167
- console.log(`🔧 [PlayFrameworkClient] Executing ${pendingInteractions.length} client interaction(s)`);
167
+ console.log(`[PlayFrameworkClient] Executing ${pendingInteractions.length} client interaction(s)`);
168
168
  // Execute ALL pending interactions in parallel
169
169
  const allResults = [];
170
170
  let hasNonCommandInteraction = false;
@@ -172,7 +172,7 @@ class PlayFrameworkClient {
172
172
  const clientRequest = interaction.clientInteractionRequest;
173
173
  if (!clientRequest)
174
174
  continue;
175
- console.log(`🔧 [PlayFrameworkClient] Executing: ${clientRequest.toolName} (${clientRequest.isCommand ? 'command' : 'tool'})`);
175
+ console.log(`[PlayFrameworkClient] Executing: ${clientRequest.toolName} (${clientRequest.isCommand ? 'command' : 'tool'})`);
176
176
  const result = await this.clientRegistry.execute(clientRequest);
177
177
  if (clientRequest.isCommand === true) {
178
178
  // Command: check feedbackMode to decide whether to send result
@@ -192,7 +192,7 @@ class PlayFrameworkClient {
192
192
  }
193
193
  }
194
194
  if (hasNonCommandInteraction || allResults.length > 0) {
195
- console.log(`✅ [PlayFrameworkClient] ${allResults.length} result(s) to send back, resuming`);
195
+ console.log(`[PlayFrameworkClient] ${allResults.length} result(s) to send back, resuming`);
196
196
  // Prepare resume request with ALL applicable results
197
197
  // Use captured conversationKey so the server finds the batch in cache
198
198
  currentRequest = {
@@ -200,16 +200,16 @@ class PlayFrameworkClient {
200
200
  clientInteractionResults: allResults,
201
201
  conversationKey: capturedConversationKey ?? currentRequest.conversationKey
202
202
  };
203
- console.log('📤 [PlayFrameworkClient] Sending resume request with clientInteractionResults');
203
+ console.log('[PlayFrameworkClient] Sending resume request with clientInteractionResults');
204
204
  shouldContinue = true;
205
205
  }
206
206
  else {
207
- console.log('✅ [PlayFrameworkClient] All interactions were fire-and-forget commands. No resume needed.');
207
+ console.log('[PlayFrameworkClient] All interactions were fire-and-forget commands. No resume needed.');
208
208
  shouldContinue = false;
209
209
  }
210
210
  }
211
211
  else {
212
- console.log('✅ [PlayFrameworkClient] Stream completed normally (no client interaction)');
212
+ console.log('[PlayFrameworkClient] Stream completed normally (no client interaction)');
213
213
  shouldContinue = false; // Normal completion or already closed by completed/error
214
214
  }
215
215
  }
@@ -355,5 +355,93 @@ class PlayFrameworkClient {
355
355
  queryParams.push(`includeContents=${includeContents}`);
356
356
  return queryParams.length > 0 ? `?${queryParams.join('&')}` : '';
357
357
  }
358
+ // ─── Voice Pipeline Methods ──────────────────────────────────────────────────
359
+ /**
360
+ * Execute the voice pipeline: audio → STT → PlayFramework → TTS → audio streaming.
361
+ * Sends audio as multipart/form-data, receives SSE stream of VoiceEvent.
362
+ *
363
+ * @param options - Voice request options (audio blob, conversationKey, metadata).
364
+ * @returns AsyncIterableIterator of VoiceEvent (transcription, audio chunks, scene events, completion).
365
+ *
366
+ * @example
367
+ * ```ts
368
+ * const audioBlob = await recordAudio();
369
+ * for await (const event of client.executeVoice({ audio: audioBlob })) {
370
+ * if (event.type === 'transcription') console.log('User said:', event.text);
371
+ * if (event.type === 'audio') playAudioBase64(event.audio!);
372
+ * if (event.type === 'scene') console.log('Scene:', event.status, event.message);
373
+ * }
374
+ * ```
375
+ */
376
+ async *executeVoice(options) {
377
+ const url = `${this.settings.baseUrl}/${this.settings.factoryName}/voice`;
378
+ const effectiveSignal = this.createTimeoutSignal(options.signal);
379
+ // Build multipart/form-data
380
+ const formData = new FormData();
381
+ const audioFile = options.audio instanceof File
382
+ ? options.audio
383
+ : new File([options.audio], 'recording.webm', { type: options.audio.type || 'audio/webm' });
384
+ formData.append('audio', audioFile);
385
+ if (options.conversationKey) {
386
+ formData.append('conversationKey', options.conversationKey);
387
+ }
388
+ if (options.metadata) {
389
+ formData.append('metadata', JSON.stringify(options.metadata));
390
+ }
391
+ // Build headers WITHOUT Content-Type (browser sets multipart boundary automatically)
392
+ const baseHeaders = await this.settings.enrichHeaders(url, "POST", undefined, undefined);
393
+ const headers = new Headers(baseHeaders);
394
+ headers.delete('Content-Type'); // Let browser set multipart boundary
395
+ const response = await fetch(url, {
396
+ method: 'POST',
397
+ headers,
398
+ body: formData,
399
+ signal: effectiveSignal || undefined
400
+ });
401
+ if (!response.ok) {
402
+ const errorText = await response.text().catch(() => response.statusText);
403
+ throw new Error(`Voice pipeline error (${response.status}): ${errorText}`);
404
+ }
405
+ if (!response.body) {
406
+ throw new Error('Response body is null');
407
+ }
408
+ // Parse SSE stream
409
+ const reader = response.body.getReader();
410
+ const decoder = new TextDecoder();
411
+ let buffer = '';
412
+ try {
413
+ while (true) {
414
+ const { done, value } = await reader.read();
415
+ if (done)
416
+ break;
417
+ buffer += decoder.decode(value, { stream: true });
418
+ const lines = buffer.split('\n');
419
+ buffer = lines.pop() || '';
420
+ for (const line of lines) {
421
+ if (line.startsWith('data: ')) {
422
+ const data = line.substring(6).trim();
423
+ if (!data)
424
+ continue;
425
+ let event;
426
+ try {
427
+ event = JSON.parse(data);
428
+ }
429
+ catch {
430
+ console.error('Failed to parse voice SSE event:', data);
431
+ continue;
432
+ }
433
+ yield event;
434
+ // Stop on completed or error
435
+ if (event.type === 'completed' || event.type === 'error') {
436
+ return;
437
+ }
438
+ }
439
+ }
440
+ }
441
+ }
442
+ finally {
443
+ reader.releaseLock();
444
+ }
445
+ }
358
446
  }
359
447
  exports.PlayFrameworkClient = PlayFrameworkClient;
package/lib/index.d.ts CHANGED
@@ -9,11 +9,20 @@ export type { StoredMessage } from "./models/StoredMessage";
9
9
  export type { ExecutionState } from "./models/ExecutionState";
10
10
  export type { CommandResult } from "./models/CommandResult";
11
11
  export { CommandResult as CommandResultHelper } from "./models/CommandResult";
12
+ export type { VoiceEvent, VoiceRequestOptions, VoiceResponseType } from "./models/VoiceResponse";
12
13
  export { PlayFrameworkClient } from "./engine/PlayFrameworkClient";
13
14
  export { ClientInteractionRegistry } from "./engine/ClientInteractionRegistry";
14
15
  export type { ClientTool, ClientCommand, CommandFeedbackMode, CommandOptions } from "./engine/ClientInteractionRegistry";
15
16
  export { AIContentConverter } from "./utils/AIContentConverter";
16
17
  export { ContentUrlConverter } from "./utils/ContentUrlConverter";
18
+ export { VoiceRecorder } from "./utils/VoiceRecorder";
19
+ export type { VoiceRecordingMode, VoiceRecorderOptions, VoiceRecorderCallbacks } from "./utils/VoiceRecorder";
20
+ export { BrowserSpeechRecognizer } from "./utils/BrowserSpeechRecognizer";
21
+ export type { BrowserSpeechRecognizerOptions, BrowserSpeechRecognizerCallbacks, SpeechRecognitionResult } from "./utils/BrowserSpeechRecognizer";
22
+ export { BrowserSpeechSynthesizer } from "./utils/BrowserSpeechSynthesizer";
23
+ export type { BrowserSpeechSynthesizerOptions, BrowserSpeechSynthesizerCallbacks } from "./utils/BrowserSpeechSynthesizer";
24
+ export { BrowserVoiceClient } from "./utils/BrowserVoiceClient";
25
+ export type { BrowserVoiceOptions, BrowserVoiceEvent, BrowserVoiceStatus, BrowserVoiceStreamingMode } from "./utils/BrowserVoiceClient";
17
26
  export { PlayFrameworkSettings } from "./servicecollection/PlayFrameworkSettings";
18
27
  export { PlayFrameworkServices } from "./servicecollection/PlayFrameworkServices";
19
28
  export { usePlayFramework } from "./hooks/hooks";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,YAAY,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACxD,YAAY,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnI,YAAY,EAAE,eAAe,EAAE,gBAAgB,EAAE,QAAQ,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAC3H,YAAY,EAAE,wBAAwB,EAAE,MAAM,mCAAmC,CAAC;AAClF,YAAY,EAAE,uBAAuB,EAAE,SAAS,EAAE,MAAM,kCAAkC,CAAC;AAC3F,YAAY,EAAE,kBAAkB,EAAE,2BAA2B,EAAE,mCAAmC,EAAE,MAAM,6BAA6B,CAAC;AACxI,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AACpE,YAAY,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAC5D,YAAY,EAAE,cAAc,EAAE,MAAM,yBAAyB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"}
package/lib/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.usePlayFramework = exports.PlayFrameworkServices = exports.PlayFrameworkSettings = exports.ContentUrlConverter = exports.AIContentConverter = exports.ClientInteractionRegistry = exports.PlayFrameworkClient = exports.CommandResultHelper = exports.ConversationSortOrder = void 0;
3
+ exports.usePlayFramework = exports.PlayFrameworkServices = exports.PlayFrameworkSettings = exports.BrowserVoiceClient = exports.BrowserSpeechSynthesizer = exports.BrowserSpeechRecognizer = exports.VoiceRecorder = exports.ContentUrlConverter = exports.AIContentConverter = exports.ClientInteractionRegistry = exports.PlayFrameworkClient = exports.CommandResultHelper = exports.ConversationSortOrder = void 0;
4
4
  var StoredConversation_1 = require("./models/StoredConversation");
5
5
  Object.defineProperty(exports, "ConversationSortOrder", { enumerable: true, get: function () { return StoredConversation_1.ConversationSortOrder; } });
6
6
  var CommandResult_1 = require("./models/CommandResult");
@@ -15,6 +15,14 @@ var AIContentConverter_1 = require("./utils/AIContentConverter");
15
15
  Object.defineProperty(exports, "AIContentConverter", { enumerable: true, get: function () { return AIContentConverter_1.AIContentConverter; } });
16
16
  var ContentUrlConverter_1 = require("./utils/ContentUrlConverter");
17
17
  Object.defineProperty(exports, "ContentUrlConverter", { enumerable: true, get: function () { return ContentUrlConverter_1.ContentUrlConverter; } });
18
+ var VoiceRecorder_1 = require("./utils/VoiceRecorder");
19
+ Object.defineProperty(exports, "VoiceRecorder", { enumerable: true, get: function () { return VoiceRecorder_1.VoiceRecorder; } });
20
+ var BrowserSpeechRecognizer_1 = require("./utils/BrowserSpeechRecognizer");
21
+ Object.defineProperty(exports, "BrowserSpeechRecognizer", { enumerable: true, get: function () { return BrowserSpeechRecognizer_1.BrowserSpeechRecognizer; } });
22
+ var BrowserSpeechSynthesizer_1 = require("./utils/BrowserSpeechSynthesizer");
23
+ Object.defineProperty(exports, "BrowserSpeechSynthesizer", { enumerable: true, get: function () { return BrowserSpeechSynthesizer_1.BrowserSpeechSynthesizer; } });
24
+ var BrowserVoiceClient_1 = require("./utils/BrowserVoiceClient");
25
+ Object.defineProperty(exports, "BrowserVoiceClient", { enumerable: true, get: function () { return BrowserVoiceClient_1.BrowserVoiceClient; } });
18
26
  // Service Collection
19
27
  var PlayFrameworkSettings_1 = require("./servicecollection/PlayFrameworkSettings");
20
28
  Object.defineProperty(exports, "PlayFrameworkSettings", { enumerable: true, get: function () { return PlayFrameworkSettings_1.PlayFrameworkSettings; } });
@@ -40,6 +40,16 @@ export interface SceneRequestSettings {
40
40
  sceneName?: string;
41
41
  /** Results from client-side tool executions. */
42
42
  clientInteractionResults?: ClientInteractionResult[];
43
+ /**
44
+ * Additional system-level instructions appended to the system prompt.
45
+ * Used by voice pipeline to inject conversational style and language instructions.
46
+ */
47
+ additionalSystemInstructions?: string[];
48
+ /**
49
+ * When true, the server injects a voice-style system instruction
50
+ * that tells the LLM to respond conversationally (no tables, no markdown).
51
+ */
52
+ isVoiceMode?: boolean;
43
53
  }
44
54
  /**
45
55
  * Request model for PlayFramework HTTP API.
@@ -1 +1 @@
1
- {"version":3,"file":"PlayFrameworkRequest.d.ts","sourceRoot":"","sources":["../../src/models/PlayFrameworkRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAEpE;;GAEG;AACH,MAAM,MAAM,kBAAkB,GAAG,QAAQ,GAAG,UAAU,GAAG,iBAAiB,GAAG,OAAO,CAAC;AAErF;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,SAAS,GAAG,WAAW,GAAG,SAAS,CAAC;AAEhE;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACjC,yDAAyD;IACzD,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,gEAAgE;IAChE,aAAa,CAAC,EAAE,kBAAkB,CAAC;IACnC,uCAAuC;IACvC,mB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,MAAM,EAAE,GAAG,CAAC,CAAC;IAE/B;;OAEG;IACH,QAAQ,CAAC,EAAE,oBAAoB,CAAC;IAEhC;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;OAGG;IACH,wBAAwB,CAAC,EAAE,uBAAuB,EAAE,CAAC;CACxD"}
@@ -0,0 +1,39 @@
1
+ import { AiSceneResponse } from "./AiSceneResponse";
2
+ /**
3
+ * Type of voice pipeline response event.
4
+ */
5
+ export type VoiceResponseType = "transcription" | "audio" | "scene" | "completed" | "error";
6
+ /**
7
+ * Single event from the voice pipeline SSE stream.
8
+ * The server sends these as `data: {...}\n\n` lines.
9
+ */
10
+ export interface VoiceEvent {
11
+ /** Event type discriminator. */
12
+ type: VoiceResponseType;
13
+ /** Text content (transcript for "transcription", synthesized sentence for "audio"). */
14
+ text?: string;
15
+ /** Base64-encoded audio chunk (only for type === "audio"). */
16
+ audio?: string;
17
+ /** PlayFramework scene status (only for type === "scene"). */
18
+ status?: string;
19
+ /** Full scene response (only for type === "scene"). */
20
+ sceneResponse?: AiSceneResponse;
21
+ /** Scene message (only for type === "scene"). */
22
+ message?: string;
23
+ /** Error message (only for type === "error"). */
24
+ errorMessage?: string;
25
+ }
26
+ /**
27
+ * Options for the voice pipeline request.
28
+ */
29
+ export interface VoiceRequestOptions {
30
+ /** Raw audio data as Blob or File. */
31
+ audio: Blob | File;
32
+ /** Optional conversation key for multi-turn voice conversations. */
33
+ conversationKey?: string;
34
+ /** Optional metadata (userId, tenantId, etc.). */
35
+ metadata?: Record<string, any>;
36
+ /** Optional abort signal. */
37
+ signal?: AbortSignal;
38
+ }
39
+ //# sourceMappingURL=VoiceResponse.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"VoiceResponse.d.ts","sourceRoot":"","sources":["../../src/models/VoiceResponse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAEpD;;GAEG;AACH,MAAM,MAAM,iBAAiB,GAAG,eAAe,GAAG,OAAO,GAAG,OAAO,GAAG,WAAW,GAAG,OAAO,CAAC;AAE5F;;;GAGG;AACH,MAAM,WAAW,UAAU;IACvB,gCAAgC;IAChC,IAAI,EAAE,iBAAiB,CAAC;IAExB,uFAAuF;IACvF,IAAI,CAAC,EAAE,MAAM,CAAC;IAEd,8DAA8D;IAC9D,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf,8DAA8D;IAC9D,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB,uDAAuD;IACvD,aAAa,CAAC,EAAE,eAAe,CAAC;IAEhC,iDAAiD;IACjD,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB,iDAAiD;IACjD,YAAY,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAChC,sCAAsC;IACtC,KAAK,EAAE,IAAI,GAAG,IAAI,CAAC;IAEnB,oEAAoE;IACpE,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB,kDAAkD;IAClD,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAE/B,6BAA6B;IAC7B,MAAM,CAAC,EAAE,WAAW,CAAC;CACxB"}
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Options for BrowserSpeechRecognizer.
3
+ */
4
+ export interface BrowserSpeechRecognizerOptions {
5
+ /** BCP-47 language code (e.g. 'it-IT', 'en-US'). If omitted, the browser's default is used. */
6
+ lang?: string;
7
+ /** Whether to return interim (partial) results. Default: `true`. */
8
+ interimResults?: boolean;
9
+ /** Whether recognition restarts automatically on end. Default: `false`. */
10
+ continuous?: boolean;
11
+ /** Maximum alternatives per result. Default: `1`. */
12
+ maxAlternatives?: number;
13
+ }
14
+ /**
15
+ * Result from a speech recognition session.
16
+ */
17
+ export interface SpeechRecognitionResult {
18
+ /** The final transcribed text. */
19
+ transcript: string;
20
+ /** Confidence score (0-1). */
21
+ confidence: number;
22
+ /** Whether this is a final (not interim) result. */
23
+ isFinal: boolean;
24
+ }
25
+ /**
26
+ * Callbacks emitted by BrowserSpeechRecognizer.
27
+ */
28
+ export interface BrowserSpeechRecognizerCallbacks {
29
+ /** Called with each interim or final result. */
30
+ onResult?: (result: SpeechRecognitionResult) => void;
31
+ /** Called when recognition ends (user stopped or no more speech). */
32
+ onEnd?: () => void;
33
+ /** Called on recognition error. */
34
+ onError?: (error: Error) => void;
35
+ /** Called when recognition starts. */
36
+ onStart?: () => void;
37
+ }
38
+ interface SpeechRecognitionEvent extends Event {
39
+ results: SpeechRecognitionResultList;
40
+ resultIndex: number;
41
+ }
42
+ interface SpeechRecognitionErrorEvent extends Event {
43
+ error: string;
44
+ message: string;
45
+ }
46
+ interface SpeechRecognitionResultList {
47
+ length: number;
48
+ item(index: number): SpeechRecognitionResultItem;
49
+ [index: number]: SpeechRecognitionResultItem;
50
+ }
51
+ interface SpeechRecognitionResultItem {
52
+ isFinal: boolean;
53
+ length: number;
54
+ item(index: number): SpeechRecognitionAlternative;
55
+ [index: number]: SpeechRecognitionAlternative;
56
+ }
57
+ interface SpeechRecognitionAlternative {
58
+ transcript: string;
59
+ confidence: number;
60
+ }
61
+ interface SpeechRecognitionAPI extends EventTarget {
62
+ lang: string;
63
+ continuous: boolean;
64
+ interimResults: boolean;
65
+ maxAlternatives: number;
66
+ start(): void;
67
+ stop(): void;
68
+ abort(): void;
69
+ onresult: ((event: SpeechRecognitionEvent) => void) | null;
70
+ onend: (() => void) | null;
71
+ onerror: ((event: SpeechRecognitionErrorEvent) => void) | null;
72
+ onstart: (() => void) | null;
73
+ }
74
+ declare global {
75
+ interface Window {
76
+ SpeechRecognition?: new () => SpeechRecognitionAPI;
77
+ webkitSpeechRecognition?: new () => SpeechRecognitionAPI;
78
+ }
79
+ }
80
+ /**
81
+ * Wraps the browser Web Speech API `SpeechRecognition` for speech-to-text.
82
+ *
83
+ * @example
84
+ * ```ts
85
+ * const recognizer = new BrowserSpeechRecognizer({ lang: 'it-IT' });
86
+ *
87
+ * // One-shot usage — returns final transcript as a Promise
88
+ * const text = await recognizer.listen();
89
+ *
90
+ * // Event-based usage
91
+ * recognizer.start({
92
+ * onResult: (r) => console.log(r.transcript, r.isFinal),
93
+ * onEnd: () => console.log('done'),
94
+ * });
95
+ * // later...
96
+ * recognizer.stop();
97
+ * ```
98
+ */
99
+ export declare class BrowserSpeechRecognizer {
100
+ private options;
101
+ private recognition;
102
+ private _isListening;
103
+ constructor(options?: BrowserSpeechRecognizerOptions);
104
+ /** Whether recognition is currently active. */
105
+ get isListening(): boolean;
106
+ /** Returns `true` if the browser supports the Web Speech Recognition API. */
107
+ static isSupported(): boolean;
108
+ /**
109
+ * Start recognition with event callbacks.
110
+ * If already listening, this is a no-op.
111
+ */
112
+ start(callbacks?: BrowserSpeechRecognizerCallbacks): void;
113
+ /** Stop recognition gracefully (delivers final result). */
114
+ stop(): void;
115
+ /** Abort recognition immediately (no final result). */
116
+ abort(): void;
117
+ /**
118
+ * One-shot recognition: starts listening and returns a Promise that resolves
119
+ * with the final transcript when speech ends.
120
+ *
121
+ * @param timeoutMs - Maximum wait time (default: 15000ms). Resolves with '' on timeout.
122
+ */
123
+ listen(timeoutMs?: number): Promise<string>;
124
+ /** Update language at runtime (takes effect on next `start()`). */
125
+ setLang(lang: string): void;
126
+ }
127
+ export {};
128
+ //# sourceMappingURL=BrowserSpeechRecognizer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BrowserSpeechRecognizer.d.ts","sourceRoot":"","sources":["../../src/utils/BrowserSpeechRecognizer.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,8BAA8B;IAC3C,+FAA+F;IAC/F,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,oEAAoE;IACpE,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,2EAA2E;IAC3E,UAAU,CAAC,EAAE,OAA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AAE,MAAM,GAAG,IAAI;CAG9B"}
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BrowserSpeechRecognizer = void 0;
4
+ /**
5
+ * Wraps the browser Web Speech API `SpeechRecognition` for speech-to-text.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * const recognizer = new BrowserSpeechRecognizer({ lang: 'it-IT' });
10
+ *
11
+ * // One-shot usage — returns final transcript as a Promise
12
+ * const text = await recognizer.listen();
13
+ *
14
+ * // Event-based usage
15
+ * recognizer.start({
16
+ * onResult: (r) => console.log(r.transcript, r.isFinal),
17
+ * onEnd: () => console.log('done'),
18
+ * });
19
+ * // later...
20
+ * recognizer.stop();
21
+ * ```
22
+ */
23
+ class BrowserSpeechRecognizer {
24
+ options;
25
+ recognition = null;
26
+ _isListening = false;
27
+ constructor(options) {
28
+ this.options = {
29
+ lang: options?.lang ?? '',
30
+ interimResults: options?.interimResults ?? true,
31
+ continuous: options?.continuous ?? false,
32
+ maxAlternatives: options?.maxAlternatives ?? 1,
33
+ };
34
+ }
35
+ /** Whether recognition is currently active. */
36
+ get isListening() {
37
+ return this._isListening;
38
+ }
39
+ /** Returns `true` if the browser supports the Web Speech Recognition API. */
40
+ static isSupported() {
41
+ return typeof window !== 'undefined' &&
42
+ !!(window.SpeechRecognition || window.webkitSpeechRecognition);
43
+ }
44
+ /**
45
+ * Start recognition with event callbacks.
46
+ * If already listening, this is a no-op.
47
+ */
48
+ start(callbacks) {
49
+ if (this._isListening)
50
+ return;
51
+ const SpeechRecognitionCtor = window.SpeechRecognition || window.webkitSpeechRecognition;
52
+ if (!SpeechRecognitionCtor) {
53
+ callbacks?.onError?.(new Error('SpeechRecognition API is not supported in this browser.'));
54
+ return;
55
+ }
56
+ const recognition = new SpeechRecognitionCtor();
57
+ this.recognition = recognition;
58
+ if (this.options.lang)
59
+ recognition.lang = this.options.lang;
60
+ recognition.continuous = this.options.continuous;
61
+ recognition.interimResults = this.options.interimResults;
62
+ recognition.maxAlternatives = this.options.maxAlternatives;
63
+ recognition.onstart = () => {
64
+ this._isListening = true;
65
+ callbacks?.onStart?.();
66
+ };
67
+ recognition.onresult = (event) => {
68
+ for (let i = event.resultIndex; i < event.results.length; i++) {
69
+ const result = event.results[i];
70
+ const alt = result[0];
71
+ callbacks?.onResult?.({
72
+ transcript: alt.transcript,
73
+ confidence: alt.confidence,
74
+ isFinal: result.isFinal,
75
+ });
76
+ }
77
+ };
78
+ recognition.onerror = (event) => {
79
+ // 'no-speech' and 'aborted' are common non-fatal errors
80
+ const nonFatal = ['no-speech', 'aborted'];
81
+ if (!nonFatal.includes(event.error)) {
82
+ callbacks?.onError?.(new Error(`SpeechRecognition error: ${event.error} — ${event.message}`));
83
+ }
84
+ };
85
+ recognition.onend = () => {
86
+ this._isListening = false;
87
+ this.recognition = null;
88
+ callbacks?.onEnd?.();
89
+ };
90
+ recognition.start();
91
+ }
92
+ /** Stop recognition gracefully (delivers final result). */
93
+ stop() {
94
+ if (this.recognition) {
95
+ this.recognition.stop();
96
+ }
97
+ }
98
+ /** Abort recognition immediately (no final result). */
99
+ abort() {
100
+ if (this.recognition) {
101
+ this.recognition.abort();
102
+ this._isListening = false;
103
+ this.recognition = null;
104
+ }
105
+ }
106
+ /**
107
+ * One-shot recognition: starts listening and returns a Promise that resolves
108
+ * with the final transcript when speech ends.
109
+ *
110
+ * @param timeoutMs - Maximum wait time (default: 15000ms). Resolves with '' on timeout.
111
+ */
112
+ listen(timeoutMs = 15000) {
113
+ return new Promise((resolve, reject) => {
114
+ let finalTranscript = '';
115
+ let timer = null;
116
+ const cleanup = () => {
117
+ if (timer) {
118
+ clearTimeout(timer);
119
+ timer = null;
120
+ }
121
+ };
122
+ if (timeoutMs > 0) {
123
+ timer = setTimeout(() => {
124
+ this.stop();
125
+ // onEnd will fire and resolve with whatever we have
126
+ }, timeoutMs);
127
+ }
128
+ this.start({
129
+ onResult: (result) => {
130
+ if (result.isFinal) {
131
+ finalTranscript += result.transcript;
132
+ }
133
+ },
134
+ onEnd: () => {
135
+ cleanup();
136
+ resolve(finalTranscript);
137
+ },
138
+ onError: (err) => {
139
+ cleanup();
140
+ reject(err);
141
+ },
142
+ });
143
+ });
144
+ }
145
+ /** Update language at runtime (takes effect on next `start()`). */
146
+ setLang(lang) {
147
+ this.options.lang = lang;
148
+ }
149
+ }
150
+ exports.BrowserSpeechRecognizer = BrowserSpeechRecognizer;