rystem.playframework.client 0.1.1 → 0.1.2

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
@@ -283,12 +283,12 @@ const request: PlayFrameworkRequest = {
283
283
  contents: [
284
284
  {
285
285
  type: "image",
286
- base64Data: "iVBORw0KGgoAAAANSUhEUgAA...",
286
+ data: "iVBORw0KGgoAAAANSUhEUgAA...",
287
287
  mediaType: "image/png"
288
288
  },
289
289
  {
290
290
  type: "data",
291
- base64Data: "JVBERi0xLjQKJeLjz9M...",
291
+ data: "JVBERi0xLjQKJeLjz9M...",
292
292
  mediaType: "application/pdf"
293
293
  },
294
294
  {
@@ -420,6 +420,879 @@ for await (const step of client.executeStepByStep({
420
420
 
421
421
  ---
422
422
 
423
+ ## 💾 Conversation Management (Repository Pattern)
424
+
425
+ If the backend has **Repository persistence enabled**, you can manage conversations using REST endpoints.
426
+
427
+ ### List Conversations
428
+
429
+ ```typescript
430
+ import { ConversationSortOrder } from "@rystem/playframework-client";
431
+
432
+ // Get conversations with filters
433
+ const conversations = await client.listConversations({
434
+ searchText: "weather", // Search in message text
435
+ includePublic: true, // Include public conversations
436
+ includePrivate: true, // Include private conversations
437
+ orderBy: ConversationSortOrder.TimestampDescending, // Sort by newest first
438
+ skip: 0, // Pagination offset
439
+ take: 50 // Page size
440
+ });
441
+
442
+ console.log(conversations);
443
+ // [
444
+ // {
445
+ // conversationKey: "abc-123",
446
+ // userId: "user@example.com",
447
+ // isPublic: false,
448
+ // timestamp: "2025-01-15T10:30:00Z",
449
+ // messages: [...],
450
+ // executionState: {...}
451
+ // }
452
+ // ]
453
+ ```
454
+
455
+ ### Get Single Conversation
456
+
457
+ ```typescript
458
+ const conversation = await client.getConversation("abc-123");
459
+
460
+ if (conversation) {
461
+ console.log(conversation.messages); // Full message history
462
+ console.log(conversation.isPublic); // Public vs private
463
+ } else {
464
+ console.log("Conversation not found or unauthorized");
465
+ }
466
+ ```
467
+
468
+ **Authorization**: Private conversations require userId match (set via backend `IAuthorizationLayer`).
469
+
470
+ ### Delete Conversation
471
+
472
+ ```typescript
473
+ // Owner-only operation
474
+ await client.deleteConversation("abc-123");
475
+ console.log("Conversation deleted");
476
+ ```
477
+
478
+ **Response:**
479
+ - ✅ Success - Conversation deleted
480
+ - ❌ `403 Forbidden` - Not the owner
481
+ - ❌ `404 Not Found` - Conversation not found
482
+
483
+ ### Update Visibility (Public/Private)
484
+
485
+ ```typescript
486
+ // Toggle conversation visibility (owner-only)
487
+ const updated = await client.updateConversationVisibility("abc-123", true);
488
+ console.log(`Conversation is now ${updated.isPublic ? "public" : "private"}`);
489
+ ```
490
+
491
+ ### React Example: Conversation List UI
492
+
493
+ ```tsx
494
+ import { useState, useEffect } from "react";
495
+ import { usePlayFramework, StoredConversation, ConversationSortOrder } from "@rystem/playframework-client";
496
+
497
+ function ConversationList() {
498
+ const client = usePlayFramework("default");
499
+ const [conversations, setConversations] = useState<StoredConversation[]>([]);
500
+ const [searchText, setSearchText] = useState("");
501
+ const [showPublic, setShowPublic] = useState(true);
502
+ const [showPrivate, setShowPrivate] = useState(true);
503
+ const [loading, setLoading] = useState(false);
504
+
505
+ const loadConversations = async () => {
506
+ setLoading(true);
507
+ try {
508
+ const result = await client.listConversations({
509
+ searchText: searchText || undefined,
510
+ includePublic: showPublic,
511
+ includePrivate: showPrivate,
512
+ orderBy: ConversationSortOrder.TimestampDescending,
513
+ take: 100
514
+ });
515
+ setConversations(result);
516
+ } catch (error) {
517
+ console.error("Failed to load conversations:", error);
518
+ } finally {
519
+ setLoading(false);
520
+ }
521
+ };
522
+
523
+ useEffect(() => {
524
+ loadConversations();
525
+ }, [showPublic, showPrivate]);
526
+
527
+ const handleDelete = async (key: string) => {
528
+ if (!window.confirm("Delete this conversation?")) return;
529
+ try {
530
+ await client.deleteConversation(key);
531
+ await loadConversations(); // Reload list
532
+ } catch (error: any) {
533
+ alert(`Failed to delete: ${error.message}`);
534
+ }
535
+ };
536
+
537
+ const handleLoadConversation = async (key: string) => {
538
+ const conv = await client.getConversation(key);
539
+ if (conv) {
540
+ // Load conversation into chat UI
541
+ console.log("Loaded:", conv.messages);
542
+ }
543
+ };
544
+
545
+ return (
546
+ <div>
547
+ <h2>Conversations</h2>
548
+
549
+ {/* Search & Filters */}
550
+ <input
551
+ type="text"
552
+ placeholder="Search messages..."
553
+ value={searchText}
554
+ onChange={e => setSearchText(e.target.value)}
555
+ />
556
+ <button onClick={loadConversations}>Search</button>
557
+
558
+ <label>
559
+ <input
560
+ type="checkbox"
561
+ checked={showPublic}
562
+ onChange={e => setShowPublic(e.target.checked)}
563
+ />
564
+ Public
565
+ </label>
566
+ <label>
567
+ <input
568
+ type="checkbox"
569
+ checked={showPrivate}
570
+ onChange={e => setShowPrivate(e.target.checked)}
571
+ />
572
+ Private
573
+ </label>
574
+
575
+ {/* Conversation List */}
576
+ {loading ? (
577
+ <div>Loading...</div>
578
+ ) : (
579
+ <ul>
580
+ {conversations.map(conv => (
581
+ <li key={conv.conversationKey}>
582
+ <div onClick={() => handleLoadConversation(conv.conversationKey)}>
583
+ <strong>{new Date(conv.timestamp).toLocaleString()}</strong>
584
+ <span style={{ color: conv.isPublic ? "green" : "red" }}>
585
+ {conv.isPublic ? "Public" : "Private"}
586
+ </span>
587
+ <p>{conv.messages[0]?.text || "Empty conversation"}</p>
588
+ <small>{conv.messages.length} messages</small>
589
+ </div>
590
+ <button onClick={() => handleDelete(conv.conversationKey)}>Delete</button>
591
+ </li>
592
+ ))}
593
+ </ul>
594
+ )}
595
+ </div>
596
+ );
597
+ }
598
+ ```
599
+
600
+ ### Backend Setup Required
601
+
602
+ For conversation management to work, the backend must:
603
+
604
+ 1. **Enable Repository persistence:**
605
+ ```csharp
606
+ builder.Services.AddPlayFramework("default", pb => pb
607
+ .UseRepository());
608
+ ```
609
+
610
+ 2. **Enable conversation endpoints:**
611
+ ```csharp
612
+ app.MapPlayFramework("default", settings =>
613
+ {
614
+ settings.EnableConversationEndpoints = true;
615
+ });
616
+ ```
617
+
618
+ See [Backend README](../../../README.md) for full setup guide.
619
+
620
+ ---
621
+
622
+ ## 🔄 Combining Stored Conversations with Live Streaming
623
+
624
+ This section shows how to **load historic messages** from `StoredConversation` and **continue the conversation** with live SSE streaming.
625
+
626
+ ### Understanding the Two Models
627
+
628
+ PlayFramework uses **two different models** for different purposes:
629
+
630
+ | Model | Purpose | When | Format | Content |
631
+ |-------|---------|------|--------|---------|
632
+ | **`AiSceneResponse`** | Real-time execution tracking | During `executeStepByStep()` / `executeTokenStreaming()` | SSE (Server-Sent Events) | Status updates, streaming chunks, scene metadata |
633
+ | **`StoredConversation`** | Persistent conversation history | When loading from repository via REST API | JSON | Complete messages, user metadata, execution state |
634
+
635
+ **Why two models?**
636
+ - `AiSceneResponse` contains **temporary execution metadata** (status, sceneName, functionName) needed for real-time UI updates
637
+ - `StoredConversation` contains **only essential data** (messages, userId, timestamp) for efficient storage and querying
638
+
639
+ ### Complete Example: Chat with History
640
+
641
+ ```tsx
642
+ import React, { useState, useEffect } from 'react';
643
+ import { usePlayFramework, StoredConversation, AiSceneResponse } from '@rystem/playframework-client';
644
+
645
+ interface ChatMessage {
646
+ role: 'user' | 'assistant';
647
+ text: string;
648
+ isStreaming?: boolean; // Distinguishes streaming vs historic messages
649
+ status?: string; // For showing execution status
650
+ }
651
+
652
+ function ChatWithHistory() {
653
+ const client = usePlayFramework('default');
654
+
655
+ // State
656
+ const [messages, setMessages] = useState<ChatMessage[]>([]);
657
+ const [input, setInput] = useState('');
658
+ const [conversationKey, setConversationKey] = useState<string | null>(null);
659
+ const [loading, setLoading] = useState(false);
660
+
661
+ // 📥 LOAD: Load historic conversation from repository
662
+ const loadConversation = async (key: string) => {
663
+ try {
664
+ // Fetch from REST API → StoredConversation
665
+ const stored = await client.getConversation(key);
666
+
667
+ if (!stored) {
668
+ alert('Conversation not found or unauthorized');
669
+ return;
670
+ }
671
+
672
+ // Convert StoredMessage[] → ChatMessage[]
673
+ const historicMessages: ChatMessage[] = stored.messages.map(msg => ({
674
+ role: msg.role as 'user' | 'assistant',
675
+ text: msg.text || '',
676
+ isStreaming: false // Historic messages are complete
677
+ }));
678
+
679
+ setMessages(historicMessages);
680
+ setConversationKey(stored.conversationKey);
681
+
682
+ console.log(`✅ Loaded ${stored.messages.length} messages from conversation ${key}`);
683
+ } catch (error) {
684
+ console.error('Failed to load conversation:', error);
685
+ alert(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);
686
+ }
687
+ };
688
+
689
+ // 📤 SEND: Send message and stream response
690
+ const sendMessage = async () => {
691
+ if (!input.trim() || loading) return;
692
+
693
+ const userMessage = input;
694
+ setInput('');
695
+ setLoading(true);
696
+
697
+ // Add user message to UI
698
+ const userMsg: ChatMessage = { role: 'user', text: userMessage };
699
+ setMessages(prev => [...prev, userMsg]);
700
+
701
+ // Add placeholder for assistant response
702
+ const assistantMsg: ChatMessage = {
703
+ role: 'assistant',
704
+ text: '',
705
+ isStreaming: true, // Flag: currently streaming
706
+ status: 'initializing'
707
+ };
708
+ setMessages(prev => [...prev, assistantMsg]);
709
+
710
+ try {
711
+ // 🔄 Stream from PlayFramework → AiSceneResponse events
712
+ for await (const step of client.executeStepByStep({
713
+ message: userMessage,
714
+ settings: {
715
+ conversationKey: conversationKey || undefined, // Resume existing or start new
716
+ enableStreaming: true
717
+ }
718
+ })) {
719
+ // Update conversationKey from first response
720
+ if (step.conversationKey && !conversationKey) {
721
+ setConversationKey(step.conversationKey);
722
+ }
723
+
724
+ // Update message with streaming chunks
725
+ if (step.streamingChunk) {
726
+ setMessages(prev => {
727
+ const updated = [...prev];
728
+ const last = updated[updated.length - 1];
729
+ last.text += step.streamingChunk;
730
+ last.status = step.status;
731
+ return updated;
732
+ });
733
+ }
734
+
735
+ // Update status (planning, executingScene, etc.)
736
+ else if (step.status) {
737
+ setMessages(prev => {
738
+ const updated = [...prev];
739
+ const last = updated[updated.length - 1];
740
+ last.status = step.status;
741
+ return updated;
742
+ });
743
+ }
744
+ }
745
+
746
+ // Mark streaming as complete
747
+ setMessages(prev => {
748
+ const updated = [...prev];
749
+ const last = updated[updated.length - 1];
750
+ last.isStreaming = false;
751
+ delete last.status;
752
+ return updated;
753
+ });
754
+
755
+ } catch (error) {
756
+ console.error('Streaming error:', error);
757
+ setMessages(prev => {
758
+ const updated = [...prev];
759
+ updated[updated.length - 1] = {
760
+ role: 'assistant',
761
+ text: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`,
762
+ isStreaming: false,
763
+ status: 'error'
764
+ };
765
+ return updated;
766
+ });
767
+ } finally {
768
+ setLoading(false);
769
+ }
770
+ };
771
+
772
+ // 🗑️ CLEAR: Start new conversation
773
+ const clearConversation = () => {
774
+ setMessages([]);
775
+ setConversationKey(null);
776
+ };
777
+
778
+ return (
779
+ <div style={{ maxWidth: '900px', margin: '0 auto', padding: '20px', fontFamily: 'sans-serif' }}>
780
+ <h1>💬 PlayFramework Chat</h1>
781
+
782
+ {/* Conversation Info */}
783
+ <div style={{
784
+ padding: '10px',
785
+ marginBottom: '10px',
786
+ backgroundColor: '#f0f0f0',
787
+ borderRadius: '8px',
788
+ display: 'flex',
789
+ justifyContent: 'space-between',
790
+ alignItems: 'center'
791
+ }}>
792
+ <div>
793
+ {conversationKey ? (
794
+ <>
795
+ <strong>Conversation:</strong> {conversationKey.substring(0, 8)}...
796
+ <span style={{ marginLeft: '10px', color: '#666' }}>
797
+ ({messages.length} messages)
798
+ </span>
799
+ </>
800
+ ) : (
801
+ <span style={{ color: '#999' }}>New conversation</span>
802
+ )}
803
+ </div>
804
+ <button
805
+ onClick={clearConversation}
806
+ style={{
807
+ padding: '5px 15px',
808
+ borderRadius: '6px',
809
+ border: '1px solid #ccc',
810
+ backgroundColor: '#fff',
811
+ cursor: 'pointer'
812
+ }}
813
+ >
814
+ Clear
815
+ </button>
816
+ </div>
817
+
818
+ {/* Messages */}
819
+ <div style={{
820
+ height: '500px',
821
+ overflowY: 'auto',
822
+ border: '1px solid #ddd',
823
+ borderRadius: '8px',
824
+ padding: '15px',
825
+ marginBottom: '15px',
826
+ backgroundColor: '#fafafa'
827
+ }}>
828
+ {messages.length === 0 ? (
829
+ <div style={{ textAlign: 'center', color: '#999', marginTop: '50px' }}>
830
+ <p>No messages yet. Start a conversation or load an existing one.</p>
831
+ <button
832
+ onClick={() => loadConversation('some-conversation-key')}
833
+ style={{
834
+ padding: '8px 16px',
835
+ borderRadius: '6px',
836
+ border: '1px solid #61dafb',
837
+ backgroundColor: '#61dafb',
838
+ color: '#fff',
839
+ cursor: 'pointer',
840
+ marginTop: '10px'
841
+ }}
842
+ >
843
+ Load Example Conversation
844
+ </button>
845
+ </div>
846
+ ) : (
847
+ messages.map((msg, i) => (
848
+ <div
849
+ key={i}
850
+ style={{
851
+ padding: '12px',
852
+ margin: '8px 0',
853
+ borderRadius: '12px',
854
+ backgroundColor: msg.role === 'user' ? '#e3f2fd' : '#fff',
855
+ border: msg.role === 'assistant' ? '1px solid #e0e0e0' : 'none',
856
+ maxWidth: '85%',
857
+ marginLeft: msg.role === 'user' ? 'auto' : '0',
858
+ marginRight: msg.role === 'user' ? '0' : 'auto',
859
+ }}
860
+ >
861
+ <div style={{
862
+ display: 'flex',
863
+ justifyContent: 'space-between',
864
+ marginBottom: '6px',
865
+ fontSize: '12px',
866
+ color: '#666'
867
+ }}>
868
+ <strong style={{ color: msg.role === 'user' ? '#1976d2' : '#388e3c' }}>
869
+ {msg.role === 'user' ? '👤 You' : '🤖 AI'}
870
+ </strong>
871
+
872
+ {/* Show streaming indicator or status */}
873
+ {msg.isStreaming && (
874
+ <span style={{
875
+ color: '#ff6b6b',
876
+ fontStyle: 'italic',
877
+ fontSize: '11px'
878
+ }}>
879
+ {msg.status || 'streaming'} ●
880
+ </span>
881
+ )}
882
+ </div>
883
+
884
+ <div style={{
885
+ whiteSpace: 'pre-wrap',
886
+ wordBreak: 'break-word',
887
+ lineHeight: '1.5'
888
+ }}>
889
+ {msg.text || '...'}
890
+ </div>
891
+ </div>
892
+ ))
893
+ )}
894
+ </div>
895
+
896
+ {/* Input */}
897
+ <div style={{ display: 'flex', gap: '10px' }}>
898
+ <input
899
+ type="text"
900
+ value={input}
901
+ onChange={e => setInput(e.target.value)}
902
+ onKeyDown={e => e.key === 'Enter' && !loading && sendMessage()}
903
+ placeholder={loading ? 'AI is responding...' : 'Type your message...'}
904
+ disabled={loading}
905
+ style={{
906
+ flex: 1,
907
+ padding: '12px 16px',
908
+ fontSize: '15px',
909
+ borderRadius: '8px',
910
+ border: '1px solid #ddd',
911
+ outline: 'none'
912
+ }}
913
+ />
914
+ <button
915
+ onClick={sendMessage}
916
+ disabled={loading || !input.trim()}
917
+ style={{
918
+ padding: '12px 24px',
919
+ fontSize: '15px',
920
+ borderRadius: '8px',
921
+ border: 'none',
922
+ backgroundColor: loading ? '#ccc' : '#61dafb',
923
+ color: loading ? '#666' : '#fff',
924
+ cursor: loading ? 'not-allowed' : 'pointer',
925
+ fontWeight: 600
926
+ }}
927
+ >
928
+ {loading ? 'Sending...' : 'Send'}
929
+ </button>
930
+ </div>
931
+
932
+ {/* Helper Text */}
933
+ <div style={{
934
+ marginTop: '15px',
935
+ fontSize: '13px',
936
+ color: '#666',
937
+ textAlign: 'center'
938
+ }}>
939
+ 💡 Messages are automatically saved to the repository when backend persistence is enabled.
940
+ <br />
941
+ Use the conversation list to browse and load previous conversations.
942
+ </div>
943
+ </div>
944
+ );
945
+ }
946
+
947
+ export default ChatWithHistory;
948
+ ```
949
+
950
+ ### Key Features Demonstrated
951
+
952
+ ✅ **Load Historic Messages**: Converts `StoredMessage[]` → `ChatMessage[]`
953
+ ✅ **Continue Conversation**: Uses same `conversationKey` to resume context
954
+ ✅ **Real-Time Streaming**: Updates UI with `AiSceneResponse` chunks
955
+ ✅ **Status Indicators**: Shows execution status during streaming
956
+ ✅ **Seamless UX**: Historic + streaming messages in same UI
957
+
958
+ ### Flow Diagram
959
+
960
+ ```
961
+ 1. User clicks "Load Conversation"
962
+ ↓
963
+ 2. GET /api/ai/default/conversations/{key}
964
+ ↓
965
+ 3. Receives StoredConversation (REST JSON)
966
+ ├─ messages: StoredMessage[]
967
+ ├─ conversationKey: "abc-123"
968
+ └─ timestamp, userId, isPublic
969
+ ↓
970
+ 4. Convert to ChatMessage[] and display
971
+ ↓
972
+ 5. User types new message
973
+ ↓
974
+ 6. POST /api/ai/default (SSE streaming)
975
+ settings: { conversationKey: "abc-123" }
976
+ ↓
977
+ 7. Receives AiSceneResponse events (SSE)
978
+ ├─ status: "planning" → "executingScene" → "streaming"
979
+ ├─ streamingChunk: "Hello", " world", "!"
980
+ └─ conversationKey: "abc-123" (same as before)
981
+ ↓
982
+ 8. Backend loads context from cache/repository
983
+ ↓
984
+ 9. LLM generates response using historic context
985
+ ↓
986
+ 10. Response streamed to UI in real-time
987
+ ↓
988
+ 11. Backend saves new messages to repository
989
+ ↓
990
+ 12. Conversation continues seamlessly
991
+ ```
992
+
993
+ ### Best Practices
994
+
995
+ 1. **Separate concerns**: Use `StoredMessage` for storage, `AiSceneResponse` for streaming
996
+ 2. **Flag streaming state**: Add `isStreaming` flag to distinguish live vs historic
997
+ 3. **Show status**: Display execution status (`planning`, `executingScene`) during streaming
998
+ 4. **Handle errors**: Wrap streaming in try-catch and show error messages
999
+ 5. **Auto-save**: Backend automatically persists conversations when repository is enabled
1000
+
1001
+ ---
1002
+
1003
+ ## 📸 Multi-Modal Content (Images, Audio, Video, PDFs)
1004
+
1005
+ PlayFramework supports **base64-encoded media content** in messages. The client provides helper utilities to convert Base64 data to Blob URLs for browser display.
1006
+
1007
+ ### ContentUrlConverter Helper
1008
+
1009
+ Converts `AIContent` (base64 data) to Blob URLs that can be used in HTML `<img>`, `<audio>`, `<video>`, and `<iframe>` elements.
1010
+
1011
+ ```typescript
1012
+ import { ContentUrlConverter, AIContent } from "@rystem/playframework-client";
1013
+
1014
+ const content: AIContent = {
1015
+ type: "data",
1016
+ data: "iVBORw0KGgoAAAANSUhEUgAA...", // Base64 JPEG
1017
+ mediaType: "image/jpeg"
1018
+ };
1019
+
1020
+ // Convert to Blob URL
1021
+ const url = ContentUrlConverter.toBlobUrl(content);
1022
+
1023
+ // Use in <img> tag
1024
+ <img src={url} alt="Image" />
1025
+
1026
+ // IMPORTANT: Cleanup when done (frees memory!)
1027
+ ContentUrlConverter.revokeUrl(url);
1028
+ ```
1029
+
1030
+ ### API Methods
1031
+
1032
+ #### `toBlob(content: AIContent): Blob | null`
1033
+ Decodes Base64 string to Blob object.
1034
+
1035
+ ```typescript
1036
+ const blob = ContentUrlConverter.toBlob(content);
1037
+ ```
1038
+
1039
+ #### `toBlobUrl(content: AIContent, cacheKey?: string): string | null`
1040
+ Creates `blob:` URL for browser display. Supports optional caching.
1041
+
1042
+ ```typescript
1043
+ const url = ContentUrlConverter.toBlobUrl(content, 'image-123');
1044
+ ```
1045
+
1046
+ #### `revokeUrl(url: string, cacheKey?: string): void`
1047
+ Revokes Blob URL to free memory. **Always call this when done!**
1048
+
1049
+ ```typescript
1050
+ ContentUrlConverter.revokeUrl(url, 'image-123');
1051
+ ```
1052
+
1053
+ #### `clearCache(): void`
1054
+ Revokes all cached URLs at once.
1055
+
1056
+ ```typescript
1057
+ ContentUrlConverter.clearCache();
1058
+ ```
1059
+
1060
+ #### `downloadAsFile(content: AIContent, filename?: string): void`
1061
+ Triggers browser download.
1062
+
1063
+ ```typescript
1064
+ ContentUrlConverter.downloadAsFile(content, 'image.jpg');
1065
+ ```
1066
+
1067
+ #### `getFileExtension(mediaType?: string): string`
1068
+ Maps MIME type to file extension.
1069
+
1070
+ ```typescript
1071
+ const ext = ContentUrlConverter.getFileExtension('image/jpeg'); // ".jpg"
1072
+ ```
1073
+
1074
+ ---
1075
+
1076
+ ### React Example: Image Viewer
1077
+
1078
+ ```tsx
1079
+ import { useState, useEffect } from 'react';
1080
+ import { ContentUrlConverter, AIContent } from "@rystem/playframework-client";
1081
+
1082
+ interface ImageViewerProps {
1083
+ content: AIContent;
1084
+ }
1085
+
1086
+ function ImageViewer({ content }: ImageViewerProps) {
1087
+ const [url, setUrl] = useState<string | null>(null);
1088
+
1089
+ useEffect(() => {
1090
+ // Create Blob URL when component mounts
1091
+ const blobUrl = ContentUrlConverter.toBlobUrl(content, `image-${Date.now()}`);
1092
+ setUrl(blobUrl);
1093
+
1094
+ // Cleanup when component unmounts (important for memory!)
1095
+ return () => {
1096
+ if (blobUrl) {
1097
+ ContentUrlConverter.revokeUrl(blobUrl);
1098
+ }
1099
+ };
1100
+ }, [content]);
1101
+
1102
+ if (!url) return <div>Loading image...</div>;
1103
+
1104
+ return (
1105
+ <div>
1106
+ <img src={url} alt="Image" style={{ maxWidth: '100%' }} />
1107
+ <button onClick={() => ContentUrlConverter.downloadAsFile(content, 'image.jpg')}>
1108
+ Download
1109
+ </button>
1110
+ </div>
1111
+ );
1112
+ }
1113
+ ```
1114
+
1115
+ ---
1116
+
1117
+ ### React Example: Auto-Detection Content Viewer
1118
+
1119
+ ```tsx
1120
+ import { ContentUrlConverter, AIContent } from "@rystem/playframework-client";
1121
+
1122
+ function ContentViewer({ content }: { content: AIContent }) {
1123
+ const mediaType = content.mediaType?.toLowerCase() || '';
1124
+ const [url, setUrl] = useState<string | null>(null);
1125
+
1126
+ useEffect(() => {
1127
+ const blobUrl = ContentUrlConverter.toBlobUrl(content);
1128
+ setUrl(blobUrl);
1129
+
1130
+ return () => {
1131
+ if (blobUrl) ContentUrlConverter.revokeUrl(blobUrl);
1132
+ };
1133
+ }, [content]);
1134
+
1135
+ if (!url) return <div>Loading...</div>;
1136
+
1137
+ // Image
1138
+ if (mediaType.startsWith('image/')) {
1139
+ return <img src={url} alt="Image" style={{ maxWidth: '100%' }} />;
1140
+ }
1141
+
1142
+ // Audio
1143
+ if (mediaType.startsWith('audio/')) {
1144
+ return (
1145
+ <audio controls style={{ width: '100%' }}>
1146
+ <source src={url} type={mediaType} />
1147
+ </audio>
1148
+ );
1149
+ }
1150
+
1151
+ // Video
1152
+ if (mediaType.startsWith('video/')) {
1153
+ return (
1154
+ <video controls style={{ maxWidth: '100%' }}>
1155
+ <source src={url} type={mediaType} />
1156
+ </video>
1157
+ );
1158
+ }
1159
+
1160
+ // PDF
1161
+ if (mediaType === 'application/pdf') {
1162
+ return (
1163
+ <iframe
1164
+ src={url}
1165
+ title="PDF Document"
1166
+ style={{ width: '100%', height: '600px', border: '1px solid #ddd' }}
1167
+ />
1168
+ );
1169
+ }
1170
+
1171
+ // Fallback for unknown types
1172
+ return (
1173
+ <div>
1174
+ <p>📎 Attachment: {content.mediaType || 'unknown type'}</p>
1175
+ <button onClick={() => ContentUrlConverter.downloadAsFile(content)}>
1176
+ Download File
1177
+ </button>
1178
+ </div>
1179
+ );
1180
+ }
1181
+ ```
1182
+
1183
+ ---
1184
+
1185
+ ### includeContents Parameter
1186
+
1187
+ When loading conversations, control whether to fetch base64 content:
1188
+
1189
+ ```typescript
1190
+ // ❌ List conversations WITHOUT media (faster, smaller payload)
1191
+ const list = await client.listConversations({
1192
+ includeContents: false, // Default: false
1193
+ take: 50
1194
+ });
1195
+
1196
+ // ✅ Load single conversation WITH media (for display)
1197
+ const conv = await client.getConversation(key, true); // includeContents=true
1198
+ ```
1199
+
1200
+ **Why this matters:**
1201
+
1202
+ | Operation | includeContents | Payload Size | Speed |
1203
+ |-----------|----------------|--------------|-------|
1204
+ | List 100 conversations | `false` | ~50 KB | ⚡ Fast (~50ms) |
1205
+ | List 100 conversations | `true` | ~5-50 MB | 🐢 Slow (~500ms) |
1206
+ | Get single conversation | `true` | ~50-500 KB | ✅ Acceptable |
1207
+
1208
+ **Best Practice**: Always use `includeContents=false` for list operations, `true` only when loading a conversation for display.
1209
+
1210
+ ---
1211
+
1212
+ ### Full Example: Chat with Multi-Modal Support
1213
+
1214
+ ```tsx
1215
+ import { useState, useEffect } from 'react';
1216
+ import { usePlayFramework, StoredMessage, AIContent, ContentUrlConverter } from "@rystem/playframework-client";
1217
+
1218
+ function ChatWithMedia() {
1219
+ const client = usePlayFramework('default');
1220
+ const [messages, setMessages] = useState<StoredMessage[]>([]);
1221
+ const [conversationKey, setConversationKey] = useState<string | null>(null);
1222
+
1223
+ const loadConversation = async (key: string) => {
1224
+ // Load conversation WITH contents
1225
+ const conv = await client.getConversation(key, true);
1226
+
1227
+ if (conv) {
1228
+ setMessages(conv.messages);
1229
+ setConversationKey(conv.conversationKey);
1230
+ }
1231
+ };
1232
+
1233
+ return (
1234
+ <div>
1235
+ <h1>Chat with Media Support</h1>
1236
+
1237
+ {messages.map((msg, i) => (
1238
+ <div key={i} style={{
1239
+ backgroundColor: msg.role === 'user' ? '#e3f2fd' : '#fff',
1240
+ padding: '12px',
1241
+ margin: '8px 0',
1242
+ borderRadius: '8px'
1243
+ }}>
1244
+ <strong>{msg.role === 'user' ? '👤 You' : '🤖 AI'}</strong>
1245
+ <p>{msg.text}</p>
1246
+
1247
+ {/* Display attached content (images, PDFs, etc.) */}
1248
+ {msg.contents && msg.contents.length > 0 && (
1249
+ <div style={{ marginTop: '8px' }}>
1250
+ {msg.contents.map((content, idx) => (
1251
+ <ContentViewer key={idx} content={content} />
1252
+ ))}
1253
+ </div>
1254
+ )}
1255
+ </div>
1256
+ ))}
1257
+
1258
+ <button onClick={() => loadConversation('example-key')}>
1259
+ Load Example Conversation
1260
+ </button>
1261
+ </div>
1262
+ );
1263
+ }
1264
+ ```
1265
+
1266
+ ---
1267
+
1268
+ ### Memory Management Best Practices
1269
+
1270
+ 1. **Always cleanup Blob URLs**: Use `useEffect` cleanup function in React
1271
+ 2. **Use caching for repeated content**: Pass `cacheKey` parameter
1272
+ 3. **Clear cache on unmount**: Call `ContentUrlConverter.clearCache()` when appropriate
1273
+ 4. **Lazy load media**: Only convert to Blob URL when needed for display
1274
+ 5. **Use includeContents wisely**: Exclude contents from list operations
1275
+
1276
+ **Example cleanup:**
1277
+ ```tsx
1278
+ useEffect(() => {
1279
+ const url = ContentUrlConverter.toBlobUrl(content);
1280
+ setImageUrl(url);
1281
+
1282
+ // Cleanup when component unmounts
1283
+ return () => {
1284
+ if (url) ContentUrlConverter.revokeUrl(url);
1285
+ };
1286
+ }, [content]);
1287
+
1288
+ // Clear all on app unmount
1289
+ useEffect(() => {
1290
+ return () => ContentUrlConverter.clearCache();
1291
+ }, []);
1292
+ ```
1293
+
1294
+ ---
1295
+
423
1296
  ## 🚫 Cancellation
424
1297
 
425
1298
  Use `AbortController` to **cancel ongoing requests**:
@@ -453,16 +1326,27 @@ setTimeout(() => controller.abort(), 5000);
453
1326
 
454
1327
  ```typescript
