rystem.playframework.client 0.1.3 → 0.1.5

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
@@ -1,2311 +1,645 @@
1
- # 🎮 Rystem PlayFramework Client
1
+ # rystem.playframework.client
2
2
 
3
- [![npm version](https://img.shields.io/npm/v/@rystem/playframework-client.svg)](https://www.npmjs.com/package/@rystem/playframework-client)
4
- [![TypeScript](https://img.shields.io/badge/TypeScript-5.7%2B-blue?logo=typescript)](https://www.typescriptlang.org/)
5
- [![License](https://img.shields.io/badge/License-MIT-green)](LICENSE)
3
+ `rystem.playframework.client` is the published TypeScript client for the PlayFramework HTTP API.
6
4
 
7
- > **Official TypeScript/JavaScript client for [Rystem PlayFramework](https://rystem.net) HTTP API**
5
+ It wraps PlayFramework SSE endpoints, auto-runs client-side tools, supports conversation CRUD and the server voice endpoint, and also ships browser-native helpers such as `AIContentConverter`, `ContentUrlConverter`, `VoiceRecorder`, and `BrowserVoiceClient`.
8
6
 
9
- Production-ready client with full support for:
10
- - ✅ **Step-by-step streaming** (SSE) - Each scene/actor as separate event
11
- - ✅ **Token-level streaming** (SSE) - Real-time text chunks
12
- - ✅ **Client-side tools** - Camera, geolocation, file picker, microphone
13
- - ✅ **Multi-modal content** - Images, audio, video, PDFs, URIs
14
- - ✅ **React hooks** - `usePlayFramework()` for easy integration
15
- - ✅ **Execution modes** - Direct, Planning, DynamicChaining, Scene
16
- - ✅ **Configurable** - Headers, retry, error handling, timeouts
17
- - ✅ **Type-safe** - Full TypeScript definitions
18
- - ✅ **Browser Voice** - Client-side STT/TTS via Web Speech API (zero-latency, no server needed)
19
-
20
- ---
21
-
22
- ## 📦 Installation
7
+ ## Installation
23
8
 
24
9
  ```bash
25
- npm install @rystem/playframework-client
26
- ```
27
-
28
- Or with yarn:
29
- ```bash
30
- yarn add @rystem/playframework-client
31
- ```
32
-
33
- ---
34
-
35
- ## 🚀 Quick Start
36
-
37
- ### 1. Configure Client
38
-
39
- ```typescript
40
- import { PlayFrameworkServices } from "@rystem/playframework-client";
41
-
42
- // Configure factory (once at app startup)
43
- await PlayFrameworkServices.configure("default", "http://localhost:5158/api/ai", settings => {
44
- settings.timeout = 120_000; // 2 minutes
45
- settings.maxReconnectAttempts = 3;
46
- settings.reconnectBaseDelay = 1000;
47
- });
48
- ```
49
-
50
- ### 2. Use Client (Vanilla JS/TS)
51
-
52
- ```typescript
53
- const client = PlayFrameworkServices.resolve("default");
54
-
55
- // Step-by-step streaming
56
- for await (const step of client.executeStepByStep({
57
- message: "Tell me a joke"
58
- })) {
59
- console.log(`[${step.status}] ${step.message}`);
60
- }
61
- // Output:
62
- // [planning] Analyzing request...
63
- // [executingScene] Generating joke...
64
- // [completed] Why did the chicken cross the road? To get to the other side!
65
-
66
- // Token-level streaming (real-time chunks)
67
- for await (const chunk of client.executeTokenStreaming({
68
- message: "Write a short story"
69
- })) {
70
- process.stdout.write(chunk.streamingChunk || "");
71
- }
72
- // Output: "Once" → " upon" → " a" → " time" → "..."
73
- ```
74
-
75
- ### 3. Use with React
76
-
77
- ```tsx
78
- import { usePlayFramework } from "@rystem/playframework-client";
79
- import { useState } from "react";
80
-
81
- function ChatComponent() {
82
- const client = usePlayFramework("default");
83
- const [messages, setMessages] = useState<string[]>([]);
84
- const [loading, setLoading] = useState(false);
85
-
86
- const handleSend = async (input: string) => {
87
- setLoading(true);
88
- const newMessages: string[] = [];
89
-
90
- try {
91
- for await (const step of client.executeStepByStep({
92
- message: input
93
- })) {
94
- if (step.streamingChunk) {
95
- // Real-time token streaming
96
- newMessages.push(step.streamingChunk);
97
- } else if (step.message) {
98
- // Step-by-step message
99
- newMessages.push(`[${step.status}] ${step.message}`);
100
- }
101
- setMessages([...newMessages]);
102
- }
103
- } finally {
104
- setLoading(false);
105
- }
106
- };
107
-
108
- return (
109
- <div>
110
- <input onKeyDown={e => e.key === 'Enter' && handleSend(e.currentTarget.value)} />
111
- <div>
112
- {messages.map((msg, i) => <div key={i}>{msg}</div>)}
113
- </div>
114
- </div>
115
- );
116
- }
10
+ npm install rystem.playframework.client
117
11
  ```
118
12
 
119
- ---
120
-
121
- ## 🎯 Core Features
122
-
123
- ### Step-by-Step vs Token Streaming
124
-
125
- **Step-by-Step** (`executeStepByStep`):
126
- - Returns each **scene/actor execution** as separate event
127
- - Best for: Multi-step workflows, debugging, progress tracking
128
- - Example: Planning → Actor1 → Actor2 → Completed
129
-
130
- **Token Streaming** (`executeTokenStreaming`):
131
- - Returns **individual text chunks** as they're generated
132
- - Best for: Real-time chat UIs, typewriter effects
133
- - Example: "Hello" → " world" → "!" → "..."
134
-
135
- ```typescript
136
- // Step-by-step - structured workflow
137
- for await (const step of client.executeStepByStep({ message: "..." })) {
138
- console.log(step.status); // "planning", "executingScene", "completed"
139
- console.log(step.sceneName); // "ChatScene"
140
- console.log(step.message); // Full response
141
- }
142
-
143
- // Token streaming - real-time chunks
144
- for await (const chunk of client.executeTokenStreaming({ message: "..." })) {
145
- console.log(chunk.streamingChunk); // "Hello", " world", "!"
146
- }
147
- ```
13
+ The current package name in `package.json` is `rystem.playframework.client`.
148
14
 
149
- ---
15
+ ## What this package expects from the server
150
16
 
151
- ## 🛠️ Client-Side Tools
152
-
153
- Execute **browser-specific operations** (camera, geolocation, file picker) when LLM requests them.
154
-
155
- ### Server Setup (C#)
17
+ This client assumes a backend that maps PlayFramework under a base path such as:
156
18
 
157
19
  ```csharp
158
- services.AddPlayFramework(builder =>
20
+ app.MapPlayFramework("default", settings =>
159
21
  {
160
- builder.AddScene("vision", "Analyze user photos", scene =>
161
- {
162
- scene.OnClient(client =>
163
- {
164
- client.AddTool("capturePhoto", "Take photo from camera");
165
- client.AddTool("getCurrentLocation", "Get GPS coordinates");
166
- client.AddTool("selectFiles", "Open file picker");
167
- });
168
- });
22
+ settings.BasePath = "/api/ai";
23
+ settings.EnableConversationEndpoints = true;
24
+ settings.EnableVoiceEndpoints = true;
169
25
  });
170
26
  ```
171
27
 
172
- ### Client Setup (TypeScript)
173
-
174
- ```typescript
175
- import { PlayFrameworkServices, AIContentConverter } from "@rystem/playframework-client";
176
-
177
- const client = PlayFrameworkServices.resolve("default");
178
- const registry = client.getClientRegistry();
179
-
180
- // Register camera tool
181
- registry.register("capturePhoto", async () => {
182
- const content = await AIContentConverter.fromCamera(
183
- { video: { facingMode: "environment" } }, // Rear camera
184
- 1920, 1080
185
- );
186
- return [content];
187
- });
188
-
189
- // Register geolocation tool
190
- registry.register("getCurrentLocation", async () => {
191
- const content = await AIContentConverter.fromGeolocation({ timeout: 10_000 });
192
- return [content];
193
- });
28
+ When you configure the TypeScript client with:
194
29
 
195
- // Register file picker
196
- registry.register("selectFiles", async (args?: { accept?: string }) => {
197
- return new Promise((resolve) => {
198
- const input = document.createElement("input");
199
- input.type = "file";
200
- input.accept = args?.accept || "*/*";
201
- input.onchange = async () => {
202
- const contents = await AIContentConverter.fromMultipleFiles(input.files!);
203
- resolve(contents);
204
- };
205
- input.click();
206
- });
207
- });
30
+ ```text
31
+ http://localhost:5158/api/ai
208
32
  ```
209
33
 
210
- **Client automatically resumes execution after tool completion!**
34
+ the library appends `/{factoryName}` itself.
211
35
 
212
- ```typescript
213
- for await (const step of client.executeStepByStep({ message: "Take a photo and describe it" })) {
214
- console.log(step.status);
215
- // 1. "executingScene" - LLM requests camera
216
- // 2. "awaitingClient" - Client executes tool
217
- // 3. "executingScene" - LLM analyzes photo
218
- // 4. "completed" - Final response
219
- }
220
- ```
221
-
222
- ### AIContentConverter Helpers
223
-
224
- ```typescript
225
- // Camera (returns Base64 JPEG)
226
- const photo = await AIContentConverter.fromCamera();
36
+ So for the `default` factory it calls:
227
37
 
228
- // Geolocation (returns JSON with lat/lng)
229
- const location = await AIContentConverter.fromGeolocation();
38
+ - `POST http://localhost:5158/api/ai/default`
39
+ - `POST http://localhost:5158/api/ai/default/streaming`
40
+ - `GET http://localhost:5158/api/ai/default/discovery`
41
+ - `GET http://localhost:5158/api/ai/default/conversations`
42
+ - `POST http://localhost:5158/api/ai/default/voice`
230
43
 
231
- // File upload (returns Base64 data)
232
- const file = await AIContentConverter.fromFile(fileInput.files[0]);
44
+ ## Architecture
233
45
 
234
- // Multiple files
235
- const files = await AIContentConverter.fromMultipleFiles(fileInput.files);
46
+ The package is built around:
236
47
 
237
- // Microphone (returns Base64 audio)
238
- const audio = await AIContentConverter.fromMicrophone(5000); // 5 seconds
48
+ - `PlayFrameworkServices`
49
+ - `PlayFrameworkClient`
50
+ - `ClientInteractionRegistry`
51
+ - `AIContentConverter`
52
+ - `ContentUrlConverter`
53
+ - `VoiceRecorder`
54
+ - `BrowserVoiceClient`
55
+ - `usePlayFramework`
239
56
 
240
- // Plain text
241
- const text = AIContentConverter.fromText("Hello world");
242
- ```
57
+ The usual lifecycle is:
243
58
 
244
- ---
59
+ 1. configure one or more client factories with `PlayFrameworkServices.configure(...)`
60
+ 2. resolve a `PlayFrameworkClient`
61
+ 3. call `executeStepByStep(...)` or `executeTokenStreaming(...)`
62
+ 4. optionally register browser-side tools through `getClientRegistry()`
63
+ 5. optionally use conversation or voice helpers
245
64
 
246
- ## 🎛️ Execution Modes
65
+ ## Example: bootstrap one client
247
66
 
248
- Control **how scenes are selected and executed**:
67
+ `PlayFrameworkServices.configure(...)` is async and should usually run during application startup.
249
68
 
250
69
  ```typescript
251
- import { PlayFrameworkRequest } from "@rystem/playframework-client";
252
-
253
- const request: PlayFrameworkRequest = {
254
- message: "Book a flight to Paris",
255
- settings: {
256
- executionMode: "Planning", // Direct | Planning | DynamicChaining | Scene
257
- maxRecursionDepth: 5,
258
- enableSummarization: true,
259
- enableDirector: false
260
- }
261
- };
262
- ```
70
+ import { PlayFrameworkServices } from "rystem.playframework.client";
263
71
 
264
- ### Available Modes
265
-
266
- | Mode | Description | Use Case |
267
- |------|-------------|----------|
268
- | `Direct` | Single scene, no planning | Simple queries, fast responses |
269
- | `Planning` | Upfront multi-step plan | Known workflows (booking, checkout) |
270
- | `DynamicChaining` | LLM decides next step live | Exploratory tasks (research, debugging) |
271
- | `Scene` | Execute specific scene by name | Resuming after client interaction |
272
-
273
- ---
274
-
275
- ## 📸 Multi-Modal Content
276
-
277
- Send **images, audio, video, PDFs, URIs** with your request:
278
-
279
- ```typescript
280
- import { PlayFrameworkRequest, ContentItem } from "@rystem/playframework-client";
281
-
282
- const request: PlayFrameworkRequest = {
283
- message: "Describe this image and summarize the PDF",
284
- contents: [
285
- {
286
- type: "image",
287
- data: "iVBORw0KGgoAAAANSUhEUgAA...",
288
- mediaType: "image/png"
289
- },
290
- {
291
- type: "data",
292
- data: "JVBERi0xLjQKJeLjz9M...",
293
- mediaType: "application/pdf"
294
- },
295
- {
296
- type: "uri",
297
- uri: "https://example.com/document.pdf",
298
- mediaType: "application/pdf"
299
- },
300
- {
301
- type: "text",
302
- text: "Additional context"
303
- }
304
- ]
305
- };
306
-
307
- for await (const step of client.executeStepByStep(request)) {
308
- console.log(step.message);
309
- }
310
- ```
72
+ await PlayFrameworkServices.configure("default", "http://localhost:5158/api/ai", async settings => {
73
+ settings.timeout = 120_000;
74
+ settings.maxReconnectAttempts = 3;
75
+ settings.reconnectBaseDelay = 1000;
311
76
 
312
- ---
313
-
314
- ## ⚙️ Configuration & Settings
315
-
316
- ### Global Configuration
317
-
318
- ```typescript
319
- import { PlayFrameworkServices } from "@rystem/playframework-client";
320
-
321
- await PlayFrameworkServices.configure("premium", "https://api.example.com/api/ai", settings => {
322
- // Timeout (ms)
323
- settings.timeout = 120_000; // 2 minutes
324
-
325
- // Reconnection on SSE failures
326
- settings.maxReconnectAttempts = 3;
327
- settings.reconnectBaseDelay = 1000; // 1 second
328
-
329
- // Default headers
330
- settings.defaultHeaders = {
331
- "Content-Type": "application/json",
332
- "X-App-Version": "1.0.0"
77
+ settings.addHeadersEnricher(async (_url, _method, headers) => {
78
+ return {
79
+ ...Object.fromEntries(new Headers(headers).entries()),
80
+ Authorization: `Bearer ${localStorage.getItem("token") ?? ""}`
333
81
  };
82
+ });
334
83
 
335
- // Dynamic headers (auth token)
336
- settings.addHeadersEnricher(async (url, method, headers, body) => {
337
- const token = await getAuthToken();
338
- return {
339
- ...headers,
340
- "Authorization": `Bearer ${token}`
341
- };
342
- });
343
-
344
- // Error handling with retry
345
- settings.addErrorHandler(async (url, method, headers, body, error) => {
346
- if (error.message.includes("401")) {
347
- await refreshAuthToken();
348
- return true; // Retry
349
- }
350
- return false; // Don't retry
351
- });
352
- });
353
- ```
354
-
355
- ### Per-Request Settings
356
-
357
- ```typescript
358
- const request: PlayFrameworkRequest = {
359
- message: "Your query",
360
- settings: {
361
- // Execution mode
362
- executionMode: "Planning", // Direct | Planning | DynamicChaining | Scene
363
-
364
- // Planning settings
365
- maxRecursionDepth: 5, // Max planning depth
366
- maxDynamicScenes: 10, // Max scenes in DynamicChaining
367
-
368
- // Features
369
- enableSummarization: true, // Auto-summarize long contexts
370
- enableDirector: false, // Multi-scene orchestration
371
- enableStreaming: true, // Token-level streaming
372
-
373
- // Model overrides
374
- modelId: "gpt-4o", // Override default model
375
- temperature: 0.7, // 0.0 - 2.0
376
- maxTokens: 4096, // Max response tokens
377
-
378
- // Caching
379
- cacheBehavior: "Default", // Default | Avoidable | Forever
380
- conversationKey: "user-123-session-1", // Unique conversation ID
381
-
382
- // Budget
383
- maxBudget: 0.50, // Max cost in USD (null = unlimited)
384
-
385
- // Scene selection (Scene mode only)
386
- sceneName: "SpecificScene" // Execute specific scene
387
- },
388
- metadata: {
389
- userId: "user-123",
390
- sessionId: "session-abc",
391
- customKey: "customValue"
84
+ settings.addErrorHandler(async (_url, _method, _headers, _body, error) => {
85
+ if (error instanceof Error && error.message.includes("401")) {
86
+ localStorage.removeItem("token");
392
87
  }
393
- };
394
- ```
395
-
396
- ---
397
-
398
- ## 🔄 Conversation State & Caching
399
-
400
- Use `conversationKey` to maintain **multi-turn conversations**:
401
-
402
- ```typescript
403
- const conversationKey = crypto.randomUUID();
404
-
405
- // First request
406
- for await (const step of client.executeStepByStep({
407
- message: "What's the weather in Paris?",
408
- settings: { conversationKey }
409
- })) {
410
- console.log(step.message);
411
- }
412
-
413
- // Follow-up request (uses cached context)
414
- for await (const step of client.executeStepByStep({
415
- message: "And in London?",
416
- settings: { conversationKey }
417
- })) {
418
- console.log(step.message); // LLM remembers Paris context
419
- }
420
- ```
421
-
422
- ---
423
-
424
- ## 💾 Conversation Management (Repository Pattern)
425
-
426
- If the backend has **Repository persistence enabled**, you can manage conversations using REST endpoints.
427
-
428
- ### List Conversations
429
-
430
- ```typescript
431
- import { ConversationSortOrder } from "@rystem/playframework-client";
432
-
433
- // Get conversations with filters
434
- const conversations = await client.listConversations({
435
- searchText: "weather", // Search in message text
436
- includePublic: true, // Include public conversations
437
- includePrivate: true, // Include private conversations
438
- orderBy: ConversationSortOrder.TimestampDescending, // Sort by newest first
439
- skip: 0, // Pagination offset
440
- take: 50 // Page size
88
+ return false;
89
+ });
441
90
  });
442
91
 
443
- console.log(conversations);
444
- // [
445
- // {
446
- // conversationKey: "abc-123",
447
- // userId: "user@example.com",
448
- // isPublic: false,
449
- // timestamp: "2025-01-15T10:30:00Z",
450
- // messages: [...],
451
- // executionState: {...}
452
- // }
453
- // ]
454
- ```
455
-
456
- ### Get Single Conversation
457
-
458
- ```typescript
459
- const conversation = await client.getConversation("abc-123");
460
-
461
- if (conversation) {
462
- console.log(conversation.messages); // Full message history
463
- console.log(conversation.isPublic); // Public vs private
464
- } else {
465
- console.log("Conversation not found or unauthorized");
466
- }
92
+ const client = PlayFrameworkServices.resolve("default");
467
93
  ```
468
94
 
469
- **Authorization**: Private conversations require userId match (set via backend `IAuthorizationLayer`).
470
-
471
- ### Delete Conversation
95
+ If you only configure one factory, `resolve()` with no name returns the first configured client:
472
96
 
473
97
  ```typescript
474
- // Owner-only operation
475
- await client.deleteConversation("abc-123");
476
- console.log("Conversation deleted");
98
+ const defaultClient = PlayFrameworkServices.resolve();
477
99
  ```
478
100
 
479
- **Response:**
480
- - ✅ Success - Conversation deleted
481
- - ❌ `403 Forbidden` - Not the owner
482
- - ❌ `404 Not Found` - Conversation not found
101
+ ## Example: configure multiple factories
483
102
 
484
- ### Update Visibility (Public/Private)
103
+ The sample workspace in `src/AI/Rystem.PlayFramework.Client/src/App.tsx` configures both `default` and `foundry` against the same base path.
485
104
 
486
105
  ```typescript
487
- // Toggle conversation visibility (owner-only)
488
- const updated = await client.updateConversationVisibility("abc-123", true);
489
- console.log(`Conversation is now ${updated.isPublic ? "public" : "private"}`);
490
- ```
491
-
492
- ### React Example: Conversation List UI
493
-
494
- ```tsx
495
- import { useState, useEffect } from "react";
496
- import { usePlayFramework, StoredConversation, ConversationSortOrder } from "@rystem/playframework-client";
497
-
498
- function ConversationList() {
499
- const client = usePlayFramework("default");
500
- const [conversations, setConversations] = useState<StoredConversation[]>([]);
501
- const [searchText, setSearchText] = useState("");
502
- const [showPublic, setShowPublic] = useState(true);
503
- const [showPrivate, setShowPrivate] = useState(true);
504
- const [loading, setLoading] = useState(false);
505
-
506
- const loadConversations = async () => {
507
- setLoading(true);
508
- try {
509
- const result = await client.listConversations({
510
- searchText: searchText || undefined,
511
- includePublic: showPublic,
512
- includePrivate: showPrivate,
513
- orderBy: ConversationSortOrder.TimestampDescending,
514
- take: 100
515
- });
516
- setConversations(result);
517
- } catch (error) {
518
- console.error("Failed to load conversations:", error);
519
- } finally {
520
- setLoading(false);
521
- }
522
- };
523
-
524
- useEffect(() => {
525
- loadConversations();
526
- }, [showPublic, showPrivate]);
527
-
528
- const handleDelete = async (key: string) => {
529
- if (!window.confirm("Delete this conversation?")) return;
530
- try {
531
- await client.deleteConversation(key);
532
- await loadConversations(); // Reload list
533
- } catch (error: any) {
534
- alert(`Failed to delete: ${error.message}`);
535
- }
536
- };
537
-
538
- const handleLoadConversation = async (key: string) => {
539
- const conv = await client.getConversation(key);
540
- if (conv) {
541
- // Load conversation into chat UI
542
- console.log("Loaded:", conv.messages);
543
- }
544
- };
106
+ await Promise.all([
107
+ PlayFrameworkServices.configure("default", "http://localhost:5158/api/ai", settings => {
108
+ settings.timeout = 120_000;
109
+ }),
110
+ PlayFrameworkServices.configure("foundry", "http://localhost:5158/api/ai", settings => {
111
+ settings.timeout = 120_000;
112
+ })
113
+ ]);
545
114
 
546
- return (
547
- <div>
548
- <h2>Conversations</h2>
549
-
550
- {/* Search & Filters */}
551
- <input
552
- type="text"
553
- placeholder="Search messages..."
554
- value={searchText}
555
- onChange={e => setSearchText(e.target.value)}
556
- />
557
- <button onClick={loadConversations}>Search</button>
558
-
559
- <label>
560
- <input
561
- type="checkbox"
562
- checked={showPublic}
563
- onChange={e => setShowPublic(e.target.checked)}
564
- />
565
- Public
566
- </label>
567
- <label>
568
- <input
569
- type="checkbox"
570
- checked={showPrivate}
571
- onChange={e => setShowPrivate(e.target.checked)}
572
- />
573
- Private
574
- </label>
575
-
576
- {/* Conversation List */}
577
- {loading ? (
578
- <div>Loading...</div>
579
- ) : (
580
- <ul>
581
- {conversations.map(conv => (
582
- <li key={conv.conversationKey}>
583
- <div onClick={() => handleLoadConversation(conv.conversationKey)}>
584
- <strong>{new Date(conv.timestamp).toLocaleString()}</strong>
585
- <span style={{ color: conv.isPublic ? "green" : "red" }}>
586
- {conv.isPublic ? "Public" : "Private"}
587
- </span>
588
- <p>{conv.messages[0]?.text || "Empty conversation"}</p>
589
- <small>{conv.messages.length} messages</small>
590
- </div>
591
- <button onClick={() => handleDelete(conv.conversationKey)}>Delete</button>
592
- </li>
593
- ))}
594
- </ul>
595
- )}
596
- </div>
597
- );
598
- }
115
+ const cloudClient = PlayFrameworkServices.resolve("default");
116
+ const localClient = PlayFrameworkServices.resolve("foundry");
599
117
  ```
600
118
 
601
- ### Backend Setup Required
602
-
603
- For conversation management to work, the backend must:
604
-
605
- 1. **Enable Repository persistence:**
606
- ```csharp
607
- builder.Services.AddPlayFramework("default", pb => pb
608
- .UseRepository());
609
- ```
610
-
611
- 2. **Enable conversation endpoints:**
612
- ```csharp
613
- app.MapPlayFramework("default", settings =>
614
- {
615
- settings.EnableConversationEndpoints = true;
616
- });
617
- ```
618
-
619
- See [Backend README](../../../README.md) for full setup guide.
620
-
621
- ---
622
-
623
- ## 🔄 Combining Stored Conversations with Live Streaming
119
+ This is useful when the backend exposes multiple PlayFramework factories with different scenes or model providers.
624
120
 
625
- This section shows how to **load historic messages** from `StoredConversation` and **continue the conversation** with live SSE streaming.
121
+ ## Example: load scenes and tool metadata from the server
626
122
 
627
- ### Understanding the Two Models
628
-
629
- PlayFramework uses **two different models** for different purposes:
630
-
631
- | Model | Purpose | When | Format | Content |
632
- |-------|---------|------|--------|---------|
633
- | **`AiSceneResponse`** | Real-time execution tracking | During `executeStepByStep()` / `executeTokenStreaming()` | SSE (Server-Sent Events) | Status updates, streaming chunks, scene metadata |
634
- | **`StoredConversation`** | Persistent conversation history | When loading from repository via REST API | JSON | Complete messages, user metadata, execution state |
635
-
636
- **Why two models?**
637
- - `AiSceneResponse` contains **temporary execution metadata** (status, sceneName, functionName) needed for real-time UI updates
638
- - `StoredConversation` contains **only essential data** (messages, userId, timestamp) for efficient storage and querying
639
-
640
- ### Complete Example: Chat with History
641
-
642
- ```tsx
643
- import React, { useState, useEffect } from 'react';
644
- import { usePlayFramework, StoredConversation, AiSceneResponse } from '@rystem/playframework-client';
645
-
646
- interface ChatMessage {
647
- role: 'user' | 'assistant';
648
- text: string;
649
- isStreaming?: boolean; // Distinguishes streaming vs historic messages
650
- status?: string; // For showing execution status
651
- }
123
+ Use `getDiscovery()` when the frontend needs to know which scenes, DI tools, client tools, or MCP tools are currently available for a factory.
652
124
 
653
- function ChatWithHistory() {
654
- const client = usePlayFramework('default');
655
-
656
- // State
657
- const [messages, setMessages] = useState<ChatMessage[]>([]);
658
- const [input, setInput] = useState('');
659
- const [conversationKey, setConversationKey] = useState<string | null>(null);
660
- const [loading, setLoading] = useState(false);
661
-
662
- // 📥 LOAD: Load historic conversation from repository
663
- const loadConversation = async (key: string) => {
664
- try {
665
- // Fetch from REST API → StoredConversation
666
- const stored = await client.getConversation(key);
667
-
668
- if (!stored) {
669
- alert('Conversation not found or unauthorized');
670
- return;
671
- }
672
-
673
- // Convert StoredMessage[] → ChatMessage[]
674
- const historicMessages: ChatMessage[] = stored.messages.map(msg => ({
675
- role: msg.role as 'user' | 'assistant',
676
- text: msg.text || '',
677
- isStreaming: false // Historic messages are complete
678
- }));
679
-
680
- setMessages(historicMessages);
681
- setConversationKey(stored.conversationKey);
682
-
683
- console.log(`✅ Loaded ${stored.messages.length} messages from conversation ${key}`);
684
- } catch (error) {
685
- console.error('Failed to load conversation:', error);
686
- alert(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);
687
- }
688
- };
125
+ ```typescript
126
+ const metadata = await client.getDiscovery();
689
127
 
690
- // 📤 SEND: Send message and stream response
691
- const sendMessage = async () => {
692
- if (!input.trim() || loading) return;
693
-
694
- const userMessage = input;
695
- setInput('');
696
- setLoading(true);
697
-
698
- // Add user message to UI
699
- const userMsg: ChatMessage = { role: 'user', text: userMessage };
700
- setMessages(prev => [...prev, userMsg]);
701
-
702
- // Add placeholder for assistant response
703
- const assistantMsg: ChatMessage = {
704
- role: 'assistant',
705
- text: '',
706
- isStreaming: true, // Flag: currently streaming
707
- status: 'initializing'
708
- };
709
- setMessages(prev => [...prev, assistantMsg]);
710
-
711
- try {
712
- // 🔄 Stream from PlayFramework → AiSceneResponse events
713
- for await (const step of client.executeStepByStep({
714
- message: userMessage,
715
- settings: {
716
- conversationKey: conversationKey || undefined, // Resume existing or start new
717
- enableStreaming: true
718
- }
719
- })) {
720
- // Update conversationKey from first response
721
- if (step.conversationKey && !conversationKey) {
722
- setConversationKey(step.conversationKey);
723
- }
724
-
725
- // Update message with streaming chunks
726
- if (step.streamingChunk) {
727
- setMessages(prev => {
728
- const updated = [...prev];
729
- const last = updated[updated.length - 1];
730
- last.text += step.streamingChunk;
731
- last.status = step.status;
732
- return updated;
733
- });
734
- }
735
-
736
- // Update status (planning, executingScene, etc.)
737
- else if (step.status) {
738
- setMessages(prev => {
739
- const updated = [...prev];
740
- const last = updated[updated.length - 1];
741
- last.status = step.status;
742
- return updated;
743
- });
744
- }
745
- }
746
-
747
- // Mark streaming as complete
748
- setMessages(prev => {
749
- const updated = [...prev];
750
- const last = updated[updated.length - 1];
751
- last.isStreaming = false;
752
- delete last.status;
753
- return updated;
754
- });
755
-
756
- } catch (error) {
757
- console.error('Streaming error:', error);
758
- setMessages(prev => {
759
- const updated = [...prev];
760
- updated[updated.length - 1] = {
761
- role: 'assistant',
762
- text: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`,
763
- isStreaming: false,
764
- status: 'error'
765
- };
766
- return updated;
767
- });
768
- } finally {
769
- setLoading(false);
770
- }
771
- };
128
+ for (const scene of metadata.scenes ?? []) {
129
+ console.log(scene.name, scene.description);
772
130
 
773
- // 🗑️ CLEAR: Start new conversation
774
- const clearConversation = () => {
775
- setMessages([]);
776
- setConversationKey(null);
777
- };
778
-
779
- return (
780
- <div style={{ maxWidth: '900px', margin: '0 auto', padding: '20px', fontFamily: 'sans-serif' }}>
781
- <h1>💬 PlayFramework Chat</h1>
782
-
783
- {/* Conversation Info */}
784
- <div style={{
785
- padding: '10px',
786
- marginBottom: '10px',
787
- backgroundColor: '#f0f0f0',
788
- borderRadius: '8px',
789
- display: 'flex',
790
- justifyContent: 'space-between',
791
- alignItems: 'center'
792
- }}>
793
- <div>
794
- {conversationKey ? (
795
- <>
796
- <strong>Conversation:</strong> {conversationKey.substring(0, 8)}...
797
- <span style={{ marginLeft: '10px', color: '#666' }}>
798
- ({messages.length} messages)
799
- </span>
800
- </>
801
- ) : (
802
- <span style={{ color: '#999' }}>New conversation</span>
803
- )}
804
- </div>
805
- <button
806
- onClick={clearConversation}
807
- style={{
808
- padding: '5px 15px',
809
- borderRadius: '6px',
810
- border: '1px solid #ccc',
811
- backgroundColor: '#fff',
812
- cursor: 'pointer'
813
- }}
814
- >
815
- Clear
816
- </button>
817
- </div>
818
-
819
- {/* Messages */}
820
- <div style={{
821
- height: '500px',
822
- overflowY: 'auto',
823
- border: '1px solid #ddd',
824
- borderRadius: '8px',
825
- padding: '15px',
826
- marginBottom: '15px',
827
- backgroundColor: '#fafafa'
828
- }}>
829
- {messages.length === 0 ? (
830
- <div style={{ textAlign: 'center', color: '#999', marginTop: '50px' }}>
831
- <p>No messages yet. Start a conversation or load an existing one.</p>
832
- <button
833
- onClick={() => loadConversation('some-conversation-key')}
834
- style={{
835
- padding: '8px 16px',
836
- borderRadius: '6px',
837
- border: '1px solid #61dafb',
838
- backgroundColor: '#61dafb',
839
- color: '#fff',
840
- cursor: 'pointer',
841
- marginTop: '10px'
842
- }}
843
- >
844
- Load Example Conversation
845
- </button>
846
- </div>
847
- ) : (
848
- messages.map((msg, i) => (
849
- <div
850
- key={i}
851
- style={{
852
- padding: '12px',
853
- margin: '8px 0',
854
- borderRadius: '12px',
855
- backgroundColor: msg.role === 'user' ? '#e3f2fd' : '#fff',
856
- border: msg.role === 'assistant' ? '1px solid #e0e0e0' : 'none',
857
- maxWidth: '85%',
858
- marginLeft: msg.role === 'user' ? 'auto' : '0',
859
- marginRight: msg.role === 'user' ? '0' : 'auto',
860
- }}
861
- >
862
- <div style={{
863
- display: 'flex',
864
- justifyContent: 'space-between',
865
- marginBottom: '6px',
866
- fontSize: '12px',
867
- color: '#666'
868
- }}>
869
- <strong style={{ color: msg.role === 'user' ? '#1976d2' : '#388e3c' }}>
870
- {msg.role === 'user' ? '👤 You' : '🤖 AI'}
871
- </strong>
872
-
873
- {/* Show streaming indicator or status */}
874
- {msg.isStreaming && (
875
- <span style={{
876
- color: '#ff6b6b',
877
- fontStyle: 'italic',
878
- fontSize: '11px'
879
- }}>
880
- {msg.status || 'streaming'} ●
881
- </span>
882
- )}
883
- </div>
884
-
885
- <div style={{
886
- whiteSpace: 'pre-wrap',
887
- wordBreak: 'break-word',
888
- lineHeight: '1.5'
889
- }}>
890
- {msg.text || '...'}
891
- </div>
892
- </div>
893
- ))
894
- )}
895
- </div>
896
-
897
- {/* Input */}
898
- <div style={{ display: 'flex', gap: '10px' }}>
899
- <input
900
- type="text"
901
- value={input}
902
- onChange={e => setInput(e.target.value)}
903
- onKeyDown={e => e.key === 'Enter' && !loading && sendMessage()}
904
- placeholder={loading ? 'AI is responding...' : 'Type your message...'}
905
- disabled={loading}
906
- style={{
907
- flex: 1,
908
- padding: '12px 16px',
909
- fontSize: '15px',
910
- borderRadius: '8px',
911
- border: '1px solid #ddd',
912
- outline: 'none'
913
- }}
914
- />
915
- <button
916
- onClick={sendMessage}
917
- disabled={loading || !input.trim()}
918
- style={{
919
- padding: '12px 24px',
920
- fontSize: '15px',
921
- borderRadius: '8px',
922
- border: 'none',
923
- backgroundColor: loading ? '#ccc' : '#61dafb',
924
- color: loading ? '#666' : '#fff',
925
- cursor: loading ? 'not-allowed' : 'pointer',
926
- fontWeight: 600
927
- }}
928
- >
929
- {loading ? 'Sending...' : 'Send'}
930
- </button>
931
- </div>
932
-
933
- {/* Helper Text */}
934
- <div style={{
935
- marginTop: '15px',
936
- fontSize: '13px',
937
- color: '#666',
938
- textAlign: 'center'
939
- }}>
940
- 💡 Messages are automatically saved to the repository when backend persistence is enabled.
941
- <br />
942
- Use the conversation list to browse and load previous conversations.
943
- </div>
944
- </div>
945
- );
131
+ for (const tool of scene.tools ?? []) {
132
+ console.log(tool.toolName, tool.sourceType, tool.sourceName, tool.memberName);
133
+ }
946
134
  }
947
-
948
- export default ChatWithHistory;
949
135
  ```
950
136
 
951
- ### Key Features Demonstrated
952
-
953
- ✅ **Load Historic Messages**: Converts `StoredMessage[]` → `ChatMessage[]`
954
- ✅ **Continue Conversation**: Uses same `conversationKey` to resume context
955
- ✅ **Real-Time Streaming**: Updates UI with `AiSceneResponse` chunks
956
- ✅ **Status Indicators**: Shows execution status during streaming
957
- ✅ **Seamless UX**: Historic + streaming messages in same UI
137
+ This calls:
958
138
 
959
- ### Flow Diagram
960
-
961
- ```
962
- 1. User clicks "Load Conversation"
963
- ↓
964
- 2. GET /api/ai/default/conversations/{key}
965
- ↓
966
- 3. Receives StoredConversation (REST JSON)
967
- ├─ messages: StoredMessage[]
968
- ├─ conversationKey: "abc-123"
969
- └─ timestamp, userId, isPublic
970
- ↓
971
- 4. Convert to ChatMessage[] and display
972
- ↓
973
- 5. User types new message
974
- ↓
975
- 6. POST /api/ai/default (SSE streaming)
976
- settings: { conversationKey: "abc-123" }
977
- ↓
978
- 7. Receives AiSceneResponse events (SSE)
979
- ├─ status: "planning" → "executingScene" → "streaming"
980
- ├─ streamingChunk: "Hello", " world", "!"
981
- └─ conversationKey: "abc-123" (same as before)
982
- ↓
983
- 8. Backend loads context from cache/repository
984
- ↓
985
- 9. LLM generates response using historic context
986
- ↓
987
- 10. Response streamed to UI in real-time
988
- ↓
989
- 11. Backend saves new messages to repository
990
- ↓
991
- 12. Conversation continues seamlessly
139
+ ```text
140
+ GET {baseUrl}/{factoryName}/discovery
992
141
  ```
993
142
 
994
- ### Best Practices
995
-
996
- 1. **Separate concerns**: Use `StoredMessage` for storage, `AiSceneResponse` for streaming
997
- 2. **Flag streaming state**: Add `isStreaming` flag to distinguish live vs historic
998
- 3. **Show status**: Display execution status (`planning`, `executingScene`) during streaming
999
- 4. **Handle errors**: Wrap streaming in try-catch and show error messages
1000
- 5. **Auto-save**: Backend automatically persists conversations when repository is enabled
143
+ Typical uses:
1001
144
 
1002
- ---
145
+ - populate a scene dropdown with the normalized names expected by `settings.sceneName`
146
+ - show which tools come from DI services, client interactions, or MCP servers
147
+ - build `forcedTools` values without hardcoding service or MCP metadata in the frontend
1003
148
 
1004
- ## 📸 Multi-Modal Content (Images, Audio, Video, PDFs)
149
+ ## Example: step-by-step streaming
1005
150
 
1006
- PlayFramework supports **base64-encoded media content** in messages. The client provides helper utilities to convert Base64 data to Blob URLs for browser display.
1007
-
1008
- ### ContentUrlConverter Helper
1009
-
1010
- Converts `AIContent` (base64 data) to Blob URLs that can be used in HTML `<img>`, `<audio>`, `<video>`, and `<iframe>` elements.
151
+ `executeStepByStep(...)` yields full `AiSceneResponse` events as the backend progresses through planning, scene execution, tool calls, and final output.
1011
152
 
1012
153
  ```typescript
1013
- import { ContentUrlConverter, AIContent } from "@rystem/playframework-client";
154
+ import type { PlayFrameworkRequest } from "rystem.playframework.client";
1014
155
 
1015
- const content: AIContent = {
1016
- type: "data",
1017
- data: "iVBORw0KGgoAAAANSUhEUgAA...", // Base64 JPEG
1018
- mediaType: "image/jpeg"
156
+ const request: PlayFrameworkRequest = {
157
+ message: "Calculate 12 * 7",
158
+ metadata: {
159
+ userId: "user-42",
160
+ tenantId: "tenant-a"
161
+ },
162
+ settings: {
163
+ executionMode: "Scene",
164
+ sceneName: "Calculator"
165
+ }
1019
166
  };
1020
167
 
1021
- // Convert to Blob URL
1022
- const url = ContentUrlConverter.toBlobUrl(content);
1023
-
1024
- // Use in <img> tag
1025
- <img src={url} alt="Image" />
1026
-
1027
- // IMPORTANT: Cleanup when done (frees memory!)
1028
- ContentUrlConverter.revokeUrl(url);
1029
- ```
1030
-
1031
- ### API Methods
1032
-
1033
- #### `toBlob(content: AIContent): Blob | null`
1034
- Decodes Base64 string to Blob object.
168
+ for await (const step of client.executeStepByStep(request)) {
169
+ console.log(step.status, step.sceneName, step.message);
1035
170
 
1036
- ```typescript
1037
- const blob = ContentUrlConverter.toBlob(content);
171
+ if (step.totalTokens != null || step.totalCost != null) {
172
+ console.log("usage", step.totalTokens, step.totalCost);
173
+ }
174
+ }
1038
175
  ```
1039
176
 
1040
- #### `toBlobUrl(content: AIContent, cacheKey?: string): string | null`
1041
- Creates `blob:` URL for browser display. Supports optional caching.
177
+ This calls:
1042
178
 
1043
- ```typescript
1044
- const url = ContentUrlConverter.toBlobUrl(content, 'image-123');
179
+ ```text
180
+ POST {baseUrl}/{factoryName}
1045
181
  ```
1046
182
 
1047
- #### `revokeUrl(url: string, cacheKey?: string): void`
1048
- Revokes Blob URL to free memory. **Always call this when done!**
183
+ Common yielded statuses include:
1049
184
 
1050
- ```typescript
1051
- ContentUrlConverter.revokeUrl(url, 'image-123');
1052
- ```
185
+ - `initializing`
186
+ - `planning`
187
+ - `executingScene`
188
+ - `functionRequest`
189
+ - `functionCompleted`
190
+ - `running`
191
+ - `awaitingClient`
192
+ - `commandClient`
1053
193
 
1054
- #### `clearCache(): void`
1055
- Revokes all cached URLs at once.
194
+ Completion and error markers are handled internally by the client runtime rather than surfaced as normal yielded events.
1056
195
 
1057
- ```typescript
1058
- ContentUrlConverter.clearCache();
1059
- ```
196
+ ## Example: token streaming
1060
197
 
1061
- #### `downloadAsFile(content: AIContent, filename?: string): void`
1062
- Triggers browser download.
198
+ `executeTokenStreaming(...)` still yields `AiSceneResponse` objects, but the text arrives through `streamingChunk`.
1063
199
 
1064
200
  ```typescript
1065
- ContentUrlConverter.downloadAsFile(content, 'image.jpg');
1066
- ```
201
+ let finalText = "";
1067
202
 
1068
- #### `getFileExtension(mediaType?: string): string`
1069
- Maps MIME type to file extension.
1070
-
1071
- ```typescript
1072
- const ext = ContentUrlConverter.getFileExtension('image/jpeg'); // ".jpg"
1073
- ```
1074
-
1075
- ---
1076
-
1077
- ### React Example: Image Viewer
1078
-
1079
- ```tsx
1080
- import { useState, useEffect } from 'react';
1081
- import { ContentUrlConverter, AIContent } from "@rystem/playframework-client";
1082
-
1083
- interface ImageViewerProps {
1084
- content: AIContent;
203
+ for await (const chunk of client.executeTokenStreaming({
204
+ message: "Write a short summary of PlayFramework",
205
+ settings: {
206
+ executionMode: "Direct"
207
+ }
208
+ })) {
209
+ if (chunk.streamingChunk) {
210
+ finalText += chunk.streamingChunk;
211
+ console.log(chunk.streamingChunk);
212
+ }
1085
213
  }
1086
214
 
1087
- function ImageViewer({ content }: ImageViewerProps) {
1088
- const [url, setUrl] = useState<string | null>(null);
1089
-
1090
- useEffect(() => {
1091
- // Create Blob URL when component mounts
1092
- const blobUrl = ContentUrlConverter.toBlobUrl(content, `image-${Date.now()}`);
1093
- setUrl(blobUrl);
1094
-
1095
- // Cleanup when component unmounts (important for memory!)
1096
- return () => {
1097
- if (blobUrl) {
1098
- ContentUrlConverter.revokeUrl(blobUrl);
1099
- }
1100
- };
1101
- }, [content]);
1102
-
1103
- if (!url) return <div>Loading image...</div>;
1104
-
1105
- return (
1106
- <div>
1107
- <img src={url} alt="Image" style={{ maxWidth: '100%' }} />
1108
- <button onClick={() => ContentUrlConverter.downloadAsFile(content, 'image.jpg')}>
1109
- Download
1110
- </button>
1111
- </div>
1112
- );
1113
- }
215
+ console.log("final", finalText);
1114
216
  ```
1115
217
 
1116
- ---
1117
-
1118
- ### React Example: Auto-Detection Content Viewer
1119
-
1120
- ```tsx
1121
- import { ContentUrlConverter, AIContent } from "@rystem/playframework-client";
1122
-
1123
- function ContentViewer({ content }: { content: AIContent }) {
1124
- const mediaType = content.mediaType?.toLowerCase() || '';
1125
- const [url, setUrl] = useState<string | null>(null);
218
+ This calls:
1126
219
 
1127
- useEffect(() => {
1128
- const blobUrl = ContentUrlConverter.toBlobUrl(content);
1129
- setUrl(blobUrl);
1130
-
1131
- return () => {
1132
- if (blobUrl) ContentUrlConverter.revokeUrl(blobUrl);
1133
- };
1134
- }, [content]);
1135
-
1136
- if (!url) return <div>Loading...</div>;
1137
-
1138
- // Image
1139
- if (mediaType.startsWith('image/')) {
1140
- return <img src={url} alt="Image" style={{ maxWidth: '100%' }} />;
1141
- }
1142
-
1143
- // Audio
1144
- if (mediaType.startsWith('audio/')) {
1145
- return (
1146
- <audio controls style={{ width: '100%' }}>
1147
- <source src={url} type={mediaType} />
1148
- </audio>
1149
- );
1150
- }
1151
-
1152
- // Video
1153
- if (mediaType.startsWith('video/')) {
1154
- return (
1155
- <video controls style={{ maxWidth: '100%' }}>
1156
- <source src={url} type={mediaType} />
1157
- </video>
1158
- );
1159
- }
1160
-
1161
- // PDF
1162
- if (mediaType === 'application/pdf') {
1163
- return (
1164
- <iframe
1165
- src={url}
1166
- title="PDF Document"
1167
- style={{ width: '100%', height: '600px', border: '1px solid #ddd' }}
1168
- />
1169
- );
1170
- }
1171
-
1172
- // Fallback for unknown types
1173
- return (
1174
- <div>
1175
- <p>📎 Attachment: {content.mediaType || 'unknown type'}</p>
1176
- <button onClick={() => ContentUrlConverter.downloadAsFile(content)}>
1177
- Download File
1178
- </button>
1179
- </div>
1180
- );
1181
- }
220
+ ```text
221
+ POST {baseUrl}/{factoryName}/streaming
1182
222
  ```
1183
223
 
1184
- ---
1185
-
1186
- ### includeContents Parameter
224
+ ## Request model
1187
225
 
1188
- When loading conversations, control whether to fetch base64 content:
226
+ The main request type is `PlayFrameworkRequest`.
1189
227
 
1190
228
  ```typescript
1191
- // ❌ List conversations WITHOUT media (faster, smaller payload)
1192
- const list = await client.listConversations({
1193
- includeContents: false, // Default: false
1194
- take: 50
1195
- });
1196
-
1197
- // ✅ Load single conversation WITH media (for display)
1198
- const conv = await client.getConversation(key, true); // includeContents=true
229
+ const request = {
230
+ message: "Book a flight to Paris",
231
+ metadata: {
232
+ userId: "123",
233
+ tenantId: "tenant-a"
234
+ },
235
+ settings: {
236
+ executionMode: "Planning",
237
+ maxRecursionDepth: 5,
238
+ sceneName: "Travel"
239
+ },
240
+ conversationKey: "conversation-123"
241
+ };
1199
242
  ```
1200
243
 
1201
- **Why this matters:**
1202
-
1203
- | Operation | includeContents | Payload Size | Speed |
1204
- |-----------|----------------|--------------|-------|
1205
- | List 100 conversations | `false` | ~50 KB | ⚡ Fast (~50ms) |
1206
- | List 100 conversations | `true` | ~5-50 MB | 🐢 Slow (~500ms) |
1207
- | Get single conversation | `true` | ~50-500 KB | ✅ Acceptable |
244
+ The `settings` object mirrors the server-side `SceneRequestSettings`, including:
1208
245
 
1209
- **Best Practice**: Always use `includeContents=false` for list operations, `true` only when loading a conversation for display.
246
+ - `executionMode`
247
+ - `sceneName`
248
+ - `forcedTools`
249
+ - `conversationKey`
250
+ - `clientInteractionResults`
251
+ - `enableStreaming`
252
+ - `enableSummarization`
253
+ - `enableDirector`
254
+ - `maxRecursionDepth`
1210
255
 
1211
- ---
256
+ The request can also include `contents` for multi-modal inputs.
1212
257
 
1213
- ### Full Example: Chat with Multi-Modal Support
258
+ ## Example: force specific tools for a selected scene
1214
259
 
1215
- ```tsx
1216
- import { useState, useEffect } from 'react';
1217
- import { usePlayFramework, StoredMessage, AIContent, ContentUrlConverter } from "@rystem/playframework-client";
260
+ The discovery payload returns the exact values you can send back inside `settings.forcedTools`.
1218
261
 
1219
- function ChatWithMedia() {
1220
- const client = usePlayFramework('default');
1221
- const [messages, setMessages] = useState<StoredMessage[]>([]);
1222
- const [conversationKey, setConversationKey] = useState<string | null>(null);
1223
-
1224
- const loadConversation = async (key: string) => {
1225
- // Load conversation WITH contents
1226
- const conv = await client.getConversation(key, true);
1227
-
1228
- if (conv) {
1229
- setMessages(conv.messages);
1230
- setConversationKey(conv.conversationKey);
1231
- }
1232
- };
262
+ ```typescript
263
+ const discovery = await client.getDiscovery();
264
+ const calculatorScene = discovery.scenes?.find(scene => scene.name === "Calculator");
265
+ const addTool = calculatorScene?.tools?.find(tool => tool.toolName === "Add");
266
+ const subtractTool = calculatorScene?.tools?.find(tool => tool.toolName === "Subtract");
1233
267
 
1234
- return (
1235
- <div>
1236
- <h1>Chat with Media Support</h1>
1237
-
1238
- {messages.map((msg, i) => (
1239
- <div key={i} style={{
1240
- backgroundColor: msg.role === 'user' ? '#e3f2fd' : '#fff',
1241
- padding: '12px',
1242
- margin: '8px 0',
1243
- borderRadius: '8px'
1244
- }}>
1245
- <strong>{msg.role === 'user' ? '👤 You' : '🤖 AI'}</strong>
1246
- <p>{msg.text}</p>
1247
-
1248
- {/* Display attached content (images, PDFs, etc.) */}
1249
- {msg.contents && msg.contents.length > 0 && (
1250
- <div style={{ marginTop: '8px' }}>
1251
- {msg.contents.map((content, idx) => (
1252
- <ContentViewer key={idx} content={content} />
1253
- ))}
1254
- </div>
1255
- )}
1256
- </div>
1257
- ))}
1258
-
1259
- <button onClick={() => loadConversation('example-key')}>
1260
- Load Example Conversation
1261
- </button>
1262
- </div>
1263
- );
268
+ for await (const step of client.executeStepByStep({
269
+ message: "Use only add and subtract",
270
+ settings: {
271
+ executionMode: "Scene",
272
+ sceneName: "Calculator",
273
+ forcedTools: [addTool, subtractTool]
274
+ .filter((tool): tool is NonNullable<typeof tool> => Boolean(tool))
275
+ .map(tool => ({
276
+ sceneName: tool.sceneName,
277
+ toolName: tool.toolName,
278
+ sourceType: tool.sourceType,
279
+ sourceName: tool.sourceName,
280
+ memberName: tool.memberName
281
+ }))
282
+ }
283
+ })) {
284
+ console.log(step.status, step.message);
1264
285
  }
1265
286
  ```
1266
287
 
1267
- ---
288
+ Notes:
1268
289
 
1269
- ### Memory Management Best Practices
290
+ - `sceneName` must use the normalized server name from discovery
291
+ - `toolName` must use the normalized tool name from discovery
292
+ - `sourceName` is usually the DI service type name for service tools or the MCP server/factory name for MCP tools
293
+ - `memberName` is usually the service method name or the original MCP tool name
1270
294
 
1271
- 1. **Always cleanup Blob URLs**: Use `useEffect` cleanup function in React
1272
- 2. **Use caching for repeated content**: Pass `cacheKey` parameter
1273
- 3. **Clear cache on unmount**: Call `ContentUrlConverter.clearCache()` when appropriate
1274
- 4. **Lazy load media**: Only convert to Blob URL when needed for display
1275
- 5. **Use includeContents wisely**: Exclude contents from list operations
295
+ ## Example: send files and multi-modal contents
1276
296
 
1277
- **Example cleanup:**
1278
- ```tsx
1279
- useEffect(() => {
1280
- const url = ContentUrlConverter.toBlobUrl(content);
1281
- setImageUrl(url);
1282
-
1283
- // Cleanup when component unmounts
1284
- return () => {
1285
- if (url) ContentUrlConverter.revokeUrl(url);
1286
- };
1287
- }, [content]);
1288
-
1289
- // Clear all on app unmount
1290
- useEffect(() => {
1291
- return () => ContentUrlConverter.clearCache();
1292
- }, []);
1293
- ```
1294
-
1295
- ---
1296
-
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.
1302
-
1303
- ### Browser Support
1304
-
1305
- | Feature | Chrome | Edge | Safari | Firefox |
1306
- |---|---|---|---|---|
1307
- | SpeechRecognition | ✅ | ✅ | ✅ | ❌ |
1308
- | SpeechSynthesis | ✅ | ✅ | ✅ | ✅ |
1309
-
1310
- ### Quick Start
297
+ The request model accepts `ContentItem[]`, while `AIContentConverter` helps you build the base64 payloads in the browser.
1311
298
 
1312
299
  ```typescript
1313
300
  import {
1314
- PlayFrameworkServices,
1315
- BrowserVoiceClient,
1316
- } from "@rystem/playframework-client";
1317
-
1318
- // 1. Configure PlayFramework client
1319
- await PlayFrameworkServices.configure("default", "http://localhost:5158/api/ai");
1320
- const client = PlayFrameworkServices.resolve("default");
301
+ AIContentConverter,
302
+ type ContentItem,
303
+ type PlayFrameworkRequest
304
+ } from "rystem.playframework.client";
1321
305
 
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
- );
306
+ async function buildRequest(file: File): Promise<PlayFrameworkRequest> {
307
+ const converted = await AIContentConverter.fromFile(file);
1328
308
 
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.");
309
+ const contents: ContentItem[] = [
310
+ {
311
+ type: "file",
312
+ data: converted.data,
313
+ mediaType: converted.mediaType,
314
+ name: file.name
1339
315
  }
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
- ```
316
+ ];
1408
317
 
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);
318
+ return {
319
+ message: "Summarize the attached document and extract the risks.",
320
+ contents,
321
+ settings: {
322
+ executionMode: "Planning"
1457
323
  }
324
+ };
1458
325
  }
1459
326
 
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);
1551
- }
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);
1573
- }
1574
- };
327
+ const request = await buildRequest(selectedFile);
1575
328
 
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);
1637
- }
1638
- } catch (error) {
1639
- if (error instanceof DOMException && error.name === "AbortError") {
1640
- console.log("Request cancelled");
1641
- }
329
+ for await (const step of client.executeStepByStep(request)) {
330
+ console.log(step.status, step.message);
1642
331
  }
1643
-
1644
- // Cancel after 5 seconds
1645
- setTimeout(() => controller.abort(), 5000);
1646
332
  ```
1647
333
 
1648
- The same pattern applies to every endpoint:
334
+ Browser helpers available in this package include:
1649
335
 
1650
- ```typescript
1651
- // Token streaming
1652
- client.executeTokenStreaming(request, controller.signal);
336
+ - `AIContentConverter.fromFile(...)`
337
+ - `AIContentConverter.fromMultipleFiles(...)`
338
+ - `AIContentConverter.fromCamera(...)`
339
+ - `AIContentConverter.fromGeolocation(...)`
340
+ - `AIContentConverter.fromMicrophone(...)`
341
+ - `AIContentConverter.fromText(...)`
1653
342
 
1654
- // Server voice pipeline
1655
- client.executeVoice({ audio: blob, signal: controller.signal });
343
+ ## Example: render or download returned contents
1656
344
 
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)
345
+ `AiSceneResponse.contents` can include generated images, audio, or files. `ContentUrlConverter` is the browser-side helper for previewing or downloading them.
1675
346
 
1676
347
  ```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
- })();
348
+ import { ContentUrlConverter } from "rystem.playframework.client";
1688
349
 
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
350
+ for await (const step of client.executeStepByStep({
351
+ message: "Generate an image of a blue robot"
352
+ })) {
353
+ const media = step.contents?.[0];
354
+ if (!media) continue;
1723
355
 
1724
- ```tsx
1725
- function VoiceChat() {
1726
- const voiceRef = useRef<BrowserVoiceClient>(null);
1727
- const [messages, setMessages] = useState<string[]>([]);
356
+ const url = ContentUrlConverter.toBlobUrl(media, `response-${Date.now()}`);
357
+ if (url) {
358
+ console.log("preview", url);
359
+ }
1728
360
 
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
- );
361
+ ContentUrlConverter.downloadAsFile(media, "playframework-output");
1750
362
  }
1751
363
  ```
1752
364
 
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:
365
+ Remember to revoke blob URLs you keep around:
1757
366
 
1758
367
  ```typescript
1759
- const settings: PlayFrameworkSettings = {
1760
- baseUrl: '/api/play',
1761
- factoryName: 'assistant',
1762
- timeout: 30000, // 30-second timeout for ALL requests
1763
- // ...
1764
- };
368
+ ContentUrlConverter.revokeUrl(url, cacheKey);
1765
369
  ```
1766
370
 
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.
371
+ ## Example: client-side tools and commands
1769
372
 
1770
- ---
373
+ When the server emits `awaitingClient` or `commandClient`, the library can execute browser-side tools locally and resume automatically.
1771
374
 
1772
- ## 📊 Response Status Types
375
+ This is the same pattern used by the sample app in `src/AI/Rystem.PlayFramework.Client/src/App.tsx`.
1773
376
 
1774
377
  ```typescript
1775
- type AiResponseStatus =
1776
- | "initializing" // Starting execution
1777
- | "loadingCache" // Loading cached conversation context
1778
- | "executingMainActors" // Running global system prompts
1779
- | "planning" // Creating execution plan
1780
- | "executingScene" // Running scene/actor
1781
- | "functionRequest" // Calling server-side tool
1782
- | "functionCompleted" // Tool call completed
1783
- | "toolSkipped" // Tool was skipped
1784
- | "streaming" // Streaming text chunks
1785
- | "running" // General execution in progress
1786
- | "summarizing" // Summarizing conversation
1787
- | "directorDecision" // Director evaluating results
1788
- | "generatingFinalResponse" // Generating final response
1789
- | "savingCache" // Saving to cache
1790
- | "savingMemory" // Saving conversation memory
1791
- | "awaitingClient" // Waiting for client-side tool response
1792
- | "commandClient" // Fire-and-forget command sent to client
1793
- | "completed" // Success
1794
- | "budgetExceeded" // Max cost exceeded
1795
- | "error" // Failure
1796
- | "unauthorized"; // Authorization failed
1797
- ```
1798
-
1799
- ---
1800
-
1801
- ## 🧪 Testing
1802
-
1803
- ```typescript
1804
- import { PlayFrameworkClient, PlayFrameworkSettings } from "@rystem/playframework-client";
1805
-
1806
- describe("PlayFramework Client", () => {
1807
- it("should stream responses", async () => {
1808
- const settings = new PlayFrameworkSettings("default", "http://localhost:5158/api/ai");
1809
- const client = new PlayFrameworkClient(settings);
1810
-
1811
- const responses: string[] = [];
378
+ import {
379
+ AIContentConverter,
380
+ CommandResultHelper,
381
+ PlayFrameworkServices
382
+ } from "rystem.playframework.client";
1812
383
 
1813
- for await (const step of client.executeStepByStep({ message: "Test" })) {
1814
- if (step.message) responses.push(step.message);
1815
- }
384
+ const client = PlayFrameworkServices.resolve("default");
385
+ const registry = client.getClientRegistry();
1816
386
 
1817
- expect(responses.length).toBeGreaterThan(0);
1818
- });
387
+ registry.register("getCurrentLocation", async () => {
388
+ const content = await AIContentConverter.fromGeolocation({ timeout: 10_000 });
389
+ return [content];
1819
390
  });
1820
- ```
1821
-
1822
- ---
1823
391
 
1824
- ## 📚 API Reference
1825
-
1826
- ### `PlayFrameworkServices`
1827
-
1828
- Static service locator for managing named `PlayFrameworkClient` instances.
1829
-
1830
- | Method | Signature | Description |
1831
- |--------|-----------|-------------|
1832
- | `configure` | `(name: string, baseUrl: string, configure?: (settings: PlayFrameworkSettings) => void \| Promise<void>): Promise<PlayFrameworkSettings>` | Register and configure a named client factory |
1833
- | `resolve` | `(name?: string): PlayFrameworkClient` | Get client by name (defaults to first registered) |
1834
- | `getClient` | `(name: string): PlayFrameworkClient` | Get client by exact name (throws if not found) |
1835
- | `getDefaultClient` | `(): PlayFrameworkClient` | Get the first registered client |
1836
- | `getSettings` | `(name: string): PlayFrameworkSettings` | Get settings by name (throws if not found) |
1837
- | `isConfigured` | `(name: string): boolean` | Check if a named client exists |
1838
- | `remove` | `(name: string): void` | Remove a named client and its settings |
1839
- | `clear` | `(): void` | Remove all clients and settings |
1840
-
1841
- ```typescript
1842
- // Configure
1843
- await PlayFrameworkServices.configure("chat", "http://localhost:5158/api/ai");
392
+ registry.register<{ question?: string }>("getUserConfirmation", async (args) => {
393
+ const confirmed = window.confirm(args?.question ?? "Do you confirm?");
394
+ return [AIContentConverter.fromText(confirmed ? "confirmed" : "denied")];
395
+ });
1844
396
 
1845
- // Resolve
1846
- const client = PlayFrameworkServices.resolve("chat");
397
+ registry.registerCommand("logUserAction", async (args?: { action?: string }) => {
398
+ console.log("action", args?.action);
399
+ return CommandResultHelper.ok();
400
+ }, { feedbackMode: "never" });
1847
401
 
1848
- // Check & remove
1849
- if (PlayFrameworkServices.isConfigured("chat")) {
1850
- PlayFrameworkServices.remove("chat");
1851
- }
402
+ registry.registerCommand("saveToLocalStorage", async (args?: { key: string; value: string }) => {
403
+ if (!args) {
404
+ return CommandResultHelper.fail("Missing args");
405
+ }
406
+ localStorage.setItem(args.key, args.value);
407
+ return CommandResultHelper.ok(`Saved ${args.key}`);
408
+ }, { feedbackMode: "always" });
1852
409
  ```
1853
410
 
1854
- ---
1855
-
1856
- ### `PlayFrameworkClient`
411
+ Supported command feedback modes are:
1857
412
 
1858
- Main client for executing AI requests via SSE streaming.
413
+ - `never`
414
+ - `onError`
415
+ - `always`
1859
416
 
1860
- | Method | Signature | Description |
1861
- |--------|-----------|-------------|
1862
- | `executeStepByStep` | `(request: PlayFrameworkRequest, signal?: AbortSignal): AsyncIterableIterator<AiSceneResponse>` | Step-by-step streaming (one event per scene completion) |
1863
- | `executeTokenStreaming` | `(request: PlayFrameworkRequest, signal?: AbortSignal): AsyncIterableIterator<AiSceneResponse>` | Token-level streaming (one event per text chunk) |
1864
- | `getClientRegistry` | `(): ClientInteractionRegistry` | Get the client-side tool/command registry |
1865
- | `getConversation` | `(conversationKey: string): Promise<StoredConversation \| null>` | Load a stored conversation by key |
1866
- | `getConversations` | `(sortOrder?: ConversationSortOrder): Promise<StoredConversation[]>` | List conversations for the authenticated user |
1867
- | `deleteConversation` | `(conversationKey: string): Promise<boolean>` | Delete a stored conversation |
417
+ Important behavior:
1868
418
 
1869
- ---
419
+ - `PlayFrameworkClient` executes registered tools automatically when the server asks for them
420
+ - tool names must match what the server emits after its own normalization
421
+ - auto-resume uses the returned `conversationKey` and `clientInteractionResults` behind the scenes
422
+ - if a tool is missing, the library sends back an error result instead of silently succeeding
1870
423
 
1871
- ### `ClientInteractionRegistry`
424
+ ## Example: conversation management
1872
425
 
1873
- Registry for client-side tools and commands invoked by the AI during execution.
426
+ `PlayFrameworkClient` exposes:
1874
427
 
1875
- | Method | Signature | Description |
1876
- |--------|-----------|-------------|
1877
- | `register` | `<TArgs>(toolName: string, handler: ClientTool<TArgs>): void` | Register a tool (server waits for response) |
1878
- | `registerCommand` | `<TArgs>(toolName: string, handler: ClientCommand<TArgs>, options?: CommandOptions): void` | Register a fire-and-forget command |
1879
- | `execute` | `(request: ClientInteractionRequest): Promise<ClientInteractionResult>` | Execute a registered tool/command |
1880
- | `has` | `(toolName: string): boolean` | Check if a tool/command is registered |
1881
- | `isCommand` | `(toolName: string): boolean` | Check if the registration is a command |
1882
- | `getCommandOptions` | `(toolName: string): CommandOptions \| undefined` | Get the command's feedback options |
1883
- | `getToolNames` | `(): string[]` | List all registered tool/command names |
1884
- | `unregister` | `(toolName: string): boolean` | Remove a registration |
1885
- | `clear` | `(): void` | Remove all registrations |
428
+ - `listConversations(...)`
429
+ - `getConversation(...)`
430
+ - `deleteConversation(...)`
431
+ - `updateConversationVisibility(...)`
1886
432
 
1887
- **Types:**
433
+ Example:
1888
434
 
1889
435
  ```typescript
1890
- type ClientTool<TArgs = any> = (args?: TArgs) => Promise<AIContent[]>;
1891
- type ClientCommand<TArgs = any> = (args?: TArgs) => Promise<CommandResult>;
1892
- type CommandFeedbackMode = 'never' | 'onError' | 'always';
436
+ import {
437
+ ConversationSortOrder,
438
+ PlayFrameworkServices
439
+ } from "rystem.playframework.client";
1893
440
 
1894
- interface CommandOptions {
1895
- feedbackMode?: CommandFeedbackMode;
1896
- }
1897
- ```
441
+ const client = PlayFrameworkServices.resolve("default");
1898
442
 
1899
- ```typescript
1900
- // Tool — server waits for the result
1901
- registry.register("myTool", async (args?: { key: string }) => {
1902
- return [AIContentConverter.fromText(args?.key || "default")];
443
+ const conversations = await client.listConversations({
444
+ searchText: "weather",
445
+ orderBy: ConversationSortOrder.TimestampDescending,
446
+ includePublic: true,
447
+ includePrivate: true,
448
+ skip: 0,
449
+ take: 20
1903
450
  });
1904
451
 
1905
- // Command — fire-and-forget, feedback optional
1906
- registry.registerCommand("showNotification", async (args?: { text: string }) => {
1907
- showToast(args?.text ?? "");
1908
- return CommandResult.ok();
1909
- }, { feedbackMode: 'onError' });
1910
- ```
1911
-
1912
- ---
1913
-
1914
- ### `AIContentConverter`
1915
-
1916
- #### Static Methods
1917
-
1918
- - `fromCamera(constraints?, width?, height?): Promise<AIContent>` - Capture photo
1919
- - `fromGeolocation(options?): Promise<AIContent>` - Get GPS coordinates
1920
- - `fromFile(file: File | Blob): Promise<AIContent>` - Convert file to Base64
1921
- - `fromMultipleFiles(files: FileList): Promise<AIContent[]>` - Convert multiple files
1922
- - `fromMicrophone(durationMs?: number, mimeType?: string): Promise<AIContent>` - Record audio
1923
- - `fromText(text: string): AIContent` - Create text content
452
+ const selected = conversations[0];
1924
453
 
1925
- ---
454
+ if (selected) {
455
+ const fullConversation = await client.getConversation(selected.conversationKey, true);
456
+ console.log(fullConversation?.messages.length);
1926
457
 
1927
- ## 🎨 React Hook (`usePlayFramework`)
1928
-
1929
- ```tsx
1930
- import { usePlayFramework } from "@rystem/playframework-client";
458
+ await client.updateConversationVisibility(selected.conversationKey, true);
459
+ await client.deleteConversation(selected.conversationKey);
460
+ }
461
+ ```
1931
462
 
1932
- function MyComponent() {
1933
- const client = usePlayFramework("default");
463
+ These methods call:
1934
464
 
1935
- const handleClick = async () => {
1936
- for await (const step of client.executeStepByStep({ message: "Hello" })) {
1937
- console.log(step);
1938
- }
1939
- };
1940
-
1941
- return <button onClick={handleClick}>Send</button>;
1942
- }
465
+ ```text
466
+ {baseUrl}/{factoryName}/conversations
1943
467
  ```
1944
468
 
1945
- ---
469
+ They only work when the server has both:
1946
470
 
1947
- ## � Client Commands (Fire-and-Forget)
471
+ - `UseRepository()` and a matching `IRepository<StoredConversation, string>` registration
472
+ - `EnableConversationEndpoints = true` in `MapPlayFramework(...)`
1948
473
 
1949
- Commands are client-side tools that the server invokes but **does not wait for a response**. Use them for UI side effects (toasts, navigation, animations, etc.).
474
+ ## Example: server voice endpoint
1950
475
 
1951
- ### Registering Commands
476
+ `executeVoice(...)` targets the PlayFramework HTTP voice endpoint and streams `VoiceEvent` objects back.
1952
477
 
1953
478
  ```typescript
1954
- const registry = client.getClientRegistry();
1955
-
1956
- // Simple command — no feedback to server
1957
- registry.registerCommand("showToast", async (args?: { text: string }) => {
1958
- showNotification(args?.text ?? "");
1959
- return CommandResult.ok();
1960
- });
479
+ import {
480
+ PlayFrameworkServices,
481
+ VoiceRecorder
482
+ } from "rystem.playframework.client";
1961
483
 
1962
- // Command with error feedback — server receives failure info
1963
- registry.registerCommand("navigateTo", async (args?: { url: string }) => {
1964
- try {
1965
- window.location.href = args?.url ?? "/";
1966
- return CommandResult.ok();
1967
- } catch (e) {
1968
- return CommandResult.fail(`Navigation failed: ${e}`);
484
+ const client = PlayFrameworkServices.resolve("default");
485
+ const recorder = new VoiceRecorder({ mode: "pushToTalk" });
486
+
487
+ await recorder.start({
488
+ onRecorded: async (blob) => {
489
+ for await (const event of client.executeVoice({
490
+ audio: blob,
491
+ conversationKey: "voice-conversation-1",
492
+ metadata: { userId: "user-42" }
493
+ })) {
494
+ if (event.type === "transcription") {
495
+ console.log("user said", event.text);
496
+ }
497
+ if (event.type === "scene") {
498
+ console.log(event.status, event.message);
499
+ }
500
+ if (event.type === "audio") {
501
+ console.log("received audio chunk", event.audio?.length ?? 0);
502
+ }
1969
503
  }
1970
- }, { feedbackMode: 'onError' });
504
+ }
505
+ });
1971
506
 
1972
- // Command with always-feedback — server always gets the result
1973
- registry.registerCommand("playSound", async (args?: { soundId: string }) => {
1974
- await audioPlayer.play(args?.soundId ?? "notification");
1975
- return CommandResult.ok("Sound played");
1976
- }, { feedbackMode: 'always' });
507
+ // In push-to-talk mode you stop manually.
508
+ recorder.stop();
1977
509
  ```
1978
510
 
1979
- ### `CommandResult` Helper
511
+ This calls:
1980
512
 
1981
- ```typescript
1982
- interface CommandResult {
1983
- success: boolean;
1984
- message?: string;
1985
- }
1986
-
1987
- // Factory methods
1988
- CommandResult.ok(); // { success: true }
1989
- CommandResult.ok("Done"); // { success: true, message: "Done" }
1990
- CommandResult.fail("Reason"); // { success: false, message: "Reason" }
513
+ ```text
514
+ POST {baseUrl}/{factoryName}/voice
1991
515
  ```
1992
516
 
1993
- ### `CommandFeedbackMode`
1994
-
1995
- | Mode | Behavior |
1996
- |------|----------|
1997
- | `'never'` | Server ignores the command's result (default) |
1998
- | `'onError'` | Server receives feedback only when `success: false` |
1999
- | `'always'` | Server always receives the command's result |
517
+ It only works when the server enables the PlayFramework voice endpoint and has a matching `IVoiceAdapter`.
2000
518
 
2001
- ---
519
+ ## Example: browser-native voice flow
2002
520
 
2003
- ## 📋 `ClientInteractionRequest` Model
521
+ `BrowserVoiceClient` is different from `executeVoice(...)`.
2004
522
 
2005
- When the server invokes a client-side tool or command, it sends this object:
523
+ It does not use the server voice endpoint. Instead it uses browser speech recognition plus browser speech synthesis and sends the recognized text through the normal PlayFramework SSE endpoints.
2006
524
 
2007
525
  ```typescript
2008
- interface ClientInteractionRequest {
2009
- interactionId: string; // Unique ID for this invocation
2010
- toolName: string; // Registered tool/command name
2011
- description?: string; // Human-readable description
2012
- arguments?: Record<string, any>; // Arguments from AI
2013
- argumentsSchema?: string; // JSON Schema string
2014
- timeoutSeconds: number; // Max time to wait (tools only)
2015
- isCommand?: boolean; // true = fire-and-forget command
2016
- feedbackMode?: 'never' | 'onError' | 'always'; // Command feedback mode
2017
- }
2018
- ```
2019
-
2020
- ---
2021
-
2022
- ## 📋 `ClientInteractionResult` Model
2023
-
2024
- The response your tool handler returns to the server:
2025
-
2026
- ```typescript
2027
- interface AIContent {
2028
- type: "text" | "data";
2029
- text?: string; // For type "text"
2030
- data?: string; // Base64-encoded (for type "data")
2031
- mediaType?: string; // e.g., "image/jpeg", "audio/webm"
2032
- }
2033
-
2034
- interface ClientInteractionResult {
2035
- interactionId: string; // Must match the request
2036
- contents: AIContent[]; // Tool output
2037
- error?: string; // Error message (if failed)
2038
- executedAt: string; // ISO 8601 timestamp
2039
- }
2040
- ```
2041
-
2042
- ---
526
+ import {
527
+ BrowserVoiceClient,
528
+ PlayFrameworkServices
529
+ } from "rystem.playframework.client";
2043
530
 
2044
- ## 📋 `ExecutionState` and `ExecutionPhase`
531
+ const client = PlayFrameworkServices.resolve("default");
2045
532
 
2046
- The `ExecutionState` object tracks the AI orchestration progress during execution:
533
+ if (BrowserVoiceClient.isSupported()) {
534
+ const voice = new BrowserVoiceClient(
535
+ client,
536
+ { lang: "en-US" },
537
+ { lang: "en-US" }
538
+ );
2047
539
 
2048
- ```typescript
2049
- type ExecutionPhase =
2050
- | "notStarted"
2051
- | "initialized"
2052
- | "sceneSelected"
2053
- | "executingScene"
2054
- | "awaitingClient"
2055
- | "sceneCompleted"
2056
- | "chaining"
2057
- | "generatingFinalResponse"
2058
- | "completed"
2059
- | "completedNoResponse"
2060
- | "budgetExceeded"
2061
- | "sceneNotFound"
2062
- | "tooManyToolRequests"
2063
- | "break"
2064
- | "unauthorized";
2065
-
2066
- interface ExecutionState {
2067
- phase: ExecutionPhase; // Current execution phase
2068
- executedSceneOrder: string[]; // Scene names in execution order
2069
- executedScenes: Record<string, any[]>; // Scene name → results
2070
- executedTools: string[]; // Tool names invoked
2071
- accumulatedCost: number; // Total $ cost so far
2072
- currentSceneName?: string | null; // Currently running scene
540
+ for await (const event of voice.executeWithBrowserVoice({
541
+ streamingMode: "tokenStreaming",
542
+ request: {
543
+ metadata: { userId: "user-42" },
544
+ settings: {
545
+ executionMode: "Scene",
546
+ sceneName: "General_Requests"
547
+ }
548
+ }
549
+ })) {
550
+ if (event.voiceStatus === "recognized") {
551
+ console.log("transcript", event.transcript);
552
+ }
553
+ if (event.response?.streamingChunk) {
554
+ console.log(event.response.streamingChunk);
555
+ }
556
+ }
2073
557
  }
2074
558
  ```
2075
559
 
2076
- ---
560
+ Useful notes:
2077
561
 
2078
- ## 📋 `AiSceneResponse` Full Model
562
+ - `BrowserVoiceClient.isSupported()` checks browser STT + TTS support
563
+ - `speakResponse(...)` is a shortcut when you already have the input text
564
+ - `cancelSpeech()`, `cancelStream()`, and `cancelAll()` are available for UI controls
565
+ - scene names used in direct scene execution must match the server's normalized scene name, so a server scene like `AddScene("General Requests", ...)` is addressed as `General_Requests`
2079
566
 
2080
- Each SSE event yields an `AiSceneResponse`:
2081
-
2082
- ```typescript
2083
- interface AiSceneResponse {
2084
- status: AiResponseStatus;
2085
- sceneName?: string;
2086
- functionName?: string;
2087
- functionArguments?: string;
2088
- message?: string; // Final response text (step-by-step)
2089
- streamingChunk?: string; // Partial text (token streaming)
2090
- isStreamingComplete?: boolean;
2091
- errorMessage?: string;
2092
- inputTokens?: number;
2093
- cachedInputTokens?: number;
2094
- outputTokens?: number;
2095
- totalTokens?: number;
2096
- cost?: number; // Cost for this step
2097
- totalCost?: number; // Accumulated total cost
2098
- conversationKey?: string;
2099
- continuationToken?: string; // Token for resuming after client tool
2100
- clientInteractionRequest?: ClientInteractionRequest;
2101
- timestamp?: string;
2102
- metadata?: Record<string, any>;
2103
- contents?: Array<{
2104
- type: string;
2105
- text?: string;
2106
- data?: string; // Base64 encoded
2107
- mediaType?: string;
2108
- }>;
2109
- }
2110
- ```
567
+ ## `usePlayFramework`
2111
568
 
2112
- ---
569
+ The library exports `usePlayFramework(name?)`, but it is only a convenience accessor over `PlayFrameworkServices.resolve(name)`.
2113
570
 
2114
- ## 📋 `StoredMessage` Full Model
571
+ It does not manage React state or subscribe to updates by itself.
2115
572
 
2116
- Each message in a `StoredConversation.messages` array:
573
+ So even though the name looks React-specific, it is effectively a thin helper rather than a stateful hook system.
2117
574
 
2118
575
  ```typescript
2119
- interface StoredMessage {
2120
- businessType: number; // Internal type discriminator
2121
- label?: string | null; // Optional label (e.g., scene name)
2122
- role: string; // "user" | "assistant" | "system" | "tool"
2123
- text?: string | null; // Plain text content
2124
- contents?: any[] | null; // Multi-modal content items
2125
- additionalProperties?: Record<string, any> | null; // Extra metadata
2126
- }
2127
- ```
2128
-
2129
- ---
576
+ import { usePlayFramework } from "rystem.playframework.client";
2130
577
 
2131
- ## 📋 `ContentItem` Full Model
578
+ const client = usePlayFramework("default");
2132
579
 
2133
- Used in `PlayFrameworkRequest.contents` for multi-modal input:
2134
-
2135
- ```typescript
2136
- interface ContentItem {
2137
- type: "text" | "image" | "audio" | "video" | "file" | "uri";
2138
- text?: string; // For type "text"
2139
- data?: string; // Base64-encoded binary data
2140
- uri?: string; // For type "uri"
2141
- mediaType?: string; // MIME type (e.g., "image/png", "audio/webm")
2142
- name?: string; // Optional filename
580
+ for await (const step of client.executeStepByStep({ message: "Hello" })) {
581
+ console.log(step.message);
2143
582
  }
2144
583
  ```
2145
584
 
2146
- ---
585
+ ## Useful exports
2147
586
 
2148
- ## �📁 Where to Place This README
587
+ Besides the main client classes, the package also exports:
2149
588
 
2150
- This README should be placed in:
2151
- ```
2152
- src/AI/Rystem.PlayFramework.Client/src/rystem/README.md
2153
- ```
2154
-
2155
- This is the **library source** directory that gets published to npm.
589
+ - `AIContentConverter`
590
+ - `ContentUrlConverter`
591
+ - `VoiceRecorder`
592
+ - `BrowserSpeechRecognizer`
593
+ - `BrowserSpeechSynthesizer`
594
+ - `BrowserVoiceClient`
595
+ - `ConversationSortOrder`
596
+ - `CommandResultHelper`
2156
597
 
2157
- ---
598
+ ## Important caveats
2158
599
 
2159
- ## 🔗 Links
600
+ ### The final `completed` marker is consumed internally
2160
601
 
2161
- - 📖 **Documentation**: https://rystem.net/playframework
2162
- - 💻 **GitHub**: https://github.com/KeyserDSoze/Rystem
2163
- - 📦 **npm**: https://www.npmjs.com/package/@rystem/playframework-client
2164
- - 🎯 **MCP Tools**: https://rystem.net/mcp
602
+ `PlayFrameworkClient` treats `status === "completed"` as an internal stop marker and does not yield that marker to callers as a final event.
2165
603
 
2166
- ---
604
+ ### `status === "error"` throws
2167
605
 
2168
- ## 📄 License
606
+ Server error markers are converted into thrown exceptions rather than yielded error events.
2169
607
 
2170
- MIT © [Alessandro Rapiti](https://github.com/KeyserDSoze)
608
+ ### Library code logs to the console
2171
609
 
2172
- ---
610
+ The current runtime includes several `console.log`, `console.warn`, and `console.error` calls.
2173
611
 
2174
- ## 🤝 Contributing
612
+ ### Auto-resume depends on registered tools
2175
613
 
2176
- Contributions welcome! Please open an issue or PR.
614
+ If the server asks for a client-side tool and the registry does not contain it, the library sends back an error result rather than magically handling the operation.
2177
615
 
2178
- 1. Fork the repo
2179
- 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
2180
- 3. Commit your changes (`git commit -m 'Add amazing feature'`)
2181
- 4. Push to the branch (`git push origin feature/amazing-feature`)
2182
- 5. Open a Pull Request
616
+ ### `baseUrl` must point to the PlayFramework base path only
2183
617
 
2184
- ---
618
+ Use a base such as `http://localhost:5158/api/ai`, not `http://localhost:5158/api/ai/default`. The library appends `/{factoryName}` itself.
2185
619
 
2186
- ## 💡 Examples
620
+ ### Many helpers are browser-only
2187
621
 
2188
- ### Complete Chat Application
622
+ `AIContentConverter.fromCamera(...)`, `AIContentConverter.fromGeolocation(...)`, `AIContentConverter.fromMicrophone(...)`, `VoiceRecorder`, and `BrowserSpeech*` utilities depend on browser APIs and are not SSR-safe by default.
2189
623
 
2190
- ```tsx
2191
- import React, { useState, useRef, useEffect } from 'react';
2192
- import { usePlayFramework, AIContentConverter } from '@rystem/playframework-client';
624
+ ### Browser voice and server voice are different paths
2193
625
 
2194
- interface Message {
2195
- role: 'user' | 'assistant';
2196
- text: string;
2197
- status?: string;
2198
- }
626
+ `BrowserVoiceClient` uses browser STT/TTS plus normal SSE endpoints. `executeVoice(...)` uses the server-side `/voice` endpoint with a server `IVoiceAdapter`.
2199
627
 
2200
- function ChatApp() {
2201
- const client = usePlayFramework('default');
2202
- const [messages, setMessages] = useState<Message[]>([]);
2203
- const [input, setInput] = useState('');
2204
- const [loading, setLoading] = useState(false);
2205
- const [conversationKey] = useState(crypto.randomUUID());
2206
-
2207
- // Register client tools
2208
- useEffect(() => {
2209
- const registry = client.getClientRegistry();
2210
-
2211
- registry.register('getCurrentLocation', async () => {
2212
- const content = await AIContentConverter.fromGeolocation();
2213
- return [content];
2214
- });
2215
-
2216
- registry.register('getUserConfirmation', async (args?: { question?: string }) => {
2217
- const confirmed = window.confirm(args?.question ?? 'Do you confirm?');
2218
- return [AIContentConverter.fromText(confirmed ? 'confirmed' : 'denied')];
2219
- });
2220
- }, [client]);
2221
-
2222
- const handleSend = async () => {
2223
- if (!input.trim() || loading) return;
2224
-
2225
- const userMessage: Message = { role: 'user', text: input };
2226
- setMessages(prev => [...prev, userMessage]);
2227
- setInput('');
2228
- setLoading(true);
2229
-
2230
- try {
2231
- const assistantMessage: Message = { role: 'assistant', text: '', status: 'initializing' };
2232
- setMessages(prev => [...prev, assistantMessage]);
2233
-
2234
- for await (const step of client.executeStepByStep({
2235
- message: input,
2236
- settings: {
2237
- conversationKey,
2238
- executionMode: 'Direct',
2239
- enableStreaming: true
2240
- }
2241
- })) {
2242
- setMessages(prev => {
2243
- const updated = [...prev];
2244
- const last = updated[updated.length - 1];
2245
-
2246
- if (step.streamingChunk) {
2247
- last.text += step.streamingChunk;
2248
- } else if (step.message) {
2249
- last.text = step.message;
2250
- }
2251
- last.status = step.status;
2252
-
2253
- return updated;
2254
- });
2255
- }
2256
- } catch (error) {
2257
- console.error('Chat error:', error);
2258
- setMessages(prev => [...prev, {
2259
- role: 'assistant',
2260
- text: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`,
2261
- status: 'error'
2262
- }]);
2263
- } finally {
2264
- setLoading(false);
2265
- }
2266
- };
628
+ ### `usePlayFramework(...)` is not a real reactive hook
2267
629
 
2268
- return (
2269
- <div style={{ maxWidth: '800px', margin: '0 auto', padding: '20px' }}>
2270
- <h1>PlayFramework Chat</h1>
2271
-
2272
- <div style={{ height: '500px', overflowY: 'auto', border: '1px solid #ccc', padding: '10px', marginBottom: '10px' }}>
2273
- {messages.map((msg, i) => (
2274
- <div key={i} style={{
2275
- padding: '10px',
2276
- margin: '5px 0',
2277
- borderRadius: '8px',
2278
- backgroundColor: msg.role === 'user' ? '#e3f2fd' : '#f5f5f5',
2279
- textAlign: msg.role === 'user' ? 'right' : 'left'
2280
- }}>
2281
- <strong>{msg.role === 'user' ? 'You' : 'AI'}</strong>
2282
- {msg.status && <small style={{ color: '#666', marginLeft: '8px' }}>[{msg.status}]</small>}
2283
- <div>{msg.text}</div>
2284
- </div>
2285
- ))}
2286
- </div>
2287
-
2288
- <div style={{ display: 'flex', gap: '10px' }}>
2289
- <input
2290
- type="text"
2291
- value={input}
2292
- onChange={e => setInput(e.target.value)}
2293
- onKeyDown={e => e.key === 'Enter' && handleSend()}
2294
- placeholder="Type a message..."
2295
- disabled={loading}
2296
- style={{ flex: 1, padding: '10px', fontSize: '16px' }}
2297
- />
2298
- <button onClick={handleSend} disabled={loading} style={{ padding: '10px 20px', fontSize: '16px' }}>
2299
- {loading ? 'Sending...' : 'Send'}
2300
- </button>
2301
- </div>
2302
- </div>
2303
- );
2304
- }
630
+ It is only a resolver helper over `PlayFrameworkServices.resolve(...)`.
2305
631
 
2306
- export default ChatApp;
2307
- ```
632
+ ## Grounded by source files
2308
633
 
2309
- ---
634
+ - `src/AI/Rystem.PlayFramework.Client/src/rystem/src/servicecollection/PlayFrameworkServices.ts`
635
+ - `src/AI/Rystem.PlayFramework.Client/src/rystem/src/servicecollection/PlayFrameworkSettings.ts`
636
+ - `src/AI/Rystem.PlayFramework.Client/src/rystem/src/engine/PlayFrameworkClient.ts`
637
+ - `src/AI/Rystem.PlayFramework.Client/src/rystem/src/engine/ClientInteractionRegistry.ts`
638
+ - `src/AI/Rystem.PlayFramework.Client/src/rystem/src/utils/AIContentConverter.ts`
639
+ - `src/AI/Rystem.PlayFramework.Client/src/rystem/src/utils/ContentUrlConverter.ts`
640
+ - `src/AI/Rystem.PlayFramework.Client/src/rystem/src/utils/VoiceRecorder.ts`
641
+ - `src/AI/Rystem.PlayFramework.Client/src/rystem/src/utils/BrowserVoiceClient.ts`
642
+ - `src/AI/Rystem.PlayFramework.Client/src/rystem/src/hooks/hooks.ts`
643
+ - `src/AI/Rystem.PlayFramework.Client/src/App.tsx`
2310
644
 
2311
- **Made with ❤️ by the Rystem team**
645
+ Use this package when you want a typed client for a PlayFramework backend, including SSE execution, browser tool continuation, conversations, and both server-side and browser-side voice flows.