rystem.playframework.client 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +1617 -47
  2. package/lib/engine/ClientInteractionRegistry.d.ts +48 -1
  3. package/lib/engine/ClientInteractionRegistry.d.ts.map +1 -1
  4. package/lib/engine/ClientInteractionRegistry.js +84 -13
  5. package/lib/engine/PlayFrameworkClient.d.ts +58 -0
  6. package/lib/engine/PlayFrameworkClient.d.ts.map +1 -1
  7. package/lib/engine/PlayFrameworkClient.js +271 -24
  8. package/lib/index.d.ts +17 -1
  9. package/lib/index.d.ts.map +1 -1
  10. package/lib/index.js +15 -1
  11. package/lib/models/AiSceneResponse.d.ts +2 -2
  12. package/lib/models/AiSceneResponse.d.ts.map +1 -1
  13. package/lib/models/ClientInteractionRequest.d.ts +15 -0
  14. package/lib/models/ClientInteractionRequest.d.ts.map +1 -1
  15. package/lib/models/CommandResult.d.ts +31 -0
  16. package/lib/models/CommandResult.d.ts.map +1 -0
  17. package/lib/models/CommandResult.js +18 -0
  18. package/lib/models/ExecutionState.d.ts +35 -0
  19. package/lib/models/ExecutionState.d.ts.map +1 -0
  20. package/lib/models/ExecutionState.js +2 -0
  21. package/lib/models/PlayFrameworkRequest.d.ts +10 -0
  22. package/lib/models/PlayFrameworkRequest.d.ts.map +1 -1
  23. package/lib/models/StoredConversation.d.ts +88 -0
  24. package/lib/models/StoredConversation.d.ts.map +1 -0
  25. package/lib/models/StoredConversation.js +17 -0
  26. package/lib/models/StoredMessage.d.ts +30 -0
  27. package/lib/models/StoredMessage.d.ts.map +1 -0
  28. package/lib/models/StoredMessage.js +2 -0
  29. package/lib/models/VoiceResponse.d.ts +39 -0
  30. package/lib/models/VoiceResponse.d.ts.map +1 -0
  31. package/lib/models/VoiceResponse.js +2 -0
  32. package/lib/utils/BrowserSpeechRecognizer.d.ts +128 -0
  33. package/lib/utils/BrowserSpeechRecognizer.d.ts.map +1 -0
  34. package/lib/utils/BrowserSpeechRecognizer.js +150 -0
  35. package/lib/utils/BrowserSpeechSynthesizer.d.ts +148 -0
  36. package/lib/utils/BrowserSpeechSynthesizer.d.ts.map +1 -0
  37. package/lib/utils/BrowserSpeechSynthesizer.js +400 -0
  38. package/lib/utils/BrowserVoiceClient.d.ts +142 -0
  39. package/lib/utils/BrowserVoiceClient.d.ts.map +1 -0
  40. package/lib/utils/BrowserVoiceClient.js +200 -0
  41. package/lib/utils/ContentUrlConverter.d.ts +62 -0
  42. package/lib/utils/ContentUrlConverter.d.ts.map +1 -0
  43. package/lib/utils/ContentUrlConverter.js +151 -0
  44. package/lib/utils/VoiceRecorder.d.ts +90 -0
  45. package/lib/utils/VoiceRecorder.d.ts.map +1 -0
  46. package/lib/utils/VoiceRecorder.js +195 -0
  47. package/package.json +1 -1
@@ -1,16 +1,40 @@
1
1
  import { ClientInteractionRequest } from "../models/ClientInteractionRequest";
2
2
  import { ClientInteractionResult, AIContent } from "../models/ClientInteractionResult";
3
+ import { CommandResult } from "../models/CommandResult";
3
4
  /**
4
5
  * Type for client-side tool implementation.
5
6
  * Takes optional arguments and returns AIContent array.
6
7
  */
7
8
  export type ClientTool<TArgs = any> = (args?: TArgs) => Promise<AIContent[]>;
9
+ /**
10
+ * Type for client-side command implementation.
11
+ * Takes optional arguments and returns CommandResult (success + optional message).
12
+ */
13
+ export type ClientCommand<TArgs = any> = (args?: TArgs) => Promise<CommandResult>;
14
+ /**
15
+ * Command feedback modes:
16
+ * - 'never': Never send feedback (silent command)
17
+ * - 'onError': Send feedback only on failure (default)
18
+ * - 'always': Always send feedback (even on success)
19
+ */
20
+ export type CommandFeedbackMode = 'never' | 'onError' | 'always';
21
+ /**
22
+ * Options for command registration.
23
+ */
24
+ export interface CommandOptions {
25
+ /**
26
+ * When to send feedback to the server.
27
+ * @default 'onError'
28
+ */
29
+ feedbackMode?: CommandFeedbackMode;
30
+ }
8
31
  /**
9
32
  * Registry for client-side tools (camera, geolocation, file picker, etc.).
10
33
  * Tools are registered once and executed when server requests them.
11
34
  */