455
1328
  type AiResponseStatus =
456
- | "initializing" // Starting execution
457
- | "planning" // Creating execution plan
458
- | "executingScene" // Running scene/actor
459
- | "functionRequest" // Calling server-side tool
460
- | "functionCompleted" // Tool call completed
461
- | "streaming" // Streaming text chunks
462
- | "awaitingClient" // Waiting for client-side tool
463
- | "completed" // Success
464
- | "error" // Failure
465
- | "budgetExceeded"; // Max cost exceeded
1329
+ | "initializing" // Starting execution
1330
+ | "loadingCache" // Loading cached conversation context
1331
+ | "executingMainActors" // Running global system prompts
1332
+ | "planning" // Creating execution plan
1333
+ | "executingScene" // Running scene/actor
1334
+ | "functionRequest" // Calling server-side tool
1335
+ | "functionCompleted" // Tool call completed
1336
+ | "toolSkipped" // Tool was skipped
1337
+ | "streaming" // Streaming text chunks
1338
+ | "running" // General execution in progress
1339
+ | "summarizing" // Summarizing conversation
1340
+ | "directorDecision" // Director evaluating results
1341
+ | "generatingFinalResponse" // Generating final response
1342
+ | "savingCache" // Saving to cache
1343
+ | "savingMemory" // Saving conversation memory
1344
+ | "awaitingClient" // Waiting for client-side tool response
1345
+ | "commandClient" // Fire-and-forget command sent to client
1346
+ | "completed" // Success
1347
+ | "budgetExceeded" // Max cost exceeded
1348
+ | "error" // Failure
1349
+ | "unauthorized"; // Authorization failed
466
1350
  ```
467
1351
 
468
1352
  ---
@@ -494,50 +1378,88 @@ describe("PlayFramework Client", () => {
494
1378
 
495
1379
  ### `PlayFrameworkServices`
496
1380
 
497
- #### `configure(name: string, baseUrl: string, configure?: (settings: PlayFrameworkSettings) => void): Promise<PlayFrameworkSettings>`
1381
+ Static service locator for managing named `PlayFrameworkClient` instances.
498
1382
 
499
- Configure a PlayFramework client factory.
1383
+ | Method | Signature | Description |
1384
+ |--------|-----------|-------------|
1385
+ | `configure` | `(name: string, baseUrl: string, configure?: (settings: PlayFrameworkSettings) => void \| Promise<void>): Promise<PlayFrameworkSettings>` | Register and configure a named client factory |
1386
+ | `resolve` | `(name?: string): PlayFrameworkClient` | Get client by name (defaults to first registered) |
1387
+ | `getClient` | `(name: string): PlayFrameworkClient` | Get client by exact name (throws if not found) |
1388
+ | `getDefaultClient` | `(): PlayFrameworkClient` | Get the first registered client |
1389
+ | `getSettings` | `(name: string): PlayFrameworkSettings` | Get settings by name (throws if not found) |
1390
+ | `isConfigured` | `(name: string): boolean` | Check if a named client exists |
1391
+ | `remove` | `(name: string): void` | Remove a named client and its settings |
1392
+ | `clear` | `(): void` | Remove all clients and settings |
500
1393
 
501
1394
  ```typescript
