rystem.playframework.client 0.1.2 → 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 CHANGED
@@ -15,6 +15,7 @@ Production-ready client with full support for:
15
15
  - ✅ **Execution modes** - Direct, Planning, DynamicChaining, Scene
16
16
  - ✅ **Configurable** - Headers, retry, error handling, timeouts
17
17
  - ✅ **Type-safe** - Full TypeScript definitions
18
+ - ✅ **Browser Voice** - Client-side STT/TTS via Web Speech API (zero-latency, no server needed)
18
19
 
19
20
  ---
20
21
 
@@ -1293,33 +1294,479 @@ useEffect(() => {
1293
1294
 
1294
1295
  ---
1295
1296
 
1296
- ## 🚫 Cancellation
1297
+ ## 🎙️ Browser Voice (Web Speech API)
1298
+
1299
+ The client includes a fully client-side voice pipeline using the **Web Speech API**. This provides zero-latency speech recognition (STT) and text-to-speech (TTS) directly in the browser — no server-side Whisper or TTS-1 required.
1300
+
1301
+ > **Note:** Browser voice uses the browser's built-in speech engines. For higher quality (OpenAI Whisper + TTS-1), use the [server-side voice pipeline](#server-side-voice-pipeline) instead.
1297
1302
 
1298
- Use `AbortController` to **cancel ongoing requests**:
1303
+ ### Browser Support
1304
+
1305
+ | Feature | Chrome | Edge | Safari | Firefox |
1306
+ |---|---|---|---|---|
1307
+ | SpeechRecognition | ✅ | ✅ | ✅ | ❌ |
1308
+ | SpeechSynthesis | ✅ | ✅ | ✅ | ✅ |
1309
+
1310
+ ### Quick Start
1299
1311
 
1300
1312
  ```typescript
1301
- const controller = new AbortController();
1313
+ import {
1314
+ PlayFrameworkServices,
1315
+ BrowserVoiceClient,
1316
+ } from "@rystem/playframework-client";
1302
1317
 
1303
- // Start streaming
1304
- const promise = (async () => {
1305
- try {
1306
- for await (const step of client.executeStepByStep(
1307
- { message: "Long task..." },
1308
- controller.signal
1309
- )) {
1310
- console.log(step.message);
1318
+ // 1. Configure PlayFramework client
1319
+ await PlayFrameworkServices.configure("default", "http://localhost:5158/api/ai");
1320
+ const client = PlayFrameworkServices.resolve("default");
1321
+
1322
+ // 2. Create browser voice client
1323
+ const voice = new BrowserVoiceClient(
1324
+ client,
1325
+ { lang: "it-IT" }, // STT options
1326
+ { lang: "it-IT", rate: 1.0 }, // TTS options
1327
+ );
1328
+
1329
+ // 3. Full voice loop: listen → LLM → speak
1330
+ for await (const event of voice.executeWithBrowserVoice()) {
1331
+ if (event.voiceStatus === "recognized") {
1332
+ console.log("User said:", event.transcript);
1333
+ }
1334
+ if (event.response?.message) {
1335
+ console.log("AI:", event.response.message);
1336
+ }
1337
+ if (event.voiceStatus === "speechComplete") {
1338
+ console.log("Done speaking.");
1339
+ }
1340
+ }
1341
+ ```
1342
+
1343
+ ### BrowserSpeechRecognizer
1344
+
1345
+ Wraps `SpeechRecognition` / `webkitSpeechRecognition` for speech-to-text.
1346
+
1347
+ ```typescript
1348
+ import { BrowserSpeechRecognizer } from "@rystem/playframework-client";
1349
+
1350
+ const recognizer = new BrowserSpeechRecognizer({ lang: "en-US" });
1351
+
1352
+ // One-shot recognition (returns a Promise)
1353
+ const text = await recognizer.listen(10000); // 10s timeout
1354
+ console.log("You said:", text);
1355
+
1356
+ // Continuous recognition with callbacks
1357
+ recognizer.start({
1358
+ onResult: (result) => console.log(result.transcript, result.isFinal),
1359
+ onEnd: () => console.log("Stopped"),
1360
+ onError: (err) => console.error(err),
1361
+ });
1362
+
1363
+ // Change language at runtime
1364
+ recognizer.setLang("it-IT");
1365
+
1366
+ // Stop / abort
1367
+ recognizer.stop(); // graceful
1368
+ recognizer.abort(); // immediate
1369
+ ```
1370
+
1371
+ #### Options
1372
+
1373
+ | Property | Type | Default | Description |
1374
+ |---|---|---|---|
1375
+ | `lang` | `string` | Browser default | BCP-47 language code (e.g. `'it-IT'`, `'en-US'`) |
1376
+ | `interimResults` | `boolean` | `true` | Return partial results while speaking |
1377
+ | `continuous` | `boolean` | `false` | Auto-restart recognition on end |
1378
+ | `maxAlternatives` | `number` | `1` | Max recognition alternatives |
1379
+
1380
+ ### BrowserSpeechSynthesizer
1381
+
1382
+ Wraps `SpeechSynthesis` for text-to-speech, with built-in **sentence accumulation** for streaming scenarios and **Markdown stripping**.
1383
+
1384
+ ```typescript
1385
+ import { BrowserSpeechSynthesizer } from "@rystem/playframework-client";
1386
+
1387
+ const synth = new BrowserSpeechSynthesizer({ lang: "it-IT", rate: 1.1 });
1388
+
1389
+ // Simple: speak a complete text
1390
+ await synth.speak("Ciao, come stai?");
1391
+
1392
+ // Streaming: feed chunks as they arrive from the LLM
1393
+ synth.feedChunk("Ciao, ");
1394
+ synth.feedChunk("come stai? ");
1395
+ synth.feedChunk("Tutto bene.");
1396
+ await synth.flushAndWait(); // speak remaining buffer and wait
1397
+
1398
+ // Cancel ongoing speech
1399
+ synth.cancel();
1400
+
1401
+ // Change language at runtime
1402
+ synth.setLang("en-US");
1403
+
1404
+ // Strip Markdown before speaking
1405
+ const clean = BrowserSpeechSynthesizer.stripMarkdown("**Hello** _world_");
1406
+ // → "Hello world"
1407
+ ```
1408
+
1409
+ #### Options
1410
+
1411
+ | Property | Type | Default | Description |
1412
+ |---|---|---|---|
1413
+ | `lang` | `string` | Browser default | BCP-47 language code |
1414
+ | `rate` | `number` | `1` | Speech rate (0.1 – 10) |
1415
+ | `pitch` | `number` | `1` | Pitch (0 – 2) |
1416
+ | `volume` | `number` | `1` | Volume (0 – 1) |
1417
+ | `voiceName` | `string` | Auto | Preferred voice name (e.g. `'Google italiano'`) |
1418
+ | `sentenceDelimiters` | `string[]` | `['.','!','?','\n']` | Characters that trigger sentence flush |
1419
+ | `minCharsBeforeSpeak` | `number` | `20` | Min chars before flushing a sentence |
1420
+
1421
+ #### Streaming Sentence Accumulation
1422
+
1423
+ When using `feedChunk()`, text is buffered until a sentence delimiter is found and the buffer reaches `minCharsBeforeSpeak`. This prevents TTS from speaking tiny fragments:
1424
+
1425
+ ```
1426
+ feedChunk("Ciao, ") → buffer: "Ciao, " (no delimiter → wait)
1427
+ feedChunk("come stai? ") → "Ciao, come stai?" → speaks! (delimiter '?' found)
1428
+ feedChunk("Bene. Grazie.") → "Bene." → speaks! then "Grazie." → speaks!
1429
+ ```
1430
+
1431
+ ### BrowserVoiceClient
1432
+
1433
+ Orchestrates the full voice loop: **STT → PlayFramework → TTS**.
1434
+
1435
+ ```typescript
1436
+ import { BrowserVoiceClient } from "@rystem/playframework-client";
1437
+
1438
+ const voice = new BrowserVoiceClient(
1439
+ client, // PlayFrameworkClient
1440
+ { lang: "it-IT" }, // BrowserSpeechRecognizerOptions
1441
+ { lang: "it-IT", rate: 1.0 }, // BrowserSpeechSynthesizerOptions
1442
+ );
1443
+
1444
+ // Step-by-step mode (default) — speaks complete step messages
1445
+ for await (const ev of voice.executeWithBrowserVoice({
1446
+ streamingMode: "stepByStep",
1447
+ })) {
1448
+ console.log(ev.voiceStatus, ev.response?.status);
1449
+ }
1450
+
1451
+ // Token streaming mode — speaks tokens as they arrive
1452
+ for await (const ev of voice.executeWithBrowserVoice({
1453
+ streamingMode: "tokenStreaming",
1454
+ })) {
1455
+ if (ev.response?.streamingChunk) {
1456
+ process.stdout.write(ev.response.streamingChunk);
1457
+ }
1458
+ }
1459
+
1460
+ // Skip STT — send text directly and speak the response
1461
+ for await (const ev of voice.speakResponse("Tell me a joke", "stepByStep")) {
1462
+ // TTS speaks the AI response
1463
+ }
1464
+
1465
+ // Cancel everything
1466
+ voice.cancelAll();
1467
+
1468
+ // Or cancel just audio (text stream continues)
1469
+ voice.cancelSpeech();
1470
+
1471
+ // Or cancel the HTTP stream + audio
1472
+ voice.cancelStream();
1473
+
1474
+ // Check if a flow is active
1475
+ console.log(voice.isStreaming);
1476
+ ```
1477
+
1478
+ #### Options (`BrowserVoiceOptions`)
1479
+
1480
+ | Property | Type | Default | Description |
1481
+ |---|---|---|---|
1482
+ | `text` | `string` | — | Skip STT, use this text directly |
1483
+ | `streamingMode` | `'stepByStep'` \| `'tokenStreaming'` | `'stepByStep'` | How to stream the LLM interaction |
1484
+ | `request` | `Partial<PlayFrameworkRequest>` | — | Base request (settings, conversationKey, etc.) |
1485
+ | `recognitionTimeoutMs` | `number` | `15000` | STT listening timeout |
1486
+ | `signal` | `AbortSignal` | — | Cancel the entire voice flow |
1487
+ | `speakResponse` | `boolean` | `true` | Whether TTS speaks the LLM response |
1488
+ | `useVoiceStyle` | `boolean` | `true` | When `true`, tells the server to inject a voice-style system instruction (conversational tone, no tables/markdown). Set to `false` to keep rich formatting even in voice mode |
1489
+
1490
+ #### Voice Events
1491
+
1492
+ | `voiceStatus` | Description |
1493
+ |---|---|
1494
+ | `'recognizing'` | STT is listening for speech |
1495
+ | `'recognized'` | STT captured the transcript |
1496
+ | `'speaking'` | TTS is speaking |
1497
+ | `'speechComplete'` | TTS finished all queued speech |
1498
+
1499
+ #### Status Filtering
1500
+
1501
+ In `stepByStep` mode, the client automatically skips non-speakable statuses (system messages, tool calls, planning, etc.) and only speaks `running`, `completed`, and `streaming` responses.
1502
+
1503
+ #### Voice-Style Responses
1504
+
1505
+ By default, the `BrowserVoiceClient` sets `isVoiceMode: true` on every request. This tells the server to inject a system instruction that makes the LLM respond in a **conversational, speech-friendly style**:
1506
+
1507
+ - No tables, bullet lists, numbered lists, or markdown formatting
1508
+ - Short, clear sentences with natural discourse markers
1509
+ - Numbers spelled out when small ("three" instead of "3")
1510
+ - Concise responses aimed at ~30 seconds of spoken delivery
1511
+
1512
+ If the user explicitly asks for a table or structured format, the LLM will still provide it.
1513
+
1514
+ **To disable** (keep rich formatting even in voice mode):
1515
+
1516
+ ```typescript
1517
+ for await (const ev of voice.executeWithBrowserVoice({
1518
+ useVoiceStyle: false, // voice I/O but formatted responses
1519
+ })) { ... }
1520
+ ```
1521
+
1522
+ The voice-style instruction is fully customizable on the server via `VoiceSettings.VoiceStyleInstruction`.
1523
+
1524
+ ### React Example: Voice Chat
1525
+
1526
+ ```tsx
1527
+ import { usePlayFramework, BrowserVoiceClient } from "@rystem/playframework-client";
1528
+ import { useState, useRef, useEffect } from "react";
1529
+
1530
+ function VoiceChat() {
1531
+ const client = usePlayFramework("default");
1532
+ const [listening, setListening] = useState(false);
1533
+ const [transcript, setTranscript] = useState("");
1534
+ const [response, setResponse] = useState("");
1535
+ const [lang, setLang] = useState(navigator.language || "en-US");
1536
+ const voiceRef = useRef<BrowserVoiceClient | null>(null);
1537
+
1538
+ useEffect(() => {
1539
+ voiceRef.current = new BrowserVoiceClient(
1540
+ client,
1541
+ { lang },
1542
+ { lang, rate: 1.0 },
1543
+ );
1544
+ }, [client]);
1545
+
1546
+ // Sync language changes
1547
+ useEffect(() => {
1548
+ if (voiceRef.current) {
1549
+ voiceRef.current.getRecognizer().setLang(lang);
1550
+ voiceRef.current.getSynthesizer().setLang(lang);
1311
1551
  }
1312
- } catch (error) {
1313
- if (error instanceof DOMException && error.name === "AbortError") {
1314
- console.log("Request cancelled");
1552
+ }, [lang]);
1553
+
1554
+ const handleVoice = async () => {
1555
+ if (!voiceRef.current) return;
1556
+ setListening(true);
1557
+ setTranscript("");
1558
+ setResponse("");
1559
+
1560
+ try {
1561
+ for await (const event of voiceRef.current.executeWithBrowserVoice({
1562
+ streamingMode: "tokenStreaming",
1563
+ })) {
1564
+ if (event.voiceStatus === "recognized") {
1565
+ setTranscript(event.transcript ?? "");
1566
+ }
1567
+ if (event.response?.streamingChunk) {
1568
+ setResponse(prev => prev + event.response!.streamingChunk);
1569
+ }
1570
+ }
1571
+ } finally {
1572
+ setListening(false);
1315
1573
  }
1574
+ };
1575
+
1576
+ return (
1577
+ <div>
1578
+ <select value={lang} onChange={e => setLang(e.target.value)}>
1579
+ <option value="en-US">English</option>
1580
+ <option value="it-IT">Italiano</option>
1581
+ <option value="es-ES">Español</option>
1582
+ <option value="fr-FR">Français</option>
1583
+ <option value="de-DE">Deutsch</option>
1584
+ </select>
1585
+
1586
+ <button onClick={handleVoice} disabled={listening}>
1587
+ {listening ? "🎤 Listening..." : "🎤 Speak"}
1588
+ </button>
1589
+
1590
+ {transcript && <p><strong>You:</strong> {transcript}</p>}
1591
+ {response && <p><strong>AI:</strong> {response}</p>}
1592
+ </div>
1593
+ );
1594
+ }
1595
+ ```
1596
+
1597
+ ### Server-Side Voice Pipeline
1598
+
1599
+ For production scenarios requiring higher-quality STT/TTS (OpenAI Whisper + TTS-1), the server-side voice pipeline handles everything server-side. See the [backend README](https://github.com/KeyserDSoze/Rystem/tree/master/src/AI/Rystem.PlayFramework) for the `WithVoice()` builder and `IVoiceAdapter` setup.
1600
+
1601
+ ### Choosing Between Browser and Server Voice
1602
+
1603
+ | Aspect | Browser Voice | Server Voice |
1604
+ |---|---|---|
1605
+ | **Latency** | Zero (local) | Network round-trip |
1606
+ | **Quality** | Browser engine dependent | OpenAI Whisper + TTS-1 (high) |
1607
+ | **Languages** | Depends on browser/OS voices | All Whisper-supported languages |
1608
+ | **Cost** | Free | OpenAI API costs |
1609
+ | **Privacy** | Audio stays on device | Audio sent to server |
1610
+ | **Offline** | Works offline (TTS only) | Requires server |
1611
+ | **Setup** | Zero config | Requires `IVoiceAdapter` + Azure OpenAI |
1612
+
1613
+ ---
1614
+
1615
+ ## 🚫 Cancellation
1616
+
1617
+ The client provides **three levels of cancellation** that work across all endpoints.
1618
+ When the HTTP stream is aborted the .NET server automatically receives a cancelled `CancellationToken` and stops processing.
1619
+
1620
+ ### 1. Cancel via `AbortController` (all endpoints)
1621
+
1622
+ Every method that performs a network call accepts an `AbortSignal`.
1623
+ Create an `AbortController`, pass its signal, and call `controller.abort()` to cancel:
1624
+
1625
+ ```typescript
1626
+ const controller = new AbortController();
1627
+
1628
+ // Works with step-by-step, token streaming, voice, and all conversation methods
1629
+ const stream = client.executeStepByStep(
1630
+ { message: "Long task..." },
1631
+ controller.signal
1632
+ );
1633
+
1634
+ try {
1635
+ for await (const step of stream) {
1636
+ console.log(step.message);
1316
1637
  }
1317
- })();
1638
+ } catch (error) {
1639
+ if (error instanceof DOMException && error.name === "AbortError") {
1640
+ console.log("Request cancelled");
1641
+ }
1642
+ }
1318
1643
 
1319
1644
  // Cancel after 5 seconds
1320
1645
  setTimeout(() => controller.abort(), 5000);
1321
1646
  ```
1322
1647
 
1648
+ The same pattern applies to every endpoint:
1649
+
1650
+ ```typescript
1651
+ // Token streaming
1652
+ client.executeTokenStreaming(request, controller.signal);
1653
+
1654
+ // Server voice pipeline
1655
+ client.executeVoice({ audio: blob, signal: controller.signal });
1656
+
1657
+ // Conversation management
1658
+ client.listConversations(params, controller.signal);
1659
+ client.getConversation(key, false, controller.signal);
1660
+ client.deleteConversation(key, controller.signal);
1661
+ ```
1662
+
1663
+ ### 2. BrowserVoiceClient — Granular Cancellation
1664
+
1665
+ `BrowserVoiceClient` exposes **four** cancellation methods with different granularity:
1666
+
1667
+ | Method | Audio (TTS) | HTTP Stream | Recognition | Use Case |
1668
+ |---|---|---|---|---|
1669
+ | `cancelSpeech()` | ✅ Stopped | ❌ Continues | ❌ Continues | Mute audio but keep reading text |
1670
+ | `cancelStream()` | ✅ Stopped | ✅ Aborted | ❌ — | Stop text + audio (no more data from server) |
1671
+ | `stopRecognition()` | ❌ — | ❌ — | ✅ Stopped | Stop listening for speech |
1672
+ | `cancelAll()` | ✅ Stopped | ✅ Aborted | ✅ Stopped | Stop everything at once |
1673
+
1674
+ #### Stop audio only (keep text streaming)
1675
+
1676
+ ```typescript
1677
+ const voice = new BrowserVoiceClient(client, { lang: 'en-US' });
1678
+
1679
+ // Start voice flow
1680
+ const flowPromise = (async () => {
1681
+ for await (const event of voice.executeWithBrowserVoice({ text: "Tell me a story" })) {
1682
+ // You still receive text events even after cancelSpeech()
1683
+ if (event.response?.message) {
1684
+ appendToUI(event.response.message);
1685
+ }
1686
+ }
1687
+ })();
1688
+
1689
+ // Stop audio after 3 seconds, but keep receiving text
1690
+ setTimeout(() => voice.cancelSpeech(), 3000);
1691
+ ```
1692
+
1693
+ #### Stop the API call (cancel HTTP stream)
1694
+
1695
+ ```typescript
1696
+ // Cancel via the built-in method — aborts the HTTP/SSE connection
1697
+ voice.cancelStream();
1698
+
1699
+ // Or pass an AbortSignal via options for external control
1700
+ const controller = new AbortController();
1701
+ const flow = voice.executeWithBrowserVoice({ signal: controller.signal });
1702
+ // ...
1703
+ controller.abort(); // Same effect as cancelStream()
1704
+ ```
1705
+
1706
+ #### Stop everything at once
1707
+
1708
+ ```typescript
1709
+ // Stops recognition + aborts HTTP stream + cancels TTS
1710
+ voice.cancelAll();
1711
+ ```
1712
+
1713
+ #### Check if a flow is active
1714
+
1715
+ ```typescript
1716
+ if (voice.isStreaming) {
1717
+ // A voice flow is in progress
1718
+ voice.cancelAll();
1719
+ }
1720
+ ```
1721
+
1722
+ #### React example — Stop buttons
1723
+
1724
+ ```tsx
1725
+ function VoiceChat() {
1726
+ const voiceRef = useRef<BrowserVoiceClient>(null);
1727
+ const [messages, setMessages] = useState<string[]>([]);
1728
+
1729
+ const start = async () => {
1730
+ for await (const event of voiceRef.current!.executeWithBrowserVoice()) {
1731
+ if (event.response?.message) {
1732
+ setMessages(prev => [...prev, event.response!.message!]);
1733
+ }
1734
+ }
1735
+ };
1736
+
1737
+ return (
1738
+ <div>
1739
+ <button onClick={start}>🎤 Speak</button>
1740
+ {/* Stop audio only — text still streams */}
1741
+ <button onClick={() => voiceRef.current?.cancelSpeech()}>🔇 Mute</button>
1742
+ {/* Stop the API call + audio */}
1743
+ <button onClick={() => voiceRef.current?.cancelStream()}>⏹ Stop</button>
1744
+ {/* Stop everything including recognition */}
1745
+ <button onClick={() => voiceRef.current?.cancelAll()}>🚫 Cancel All</button>
1746
+
1747
+ {messages.map((m, i) => <p key={i}>{m}</p>)}
1748
+ </div>
1749
+ );
1750
+ }
1751
+ ```
1752
+
1753
+ ### 3. Timeout-Based Cancellation
1754
+
1755
+ Timeouts are configured globally via `PlayFrameworkSettings.timeout` (in ms).
1756
+ When set, every request is automatically aborted after the timeout expires:
1757
+
1758
+ ```typescript
1759
+ const settings: PlayFrameworkSettings = {
1760
+ baseUrl: '/api/play',
1761
+ factoryName: 'assistant',
1762
+ timeout: 30000, // 30-second timeout for ALL requests
1763
+ // ...
1764
+ };
1765
+ ```
1766
+
1767
+ When a user-provided `AbortSignal` and a timeout are both present, the client combines them
1768
+ so that whichever fires first cancels the request.
1769
+
1323
1770
  ---
1324
1771
 
1325
1772
  ## 📊 Response Status Types
@@ -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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ACrB,OAAO,CAAC,kBAAkB,EAAE,CAAC;IAmBhC;;;;;;;OAOG;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"}
@@ -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/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