rystem.playframework.client 0.1.0
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 +265 -0
- package/lib/engine/ClientInteractionRegistry.d.ts +53 -0
- package/lib/engine/ClientInteractionRegistry.js +105 -0
- package/lib/engine/PlayFrameworkClient.d.ts +45 -0
- package/lib/engine/PlayFrameworkClient.js +199 -0
- package/lib/hooks/hooks.d.ts +27 -0
- package/lib/hooks/hooks.js +32 -0
- package/lib/index.d.ts +12 -0
- package/lib/index.js +19 -0
- package/lib/models/AiSceneResponse.d.ts +118 -0
- package/lib/models/AiSceneResponse.js +2 -0
- package/lib/models/ClientInteractionRequest.d.ts +32 -0
- package/lib/models/ClientInteractionRequest.js +2 -0
- package/lib/models/ClientInteractionResult.d.ts +33 -0
- package/lib/models/ClientInteractionResult.js +2 -0
- package/lib/models/ContentItem.d.ts +30 -0
- package/lib/models/ContentItem.js +2 -0
- package/lib/models/PlayFrameworkRequest.d.ts +77 -0
- package/lib/models/PlayFrameworkRequest.js +2 -0
- package/lib/servicecollection/PlayFrameworkServices.d.ts +67 -0
- package/lib/servicecollection/PlayFrameworkServices.js +115 -0
- package/lib/servicecollection/PlayFrameworkSettings.d.ts +56 -0
- package/lib/servicecollection/PlayFrameworkSettings.js +116 -0
- package/lib/utils/AIContentConverter.d.ts +68 -0
- package/lib/utils/AIContentConverter.js +170 -0
- package/package.json +44 -0
package/README.md
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
# Rystem PlayFramework Client
|
|
2
|
+
|
|
3
|
+
TypeScript/JavaScript client for **Rystem PlayFramework HTTP API** with full support for:
|
|
4
|
+
- ✅ **Step-by-step streaming** (SSE) - Each PlayFramework step as separate event
|
|
5
|
+
- ✅ **Token-level streaming** (SSE) - Each text chunk as separate event
|
|
6
|
+
- ✅ **Multi-modal content** - Images, audio, video, files, URIs
|
|
7
|
+
- ✅ **React hooks** - Easy integration with React apps
|
|
8
|
+
- ✅ **Configurable** - Custom headers, retry logic, error handling
|
|
9
|
+
- ✅ **TypeScript** - Full type safety
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install rystem.playframework.client
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## Quick Start
|
|
22
|
+
|
|
23
|
+
### 1. Configure Client
|
|
24
|
+
|
|
25
|
+
```typescript
|
|
26
|
+
import { PlayFrameworkServices } from "rystem.playframework.client";
|
|
27
|
+
|
|
28
|
+
// Configure factory
|
|
29
|
+
PlayFrameworkServices.configure("chat", "https://api.example.com/api/ai", settings => {
|
|
30
|
+
// Add Authorization header
|
|
31
|
+
settings.addHeadersEnricher(async (url, method, headers, body) => {
|
|
32
|
+
return {
|
|
33
|
+
...headers,
|
|
34
|
+
"Authorization": `Bearer ${getToken()}`
|
|
35
|
+
};
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
// Add retry logic
|
|
39
|
+
settings.addErrorHandler(async (url, method, headers, body, error) => {
|
|
40
|
+
console.error("Request failed, retrying...", error);
|
|
41
|
+
return true; // Retry
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### 2. Use Client (Vanilla JS/TS)
|
|
47
|
+
|
|
48
|
+
```typescript
|
|
49
|
+
import { PlayFrameworkServices } from "rystem.playframework.client";
|
|
50
|
+
|
|
51
|
+
const client = PlayFrameworkServices.getClient("chat");
|
|
52
|
+
|
|
53
|
+
// Step-by-step streaming
|
|
54
|
+
for await (const step of client.executeStepByStep({
|
|
55
|
+
prompt: "Tell me a joke",
|
|
56
|
+
sceneName: "ChatScene"
|
|
57
|
+
})) {
|
|
58
|
+
console.log(`[${step.status}] ${step.message}`);
|
|
59
|
+
// Output:
|
|
60
|
+
// [Planning] Analyzing request...
|
|
61
|
+
// [Running] Generating joke...
|
|
62
|
+
// [Running] Why did the chicken cross the road? To get to the other side!
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Token-level streaming (more granular)
|
|
66
|
+
for await (const chunk of client.executeTokenStreaming({
|
|
67
|
+
prompt: "Tell me a story"
|
|
68
|
+
})) {
|
|
69
|
+
process.stdout.write(chunk.message || "");
|
|
70
|
+
// Output: "Once" → " upon" → " a" → " time" → "..."
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### 3. Use with React
|
|
75
|
+
|
|
76
|
+
```tsx
|
|
77
|
+
import { usePlayFramework } from "rystem.playframework.client";
|
|
78
|
+
import { useState } from "react";
|
|
79
|
+
|
|
80
|
+
function ChatComponent() {
|
|
81
|
+
const client = usePlayFramework("chat");
|
|
82
|
+
const [messages, setMessages] = useState<string[]>([]);
|
|
83
|
+
|
|
84
|
+
const handleSend = async () => {
|
|
85
|
+
const newMessages: string[] = [];
|
|
86
|
+
|
|
87
|
+
for await (const step of client.executeStepByStep({
|
|
88
|
+
prompt: "Hello, how are you?",
|
|
89
|
+
sceneName: "ChatScene"
|
|
90
|
+
})) {
|
|
91
|
+
if (step.message) {
|
|
92
|
+
newMessages.push(`[${step.status}] ${step.message}`);
|
|
93
|
+
setMessages([...newMessages]);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
return (
|
|
99
|
+
<div>
|
|
100
|
+
<button onClick={handleSend}>Send</button>
|
|
101
|
+
{messages.map((msg, i) => <div key={i}>{msg}</div>)}
|
|
102
|
+
</div>
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
---
|
|
108
|
+
|
|
109
|
+
## Multi-Modal Content
|
|
110
|
+
|
|
111
|
+
```typescript
|
|
112
|
+
import { PlayFrameworkRequest, ContentItem } from "rystem.playframework.client";
|
|
113
|
+
|
|
114
|
+
const request: PlayFrameworkRequest = {
|
|
115
|
+
prompt: "Describe this image",
|
|
116
|
+
sceneName: "VisionScene",
|
|
117
|
+
contents: [
|
|
118
|
+
{
|
|
119
|
+
type: "image",
|
|
120
|
+
base64Data: "iVBORw0KGgoAAAANSUhEUgAA...",
|
|
121
|
+
mediaType: "image/png"
|
|
122
|
+
},
|
|
123
|
+
{
|
|
124
|
+
type: "text",
|
|
125
|
+
text: "Additional context"
|
|
126
|
+
},
|
|
127
|
+
{
|
|
128
|
+
type: "uri",
|
|
129
|
+
uri: "https://example.com/document.pdf",
|
|
130
|
+
mediaType: "application/pdf"
|
|
131
|
+
}
|
|
132
|
+
]
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
for await (const step of client.executeStepByStep(request)) {
|
|
136
|
+
console.log(step.message);
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
---
|
|
141
|
+
|
|
142
|
+
## Configuration Options
|
|
143
|
+
|
|
144
|
+
```typescript
|
|
145
|
+
PlayFrameworkServices.configure("premium", "https://api.example.com/api/ai/premium", settings => {
|
|
146
|
+
// Factory name (used in URL)
|
|
147
|
+
settings.factoryName; // "premium"
|
|
148
|
+
|
|
149
|
+
// Base URL
|
|
150
|
+
settings.baseUrl; // "https://api.example.com/api/ai/premium"
|
|
151
|
+
|
|
152
|
+
// Default headers
|
|
153
|
+
settings.defaultHeaders = {
|
|
154
|
+
"Content-Type": "application/json",
|
|
155
|
+
"X-Custom-Header": "value"
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
// Timeout (ms)
|
|
159
|
+
settings.timeout = 120000; // 2 minutes
|
|
160
|
+
|
|
161
|
+
// Add dynamic headers (e.g., auth token)
|
|
162
|
+
settings.addHeadersEnricher(async (url, method, headers, body) => {
|
|
163
|
+
const token = await getAuthToken();
|
|
164
|
+
return {
|
|
165
|
+
...headers,
|
|
166
|
+
"Authorization": `Bearer ${token}`
|
|
167
|
+
};
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
// Error handling with retry
|
|
171
|
+
settings.addErrorHandler(async (url, method, headers, body, error) => {
|
|
172
|
+
if (error.message.includes("401")) {
|
|
173
|
+
await refreshToken();
|
|
174
|
+
return true; // Retry
|
|
175
|
+
}
|
|
176
|
+
return false; // Don't retry
|
|
177
|
+
});
|
|
178
|
+
});
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
---
|
|
182
|
+
|
|
183
|
+
## Cancellation
|
|
184
|
+
|
|
185
|
+
```typescript
|
|
186
|
+
const controller = new AbortController();
|
|
187
|
+
|
|
188
|
+
// Start streaming
|
|
189
|
+
const promise = (async () => {
|
|
190
|
+
for await (const step of client.executeStepByStep(
|
|
191
|
+
{ prompt: "Long task" },
|
|
192
|
+
controller.signal // Pass AbortSignal
|
|
193
|
+
)) {
|
|
194
|
+
console.log(step.message);
|
|
195
|
+
}
|
|
196
|
+
})();
|
|
197
|
+
|
|
198
|
+
// Cancel after 5 seconds
|
|
199
|
+
setTimeout(() => controller.abort(), 5000);
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
---
|
|
203
|
+
|
|
204
|
+
## API Reference
|
|
205
|
+
|
|
206
|
+
### PlayFrameworkClient
|
|
207
|
+
|
|
208
|
+
#### `executeStepByStep(request, signal?): AsyncIterableIterator<AiSceneResponse>`
|
|
209
|
+
|
|
210
|
+
Execute with **step-by-step streaming** (each PlayFramework step as SSE event).
|
|
211
|
+
|
|
212
|
+
**Returns:** Each step (Planning, Actor1, Actor2, etc.) as separate event.
|
|
213
|
+
|
|
214
|
+
#### `executeTokenStreaming(request, signal?): AsyncIterableIterator<AiSceneResponse>`
|
|
215
|
+
|
|
216
|
+
Execute with **token-level streaming** (each text chunk as SSE event).
|
|
217
|
+
|
|
218
|
+
**Returns:** Each text chunk as separate event (more granular than step-by-step).
|
|
219
|
+
|
|
220
|
+
---
|
|
221
|
+
|
|
222
|
+
### PlayFrameworkServices
|
|
223
|
+
|
|
224
|
+
#### `configure(name, baseUrl, configure?): PlayFrameworkSettings`
|
|
225
|
+
|
|
226
|
+
Configure a PlayFramework client factory.
|
|
227
|
+
|
|
228
|
+
```typescript
|
|
229
|
+
PlayFrameworkServices.configure("chat", "https://api.example.com/api/ai");
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
#### `getClient(name): PlayFrameworkClient`
|
|
233
|
+
|
|
234
|
+
Get configured client.
|
|
235
|
+
|
|
236
|
+
```typescript
|
|
237
|
+
const client = PlayFrameworkServices.getClient("chat");
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
#### `getSettings(name): PlayFrameworkSettings`
|
|
241
|
+
|
|
242
|
+
Get settings for modification.
|
|
243
|
+
|
|
244
|
+
```typescript
|
|
245
|
+
const settings = PlayFrameworkServices.getSettings("chat");
|
|
246
|
+
settings.timeout = 30000;
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
---
|
|
250
|
+
|
|
251
|
+
### PlayFrameworkSettings
|
|
252
|
+
|
|
253
|
+
#### `addHeadersEnricher(enricher): this`
|
|
254
|
+
|
|
255
|
+
Add dynamic header enricher (e.g., Authorization).
|
|
256
|
+
|
|
257
|
+
#### `addErrorHandler(handler): this`
|
|
258
|
+
|
|
259
|
+
Add error handler for retry logic.
|
|
260
|
+
|
|
261
|
+
---
|
|
262
|
+
|
|
263
|
+
## License
|
|
264
|
+
|
|
265
|
+
MIT © Alessandro Rapiti
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { ClientInteractionRequest } from "../models/ClientInteractionRequest";
|
|
2
|
+
import { ClientInteractionResult, AIContent } from "../models/ClientInteractionResult";
|
|
3
|
+
/**
|
|
4
|
+
* Type for client-side tool implementation.
|
|
5
|
+
* Takes optional arguments and returns AIContent array.
|
|
6
|
+
*/
|
|
7
|
+
export type ClientTool<TArgs = any> = (args?: TArgs) => Promise<AIContent[]>;
|
|
8
|
+
/**
|
|
9
|
+
* Registry for client-side tools (camera, geolocation, file picker, etc.).
|
|
10
|
+
* Tools are registered once and executed when server requests them.
|
|
11
|
+
*/
|
|
12
|
+
export declare class ClientInteractionRegistry {
|
|
13
|
+
private tools;
|
|
14
|
+
/**
|
|
15
|
+
* Registers a client-side tool.
|
|
16
|
+
* @param toolName - Unique tool name matching server OnClient() registration.
|
|
17
|
+
* @param implementation - Async function that executes the tool.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* registry.register("capturePhoto", async () => {
|
|
21
|
+
* const stream = await navigator.mediaDevices.getUserMedia({ video: true });
|
|
22
|
+
* // ... capture frame and return Base64
|
|
23
|
+
* return [{ type: "data", data: base64, mediaType: "image/jpeg" }];
|
|
24
|
+
* });
|
|
25
|
+
*/
|
|
26
|
+
register<TArgs = any>(toolName: string, implementation: ClientTool<TArgs>): void;
|
|
27
|
+
/**
|
|
28
|
+
* Executes a registered tool and returns the result.
|
|
29
|
+
* @param request - Client interaction request from server.
|
|
30
|
+
* @returns ClientInteractionResult with contents or error.
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* const result = await registry.execute(request);
|
|
34
|
+
* // Send result back to server with continuation token
|
|
35
|
+
*/
|
|
36
|
+
execute(request: ClientInteractionRequest): Promise<ClientInteractionResult>;
|
|
37
|
+
/**
|
|
38
|
+
* Checks if a tool is registered.
|
|
39
|
+
*/
|
|
40
|
+
has(toolName: string): boolean;
|
|
41
|
+
/**
|
|
42
|
+
* Gets all registered tool names.
|
|
43
|
+
*/
|
|
44
|
+
getToolNames(): string[];
|
|
45
|
+
/**
|
|
46
|
+
* Unregisters a tool.
|
|
47
|
+
*/
|
|
48
|
+
unregister(toolName: string): boolean;
|
|
49
|
+
/**
|
|
50
|
+
* Clears all registered tools.
|
|
51
|
+
*/
|
|
52
|
+
clear(): void;
|
|
53
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ClientInteractionRegistry = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Registry for client-side tools (camera, geolocation, file picker, etc.).
|
|
6
|
+
* Tools are registered once and executed when server requests them.
|
|
7
|
+
*/
|
|
8
|
+
class ClientInteractionRegistry {
|
|
9
|
+
tools = new Map();
|
|
10
|
+
/**
|
|
11
|
+
* Registers a client-side tool.
|
|
12
|
+
* @param toolName - Unique tool name matching server OnClient() registration.
|
|
13
|
+
* @param implementation - Async function that executes the tool.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* registry.register("capturePhoto", async () => {
|
|
17
|
+
* const stream = await navigator.mediaDevices.getUserMedia({ video: true });
|
|
18
|
+
* // ... capture frame and return Base64
|
|
19
|
+
* return [{ type: "data", data: base64, mediaType: "image/jpeg" }];
|
|
20
|
+
* });
|
|
21
|
+
*/
|
|
22
|
+
register(toolName, implementation) {
|
|
23
|
+
if (this.tools.has(toolName)) {
|
|
24
|
+
console.warn(`ClientInteractionRegistry: Tool "${toolName}" is already registered. Overwriting.`);
|
|
25
|
+
}
|
|
26
|
+
this.tools.set(toolName, implementation);
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Executes a registered tool and returns the result.
|
|
30
|
+
* @param request - Client interaction request from server.
|
|
31
|
+
* @returns ClientInteractionResult with contents or error.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* const result = await registry.execute(request);
|
|
35
|
+
* // Send result back to server with continuation token
|
|
36
|
+
*/
|
|
37
|
+
async execute(request) {
|
|
38
|
+
const startTime = Date.now();
|
|
39
|
+
try {
|
|
40
|
+
const tool = this.tools.get(request.toolName);
|
|
41
|
+
if (!tool) {
|
|
42
|
+
return {
|
|
43
|
+
interactionId: request.interactionId,
|
|
44
|
+
contents: [],
|
|
45
|
+
error: `Tool "${request.toolName}" not found in registry. Did you forget to register it?`,
|
|
46
|
+
executedAt: new Date().toISOString()
|
|
47
|
+
};
|
|
48
|
+
}
|
|
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
|
+
});
|
|
56
|
+
const executionPromise = tool(request.arguments);
|
|
57
|
+
let contents;
|
|
58
|
+
try {
|
|
59
|
+
contents = await Promise.race([executionPromise, timeoutPromise]);
|
|
60
|
+
}
|
|
61
|
+
finally {
|
|
62
|
+
if (timer !== undefined)
|
|
63
|
+
clearTimeout(timer);
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
interactionId: request.interactionId,
|
|
67
|
+
contents,
|
|
68
|
+
executedAt: new Date().toISOString()
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
return {
|
|
73
|
+
interactionId: request.interactionId,
|
|
74
|
+
contents: [],
|
|
75
|
+
error: error.message || "Unknown error during tool execution",
|
|
76
|
+
executedAt: new Date().toISOString()
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Checks if a tool is registered.
|
|
82
|
+
*/
|
|
83
|
+
has(toolName) {
|
|
84
|
+
return this.tools.has(toolName);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Gets all registered tool names.
|
|
88
|
+
*/
|
|
89
|
+
getToolNames() {
|
|
90
|
+
return Array.from(this.tools.keys());
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Unregisters a tool.
|
|
94
|
+
*/
|
|
95
|
+
unregister(toolName) {
|
|
96
|
+
return this.tools.delete(toolName);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Clears all registered tools.
|
|
100
|
+
*/
|
|
101
|
+
clear() {
|
|
102
|
+
this.tools.clear();
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
exports.ClientInteractionRegistry = ClientInteractionRegistry;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { PlayFrameworkRequest } from "../models/PlayFrameworkRequest";
|
|
2
|
+
import { AiSceneResponse } from "../models/AiSceneResponse";
|
|
3
|
+
import { PlayFrameworkSettings } from "../servicecollection/PlayFrameworkSettings";
|
|
4
|
+
import { ClientInteractionRegistry } from "./ClientInteractionRegistry";
|
|
5
|
+
/**
|
|
6
|
+
* PlayFramework HTTP client with step-by-step and token-level streaming support.
|
|
7
|
+
* Supports client-side tool execution with continuation tokens.
|
|
8
|
+
*/
|
|
9
|
+
export declare class PlayFrameworkClient {
|
|
10
|
+
private settings;
|
|
11
|
+
private clientRegistry;
|
|
12
|
+
constructor(settings: PlayFrameworkSettings, clientRegistry?: ClientInteractionRegistry);
|
|
13
|
+
/**
|
|
14
|
+
* Gets the client interaction registry for registering client-side tools.
|
|
15
|
+
*/
|
|
16
|
+
getClientRegistry(): ClientInteractionRegistry;
|
|
17
|
+
/**
|
|
18
|
+
* Execute PlayFramework with step-by-step streaming (SSE).
|
|
19
|
+
* Each step (Planning, Actor execution, etc.) is yielded as it happens.
|
|
20
|
+
*
|
|
21
|
+
* @param request - PlayFramework request.
|
|
22
|
+
* @param signal - AbortSignal for cancellation.
|
|
23
|
+
* @returns AsyncIterableIterator of AiSceneResponse steps.
|
|
24
|
+
*/
|
|
25
|
+
executeStepByStep(request: PlayFrameworkRequest, signal?: AbortSignal): AsyncIterableIterator<AiSceneResponse>;
|
|
26
|
+
/**
|
|
27
|
+
* Execute PlayFramework with token-level streaming (SSE).
|
|
28
|
+
* Each text chunk is yielded as it's generated (more granular than step-by-step).
|
|
29
|
+
*
|
|
30
|
+
* @param request - PlayFramework request.
|
|
31
|
+
* @param signal - AbortSignal for cancellation.
|
|
32
|
+
* @returns AsyncIterableIterator of AiSceneResponse chunks.
|
|
33
|
+
*/
|
|
34
|
+
executeTokenStreaming(request: PlayFrameworkRequest, signal?: AbortSignal): AsyncIterableIterator<AiSceneResponse>;
|
|
35
|
+
/**
|
|
36
|
+
* Creates an AbortSignal combining user signal and timeout.
|
|
37
|
+
* Uses AbortController to combine signals for broad compatibility.
|
|
38
|
+
*/
|
|
39
|
+
private createTimeoutSignal;
|
|
40
|
+
/**
|
|
41
|
+
* Internal SSE streaming implementation with continuation token support
|
|
42
|
+
* and automatic reconnection on network failures.
|
|
43
|
+
*/
|
|
44
|
+
private streamSSE;
|
|
45
|
+
}
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PlayFrameworkClient = void 0;
|
|
4
|
+
const ClientInteractionRegistry_1 = require("./ClientInteractionRegistry");
|
|
5
|
+
/**
|
|
6
|
+
* PlayFramework HTTP client with step-by-step and token-level streaming support.
|
|
7
|
+
* Supports client-side tool execution with continuation tokens.
|
|
8
|
+
*/
|
|
9
|
+
class PlayFrameworkClient {
|
|
10
|
+
settings;
|
|
11
|
+
clientRegistry;
|
|
12
|
+
constructor(settings, clientRegistry) {
|
|
13
|
+
this.settings = settings;
|
|
14
|
+
this.clientRegistry = clientRegistry || new ClientInteractionRegistry_1.ClientInteractionRegistry();
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Gets the client interaction registry for registering client-side tools.
|
|
18
|
+
*/
|
|
19
|
+
getClientRegistry() {
|
|
20
|
+
return this.clientRegistry;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Execute PlayFramework with step-by-step streaming (SSE).
|
|
24
|
+
* Each step (Planning, Actor execution, etc.) is yielded as it happens.
|
|
25
|
+
*
|
|
26
|
+
* @param request - PlayFramework request.
|
|
27
|
+
* @param signal - AbortSignal for cancellation.
|
|
28
|
+
* @returns AsyncIterableIterator of AiSceneResponse steps.
|
|
29
|
+
*/
|
|
30
|
+
async *executeStepByStep(request, signal) {
|
|
31
|
+
const url = `${this.settings.baseUrl}/${this.settings.factoryName}`;
|
|
32
|
+
yield* this.streamSSE(url, request, signal);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Execute PlayFramework with token-level streaming (SSE).
|
|
36
|
+
* Each text chunk is yielded as it's generated (more granular than step-by-step).
|
|
37
|
+
*
|
|
38
|
+
* @param request - PlayFramework request.
|
|
39
|
+
* @param signal - AbortSignal for cancellation.
|
|
40
|
+
* @returns AsyncIterableIterator of AiSceneResponse chunks.
|
|
41
|
+
*/
|
|
42
|
+
async *executeTokenStreaming(request, signal) {
|
|
43
|
+
const url = `${this.settings.baseUrl}/${this.settings.factoryName}/streaming`;
|
|
44
|
+
yield* this.streamSSE(url, request, signal);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Creates an AbortSignal combining user signal and timeout.
|
|
48
|
+
* Uses AbortController to combine signals for broad compatibility.
|
|
49
|
+
*/
|
|
50
|
+
createTimeoutSignal(signal) {
|
|
51
|
+
const hasTimeout = this.settings.timeout > 0;
|
|
52
|
+
if (signal && hasTimeout) {
|
|
53
|
+
// Combine user signal + timeout via AbortController
|
|
54
|
+
const controller = new AbortController();
|
|
55
|
+
const timer = setTimeout(() => controller.abort(new DOMException('The operation was aborted due to timeout', 'TimeoutError')), this.settings.timeout);
|
|
56
|
+
signal.addEventListener('abort', () => {
|
|
57
|
+
clearTimeout(timer);
|
|
58
|
+
controller.abort(signal.reason);
|
|
59
|
+
}, { once: true });
|
|
60
|
+
// Clean up timer if our combined signal is aborted
|
|
61
|
+
controller.signal.addEventListener('abort', () => clearTimeout(timer), { once: true });
|
|
62
|
+
return controller.signal;
|
|
63
|
+
}
|
|
64
|
+
if (signal)
|
|
65
|
+
return signal;
|
|
66
|
+
if (hasTimeout)
|
|
67
|
+
return AbortSignal.timeout(this.settings.timeout);
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Internal SSE streaming implementation with continuation token support
|
|
72
|
+
* and automatic reconnection on network failures.
|
|
73
|
+
*/
|
|
74
|
+
async *streamSSE(url, request, signal) {
|
|
75
|
+
let currentRequest = { ...request };
|
|
76
|
+
let shouldContinue = true;
|
|
77
|
+
const effectiveSignal = this.createTimeoutSignal(signal);
|
|
78
|
+
while (shouldContinue) {
|
|
79
|
+
const headers = await this.settings.enrichHeaders(url, "POST", undefined, currentRequest);
|
|
80
|
+
let reconnectAttempts = 0;
|
|
81
|
+
let shouldRetry = true;
|
|
82
|
+
while (shouldRetry) {
|
|
83
|
+
try {
|
|
84
|
+
const response = await fetch(url, {
|
|
85
|
+
method: "POST",
|
|
86
|
+
headers,
|
|
87
|
+
body: JSON.stringify(currentRequest),
|
|
88
|
+
signal: effectiveSignal || undefined
|
|
89
|
+
});
|
|
90
|
+
if (!response.ok) {
|
|
91
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
92
|
+
}
|
|
93
|
+
if (!response.body) {
|
|
94
|
+
throw new Error("Response body is null");
|
|
95
|
+
}
|
|
96
|
+
// Reset reconnect counter on successful connection
|
|
97
|
+
reconnectAttempts = 0;
|
|
98
|
+
const reader = response.body.getReader();
|
|
99
|
+
const decoder = new TextDecoder();
|
|
100
|
+
let buffer = "";
|
|
101
|
+
let awaitingClientResponse = null;
|
|
102
|
+
try {
|
|
103
|
+
while (true) {
|
|
104
|
+
const { done, value } = await reader.read();
|
|
105
|
+
if (done) {
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
buffer += decoder.decode(value, { stream: true });
|
|
109
|
+
// Process complete SSE messages
|
|
110
|
+
const lines = buffer.split("\n");
|
|
111
|
+
buffer = lines.pop() || ""; // Keep incomplete line in buffer
|
|
112
|
+
for (const line of lines) {
|
|
113
|
+
if (line.startsWith("data: ")) {
|
|
114
|
+
const data = line.substring(6).trim();
|
|
115
|
+
if (!data)
|
|
116
|
+
continue;
|
|
117
|
+
let event;
|
|
118
|
+
try {
|
|
119
|
+
event = JSON.parse(data);
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
console.error("Failed to parse SSE event:", data);
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
// Check for completion/error markers
|
|
126
|
+
if (event.status === "completed") {
|
|
127
|
+
shouldContinue = false;
|
|
128
|
+
return; // End streaming
|
|
129
|
+
}
|
|
130
|
+
if (event.status === "error") {
|
|
131
|
+
shouldContinue = false;
|
|
132
|
+
throw new Error(event.errorMessage || "Unknown error");
|
|
133
|
+
}
|
|
134
|
+
// Check for AwaitingClient status
|
|
135
|
+
if (event.status === "AwaitingClient") {
|
|
136
|
+
awaitingClientResponse = event;
|
|
137
|
+
yield awaitingClientResponse; // Yield to user
|
|
138
|
+
break; // Exit SSE loop to execute client tool
|
|
139
|
+
}
|
|
140
|
+
// Yield valid AiSceneResponse
|
|
141
|
+
yield event;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
// Break out of read loop if AwaitingClient
|
|
145
|
+
if (awaitingClientResponse) {
|
|
146
|
+
break;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
finally {
|
|
151
|
+
reader.releaseLock();
|
|
152
|
+
}
|
|
153
|
+
shouldRetry = false; // Success, no retry
|
|
154
|
+
// Handle client interaction if AwaitingClient
|
|
155
|
+
if (awaitingClientResponse?.clientInteractionRequest) {
|
|
156
|
+
const clientRequest = awaitingClientResponse.clientInteractionRequest;
|
|
157
|
+
// Execute client tool
|
|
158
|
+
const result = await this.clientRegistry.execute(clientRequest);
|
|
159
|
+
// Prepare new request with continuation token (inside settings for SceneManager)
|
|
160
|
+
currentRequest = {
|
|
161
|
+
...currentRequest,
|
|
162
|
+
continuationToken: awaitingClientResponse.continuationToken,
|
|
163
|
+
clientInteractionResults: [result],
|
|
164
|
+
settings: {
|
|
165
|
+
...currentRequest.settings,
|
|
166
|
+
continuationToken: awaitingClientResponse.continuationToken,
|
|
167
|
+
clientInteractionResults: [result]
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
// Continue loop to resume execution
|
|
171
|
+
shouldContinue = true;
|
|
172
|
+
}
|
|
173
|
+
else {
|
|
174
|
+
shouldContinue = false; // Normal completion
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
// Check if this is a network/connection error (not abort, not server error marker)
|
|
179
|
+
const isAbort = error instanceof DOMException && error.name === "AbortError";
|
|
180
|
+
const isServerError = error instanceof Error && (error.message.startsWith("HTTP ") || error.message === "Unknown error");
|
|
181
|
+
if (!isAbort && !isServerError && reconnectAttempts < this.settings.maxReconnectAttempts) {
|
|
182
|
+
reconnectAttempts++;
|
|
183
|
+
const delay = this.settings.reconnectBaseDelay * Math.pow(2, reconnectAttempts - 1);
|
|
184
|
+
console.warn(`SSE connection lost. Reconnecting (attempt ${reconnectAttempts}/${this.settings.maxReconnectAttempts}) in ${delay}ms...`);
|
|
185
|
+
await new Promise(resolve => setTimeout(resolve, delay));
|
|
186
|
+
continue; // retry the fetch
|
|
187
|
+
}
|
|
188
|
+
// Delegate to error handlers for custom retry logic
|
|
189
|
+
shouldRetry = await this.settings.manageError(url, "POST", headers, currentRequest, error);
|
|
190
|
+
if (!shouldRetry) {
|
|
191
|
+
shouldContinue = false;
|
|
192
|
+
throw error; // Propagate error if no retry
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
exports.PlayFrameworkClient = PlayFrameworkClient;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { PlayFrameworkClient } from "../engine/PlayFrameworkClient";
|
|
2
|
+
/**
|
|
3
|
+
* Get a PlayFrameworkClient instance by optional factory name.
|
|
4
|
+
*
|
|
5
|
+
* If `name` is provided, returns the client for that specific factory.
|
|
6
|
+
* If `name` is omitted, returns the default (first configured) client.
|
|
7
|
+
*
|
|
8
|
+
* Framework-agnostic — works with React, Vue, Angular, Svelte, or plain TypeScript.
|
|
9
|
+
*
|
|
10
|
+
* @param name - Optional factory name. Omit to use the default client.
|
|
11
|
+
* @returns PlayFrameworkClient instance.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```ts
|
|
15
|
+
* // Use default (first configured) client
|
|
16
|
+
* const client = usePlayFramework();
|
|
17
|
+
*
|
|
18
|
+
* // Use a specific factory
|
|
19
|
+
* const chatClient = usePlayFramework("chat");
|
|
20
|
+
*
|
|
21
|
+
* // Execute
|
|
22
|
+
* for await (const step of client.executeStepByStep({ message: "Hello" })) {
|
|
23
|
+
* console.log(step.message);
|
|
24
|
+
* }
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export declare function usePlayFramework(name?: string): PlayFrameworkClient;
|