1395
+ // Configure
502
1396
  await PlayFrameworkServices.configure("chat", "http://localhost:5158/api/ai");
503
- ```
504
1397
 
505
- #### `resolve(name: string): PlayFrameworkClient`
506
-
507
- Get configured client instance.
508
-
509
- ```typescript
1398
+ // Resolve
510
1399
  const client = PlayFrameworkServices.resolve("chat");
1400
+
1401
+ // Check & remove
1402
+ if (PlayFrameworkServices.isConfigured("chat")) {
1403
+ PlayFrameworkServices.remove("chat");
1404
+ }
511
1405
  ```
512
1406
 
513
1407
  ---
514
1408
 
515
1409
  ### `PlayFrameworkClient`
516
1410
 
517
- #### `executeStepByStep(request: PlayFrameworkRequest, signal?: AbortSignal): AsyncIterableIterator<AiSceneResponse>`
518
-
519
- Execute with **step-by-step streaming** (each scene as separate event).
1411
+ Main client for executing AI requests via SSE streaming.
520
1412
 
521
- #### `executeTokenStreaming(request: PlayFrameworkRequest, signal?: AbortSignal): AsyncIterableIterator<AiSceneResponse>`
1413
+ | Method | Signature | Description |
1414
+ |--------|-----------|-------------|
1415
+ | `executeStepByStep` | `(request: PlayFrameworkRequest, signal?: AbortSignal): AsyncIterableIterator<AiSceneResponse>` | Step-by-step streaming (one event per scene completion) |
1416
+ | `executeTokenStreaming` | `(request: PlayFrameworkRequest, signal?: AbortSignal): AsyncIterableIterator<AiSceneResponse>` | Token-level streaming (one event per text chunk) |
1417
+ | `getClientRegistry` | `(): ClientInteractionRegistry` | Get the client-side tool/command registry |
1418
+ | `getConversation` | `(conversationKey: string): Promise<StoredConversation \| null>` | Load a stored conversation by key |
1419
+ | `getConversations` | `(sortOrder?: ConversationSortOrder): Promise<StoredConversation[]>` | List conversations for the authenticated user |
1420
+ | `deleteConversation` | `(conversationKey: string): Promise<boolean>` | Delete a stored conversation |
522
1421
 
523
- Execute with **token-level streaming** (each text chunk as separate event).
1422
+ ---
524
1423
 
525
- #### `getClientRegistry(): ClientInteractionRegistry`
1424
+ ### `ClientInteractionRegistry`
526
1425
 
527
- Get registry for client-side tools.
1426
+ Registry for client-side tools and commands invoked by the AI during execution.
528
1427
 
529
- ---
1428
+ | Method | Signature | Description |
1429
+ |--------|-----------|-------------|
1430
+ | `register` | `<TArgs>(toolName: string, handler: ClientTool<TArgs>): void` | Register a tool (server waits for response) |
1431
+ | `registerCommand` | `<TArgs>(toolName: string, handler: ClientCommand<TArgs>, options?: CommandOptions): void` | Register a fire-and-forget command |
1432
+ | `execute` | `(request: ClientInteractionRequest): Promise<ClientInteractionResult>` | Execute a registered tool/command |
1433
+ | `has` | `(toolName: string): boolean` | Check if a tool/command is registered |
1434
+ | `isCommand` | `(toolName: string): boolean` | Check if the registration is a command |
1435
+ | `getCommandOptions` | `(toolName: string): CommandOptions \| undefined` | Get the command's feedback options |
1436
+ | `getToolNames` | `(): string[]` | List all registered tool/command names |
1437
+ | `unregister` | `(toolName: string): boolean` | Remove a registration |
1438
+ | `clear` | `(): void` | Remove all registrations |
530
1439
 
531
- ### `ClientInteractionRegistry`
1440
+ **Types:**
532
1441
 
533
- #### `register<TArgs = any>(toolName: string, handler: ClientTool<TArgs>): void`
1442
+ ```typescript
1443
+ type ClientTool<TArgs = any> = (args?: TArgs) => Promise<AIContent[]>;
1444
+ type ClientCommand<TArgs = any> = (args?: TArgs) => Promise<CommandResult>;
1445
+ type CommandFeedbackMode = 'never' | 'onError' | 'always';
534
1446
 