12
35
  export declare class ClientInteractionRegistry {
13
36
  private tools;
37
+ private commands;
14
38
  /**
15
39
  * Registers a client-side tool.
16
40
  * @param toolName - Unique tool name matching server OnClient() registration.
@@ -25,7 +49,30 @@ export declare class ClientInteractionRegistry {
25
49
  */
26
50
  register<TArgs = any>(toolName: string, implementation: ClientTool<TArgs>): void;
27
51
  /**
28
- * Executes a registered tool and returns the result.
52
+ * Registers a command (fire-and-forget tool).
53
+ * Commands return CommandResult and can optionally send feedback based on feedbackMode.
54
+ * @param toolName - Unique command name matching server AddCommand() registration.
55
+ * @param implementation - Async function that returns CommandResult.
56
+ * @param options - Feedback configuration.
57
+ *
58
+ * @example
59
+ * registry.registerCommand("logAction", async (args) => {
60
+ * console.log(args.action);
61
+ * return CommandResult.ok();
62
+ * }, { feedbackMode: 'never' });
63
+ */
64
+ registerCommand<TArgs = any>(toolName: string, implementation: ClientCommand<TArgs>, options?: CommandOptions): void;
65
+ /**
66
+ * Checks if a tool is registered as a command.
67
+ */
68
+ isCommand(toolName: string): boolean;
69
+ /**
70
+ * Gets command options.
71
+ */
72
+ getCommandOptions(toolName: string): CommandOptions | undefined;
73
+ /**
74
+ * Executes a registered tool/command and returns the result.
75
+ * For commands, converts CommandResult to AIContent[] if needed.
29
76
  * @param request - Client interaction request from server.
30
77
  * @returns ClientInteractionResult with contents or error.
31
78
  *
@@ -1 +1 @@
1
- {"version":3,"file":"ClientInteractionRegistry.d.ts","sourceRoot":"","sources":["../../src/engine/ClientInteractionRegistry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAC9E,OAAO,EAAE,uBAAuB,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAC;AAEvF;;;GAGG;AACH,MAAM,MAAM,UAAU,CAAC,KAAK,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,KAAK,KAAK,OAAO,CAAC,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,EAAE,mBAAmB,CAAC;CACtC;AAED;;;GAGG;AACH,qBAAa,yBAAyB;IAClC,OAAO,CAAC,KAAK,CAAsD;IACnE,OAAO,CAAC,QAAQ,CAA0C;IAE1D;;;;;;;;;;;OAWG;IACI,QAAQ,CAAC,KAAK,GAAG,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,cAAc,EAAE,UAAU,CAAC,KAAK,CAAC,GAAG,IAAI;IAQvF;;;;;;;;;;;;OAYG;IACI,eAAe,CAAC,KAAK,GAAG,GAAG,EAC9B,QAAQ,EAAE,MAAM,EAChB,cAAc,EAAE,aAAa,CAAC,KAAK,CAAC,EACpC,OAAO,CAAC,EAAE,cAAc,GACzB,IAAI;IAUP;;OAEG;IACI,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;IAI3C;;OAEG;IACI,iBAAiB,CAAC,QAAQ,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS;IAItE;;;;;;;;;OASG;IACU,OAAO,CAAC,OAAO,EAAE,wBAAwB,GAAG,OAAO,CAAC,uBAAuB,CAAC;IAmFzF;;OAEG;IACI,GAAG,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;IAIrC;;OAEG;IACI,YAAY,IAAI,MAAM,EAAE;IAI/B;;OAEG;IACI,UAAU,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;IAI5C;;OAEG;IACI,KAAK,IAAI,IAAI;CAGvB"}
@@ -7,6 +7,7 @@ exports.ClientInteractionRegistry = void 0;
7
7
  */
8
8
  class ClientInteractionRegistry {
9
9
  tools = new Map();
10
+ commands = new Map();
10
11
  /**
11
12
  * Registers a client-side tool.
12
13
  * @param toolName - Unique tool name matching server OnClient() registration.
@@ -24,9 +25,45 @@ class ClientInteractionRegistry {
24
25
  console.warn(`ClientInteractionRegistry: Tool "${toolName}" is already registered. Overwriting.`);
25
26
  }
26
27
  this.tools.set(toolName, implementation);
28
+ this.commands.delete(toolName); // Remove from commands if re-registered as tool
27
29
  }
28
30
  /**
29
- * Executes a registered tool and returns the result.
31
+ * Registers a command (fire-and-forget tool).
32
+ * Commands return CommandResult and can optionally send feedback based on feedbackMode.
33
+ * @param toolName - Unique command name matching server AddCommand() registration.
34
+ * @param implementation - Async function that returns CommandResult.
35
+ * @param options - Feedback configuration.
36
+ *
37
+ * @example
38
+ * registry.registerCommand("logAction", async (args) => {
39
+ * console.log(args.action);
40
+ * return CommandResult.ok();
41
+ * }, { feedbackMode: 'never' });
42
+ */
43
+ registerCommand(toolName, implementation, options) {
44
+ if (this.tools.has(toolName)) {
45
+ console.warn(`ClientInteractionRegistry: Command "${toolName}" is already registered. Overwriting.`);
46
+ }
47
+ this.tools.set(toolName, implementation);
48
+ this.commands.set(toolName, {
49
+ feedbackMode: options?.feedbackMode ?? 'onError'
50
+ });
51
+ }
52
+ /**
53
+ * Checks if a tool is registered as a command.
54
+ */
55
+ isCommand(toolName) {
56
+ return this.commands.has(toolName);
57
+ }
58
+ /**
59
+ * Gets command options.
60
+ */
61
+ getCommandOptions(toolName) {
62
+ return this.commands.get(toolName);
63
+ }
64
+ /**
65
+ * Executes a registered tool/command and returns the result.
66
+ * For commands, converts CommandResult to AIContent[] if needed.
30
67
  * @param request - Client interaction request from server.
31
68
  * @returns ClientInteractionResult with contents or error.
32
69
  *
@@ -46,21 +83,55 @@ class ClientInteractionRegistry {
46
83
  executedAt: new Date().toISOString()
47
84
  };
48
85
  }
49
- // Execute tool with timeout
50
- let timer;
51
- const timeoutPromise = new Promise((_, reject) => {
52
- timer = setTimeout(() => {
53
- reject(new Error(`Tool execution timeout after ${request.timeoutSeconds}s`));
54
- }, request.timeoutSeconds * 1000);
55
- });
86
+ const isCommand = this.isCommand(request.toolName);
87
+ // Execute tool with timeout (protects against client-side hangs/crashes)
88
+ const timeoutMs = request.timeoutSeconds > 0 ? request.timeoutSeconds * 1000 : 0;
56
89
  const executionPromise = tool(request.arguments);
90
+ let result;
91
+ if (timeoutMs > 0) {
92
+ let timer;
93
+ const timeoutPromise = new Promise((_, reject) => {
94
+ timer = setTimeout(() => {
95
+ reject(new Error(`Tool execution timeout after ${request.timeoutSeconds}s`));
96
+ }, timeoutMs);
97
+ });
98
+ try {
99
+ result = await Promise.race([executionPromise, timeoutPromise]);
100
+ }
101
+ finally {
102
+ if (timer !== undefined)
103
+ clearTimeout(timer);
104
+ }
105
+ }
106
+ else {
107
+ // No timeout — wait indefinitely for the tool to complete
108
+ result = await executionPromise;
109
+ }
110
+ // If it's a command, convert CommandResult to AIContent[]
57
111
  let contents;
58
- try {
59
- contents = await Promise.race([executionPromise, timeoutPromise]);
112
+ if (isCommand && 'success' in result) {
113
+ const cmdResult = result;
114
+ const commandOptions = this.getCommandOptions(request.toolName);
115
+ const feedbackMode = commandOptions?.feedbackMode ?? 'onError';
116
+ // Determine if feedback should be sent
117
+ const shouldSendFeedback = feedbackMode === 'always' ||
118
+ (feedbackMode === 'onError' && !cmdResult.success);
119
+ if (shouldSendFeedback) {
120
+ // Send feedback (success + message)
121
+ contents = [
122
+ { type: 'text', text: cmdResult.success ? 'true' : 'false' }
123
+ ];
124
+ if (cmdResult.message) {
125
+ contents.push({ type: 'text', text: cmdResult.message });
126
+ }
127
+ }
128
+ else {
129
+ // No feedback mode - send minimal success indicator
130
+ contents = [{ type: 'text', text: 'true' }];
131
+ }
60
132
  }
61
- finally {
62
- if (timer !== undefined)
63
- clearTimeout(timer);
133
+ else {
134
+ contents = result;
64
135
  }
65
136
  return {
66
137
  interactionId: request.interactionId,
@@ -2,6 +2,8 @@ import { PlayFrameworkRequest } from "../models/PlayFrameworkRequest";
2
2
  import { AiSceneResponse } from "../models/AiSceneResponse";
3
3
  import { PlayFrameworkSettings } from "../servicecollection/PlayFrameworkSettings";
4
4
  import { ClientInteractionRegistry } from "./ClientInteractionRegistry";
5
+ import type { StoredConversation, ConversationQueryParameters } from "../models/StoredConversation";
6
+ import type { VoiceEvent, VoiceRequestOptions } from "../models/VoiceResponse";
5
7
  /**
6
8
  * PlayFramework HTTP client with step-by-step and token-level streaming support.
7
9
  * Supports client-side tool execution with continuation tokens.
@@ -42,5 +44,61 @@ export declare class PlayFrameworkClient {
42
44
  * and automatic reconnection on network failures.
43
45
  */
44
46
  private streamSSE;
47
+ /**
48
+ * Lists conversations with filtering, sorting, and pagination.
49
+ *
50
+ * @param params - Query parameters for filtering and pagination.
51
+ * @param signal - AbortSignal for cancellation.
52
+ * @returns Promise<StoredConversation[]>
53
+ */
54
+ listConversations(params?: ConversationQueryParameters, signal?: AbortSignal): Promise<StoredConversation[]>;
55
+ /**
56
+ * Gets a single conversation by key.
57
+ *
58
+ * @param conversationKey - The conversation key to retrieve.
59
+ * @param includeContents - Whether to include message contents (images, audio, PDFs). Default: false.
60
+ * @param signal - AbortSignal for cancellation.
61
+ * @returns Promise<StoredConversation | null>
62
+ */
63
+ getConversation(conversationKey: string, includeContents?: boolean, signal?: AbortSignal): Promise<StoredConversation | null>;
64
+ /**
65
+ * Deletes a conversation (owner only).
66
+ *
67
+ * @param conversationKey - The conversation key to delete.
68
+ * @param signal - AbortSignal for cancellation.
69
+ * @returns Promise<void>
70
+ */
71
+ deleteConversation(conversationKey: string, signal?: AbortSignal): Promise<void>;
72
+ /**
73
+ * Updates conversation visibility (public/private).
74
+ *
75
+ * @param conversationKey - The conversation key to update.
76
+ * @param isPublic - Whether the conversation should be public.
77
+ * @param signal - AbortSignal for cancellation.
78
+ * @returns Promise<StoredConversation>
79
+ */
80
+ updateConversationVisibility(conversationKey: string, isPublic: boolean, signal?: AbortSignal): Promise<StoredConversation>;
81
+ /**
82
+ * Helper to build query string from parameters.
83
+ */
84
+ private buildQueryString;
85
+ /**
86
+ * Execute the voice pipeline: audio → STT → PlayFramework → TTS → audio streaming.
87
+ * Sends audio as multipart/form-data, receives SSE stream of VoiceEvent.
88
+ *
89
+ * @param options - Voice request options (audio blob, conversationKey, metadata).
90
+ * @returns AsyncIterableIterator of VoiceEvent (transcription, audio chunks, scene events, completion).
91
+ *
92
+ * @example
93
+ * ```ts
94
+ * const audioBlob = await recordAudio();
95
+ * for await (const event of client.executeVoice({ audio: audioBlob })) {
96
+ * if (event.type === 'transcription') console.log('User said:', event.text);
97
+ * if (event.type === 'audio') playAudioBase64(event.audio!);
98
+ * if (event.type === 'scene') console.log('Scene:', event.status, event.message);
99
+ * }
100
+ * ```
101
+ */
102
+ executeVoice(options: VoiceRequestOptions): AsyncIterableIterator<VoiceEvent>;
45
103
  }
46
104
  //# sourceMappingURL=PlayFrameworkClient.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"PlayFrameworkClient.d.ts","sourceRoot":"","sources":["../../src/engine/PlayFrameworkClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAAE,eAAe,EAAyB,MAAM,2BAA2B,CAAC;AACnF,OAAO,EAAE,qBAAqB,EAAE,MAAM,4CAA4C,CAAC;AACnF,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AAGxE;;;GAGG;AACH,qBAAa,mBAAmB;IAC5B,OAAO,CAAC,QAAQ,CAAwB;IACxC,OAAO,CAAC,cAAc,CAA4B;gBAEtC,QAAQ,EAAE,qBAAqB,EAAE,cAAc,CAAC,EAAE,yBAAyB;IAKvF;;OAEG;IACI,iBAAiB,IAAI,yBAAyB;IAIrD;;;;;;;OAOG;IACW,iBAAiB,CAC3B,OAAO,EAAE,oBAAoB,EAC7B,MAAM,CAAC,EAAE,WAAW,GACrB,qBAAqB,CAAC,eAAe,CAAC;IAKzC;;;;;;;OAOG;IACW,qBAAqB,CAC/B,OAAO,EAAE,oBAAoB,EAC7B,MAAM,CAAC,EAAE,WAAW,GACrB,qBAAqB,CAAC,eAAe,CAAC;IAKzC;;;OAGG;IACH,OAAO,CAAC,mBAAmB;IAuB3B;;;OAGG;YACY,SAAS;CA6J3B"}
1
+ {"version":3,"file":"PlayFrameworkClient.d.ts","sourceRoot":"","sources":["../../src/engine/PlayFrameworkClient.ts"],"names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AE,MAAM,EACvB,MAAM,CAAC,EAAE,WAAW,GACrB,OAAO,CAAC,IAAI,CAAC;IAgBhB;;;;;;;OAOG;IACU,4BAA4B,CACrC,eAAe,EAAE,MAAM,EACvB,QAAQ,EAAE,OAAO,EACjB,MAAM,CAAC,EAAE,WAAW,GACrB,OAAO,CAAC,kBAAkB,CAAC;IAoB9B;;OAEG;IACH,OAAO,CAAC,gBAAgB;IAoCxB;;;;;;;;;;;;;;;;OAgBG;IACW,YAAY,CACtB,OAAO,EAAE,mBAAmB,GAC7B,qBAAqB,CAAC,UAAU,CAAC;CAgFvC"}
@@ -78,7 +78,9 @@ class PlayFrameworkClient {
78
78
  while (shouldContinue) {
79
79
  const headers = await this.settings.enrichHeaders(url, "POST", undefined, currentRequest);
80
80
  let reconnectAttempts = 0;
81
- let awaitingClientResponse = null; // Reset for each request iteration
81
+ // Collect ALL client interaction responses (server may send multiple in a single batch)
82
+ const pendingInteractions = [];
83
+ let capturedConversationKey;
82
84
  let shouldRetry = true;
83
85
  while (shouldRetry) {
84
86
  try {
@@ -124,20 +126,27 @@ class PlayFrameworkClient {
124
126
  }
125
127
  // Check for completion/error markers
126
128
  if (event.status === "completed") {
127
- // Don't set shouldContinue = false yet - check if client interaction needed first
129
+ // Don't set shouldContinue = false yet - check if client interactions needed first
128
130
  shouldRetry = false; // Don't retry, stream closed successfully
129
- break; // Exit read loop to handle client interaction if needed
131
+ break; // Exit read loop to handle client interactions if needed
130
132
  }
131
133
  if (event.status === "error") {
132
134
  shouldContinue = false;
133
135
  shouldRetry = false; // Don't retry on error
134
136
  throw new Error(event.errorMessage || "Unknown error");
135
137
  }
136
- // Check for AwaitingClient status (camelCase from server)
137
- if (event.status === "awaitingClient") {
138
- awaitingClientResponse = event;
139
- console.log('⏸️ [PlayFrameworkClient] Received awaitingClient, tool:', awaitingClientResponse.clientInteractionRequest?.toolName);
140
- yield awaitingClientResponse; // Yield to user
138
+ // Check for AwaitingClient or CommandClient status (camelCase from JsonStringEnumConverter)
139
+ if (event.status === "awaitingClient" || event.status === "commandClient") {
140
+ const interactionResponse = event;
141
+ const isCommand = event.status === "commandClient";
142
+ console.log(isCommand ? '🔥 [PlayFrameworkClient] Received CommandClient (fire-and-forget)' : '⏸️ [PlayFrameworkClient] Received AwaitingClient', ', tool:', interactionResponse.clientInteractionRequest?.toolName);
143
+ // Capture conversationKey from the response (server sets it for resume)
144
+ if (interactionResponse.conversationKey) {
145
+ capturedConversationKey = interactionResponse.conversationKey;
146
+ }
147
+ // Collect ALL interactions (don't overwrite — the server may send multiple)
148
+ pendingInteractions.push(interactionResponse);
149
+ yield interactionResponse; // Yield to user
141
150
  // Don't break - continue reading until stream closes
142
151
  continue; // Skip the second yield below to avoid duplication
143
152
  }
@@ -153,22 +162,51 @@ class PlayFrameworkClient {
153
162
  reader.releaseLock();
154
163
  }
155
164
  shouldRetry = false; // Success, no retry
156
- // Handle client interaction if AwaitingClient (and stream wasn't closed by completed/error)
157
- if (shouldContinue && awaitingClientResponse?.clientInteractionRequest) {
158
- const clientRequest = awaitingClientResponse.clientInteractionRequest;
159
- console.log('🔧 [PlayFrameworkClient] Executing client tool:', clientRequest.toolName);
160
- // Execute client tool
161
- const result = await this.clientRegistry.execute(clientRequest);
162
- console.log('✅ [PlayFrameworkClient] Client tool completed, resuming with results');
163
- // Prepare new request with client interaction results
164
- // The server uses conversationKey + cache to restore context
165
- currentRequest = {
166
- ...currentRequest,
167
- clientInteractionResults: [result]
168
- };
169
- console.log('📤 [PlayFrameworkClient] Sending resume request with clientInteractionResults');
170
- // Continue loop to resume execution
171
- shouldContinue = true;
165
+ // Handle client interactions if any were received during this stream
166
+ if (shouldContinue && pendingInteractions.length > 0) {
167
+ console.log(`🔧 [PlayFrameworkClient] Executing ${pendingInteractions.length} client interaction(s)`);
168
+ // Execute ALL pending interactions in parallel
169
+ const allResults = [];
170
+ let hasNonCommandInteraction = false;
171
+ for (const interaction of pendingInteractions) {
172
+ const clientRequest = interaction.clientInteractionRequest;
173
+ if (!clientRequest)
174
+ continue;
175
+ console.log(`🔧 [PlayFrameworkClient] Executing: ${clientRequest.toolName} (${clientRequest.isCommand ? 'command' : 'tool'})`);
176
+ const result = await this.clientRegistry.execute(clientRequest);
177
+ if (clientRequest.isCommand === true) {
178
+ // Command: check feedbackMode to decide whether to send result
179
+ const feedbackMode = clientRequest.feedbackMode ?? 'onError';
180
+ if (feedbackMode === 'always') {
181
+ allResults.push(result);
182
+ }
183
+ else if (feedbackMode === 'onError' && result.error) {
184
+ allResults.push(result);
185
+ }
186
+ // feedbackMode === 'never': don't send result
187
+ }
188
+ else {
189
+ // Tool (AwaitingClient): always send result
190
+ hasNonCommandInteraction = true;
191
+ allResults.push(result);
192
+ }
193
+ }
194
+ if (hasNonCommandInteraction || allResults.length > 0) {
195
+ console.log(`✅ [PlayFrameworkClient] ${allResults.length} result(s) to send back, resuming`);
196
+ // Prepare resume request with ALL applicable results
197
+ // Use captured conversationKey so the server finds the batch in cache
198
+ currentRequest = {
199
+ ...currentRequest,
200
+ clientInteractionResults: allResults,
201
+ conversationKey: capturedConversationKey ?? currentRequest.conversationKey
202
+ };
203
+ console.log('📤 [PlayFrameworkClient] Sending resume request with clientInteractionResults');
204
+ shouldContinue = true;
205
+ }
206
+ else {
207
+ console.log('✅ [PlayFrameworkClient] All interactions were fire-and-forget commands. No resume needed.');
208
+ shouldContinue = false;
209
+ }
172
210
  }
173
211
  else {
174
212
  console.log('✅ [PlayFrameworkClient] Stream completed normally (no client interaction)');
@@ -196,5 +234,214 @@ class PlayFrameworkClient {
196
234
  }
197
235
  }
198
236
  }
237
+ // ─── Conversation Management Methods ────────────────────────────────────────
238
+ /**
239
+ * Lists conversations with filtering, sorting, and pagination.
240
+ *
241
+ * @param params - Query parameters for filtering and pagination.
242
+ * @param signal - AbortSignal for cancellation.
243
+ * @returns Promise<StoredConversation[]>
244
+ */
245
+ async listConversations(params, signal) {
246
+ const queryString = this.buildQueryString(params || {});
247
+ const url = `${this.settings.baseUrl}/${this.settings.factoryName}/conversations${queryString}`;
248
+ const headers = await this.settings.enrichHeaders(url, "GET", undefined, undefined);
249
+ const effectiveSignal = this.createTimeoutSignal(signal);
250
+ const response = await fetch(url, {
251
+ method: "GET",
252
+ headers,
253
+ signal: effectiveSignal
254
+ });
255
+ if (!response.ok) {
256
+ throw new Error(`Failed to list conversations: ${response.statusText}`);
257
+ }
258
+ return await response.json();
259
+ }
260
+ /**
261
+ * Gets a single conversation by key.
262
+ *
263
+ * @param conversationKey - The conversation key to retrieve.
264
+ * @param includeContents - Whether to include message contents (images, audio, PDFs). Default: false.
265
+ * @param signal - AbortSignal for cancellation.
266
+ * @returns Promise<StoredConversation | null>
267
+ */
268
+ async getConversation(conversationKey, includeContents = false, signal) {
269
+ const queryString = includeContents ? '?includeContents=true' : '';
270
+ const url = `${this.settings.baseUrl}/${this.settings.factoryName}/conversations/${conversationKey}${queryString}`;
271
+ const headers = await this.settings.enrichHeaders(url, "GET", undefined, undefined);
272
+ const effectiveSignal = this.createTimeoutSignal(signal);
273
+ const response = await fetch(url, {
274
+ method: "GET",
275
+ headers,
276
+ signal: effectiveSignal
277
+ });
278
+ if (response.status === 404) {
279
+ return null;
280
+ }
281
+ if (!response.ok) {
282
+ throw new Error(`Failed to get conversation: ${response.statusText}`);
283
+ }
284
+ return await response.json();
285
+ }
286
+ /**
287
+ * Deletes a conversation (owner only).
288
+ *
289
+ * @param conversationKey - The conversation key to delete.
290
+ * @param signal - AbortSignal for cancellation.
291
+ * @returns Promise<void>
292
+ */
293
+ async deleteConversation(conversationKey, signal) {
294
+ const url = `${this.settings.baseUrl}/${this.settings.factoryName}/conversations/${conversationKey}`;
295
+ const headers = await this.settings.enrichHeaders(url, "DELETE", undefined, undefined);
296
+ const effectiveSignal = this.createTimeoutSignal(signal);
297
+ const response = await fetch(url, {
298
+ method: "DELETE",
299
+ headers,
300
+ signal: effectiveSignal
301
+ });
302
+ if (!response.ok) {
303
+ throw new Error(`Failed to delete conversation: ${response.statusText}`);
304
+ }
305
+ }
306
+ /**
307
+ * Updates conversation visibility (public/private).
308
+ *
309
+ * @param conversationKey - The conversation key to update.
310
+ * @param isPublic - Whether the conversation should be public.
311
+ * @param signal - AbortSignal for cancellation.
312
+ * @returns Promise<StoredConversation>
313
+ */
314
+ async updateConversationVisibility(conversationKey, isPublic, signal) {
315
+ const url = `${this.settings.baseUrl}/${this.settings.factoryName}/conversations/${conversationKey}/visibility`;
316
+ const body = { isPublic };
317
+ const headers = await this.settings.enrichHeaders(url, "PATCH", undefined, body);
318
+ const effectiveSignal = this.createTimeoutSignal(signal);
319
+ const response = await fetch(url, {
320
+ method: "PATCH",
321
+ headers,
322
+ body: JSON.stringify(body),
323
+ signal: effectiveSignal
324
+ });
325
+ if (!response.ok) {
326
+ throw new Error(`Failed to update conversation visibility: ${response.statusText}`);
327
+ }
328
+ return await response.json();
329
+ }
330
+ /**
331
+ * Helper to build query string from parameters.
332
+ */
333
+ buildQueryString(params) {
334
+ const queryParams = [];
335
+ if (params.searchText) {
336
+ queryParams.push(`searchText=${encodeURIComponent(params.searchText)}`);
337
+ }
338
+ // OrderBy - default to TimestampDescending (0) if not provided
339
+ const orderBy = params.orderBy !== undefined ? params.orderBy : 0;
340
+ queryParams.push(`orderBy=${orderBy}`);
341
+ // IncludePublic - default to true if not provided
342
+ const includePublic = params.includePublic !== undefined ? params.includePublic : true;
343
+ queryParams.push(`includePublic=${includePublic}`);
344
+ // IncludePrivate - default to true if not provided
345
+ const includePrivate = params.includePrivate !== undefined ? params.includePrivate : true;
346
+ queryParams.push(`includePrivate=${includePrivate}`);
347
+ // Skip - default to 0 if not provided (REQUIRED by backend)
348
+ const skip = params.skip !== undefined ? params.skip : 0;
349
+ queryParams.push(`skip=${skip}`);
350
+ // Take - default to 50 if not provided
351
+ const take = params.take !== undefined ? params.take : 50;
352
+ queryParams.push(`take=${take}`);
353
+ // IncludeContents - default to false if not provided
354
+ const includeContents = params.includeContents !== undefined ? params.includeContents : false;
355
+ queryParams.push(`includeContents=${includeContents}`);
356
+ return queryParams.length > 0 ? `?${queryParams.join('&')}` : '';
357
+ }
358
+ // ─── Voice Pipeline Methods ──────────────────────────────────────────────────
359
+ /**
360
+ * Execute the voice pipeline: audio → STT → PlayFramework → TTS → audio streaming.
361
+ * Sends audio as multipart/form-data, receives SSE stream of VoiceEvent.
362
+ *
363
+ * @param options - Voice request options (audio blob, conversationKey, metadata).
364
+ * @returns AsyncIterableIterator of VoiceEvent (transcription, audio chunks, scene events, completion).
365
+ *
366
+ * @example
367
+ * ```ts
368
+ * const audioBlob = await recordAudio();
369
+ * for await (const event of client.executeVoice({ audio: audioBlob })) {
370
+ * if (event.type === 'transcription') console.log('User said:', event.text);
371
+ * if (event.type === 'audio') playAudioBase64(event.audio!);
372
+ * if (event.type === 'scene') console.log('Scene:', event.status, event.message);
373
+ * }
374
+ * ```
375
+ */
376
+ async *executeVoice(options) {
377
+ const url = `${this.settings.baseUrl}/${this.settings.factoryName}/voice`;
378
+ const effectiveSignal = this.createTimeoutSignal(options.signal);
379
+ // Build multipart/form-data
380
+ const formData = new FormData();
381
+ const audioFile = options.audio instanceof File
382
+ ? options.audio
383
+ : new File([options.audio], 'recording.webm', { type: options.audio.type || 'audio/webm' });
384
+ formData.append('audio', audioFile);
385
+ if (options.conversationKey) {
386
+ formData.append('conversationKey', options.conversationKey);
387
+ }
388
+ if (options.metadata) {
389
+ formData.append('metadata', JSON.stringify(options.metadata));
390
+ }
391
+ // Build headers WITHOUT Content-Type (browser sets multipart boundary automatically)
392
+ const baseHeaders = await this.settings.enrichHeaders(url, "POST", undefined, undefined);
393
+ const headers = new Headers(baseHeaders);
394
+ headers.delete('Content-Type'); // Let browser set multipart boundary
395
+ const response = await fetch(url, {
396
+ method: 'POST',
397
+ headers,
398
+ body: formData,
399
+ signal: effectiveSignal || undefined
400
+ });
401
+ if (!response.ok) {
402
+ const errorText = await response.text().catch(() => response.statusText);
403
+ throw new Error(`Voice pipeline error (${response.status}): ${errorText}`);
404
+ }
405
+ if (!response.body) {
406
+ throw new Error('Response body is null');
407
+ }
408
+ // Parse SSE stream
409
+ const reader = response.body.getReader();
410
+ const decoder = new TextDecoder();
411
+ let buffer = '';
412
+ try {
413
+ while (true) {
414
+ const { done, value } = await reader.read();
415
+ if (done)
416
+ break;
417
+ buffer += decoder.decode(value, { stream: true });
418
+ const lines = buffer.split('\n');
419
+ buffer = lines.pop() || '';
420
+ for (const line of lines) {
421
+ if (line.startsWith('data: ')) {
422
+ const data = line.substring(6).trim();
423
+ if (!data)
424
+ continue;
425
+ let event;
426
+ try {
427
+ event = JSON.parse(data);
428
+ }
429
+ catch {
430
+ console.error('Failed to parse voice SSE event:', data);
431
+ continue;
432
+ }
433
+ yield event;
434
+ // Stop on completed or error
435
+ if (event.type === 'completed' || event.type === 'error') {
436
+ return;
437
+ }
438
+ }
439
+ }
440
+ }
441
+ }
442
+ finally {
443
+ reader.releaseLock();
444
+ }
445
+ }
199
446
  }
200
447
  exports.PlayFrameworkClient = PlayFrameworkClient;
package/lib/index.d.ts CHANGED
@@ -3,10 +3,26 @@ export type { PlayFrameworkRequest, SceneRequestSettings, SceneExecutionMode, Ca
3
3
  export type { AiSceneResponse, AiResponseStatus, SSEEvent, CompletionMarker, ErrorMarker } from "./models/AiSceneResponse";
4
4
  export type { ClientInteractionRequest } from "./models/ClientInteractionRequest";
5
5
  export type { ClientInteractionResult, AIContent } from "./models/ClientInteractionResult";
6
+ export type { StoredConversation, ConversationQueryParameters, UpdateConversationVisibilityRequest } from "./models/StoredConversation";
7
+ export { ConversationSortOrder } from "./models/StoredConversation";
8
+ export type { StoredMessage } from "./models/StoredMessage";
9
+ export type { ExecutionState } from "./models/ExecutionState";
10
+ export type { CommandResult } from "./models/CommandResult";
11
+ export { CommandResult as CommandResultHelper } from "./models/CommandResult";
12
+ export type { VoiceEvent, VoiceRequestOptions, VoiceResponseType } from "./models/VoiceResponse";
6
13
  export { PlayFrameworkClient } from "./engine/PlayFrameworkClient";
7
14
  export { ClientInteractionRegistry } from "./engine/ClientInteractionRegistry";
8
- export type { ClientTool } from "./engine/ClientInteractionRegistry";
15
+ export type { ClientTool, ClientCommand, CommandFeedbackMode, CommandOptions } from "./engine/ClientInteractionRegistry";
9
16
  export { AIContentConverter } from "./utils/AIContentConverter";
17
+ export { ContentUrlConverter } from "./utils/ContentUrlConverter";
18
+ export { VoiceRecorder } from "./utils/VoiceRecorder";
19
+ export type { VoiceRecordingMode, VoiceRecorderOptions, VoiceRecorderCallbacks } from "./utils/VoiceRecorder";
20
+ export { BrowserSpeechRecognizer } from "./utils/BrowserSpeechRecognizer";
21
+ export type { BrowserSpeechRecognizerOptions, BrowserSpeechRecognizerCallbacks, SpeechRecognitionResult } from "./utils/BrowserSpeechRecognizer";
22
+ export { BrowserSpeechSynthesizer } from "./utils/BrowserSpeechSynthesizer";
23
+ export type { BrowserSpeechSynthesizerOptions, BrowserSpeechSynthesizerCallbacks } from "./utils/BrowserSpeechSynthesizer";
24
+ export { BrowserVoiceClient } from "./utils/BrowserVoiceClient";
25
+ export type { BrowserVoiceOptions, BrowserVoiceEvent, BrowserVoiceStatus, BrowserVoiceStreamingMode } from "./utils/BrowserVoiceClient";
10
26
  export { PlayFrameworkSettings } from "./servicecollection/PlayFrameworkSettings";
11
27
  export { PlayFrameworkServices } from "./servicecollection/PlayFrameworkServices";
12
28
  export { usePlayFramework } from "./hooks/hooks";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,YAAY,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACxD,YAAY,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnI,YAAY,EAAE,eAAe,EAAE,gBAAgB,EAAE,QAAQ,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAC3H,YAAY,EAAE,wBAAwB,EAAE,MAAM,mCAAmC,CAAC;A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