535
- Register client-side tool.
1447
+ interface CommandOptions {
1448
+ feedbackMode?: CommandFeedbackMode;
1449
+ }
1450
+ ```
536
1451
 
537
1452
  ```typescript
1453
+ // Tool — server waits for the result
538
1454
  registry.register("myTool", async (args?: { key: string }) => {
539
1455
  return [AIContentConverter.fromText(args?.key || "default")];
540
1456
  });
1457
+
1458
+ // Command — fire-and-forget, feedback optional
1459
+ registry.registerCommand("showNotification", async (args?: { text: string }) => {
1460
+ showToast(args?.text ?? "");
1461
+ return CommandResult.ok();
1462
+ }, { feedbackMode: 'onError' });
541
1463
  ```
542
1464
 
543
1465
  ---
@@ -575,7 +1497,208 @@ function MyComponent() {
575
1497
 
576
1498
  ---
577
1499
 
578
- ## 📁 Where to Place This README
1500
+ ## � Client Commands (Fire-and-Forget)
1501
+
1502
+ 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.).
1503
+
1504
+ ### Registering Commands
1505
+
1506
+ ```typescript
1507
+ const registry = client.getClientRegistry();
1508
+
1509
+ // Simple command — no feedback to server
1510
+ registry.registerCommand("showToast", async (args?: { text: string }) => {
1511
+ showNotification(args?.text ?? "");
1512
+ return CommandResult.ok();
1513
+ });
1514
+
1515
+ // Command with error feedback — server receives failure info
1516
+ registry.registerCommand("navigateTo", async (args?: { url: string }) => {
1517
+ try {
1518
+ window.location.href = args?.url ?? "/";
1519
+ return CommandResult.ok();
1520
+ } catch (e) {
1521
+ return CommandResult.fail(`Navigation failed: ${e}`);
1522
+ }
1523
+ }, { feedbackMode: 'onError' });
1524
+
1525
+ // Command with always-feedback — server always gets the result
1526
+ registry.registerCommand("playSound", async (args?: { soundId: string }) => {
1527
+ await audioPlayer.play(args?.soundId ?? "notification");
1528
+ return CommandResult.ok("Sound played");
1529
+ }, { feedbackMode: 'always' });
1530
+ ```
1531
+
1532
+ ### `CommandResult` Helper
1533
+
1534
+ ```typescript
1535
+ interface CommandResult {
1536
+ success: boolean;
1537
+ message?: string;
1538
+ }
1539
+
1540
+ // Factory methods
1541
+ CommandResult.ok(); // { success: true }
1542
+ CommandResult.ok("Done"); // { success: true, message: "Done" }
1543
+ CommandResult.fail("Reason"); // { success: false, message: "Reason" }
1544
+ ```
1545
+
1546
+ ### `CommandFeedbackMode`
1547
+
1548
+ | Mode | Behavior |
1549
+ |------|----------|
1550
+ | `'never'` | Server ignores the command's result (default) |
1551
+ | `'onError'` | Server receives feedback only when `success: false` |
1552
+ | `'always'` | Server always receives the command's result |
1553
+
1554
+ ---
1555
+
1556
+ ## 📋 `ClientInteractionRequest` Model
1557
+
1558
+ When the server invokes a client-side tool or command, it sends this object:
1559
+
1560
+ ```typescript
1561
+ interface ClientInteractionRequest {
1562
+ interactionId: string; // Unique ID for this invocation
1563
+ toolName: string; // Registered tool/command name
1564
+ description?: string; // Human-readable description
1565
+ arguments?: Record<string, any>; // Arguments from AI
1566
+ argumentsSchema?: string; // JSON Schema string
1567
+ timeoutSeconds: number; // Max time to wait (tools only)
1568
+ isCommand?: boolean; // true = fire-and-forget command
1569
+ feedbackMode?: 'never' | 'onError' | 'always'; // Command feedback mode
1570
+ }
1571
+ ```
1572
+
1573
+ ---
1574
+
1575
+ ## 📋 `ClientInteractionResult` Model
1576
+
1577
+ The response your tool handler returns to the server:
1578
+
1579
+ ```typescript
1580
+ interface AIContent {
1581
+ type: "text" | "data";
1582
+ text?: string; // For type "text"
1583
+ data?: string; // Base64-encoded (for type "data")
1584
+ mediaType?: string; // e.g., "image/jpeg", "audio/webm"
1585
+ }
1586
+
1587
+ interface ClientInteractionResult {
1588
+ interactionId: string; // Must match the request
1589
+ contents: AIContent[]; // Tool output
1590
+ error?: string; // Error message (if failed)
1591
+ executedAt: string; // ISO 8601 timestamp
1592
+ }
1593
+ ```
1594
+
1595
+ ---
1596
+
1597
+ ## 📋 `ExecutionState` and `ExecutionPhase`
1598
+
1599
+ The `ExecutionState` object tracks the AI orchestration progress during execution:
1600
+
1601
+ ```typescript
1602
+ type ExecutionPhase =
1603
+ | "notStarted"
1604
+ | "initialized"
1605
+ | "sceneSelected"
1606
+ | "executingScene"
1607
+ | "awaitingClient"
1608
+ | "sceneCompleted"
1609
+ | "chaining"
1610
+ | "generatingFinalResponse"
1611
+ | "completed"
1612
+ | "completedNoResponse"
1613
+ | "budgetExceeded"
1614
+ | "sceneNotFound"
1615
+ | "tooManyToolRequests"
1616
+ | "break"
1617
+ | "unauthorized";
1618
+
1619
+ interface ExecutionState {
1620
+ phase: ExecutionPhase; // Current execution phase
1621
+ executedSceneOrder: string[]; // Scene names in execution order
1622
+ executedScenes: Record<string, any[]>; // Scene name → results
1623
+ executedTools: string[]; // Tool names invoked
1624
+ accumulatedCost: number; // Total $ cost so far
1625
+ currentSceneName?: string | null; // Currently running scene
1626
+ }
1627
+ ```
1628
+
1629
+ ---
1630
+
1631
+ ## 📋 `AiSceneResponse` Full Model
1632
+
1633
+ Each SSE event yields an `AiSceneResponse`:
1634
+
1635
+ ```typescript
1636
+ interface AiSceneResponse {
1637
+ status: AiResponseStatus;
1638
+ sceneName?: string;
1639
+ functionName?: string;
1640
+ functionArguments?: string;
1641
+ message?: string; // Final response text (step-by-step)
1642
+ streamingChunk?: string; // Partial text (token streaming)
1643
+ isStreamingComplete?: boolean;
1644
+ errorMessage?: string;
1645
+ inputTokens?: number;
1646
+ cachedInputTokens?: number;
1647
+ outputTokens?: number;
1648
+ totalTokens?: number;
1649
+ cost?: number; // Cost for this step
1650
+ totalCost?: number; // Accumulated total cost
1651
+ conversationKey?: string;
1652
+ continuationToken?: string; // Token for resuming after client tool
1653
+ clientInteractionRequest?: ClientInteractionRequest;
1654
+ timestamp?: string;
1655
+ metadata?: Record<string, any>;
1656
+ contents?: Array<{
1657
+ type: string;
1658
+ text?: string;
1659
+ data?: string; // Base64 encoded
1660
+ mediaType?: string;
1661
+ }>;
1662
+ }
1663
+ ```
1664
+
1665
+ ---
1666
+
1667
+ ## 📋 `StoredMessage` Full Model
1668
+
1669
+ Each message in a `StoredConversation.messages` array:
1670
+
1671
+ ```typescript
1672
+ interface StoredMessage {
1673
+ businessType: number; // Internal type discriminator
1674
+ label?: string | null; // Optional label (e.g., scene name)
1675
+ role: string; // "user" | "assistant" | "system" | "tool"
1676
+ text?: string | null; // Plain text content
1677
+ contents?: any[] | null; // Multi-modal content items
1678
+ additionalProperties?: Record<string, any> | null; // Extra metadata
1679
+ }
1680
+ ```
1681
+
1682
+ ---
1683
+
1684
+ ## 📋 `ContentItem` Full Model
1685
+
1686
+ Used in `PlayFrameworkRequest.contents` for multi-modal input:
1687
+
1688
+ ```typescript
1689
+ interface ContentItem {
1690
+ type: "text" | "image" | "audio" | "video" | "file" | "uri";
1691
+ text?: string; // For type "text"
1692
+ data?: string; // Base64-encoded binary data
1693
+ uri?: string; // For type "uri"
1694
+ mediaType?: string; // MIME type (e.g., "image/png", "audio/webm")
1695
+ name?: string; // Optional filename
1696
+ }
1697
+ ```
1698
+
1699
+ ---
1700
+
1701
+ ## �📁 Where to Place This README
579
1702
 
580
1703
  This README should be placed in:
581
1704
  ```