@odin-ai/sdk 1.0.0 → 1.0.1
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 +106 -249
- package/dist/{src/BaseClient.d.ts → BaseClient.d.cts} +21 -2
- package/dist/BaseClient.d.ts +15 -1
- package/dist/BaseClient.d.ts.map +1 -1
- package/dist/{src/ChatSDK.d.ts → ChatSDK.d.cts} +52 -5
- package/dist/ChatSDK.d.ts +49 -3
- package/dist/ChatSDK.d.ts.map +1 -1
- package/dist/{src/SmartTablesSDK.d.ts → SmartTablesSDK.d.cts} +115 -9
- package/dist/SmartTablesSDK.d.ts +29 -7
- package/dist/SmartTablesSDK.d.ts.map +1 -1
- package/dist/VoiceSDK.d.cts +72 -0
- package/dist/VoiceSDK.d.ts +2 -2
- package/dist/VoiceSDK.d.ts.map +1 -1
- package/dist/{index.js → index.cjs} +651 -906
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +11 -0
- package/dist/index.d.ts +11 -13
- package/dist/index.d.ts.map +1 -1
- package/dist/index.esm.js +644 -900
- package/dist/index.esm.js.map +1 -1
- package/dist/react.cjs +1737 -0
- package/dist/react.cjs.map +1 -0
- package/dist/react.d.cts +3 -0
- package/dist/react.d.ts +4 -0
- package/dist/react.d.ts.map +1 -0
- package/dist/react.esm.js +1731 -0
- package/dist/react.esm.js.map +1 -0
- package/dist/resumableTurnStream.d.cts +57 -0
- package/dist/resumableTurnStream.d.ts +58 -0
- package/dist/resumableTurnStream.d.ts.map +1 -0
- package/dist/{src/types.d.ts → types.d.cts} +109 -111
- package/dist/types.d.ts +89 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/useVoiceConversation.d.cts +33 -0
- package/dist/useVoiceConversation.d.ts +5 -5
- package/dist/useVoiceConversation.d.ts.map +1 -1
- package/dist/voice-types.d.cts +168 -0
- package/dist/voice-types.d.ts +7 -7
- package/dist/voice-types.d.ts.map +1 -1
- package/package.json +53 -26
- package/LICENSE +0 -21
- package/dist/WorkflowSDK.d.ts +0 -188
- package/dist/WorkflowSDK.d.ts.map +0 -1
- package/dist/examples/basic-chat.d.ts +0 -2
- package/dist/examples/basic-chat.d.ts.map +0 -1
- package/dist/examples/react-integration.d.ts +0 -7
- package/dist/examples/react-integration.d.ts.map +0 -1
- package/dist/examples/smart-tables-basic.d.ts +0 -2
- package/dist/examples/smart-tables-basic.d.ts.map +0 -1
- package/dist/examples/smart-tables-comprehensive.d.ts +0 -2
- package/dist/examples/smart-tables-comprehensive.d.ts.map +0 -1
- package/dist/examples/smart-tables-demo.d.ts +0 -2
- package/dist/examples/smart-tables-demo.d.ts.map +0 -1
- package/dist/examples/smart-tables-import.d.ts +0 -2
- package/dist/examples/smart-tables-import.d.ts.map +0 -1
- package/dist/examples/streaming-chat.d.ts +0 -2
- package/dist/examples/streaming-chat.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/src/BaseClient.d.ts.map +0 -1
- package/dist/src/ChatSDK.d.ts.map +0 -1
- package/dist/src/SmartTablesSDK.d.ts.map +0 -1
- package/dist/src/components/MessageBubble.d.ts +0 -24
- package/dist/src/components/MessageBubble.d.ts.map +0 -1
- package/dist/src/components/MessageList.d.ts +0 -28
- package/dist/src/components/MessageList.d.ts.map +0 -1
- package/dist/src/components/index.d.ts +0 -4
- package/dist/src/components/index.d.ts.map +0 -1
- package/dist/src/index.d.ts +0 -10
- package/dist/src/index.d.ts.map +0 -1
- package/dist/src/types.d.ts.map +0 -1
- package/dist/workflow-types.d.ts +0 -431
- package/dist/workflow-types.d.ts.map +0 -1
package/dist/react.cjs
ADDED
|
@@ -0,0 +1,1737 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var react = require('react');
|
|
4
|
+
var react$1 = require('@elevenlabs/react');
|
|
5
|
+
var client = require('@elevenlabs/client');
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Picks a human-readable string out of a parsed error response body.
|
|
9
|
+
*
|
|
10
|
+
* FastAPI wraps every raised `HTTPException` as `{"detail": ...}`. `detail`
|
|
11
|
+
* is a plain string for most errors, but structured blocks -- notably the
|
|
12
|
+
* credit gate's 402 (`{code, limit_type, message, limit, used, ...}`) -- send
|
|
13
|
+
* an object instead. Interpolating that object into the error message with a
|
|
14
|
+
* template literal used to stringify it via `String(detail)`, producing
|
|
15
|
+
* "HTTP 402: [object Object]" instead of the actual message. Preferring
|
|
16
|
+
* `detail.message` when `detail` is an object keeps that readable; the raw
|
|
17
|
+
* object is still preserved on `APIError.detail` for callers that want to
|
|
18
|
+
* branch on `code`/`limit_type` (see `parseCreditLimitError`).
|
|
19
|
+
*/
|
|
20
|
+
function extractErrorMessage(errorData, fallback) {
|
|
21
|
+
if (!errorData || typeof errorData !== "object")
|
|
22
|
+
return fallback;
|
|
23
|
+
const data = errorData;
|
|
24
|
+
if (typeof data.message === "string")
|
|
25
|
+
return data.message;
|
|
26
|
+
const { detail } = data;
|
|
27
|
+
if (typeof detail === "string")
|
|
28
|
+
return detail;
|
|
29
|
+
if (detail && typeof detail === "object") {
|
|
30
|
+
const nested = detail.message;
|
|
31
|
+
if (typeof nested === "string")
|
|
32
|
+
return nested;
|
|
33
|
+
}
|
|
34
|
+
return fallback;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Generic HTTP client for AI Content Creator SDKs
|
|
38
|
+
*/
|
|
39
|
+
class BaseClient {
|
|
40
|
+
constructor(config) {
|
|
41
|
+
this.config = config;
|
|
42
|
+
// Wrap fetch in an arrow function to preserve the correct 'this' context
|
|
43
|
+
// This prevents "Illegal invocation" errors when fetch is called
|
|
44
|
+
this.customFetch =
|
|
45
|
+
config.customFetch ||
|
|
46
|
+
((...args) => fetch(...args));
|
|
47
|
+
// Validate authentication configuration
|
|
48
|
+
const hasAccessToken = config.accessToken && config.accessToken.trim() !== "";
|
|
49
|
+
const hasApiKeys = config.apiKey &&
|
|
50
|
+
config.apiSecret &&
|
|
51
|
+
config.apiKey.trim() !== "" &&
|
|
52
|
+
config.apiSecret.trim() !== "";
|
|
53
|
+
if (!hasAccessToken && !hasApiKeys) {
|
|
54
|
+
throw new Error("Authentication required: Provide either accessToken (for web app) or both apiKey and apiSecret (for external SDK)");
|
|
55
|
+
}
|
|
56
|
+
if (hasAccessToken && hasApiKeys) {
|
|
57
|
+
console.warn("Both accessToken and API keys provided. Using accessToken for authentication.");
|
|
58
|
+
}
|
|
59
|
+
// Support both API key authentication and access token authentication
|
|
60
|
+
if (hasAccessToken) {
|
|
61
|
+
// Web app authentication using access token
|
|
62
|
+
this.headers = {
|
|
63
|
+
"Content-Type": "application/json",
|
|
64
|
+
"access-token": config.accessToken,
|
|
65
|
+
"X-Project-Id": config.projectId,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
// External SDK authentication using API keys
|
|
70
|
+
this.headers = {
|
|
71
|
+
"Content-Type": "application/json",
|
|
72
|
+
"X-API-KEY": config.apiKey,
|
|
73
|
+
"X-API-SECRET": config.apiSecret,
|
|
74
|
+
"X-Project-Id": config.projectId,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Make an HTTP request with proper error handling
|
|
80
|
+
*/
|
|
81
|
+
async makeRequest(endpoint, method = "GET", body, customHeaders) {
|
|
82
|
+
const url = endpoint.startsWith("http")
|
|
83
|
+
? endpoint
|
|
84
|
+
: `${this.config.baseUrl}${endpoint}`;
|
|
85
|
+
const requestOptions = {
|
|
86
|
+
method,
|
|
87
|
+
headers: {
|
|
88
|
+
...this.headers,
|
|
89
|
+
...customHeaders,
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
if (body) {
|
|
93
|
+
if (body instanceof FormData) {
|
|
94
|
+
// Remove Content-Type header for FormData - browser will set it automatically
|
|
95
|
+
const { "Content-Type": _, ...headersWithoutContentType } = requestOptions.headers;
|
|
96
|
+
requestOptions.headers = headersWithoutContentType;
|
|
97
|
+
requestOptions.body = body;
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
requestOptions.body =
|
|
101
|
+
typeof body === "string" ? body : JSON.stringify(body);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const response = await this.customFetch(url, requestOptions);
|
|
105
|
+
if (!response.ok) {
|
|
106
|
+
await this.handleErrorResponse(response);
|
|
107
|
+
}
|
|
108
|
+
// Handle empty responses
|
|
109
|
+
const contentType = response.headers.get("content-type");
|
|
110
|
+
if (contentType && contentType.includes("application/json")) {
|
|
111
|
+
return response.json();
|
|
112
|
+
}
|
|
113
|
+
return response.text();
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Make a GET request
|
|
117
|
+
*/
|
|
118
|
+
async get(endpoint, headers) {
|
|
119
|
+
return this.makeRequest(endpoint, "GET", null, headers);
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Make a POST request
|
|
123
|
+
*/
|
|
124
|
+
async post(endpoint, body, headers) {
|
|
125
|
+
return this.makeRequest(endpoint, "POST", body, headers);
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Make a PUT request
|
|
129
|
+
*/
|
|
130
|
+
async put(endpoint, body, headers) {
|
|
131
|
+
return this.makeRequest(endpoint, "PUT", body, headers);
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Make a DELETE request
|
|
135
|
+
*/
|
|
136
|
+
async delete(endpoint, body, headers) {
|
|
137
|
+
return this.makeRequest(endpoint, "DELETE", body, headers);
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Handle error responses from the API
|
|
141
|
+
*/
|
|
142
|
+
async handleErrorResponse(response) {
|
|
143
|
+
// Only 401 expires the session; 403 (permission denied) must surface to the caller.
|
|
144
|
+
if (response.status === 401 && typeof window !== "undefined") {
|
|
145
|
+
window.dispatchEvent(new CustomEvent("sessionExpired", {
|
|
146
|
+
detail: { status: response.status, url: response.url },
|
|
147
|
+
}));
|
|
148
|
+
}
|
|
149
|
+
const error = await this.createErrorFromResponse(response);
|
|
150
|
+
throw error;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Create an error object from an HTTP response
|
|
154
|
+
*/
|
|
155
|
+
async createErrorFromResponse(response) {
|
|
156
|
+
let errorMessage = response.statusText;
|
|
157
|
+
let errorDetail;
|
|
158
|
+
try {
|
|
159
|
+
const errorData = await response.json();
|
|
160
|
+
errorMessage = extractErrorMessage(errorData, errorMessage);
|
|
161
|
+
errorDetail = errorData?.detail;
|
|
162
|
+
}
|
|
163
|
+
catch (e) {
|
|
164
|
+
// If we can't parse the error response, use the status text
|
|
165
|
+
}
|
|
166
|
+
const error = new Error(`HTTP ${response.status}: ${errorMessage}`);
|
|
167
|
+
error.status = response.status;
|
|
168
|
+
error.detail = errorDetail;
|
|
169
|
+
return error;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Update the access token at runtime. Useful when the application's session token is refreshed.
|
|
173
|
+
*/
|
|
174
|
+
setAccessToken(newAccessToken) {
|
|
175
|
+
if (!newAccessToken || newAccessToken.trim() === "") {
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
this.config.accessToken = newAccessToken;
|
|
179
|
+
// Ensure header reflects the latest token
|
|
180
|
+
this.headers = {
|
|
181
|
+
...this.headers,
|
|
182
|
+
"access-token": newAccessToken,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Reader for a resumable chat turn stream (POST /v4/chat/message with
|
|
189
|
+
* `X-Odin-Resumable-Stream: 1`, or GET /v4/chat/message/{id}/stream).
|
|
190
|
+
*
|
|
191
|
+
* The server follows every frame with `<turn_seq>N</turn_seq>` and ends the
|
|
192
|
+
* turn with `<turn_complete>status</turn_complete>`. Only text up to a seq
|
|
193
|
+
* marker is a complete frame, so this reader forwards exactly those, in
|
|
194
|
+
* order, and never twice. When the connection drops or goes silent (the
|
|
195
|
+
* server sends a keepalive marker every 15s), it reconnects from the last
|
|
196
|
+
* seq it forwarded, so the caller sees one uninterrupted stream.
|
|
197
|
+
*
|
|
198
|
+
* A response without `X-Turn-Id` comes from a server that does not journal
|
|
199
|
+
* turns; it is passed through unchanged and cannot be resumed.
|
|
200
|
+
*/
|
|
201
|
+
const SEQ_OPEN = "<turn_seq>";
|
|
202
|
+
const SEQ_CLOSE = "</turn_seq>";
|
|
203
|
+
const COMPLETE_OPEN = "<turn_complete>";
|
|
204
|
+
const COMPLETE_CLOSE = "</turn_complete>";
|
|
205
|
+
const MARKER_RE = /<turn_seq>(\d+)<\/turn_seq>|<turn_complete>([^<]*)<\/turn_complete>/g;
|
|
206
|
+
/** Where a marker that may complete in a later read starts, or -1. */
|
|
207
|
+
const partialMarkerAt = (text) => {
|
|
208
|
+
// Complete markers are already removed, so any "<turn_" left is unfinished.
|
|
209
|
+
const open = text.lastIndexOf("<turn_");
|
|
210
|
+
if (open !== -1)
|
|
211
|
+
return open;
|
|
212
|
+
const lt = text.lastIndexOf("<");
|
|
213
|
+
if (lt === -1)
|
|
214
|
+
return -1;
|
|
215
|
+
const tail = text.slice(lt);
|
|
216
|
+
return SEQ_OPEN.startsWith(tail) || COMPLETE_OPEN.startsWith(tail) ? lt : -1;
|
|
217
|
+
};
|
|
218
|
+
const RESUMABLE_STREAM_HEADER = "X-Odin-Resumable-Stream";
|
|
219
|
+
const CLIENT_TURN_ID_HEADER = "X-Client-Turn-Id";
|
|
220
|
+
const TURN_ID_HEADER = "X-Turn-Id";
|
|
221
|
+
class TurnStreamLostError extends Error {
|
|
222
|
+
constructor(message, turnId, lastSeq) {
|
|
223
|
+
super(message);
|
|
224
|
+
this.turnId = turnId;
|
|
225
|
+
this.lastSeq = lastSeq;
|
|
226
|
+
this.name = "TurnStreamLostError";
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
const newClientTurnId = () => typeof crypto !== "undefined" && "randomUUID" in crypto
|
|
230
|
+
? crypto.randomUUID()
|
|
231
|
+
: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
232
|
+
const backoffMs = (attempt) => {
|
|
233
|
+
const base = Math.min(8000, 500 * 2 ** (attempt - 1));
|
|
234
|
+
return base / 2 + Math.random() * (base / 2);
|
|
235
|
+
};
|
|
236
|
+
const isAbort = (error) => error?.name === "AbortError";
|
|
237
|
+
const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
238
|
+
if (signal?.aborted) {
|
|
239
|
+
reject(new DOMException("Aborted", "AbortError"));
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
const timer = setTimeout(() => {
|
|
243
|
+
signal?.removeEventListener("abort", onAbort);
|
|
244
|
+
resolve();
|
|
245
|
+
}, ms);
|
|
246
|
+
const onAbort = () => {
|
|
247
|
+
clearTimeout(timer);
|
|
248
|
+
reject(new DOMException("Aborted", "AbortError"));
|
|
249
|
+
};
|
|
250
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
251
|
+
});
|
|
252
|
+
async function readResumableTurn(options) {
|
|
253
|
+
const { signal, onText, stallTimeoutMs = 45000, maxReconnects = 6, } = options;
|
|
254
|
+
const turnId = options.turnId ?? options.response.headers.get(TURN_ID_HEADER) ?? null;
|
|
255
|
+
let lastSeq = options.fromSeq ?? 0;
|
|
256
|
+
const pump = async (response) => {
|
|
257
|
+
const outcome = { status: null, progressed: false };
|
|
258
|
+
if (!response.body)
|
|
259
|
+
return outcome;
|
|
260
|
+
const reader = response.body.getReader();
|
|
261
|
+
const decoder = new TextDecoder("utf-8");
|
|
262
|
+
let buffer = "";
|
|
263
|
+
const drain = () => {
|
|
264
|
+
// eslint-disable-next-line no-constant-condition
|
|
265
|
+
while (true) {
|
|
266
|
+
const seqAt = buffer.indexOf(SEQ_OPEN);
|
|
267
|
+
const completeAt = buffer.indexOf(COMPLETE_OPEN);
|
|
268
|
+
if (seqAt === -1 && completeAt === -1)
|
|
269
|
+
return false;
|
|
270
|
+
if (completeAt !== -1 && (seqAt === -1 || completeAt < seqAt)) {
|
|
271
|
+
const end = buffer.indexOf(COMPLETE_CLOSE, completeAt);
|
|
272
|
+
if (end === -1)
|
|
273
|
+
return false;
|
|
274
|
+
const text = buffer.slice(0, completeAt);
|
|
275
|
+
if (text)
|
|
276
|
+
onText(text);
|
|
277
|
+
outcome.status = buffer
|
|
278
|
+
.slice(completeAt + COMPLETE_OPEN.length, end)
|
|
279
|
+
.trim();
|
|
280
|
+
return true;
|
|
281
|
+
}
|
|
282
|
+
const end = buffer.indexOf(SEQ_CLOSE, seqAt);
|
|
283
|
+
if (end === -1)
|
|
284
|
+
return false;
|
|
285
|
+
const seq = Number(buffer.slice(seqAt + SEQ_OPEN.length, end));
|
|
286
|
+
const text = buffer.slice(0, seqAt);
|
|
287
|
+
buffer = buffer.slice(end + SEQ_CLOSE.length);
|
|
288
|
+
if (seq > lastSeq) {
|
|
289
|
+
if (text)
|
|
290
|
+
onText(text);
|
|
291
|
+
lastSeq = seq;
|
|
292
|
+
outcome.progressed = true;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
try {
|
|
297
|
+
// eslint-disable-next-line no-constant-condition
|
|
298
|
+
while (true) {
|
|
299
|
+
let stallTimer;
|
|
300
|
+
const stalled = new Promise((resolve) => {
|
|
301
|
+
stallTimer = setTimeout(() => resolve("stalled"), stallTimeoutMs);
|
|
302
|
+
});
|
|
303
|
+
const result = await Promise.race([reader.read(), stalled]);
|
|
304
|
+
clearTimeout(stallTimer);
|
|
305
|
+
if (result === "stalled") {
|
|
306
|
+
reader.cancel().catch(() => undefined);
|
|
307
|
+
return outcome;
|
|
308
|
+
}
|
|
309
|
+
if (result.done)
|
|
310
|
+
return outcome;
|
|
311
|
+
options.onActivity?.();
|
|
312
|
+
buffer += decoder.decode(result.value, { stream: true });
|
|
313
|
+
if (drain()) {
|
|
314
|
+
reader.cancel().catch(() => undefined);
|
|
315
|
+
return outcome;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
catch (error) {
|
|
320
|
+
if (isAbort(error) || signal?.aborted)
|
|
321
|
+
throw error;
|
|
322
|
+
return outcome;
|
|
323
|
+
}
|
|
324
|
+
finally {
|
|
325
|
+
try {
|
|
326
|
+
reader.releaseLock();
|
|
327
|
+
}
|
|
328
|
+
catch {
|
|
329
|
+
// already released by cancel()
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
// Without a turn id (an old server, or a cross-site caller that cannot read
|
|
334
|
+
// the header) the stream cannot be resumed, but it may still carry markers.
|
|
335
|
+
const passthrough = async (response) => {
|
|
336
|
+
if (!response.body)
|
|
337
|
+
return null;
|
|
338
|
+
const reader = response.body.getReader();
|
|
339
|
+
const decoder = new TextDecoder("utf-8");
|
|
340
|
+
let buffer = "";
|
|
341
|
+
let status = null;
|
|
342
|
+
const flush = (final) => {
|
|
343
|
+
buffer = buffer.replace(MARKER_RE, (_match, _seq, complete) => {
|
|
344
|
+
if (complete !== undefined)
|
|
345
|
+
status = complete.trim();
|
|
346
|
+
return "";
|
|
347
|
+
});
|
|
348
|
+
// Hold back a tail that could be the start of a marker split across reads.
|
|
349
|
+
const held = final ? -1 : partialMarkerAt(buffer);
|
|
350
|
+
const out = held === -1 ? buffer : buffer.slice(0, held);
|
|
351
|
+
buffer = held === -1 ? "" : buffer.slice(held);
|
|
352
|
+
if (out)
|
|
353
|
+
onText(out);
|
|
354
|
+
};
|
|
355
|
+
try {
|
|
356
|
+
// eslint-disable-next-line no-constant-condition
|
|
357
|
+
while (true) {
|
|
358
|
+
const { done, value } = await reader.read();
|
|
359
|
+
if (done) {
|
|
360
|
+
flush(true);
|
|
361
|
+
return status;
|
|
362
|
+
}
|
|
363
|
+
options.onActivity?.();
|
|
364
|
+
buffer += decoder.decode(value, { stream: true });
|
|
365
|
+
flush(false);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
finally {
|
|
369
|
+
reader.releaseLock();
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
if (!turnId) {
|
|
373
|
+
const status = await passthrough(options.response);
|
|
374
|
+
return { status, turnId: null, lastSeq };
|
|
375
|
+
}
|
|
376
|
+
let response = options.response;
|
|
377
|
+
let failures = 0;
|
|
378
|
+
// eslint-disable-next-line no-constant-condition
|
|
379
|
+
while (true) {
|
|
380
|
+
if (response) {
|
|
381
|
+
const outcome = await pump(response);
|
|
382
|
+
if (outcome.status)
|
|
383
|
+
return { status: outcome.status, turnId, lastSeq };
|
|
384
|
+
if (outcome.progressed)
|
|
385
|
+
failures = 0;
|
|
386
|
+
}
|
|
387
|
+
if (signal?.aborted)
|
|
388
|
+
throw new DOMException("Aborted", "AbortError");
|
|
389
|
+
failures += 1;
|
|
390
|
+
if (failures > maxReconnects) {
|
|
391
|
+
throw new TurnStreamLostError("Lost the connection to this response and could not reconnect.", turnId, lastSeq);
|
|
392
|
+
}
|
|
393
|
+
await sleep(backoffMs(failures), signal);
|
|
394
|
+
options.onReconnect?.(failures, lastSeq);
|
|
395
|
+
try {
|
|
396
|
+
response = await options.resume(turnId, lastSeq, signal);
|
|
397
|
+
}
|
|
398
|
+
catch (error) {
|
|
399
|
+
if (isAbort(error) || signal?.aborted)
|
|
400
|
+
throw error;
|
|
401
|
+
response = null;
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
if (response.status === 404) {
|
|
405
|
+
throw new TurnStreamLostError("This response can no longer be resumed.", turnId, lastSeq);
|
|
406
|
+
}
|
|
407
|
+
if (!response.ok)
|
|
408
|
+
response = null;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* POST a turn, retrying network failures with the same client turn id so the
|
|
413
|
+
* server attaches the retry to the turn the first attempt started.
|
|
414
|
+
*/
|
|
415
|
+
async function postTurnWithRetry(send, options = {}) {
|
|
416
|
+
const clientTurnId = options.clientTurnId || newClientTurnId();
|
|
417
|
+
const attempts = options.attempts ?? 3;
|
|
418
|
+
for (let attempt = 1;; attempt++) {
|
|
419
|
+
try {
|
|
420
|
+
return await send(clientTurnId);
|
|
421
|
+
}
|
|
422
|
+
catch (error) {
|
|
423
|
+
if (isAbort(error) || options.signal?.aborted || attempt >= attempts) {
|
|
424
|
+
throw error;
|
|
425
|
+
}
|
|
426
|
+
await sleep(backoffMs(attempt), options.signal);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Main SDK class for interacting with the AI Content Creator chat system
|
|
433
|
+
*/
|
|
434
|
+
class ChatSDK extends BaseClient {
|
|
435
|
+
/**
|
|
436
|
+
* Initialize the Chat SDK
|
|
437
|
+
* @param config Configuration object with API credentials and settings
|
|
438
|
+
*/
|
|
439
|
+
constructor(config) {
|
|
440
|
+
super(config);
|
|
441
|
+
this.messageChunkString = "";
|
|
442
|
+
this.docMessageString = "";
|
|
443
|
+
this.messageInitObject = null;
|
|
444
|
+
this.actionsMap = new Map();
|
|
445
|
+
this.hasCalledOnStart = false;
|
|
446
|
+
/** Unfinished tag payload from the previous TCP chunk (JSON split across reads). */
|
|
447
|
+
this.streamTagRemainder = "";
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Get the project ID this SDK is configured for (for use when building requests elsewhere)
|
|
451
|
+
*/
|
|
452
|
+
getProjectId() {
|
|
453
|
+
return this.config.projectId;
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Create a new chat in the project
|
|
457
|
+
* @param name Optional name for the chat (defaults to "Untitled")
|
|
458
|
+
* @param documentKeys Optional array of document keys for knowledge base context
|
|
459
|
+
* @returns Promise resolving to the created chat information
|
|
460
|
+
*/
|
|
461
|
+
async createChat(name, documentKeys) {
|
|
462
|
+
return await this.post("chat/create", {
|
|
463
|
+
project_id: this.config.projectId,
|
|
464
|
+
name: name || "Untitled",
|
|
465
|
+
document_keys: documentKeys, // This endpoint expects array format based on backend model
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* List chats in the project with pagination support
|
|
470
|
+
* @param cursor Optional cursor for pagination
|
|
471
|
+
* @param limit Number of chats to return (default: 30, max: 100)
|
|
472
|
+
* @returns Promise resolving to paginated chat list
|
|
473
|
+
*/
|
|
474
|
+
async listChats(cursor, limit = 30) {
|
|
475
|
+
const params = new URLSearchParams({
|
|
476
|
+
limit: Math.min(limit, 100).toString(),
|
|
477
|
+
...(cursor && { cursor: cursor.toString() }),
|
|
478
|
+
});
|
|
479
|
+
return await this.get(`project/${this.config.projectId}/chat?${params}`);
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* Like `listChats`, but revalidates a page the caller already holds.
|
|
483
|
+
*
|
|
484
|
+
* Pass the `etag` from the last response for the same cursor and limit. The
|
|
485
|
+
* server answers 304 when the page has not changed, and then there is no
|
|
486
|
+
* body to parse: `notModified` is true and the caller keeps its copy.
|
|
487
|
+
* @returns The fresh page with its ETag, or `notModified: true`
|
|
488
|
+
*/
|
|
489
|
+
async listChatsIfChanged(cursor, limit = 30, etag) {
|
|
490
|
+
const params = new URLSearchParams({
|
|
491
|
+
limit: Math.min(limit, 100).toString(),
|
|
492
|
+
...(cursor && { cursor: cursor.toString() }),
|
|
493
|
+
});
|
|
494
|
+
const headers = { ...this.headers };
|
|
495
|
+
if (etag)
|
|
496
|
+
headers["If-None-Match"] = etag;
|
|
497
|
+
const response = await this.customFetch(`${this.config.baseUrl}project/${this.config.projectId}/chat?${params}`, { method: "GET", headers });
|
|
498
|
+
if (response.status === 304)
|
|
499
|
+
return { notModified: true };
|
|
500
|
+
if (!response.ok)
|
|
501
|
+
await this.handleErrorResponse(response);
|
|
502
|
+
return {
|
|
503
|
+
notModified: false,
|
|
504
|
+
data: (await response.json()),
|
|
505
|
+
etag: response.headers.get("etag"),
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* Chats in the project with a turn running right now.
|
|
510
|
+
*
|
|
511
|
+
* Unlike the session list a client builds up locally, this includes turns
|
|
512
|
+
* started in another tab or device, or before a reload -- a turn's life is
|
|
513
|
+
* server-side, so this is the only way a client
|
|
514
|
+
* can tell. Poll it only while something is running.
|
|
515
|
+
* @returns Promise resolving to the running chats
|
|
516
|
+
*/
|
|
517
|
+
async listRunningChats() {
|
|
518
|
+
const response = await this.get(`v4/chat/turns/running?project_id=${encodeURIComponent(this.config.projectId)}`);
|
|
519
|
+
return response ?? { chats: [] };
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* Get a specific chat with its message history
|
|
523
|
+
* @param chatId The ID of the chat to retrieve
|
|
524
|
+
* @returns Promise resolving to chat details with messages
|
|
525
|
+
*/
|
|
526
|
+
async getChatHistory(chatId) {
|
|
527
|
+
return await this.get(`project/${this.config.projectId}/chat/${chatId}`);
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* Delete a chat and all its messages
|
|
531
|
+
* @param chatId The ID of the chat to delete
|
|
532
|
+
* @returns Promise that resolves when the chat is deleted
|
|
533
|
+
*/
|
|
534
|
+
async deleteChat(chatId) {
|
|
535
|
+
await this.delete("chat/delete", {
|
|
536
|
+
project_id: this.config.projectId,
|
|
537
|
+
chat_id: chatId,
|
|
538
|
+
});
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* Update the name of an existing chat
|
|
542
|
+
* @param chatId The ID of the chat to update
|
|
543
|
+
* @param newName The new name for the chat
|
|
544
|
+
* @returns Promise that resolves when the name is updated
|
|
545
|
+
*/
|
|
546
|
+
async updateChatName(chatId, newName) {
|
|
547
|
+
await this.post("chat/update/name", {
|
|
548
|
+
project_id: this.config.projectId,
|
|
549
|
+
chatId: chatId,
|
|
550
|
+
title: newName,
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
/** Get the current user's starred chat IDs for this project. */
|
|
554
|
+
async listStarredChatIds() {
|
|
555
|
+
const response = await this.get(`project/${this.config.projectId}/chat/stars`);
|
|
556
|
+
return Array.isArray(response?.chat_ids) ? response.chat_ids : [];
|
|
557
|
+
}
|
|
558
|
+
/** Star or unstar a chat for the current user. */
|
|
559
|
+
async setChatStarred(chatId, starred) {
|
|
560
|
+
await this.post("chat/star", {
|
|
561
|
+
project_id: this.config.projectId,
|
|
562
|
+
chat_id: chatId,
|
|
563
|
+
starred,
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
/**
|
|
567
|
+
* Send a message and get the response
|
|
568
|
+
* @param message The message text to send
|
|
569
|
+
* @param options Optional configuration for the message
|
|
570
|
+
* @returns Promise resolving to the message response
|
|
571
|
+
*/
|
|
572
|
+
async sendMessage(message, options = {}) {
|
|
573
|
+
// Convert document keys array to comma-separated string for non-streaming endpoint
|
|
574
|
+
const documentKeysString = options.documentKeys
|
|
575
|
+
? options.documentKeys.join(",")
|
|
576
|
+
: undefined;
|
|
577
|
+
return await this.post("chat/message", {
|
|
578
|
+
message,
|
|
579
|
+
project_id: this.config.projectId,
|
|
580
|
+
chat_id: options.chatId,
|
|
581
|
+
agent_type: options.agentType || "chat_agent",
|
|
582
|
+
agent_id: options.agentId,
|
|
583
|
+
document_keys: documentKeysString,
|
|
584
|
+
// No fallback model: the agent resolves its own, and inventing one here
|
|
585
|
+
// only mislabelled the audit record.
|
|
586
|
+
model_name: options.modelName,
|
|
587
|
+
use_knowledgebase: options.useKnowledgebase ?? true,
|
|
588
|
+
is_test: options.isTest ?? false,
|
|
589
|
+
google_search: options.googleSearch ?? false,
|
|
590
|
+
format_instructions: options.formatInstructions || "normal",
|
|
591
|
+
ignore_chat_history: options.ignoreChatHistory ?? false,
|
|
592
|
+
example_json: options.exampleJson,
|
|
593
|
+
skip_stream: options.skipStream ?? false,
|
|
594
|
+
request_metadata: options.metadata,
|
|
595
|
+
});
|
|
596
|
+
}
|
|
597
|
+
/**
|
|
598
|
+
* Send a message with streaming response support
|
|
599
|
+
* @param message The message text to send
|
|
600
|
+
* @param options Configuration including streaming callbacks
|
|
601
|
+
* @returns Promise that resolves when streaming is complete
|
|
602
|
+
*/
|
|
603
|
+
async sendMessageStream(message, options = {}) {
|
|
604
|
+
const formData = new FormData();
|
|
605
|
+
formData.append("message", message);
|
|
606
|
+
formData.append("project_id", this.config.projectId);
|
|
607
|
+
if (options.chatId) {
|
|
608
|
+
formData.append("chat_id", options.chatId);
|
|
609
|
+
}
|
|
610
|
+
formData.append("agent_type", options.agentType || "chat_agent");
|
|
611
|
+
if (options.agentId) {
|
|
612
|
+
formData.append("agent_id", options.agentId);
|
|
613
|
+
}
|
|
614
|
+
if (options.modelName) {
|
|
615
|
+
formData.append("model_name", options.modelName);
|
|
616
|
+
}
|
|
617
|
+
if (options.documentKeys) {
|
|
618
|
+
// Convert document keys array to indexed object format (like the old API)
|
|
619
|
+
const _documentKeys = options.documentKeys.reduce((acc, current, currentIndex) => {
|
|
620
|
+
acc[currentIndex + 1] = current;
|
|
621
|
+
return acc;
|
|
622
|
+
}, {});
|
|
623
|
+
formData.append("multipart_document_keys", JSON.stringify(_documentKeys));
|
|
624
|
+
}
|
|
625
|
+
// Send an empty selection explicitly rather than omitting the field. The
|
|
626
|
+
// caller passes undefined when the agent has a single knowledge base (there
|
|
627
|
+
// is nothing to choose between) and an array when it has several, so an
|
|
628
|
+
// empty array means the user switched every one off. Dropping it here made
|
|
629
|
+
// that indistinguishable from "no selection sent", and the backend resolves
|
|
630
|
+
// those two cases differently: absent falls back to the agent's configured
|
|
631
|
+
// knowledge bases, whereas [] now searches none of them.
|
|
632
|
+
if (options.activeKnowledgeBases !== undefined) {
|
|
633
|
+
const activeKbJson = JSON.stringify(options.activeKnowledgeBases);
|
|
634
|
+
formData.append("active_knowledgebases", activeKbJson);
|
|
635
|
+
}
|
|
636
|
+
if (options.images && options.images.length > 0) {
|
|
637
|
+
options.images.forEach((image) => {
|
|
638
|
+
const file = image instanceof File
|
|
639
|
+
? image
|
|
640
|
+
: new File([image], "image.png", {
|
|
641
|
+
type: image.type || "image/png",
|
|
642
|
+
});
|
|
643
|
+
formData.append("images", file, file.name || "image.png");
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
const mergedMetadata = { ...(options.metadata || {}) };
|
|
647
|
+
if (options.targetProjectId) {
|
|
648
|
+
mergedMetadata.target_project_id = options.targetProjectId;
|
|
649
|
+
}
|
|
650
|
+
if (Object.keys(mergedMetadata).length > 0) {
|
|
651
|
+
formData.append("request_metadata", JSON.stringify(mergedMetadata));
|
|
652
|
+
}
|
|
653
|
+
formData.append("use_knowledgebase", String(options.useKnowledgebase ?? true));
|
|
654
|
+
formData.append("is_test", String(options.isTest ?? false));
|
|
655
|
+
formData.append("google_search", String(options.googleSearch ?? false));
|
|
656
|
+
formData.append("format_instructions", options.formatInstructions || "normal");
|
|
657
|
+
formData.append("ignore_chat_history", String(options.ignoreChatHistory ?? false));
|
|
658
|
+
if (options.environment) {
|
|
659
|
+
formData.append("environment", options.environment);
|
|
660
|
+
}
|
|
661
|
+
if (options.exampleJson) {
|
|
662
|
+
formData.append("example_json", options.exampleJson);
|
|
663
|
+
}
|
|
664
|
+
// Use customFetch for streaming (defaults to native fetch if not provided).
|
|
665
|
+
// A network failure before the response is retried with the same client
|
|
666
|
+
// turn id, which the server attaches to the turn already started.
|
|
667
|
+
let response;
|
|
668
|
+
try {
|
|
669
|
+
response = await postTurnWithRetry((clientTurnId) => this.customFetch(`${this.config.baseUrl}v4/chat/message`, {
|
|
670
|
+
method: "POST",
|
|
671
|
+
headers: {
|
|
672
|
+
...this.streamHeaders(),
|
|
673
|
+
[RESUMABLE_STREAM_HEADER]: "1",
|
|
674
|
+
[CLIENT_TURN_ID_HEADER]: clientTurnId,
|
|
675
|
+
},
|
|
676
|
+
body: formData,
|
|
677
|
+
signal: options.signal,
|
|
678
|
+
}), { signal: options.signal, clientTurnId: options.clientTurnId });
|
|
679
|
+
}
|
|
680
|
+
catch (error) {
|
|
681
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
682
|
+
options.onError?.(err);
|
|
683
|
+
throw err;
|
|
684
|
+
}
|
|
685
|
+
if (!response.ok) {
|
|
686
|
+
const error = await this.createErrorFromResponse(response);
|
|
687
|
+
options.onError?.(error);
|
|
688
|
+
throw error;
|
|
689
|
+
}
|
|
690
|
+
options.onResponseAccepted?.();
|
|
691
|
+
await this.consumeTurnStream(response, options);
|
|
692
|
+
}
|
|
693
|
+
/**
|
|
694
|
+
* Status of a streamed turn, so a reloaded page can reattach to one still
|
|
695
|
+
* running. Resolves to null once the turn is no longer resumable.
|
|
696
|
+
*/
|
|
697
|
+
async getTurnStatus(messageId) {
|
|
698
|
+
try {
|
|
699
|
+
return await this.get(`v4/chat/message/${encodeURIComponent(messageId)}/turn?project_id=${encodeURIComponent(this.config.projectId)}`);
|
|
700
|
+
}
|
|
701
|
+
catch (error) {
|
|
702
|
+
if (error?.status === 404)
|
|
703
|
+
return null;
|
|
704
|
+
throw error;
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
/**
|
|
708
|
+
* Reattach to a turn (e.g. after a page reload) and stream it from the
|
|
709
|
+
* start, with the same callbacks as `sendMessageStream`.
|
|
710
|
+
*/
|
|
711
|
+
async resumeTurnStream(messageId, options = {}) {
|
|
712
|
+
const response = await this.openTurnStream(messageId, 0, options.signal);
|
|
713
|
+
if (!response.ok) {
|
|
714
|
+
const error = await this.createErrorFromResponse(response);
|
|
715
|
+
options.onError?.(error);
|
|
716
|
+
throw error;
|
|
717
|
+
}
|
|
718
|
+
await this.consumeTurnStream(response, options, messageId);
|
|
719
|
+
}
|
|
720
|
+
streamHeaders() {
|
|
721
|
+
// Don't set Content-Type for FormData - browser will set it with boundary
|
|
722
|
+
return Object.fromEntries(Object.entries(this.headers).filter(([key]) => key !== "Content-Type"));
|
|
723
|
+
}
|
|
724
|
+
openTurnStream(messageId, fromSeq, signal) {
|
|
725
|
+
const query = new URLSearchParams({
|
|
726
|
+
project_id: this.config.projectId,
|
|
727
|
+
from_seq: String(fromSeq),
|
|
728
|
+
});
|
|
729
|
+
return this.customFetch(`${this.config.baseUrl}v4/chat/message/${encodeURIComponent(messageId)}/stream?${query.toString()}`, { method: "GET", headers: this.streamHeaders(), signal });
|
|
730
|
+
}
|
|
731
|
+
async consumeTurnStream(response, options, turnId) {
|
|
732
|
+
if (!response.body) {
|
|
733
|
+
const error = new Error("ReadableStream not supported in this environment");
|
|
734
|
+
options.onError?.(error);
|
|
735
|
+
throw error;
|
|
736
|
+
}
|
|
737
|
+
// Reset streaming state for new message
|
|
738
|
+
this.resetStreamingState();
|
|
739
|
+
try {
|
|
740
|
+
let messageObject = {};
|
|
741
|
+
const { status } = await readResumableTurn({
|
|
742
|
+
response,
|
|
743
|
+
turnId,
|
|
744
|
+
signal: options.signal,
|
|
745
|
+
resume: (id, fromSeq, signal) => this.openTurnStream(id, fromSeq, signal),
|
|
746
|
+
onReconnect: options.onReconnect,
|
|
747
|
+
onActivity: options.onActivity,
|
|
748
|
+
onText: (chunk) => {
|
|
749
|
+
const parsedData = this.parseStreamChunk(chunk, options);
|
|
750
|
+
if (parsedData.messageObject) {
|
|
751
|
+
messageObject = { ...messageObject, ...parsedData.messageObject };
|
|
752
|
+
}
|
|
753
|
+
},
|
|
754
|
+
});
|
|
755
|
+
if (status) {
|
|
756
|
+
const resumedBy = this.messageInitObject?.mi?.resumed_by;
|
|
757
|
+
options.onTurnStatus?.(status, typeof resumedBy === "string" && resumedBy ? { resumedBy } : undefined);
|
|
758
|
+
}
|
|
759
|
+
// Call completion callback with final message
|
|
760
|
+
if (options.onComplete) {
|
|
761
|
+
// Merge the message init object with any other collected message data
|
|
762
|
+
const finalMessage = {
|
|
763
|
+
...messageObject,
|
|
764
|
+
...(this.messageInitObject?.mi || {}),
|
|
765
|
+
...(this.messageInitObject?.msg_object || {}),
|
|
766
|
+
};
|
|
767
|
+
if (Object.keys(finalMessage).length > 0) {
|
|
768
|
+
options.onComplete(finalMessage);
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
catch (error) {
|
|
773
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
774
|
+
options.onError?.(err);
|
|
775
|
+
throw err;
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* Send user feedback for a message
|
|
780
|
+
* @param messageId The ID of the message to provide feedback for
|
|
781
|
+
* @param chatId The ID of the chat containing the message
|
|
782
|
+
* @param feedback True for positive feedback, false for negative
|
|
783
|
+
* @returns Promise that resolves when feedback is sent
|
|
784
|
+
*/
|
|
785
|
+
async sendFeedback(messageId, chatId, feedback) {
|
|
786
|
+
await this.post("chat/message/user/feedback", {
|
|
787
|
+
message_id: messageId,
|
|
788
|
+
project_id: this.config.projectId,
|
|
789
|
+
chat_id: chatId,
|
|
790
|
+
user_feedback: feedback,
|
|
791
|
+
});
|
|
792
|
+
}
|
|
793
|
+
/**
|
|
794
|
+
* Reset streaming state for a new message
|
|
795
|
+
* @private
|
|
796
|
+
*/
|
|
797
|
+
resetStreamingState() {
|
|
798
|
+
this.messageChunkString = "";
|
|
799
|
+
this.docMessageString = "";
|
|
800
|
+
this.messageInitObject = null;
|
|
801
|
+
this.actionsMap.clear();
|
|
802
|
+
this.hasCalledOnStart = false;
|
|
803
|
+
this.streamTagRemainder = "";
|
|
804
|
+
}
|
|
805
|
+
/**
|
|
806
|
+
* Parse streaming response chunks and trigger appropriate callbacks
|
|
807
|
+
* @private
|
|
808
|
+
*/
|
|
809
|
+
parseStreamChunk(chunk, callbacks) {
|
|
810
|
+
let messageObject;
|
|
811
|
+
try {
|
|
812
|
+
let modifiedChunk = this.streamTagRemainder + chunk;
|
|
813
|
+
this.streamTagRemainder = "";
|
|
814
|
+
/**
|
|
815
|
+
* List of tags used to parse streaming response chunks.
|
|
816
|
+
* These tags act as delimiters in the streaming response, allowing the backend
|
|
817
|
+
* to send different types of structured data in a single stream.
|
|
818
|
+
*
|
|
819
|
+
* Tag definitions:
|
|
820
|
+
* - msg_chunk: Message text chunks - the actual chat message text being streamed
|
|
821
|
+
* - msmro: Message end signal - indicates the message streaming is complete
|
|
822
|
+
* - msg_object: Complete message object with full metadata (includes message ID)
|
|
823
|
+
* - mi: Message initialization - initial message metadata when streaming starts
|
|
824
|
+
* - ui_form: UI form data - form specifications for interactive elements
|
|
825
|
+
* - ma: Message action - action objects representing operations being performed
|
|
826
|
+
* - doc: Document content - document-related content chunks (separate from message)
|
|
827
|
+
* - sql: SQL query data - SQL query information as JSON
|
|
828
|
+
* - document_event: Document event notifications - events related to document processing
|
|
829
|
+
* - meta: Message identity - provides chat_id and message_id for precise updates
|
|
830
|
+
* - msg_discard: Take back streamed text - a model call that failed partway
|
|
831
|
+
* is being retried, so its partial text ({"text": ...}) must be removed
|
|
832
|
+
*/
|
|
833
|
+
const tags = [
|
|
834
|
+
"msg_chunk",
|
|
835
|
+
"msmro",
|
|
836
|
+
"msg_object",
|
|
837
|
+
"mi",
|
|
838
|
+
"ui_form",
|
|
839
|
+
"ma",
|
|
840
|
+
"doc",
|
|
841
|
+
"sql",
|
|
842
|
+
"document_event",
|
|
843
|
+
"meta",
|
|
844
|
+
"msg_discard",
|
|
845
|
+
];
|
|
846
|
+
const jsonPayloadTags = new Set([
|
|
847
|
+
"mi",
|
|
848
|
+
"msg_object",
|
|
849
|
+
"ui_form",
|
|
850
|
+
"ma",
|
|
851
|
+
"meta",
|
|
852
|
+
"msmro",
|
|
853
|
+
"sql",
|
|
854
|
+
"document_event",
|
|
855
|
+
"msg_discard",
|
|
856
|
+
]);
|
|
857
|
+
// Process the chunk as long as it contains tags
|
|
858
|
+
let stillHasTags = true;
|
|
859
|
+
while (stillHasTags) {
|
|
860
|
+
stillHasTags = false;
|
|
861
|
+
// Find the first tag in the chunk
|
|
862
|
+
let firstTagIndex = -1;
|
|
863
|
+
let firstTag = "";
|
|
864
|
+
for (const tag of tags) {
|
|
865
|
+
const tagStart = `<${tag}>`;
|
|
866
|
+
const index = modifiedChunk.indexOf(tagStart);
|
|
867
|
+
if (index !== -1 && (firstTagIndex === -1 || index < firstTagIndex)) {
|
|
868
|
+
firstTagIndex = index;
|
|
869
|
+
firstTag = tag;
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
if (firstTagIndex === -1) {
|
|
873
|
+
if (modifiedChunk.length > 0) {
|
|
874
|
+
this.streamTagRemainder = modifiedChunk;
|
|
875
|
+
}
|
|
876
|
+
break;
|
|
877
|
+
}
|
|
878
|
+
// If a tag was found, process it
|
|
879
|
+
if (firstTagIndex !== -1) {
|
|
880
|
+
stillHasTags = true;
|
|
881
|
+
const tagStart = `<${firstTag}>`;
|
|
882
|
+
const tagStartIndex = firstTagIndex;
|
|
883
|
+
// Get content after the tag
|
|
884
|
+
const afterTagStart = modifiedChunk.substring(tagStartIndex + tagStart.length);
|
|
885
|
+
// Find the next tag if any
|
|
886
|
+
let nextTagIndex = -1;
|
|
887
|
+
for (const tag of tags) {
|
|
888
|
+
const nextTag = `<${tag}>`;
|
|
889
|
+
const index = afterTagStart.indexOf(nextTag);
|
|
890
|
+
if (index !== -1 && (nextTagIndex === -1 || index < nextTagIndex)) {
|
|
891
|
+
nextTagIndex = index;
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
// Extract the content between tags or until the end
|
|
895
|
+
const content = nextTagIndex !== -1
|
|
896
|
+
? afterTagStart.substring(0, nextTagIndex)
|
|
897
|
+
: afterTagStart;
|
|
898
|
+
if (jsonPayloadTags.has(firstTag) && nextTagIndex === -1) {
|
|
899
|
+
try {
|
|
900
|
+
JSON.parse(content.trim());
|
|
901
|
+
}
|
|
902
|
+
catch {
|
|
903
|
+
this.streamTagRemainder = modifiedChunk.substring(tagStartIndex);
|
|
904
|
+
break;
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
// Process the content based on the tag
|
|
908
|
+
switch (firstTag) {
|
|
909
|
+
case "msg_chunk":
|
|
910
|
+
this.messageChunkString += content;
|
|
911
|
+
callbacks.onChunk?.(content);
|
|
912
|
+
break;
|
|
913
|
+
case "msg_discard":
|
|
914
|
+
try {
|
|
915
|
+
const { text } = JSON.parse(content.trim());
|
|
916
|
+
if (typeof text === "string" &&
|
|
917
|
+
text &&
|
|
918
|
+
this.messageChunkString.endsWith(text)) {
|
|
919
|
+
this.messageChunkString = this.messageChunkString.slice(0, -text.length);
|
|
920
|
+
callbacks.onDiscard?.(text);
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
catch (error) {
|
|
924
|
+
console.error("Error parsing msg_discard:", error);
|
|
925
|
+
}
|
|
926
|
+
break;
|
|
927
|
+
case "msmro":
|
|
928
|
+
try {
|
|
929
|
+
const parsed = JSON.parse(content.trim());
|
|
930
|
+
if (parsed.message) {
|
|
931
|
+
this.messageInitObject = {
|
|
932
|
+
...this.messageInitObject,
|
|
933
|
+
mi: {
|
|
934
|
+
...(this.messageInitObject?.mi || {}),
|
|
935
|
+
...parsed.message,
|
|
936
|
+
},
|
|
937
|
+
msg_object: {
|
|
938
|
+
...(this.messageInitObject?.msg_object || {}),
|
|
939
|
+
...parsed.message,
|
|
940
|
+
},
|
|
941
|
+
};
|
|
942
|
+
messageObject = {
|
|
943
|
+
...messageObject,
|
|
944
|
+
...parsed.message,
|
|
945
|
+
...(parsed.chat_id && { chat_id: parsed.chat_id }),
|
|
946
|
+
...(parsed.message_id && { message_id: parsed.message_id }),
|
|
947
|
+
};
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
catch {
|
|
951
|
+
// msmro may not always contain valid JSON
|
|
952
|
+
}
|
|
953
|
+
callbacks.onMessageEnd?.();
|
|
954
|
+
break;
|
|
955
|
+
case "meta":
|
|
956
|
+
try {
|
|
957
|
+
const ids = JSON.parse(content.trim());
|
|
958
|
+
if (ids && (ids.message_id || ids.chat_id)) {
|
|
959
|
+
// Notify client about ids
|
|
960
|
+
callbacks.onMeta?.({
|
|
961
|
+
chat_id: ids.chat_id,
|
|
962
|
+
message_id: ids.message_id,
|
|
963
|
+
});
|
|
964
|
+
// Also honor onStart for backward compatibility if not yet called
|
|
965
|
+
if (!this.hasCalledOnStart &&
|
|
966
|
+
ids.message_id &&
|
|
967
|
+
callbacks.onStart) {
|
|
968
|
+
callbacks.onStart(ids.message_id);
|
|
969
|
+
this.hasCalledOnStart = true;
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
catch (error) {
|
|
974
|
+
console.error("Error parsing meta:", error);
|
|
975
|
+
}
|
|
976
|
+
break;
|
|
977
|
+
case "msg_object":
|
|
978
|
+
try {
|
|
979
|
+
const parsed = JSON.parse(content.trim());
|
|
980
|
+
messageObject = parsed;
|
|
981
|
+
// Call onStart with the actual message ID if available and not called yet
|
|
982
|
+
if (!this.hasCalledOnStart && parsed.id && callbacks.onStart) {
|
|
983
|
+
callbacks.onStart(parsed.id);
|
|
984
|
+
this.hasCalledOnStart = true;
|
|
985
|
+
}
|
|
986
|
+
callbacks.onMessageObject?.(parsed);
|
|
987
|
+
}
|
|
988
|
+
catch (error) {
|
|
989
|
+
console.error("Error parsing message object:", error);
|
|
990
|
+
}
|
|
991
|
+
break;
|
|
992
|
+
case "mi":
|
|
993
|
+
try {
|
|
994
|
+
const mi = JSON.parse(content.trim());
|
|
995
|
+
this.messageInitObject = {
|
|
996
|
+
mi: mi,
|
|
997
|
+
msg_object: mi,
|
|
998
|
+
};
|
|
999
|
+
messageObject = this.messageInitObject;
|
|
1000
|
+
// Call onStart with the actual message ID if available and not called yet
|
|
1001
|
+
if (!this.hasCalledOnStart && mi.id && callbacks.onStart) {
|
|
1002
|
+
callbacks.onStart(mi.id);
|
|
1003
|
+
this.hasCalledOnStart = true;
|
|
1004
|
+
}
|
|
1005
|
+
callbacks.onMessageObject?.(this.messageInitObject);
|
|
1006
|
+
}
|
|
1007
|
+
catch (error) {
|
|
1008
|
+
console.error("Error parsing message init:", error);
|
|
1009
|
+
}
|
|
1010
|
+
break;
|
|
1011
|
+
case "ui_form":
|
|
1012
|
+
try {
|
|
1013
|
+
const uiForm = JSON.parse(content.trim());
|
|
1014
|
+
this.messageInitObject = {
|
|
1015
|
+
...this.messageInitObject,
|
|
1016
|
+
mi: {
|
|
1017
|
+
...(this.messageInitObject?.mi || {}),
|
|
1018
|
+
ui_form: uiForm,
|
|
1019
|
+
},
|
|
1020
|
+
msg_object: {
|
|
1021
|
+
...(this.messageInitObject?.msg_object || {}),
|
|
1022
|
+
ui_form: uiForm,
|
|
1023
|
+
},
|
|
1024
|
+
};
|
|
1025
|
+
messageObject = this.messageInitObject;
|
|
1026
|
+
callbacks.onMessageObject?.(this.messageInitObject);
|
|
1027
|
+
}
|
|
1028
|
+
catch (error) {
|
|
1029
|
+
console.error("Error parsing UI form:", error);
|
|
1030
|
+
}
|
|
1031
|
+
break;
|
|
1032
|
+
case "ma":
|
|
1033
|
+
try {
|
|
1034
|
+
const parsedAction = JSON.parse(content.trim());
|
|
1035
|
+
const actionId = parsedAction.action_id;
|
|
1036
|
+
if (actionId) {
|
|
1037
|
+
// Update existing action or create new one
|
|
1038
|
+
const existingAction = this.actionsMap.get(actionId);
|
|
1039
|
+
const updatedAction = existingAction
|
|
1040
|
+
? { ...existingAction, ...parsedAction }
|
|
1041
|
+
: parsedAction;
|
|
1042
|
+
this.actionsMap.set(actionId, updatedAction);
|
|
1043
|
+
const actionObj = { action: updatedAction };
|
|
1044
|
+
messageObject = actionObj;
|
|
1045
|
+
callbacks.onMessageObject?.(actionObj);
|
|
1046
|
+
}
|
|
1047
|
+
else {
|
|
1048
|
+
// If no action_id, treat as a standalone action
|
|
1049
|
+
const actionObj = { action: parsedAction };
|
|
1050
|
+
messageObject = actionObj;
|
|
1051
|
+
callbacks.onMessageObject?.(actionObj);
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
catch (error) {
|
|
1055
|
+
console.error("Error parsing message action:", error);
|
|
1056
|
+
}
|
|
1057
|
+
break;
|
|
1058
|
+
case "doc":
|
|
1059
|
+
this.docMessageString += content;
|
|
1060
|
+
callbacks.onDocumentChunk?.(content);
|
|
1061
|
+
break;
|
|
1062
|
+
case "sql":
|
|
1063
|
+
try {
|
|
1064
|
+
const sqlObj = { sql: JSON.parse(content.trim()) };
|
|
1065
|
+
messageObject = sqlObj;
|
|
1066
|
+
callbacks.onMessageObject?.(sqlObj);
|
|
1067
|
+
}
|
|
1068
|
+
catch (error) {
|
|
1069
|
+
console.error("Error parsing SQL query:", error);
|
|
1070
|
+
}
|
|
1071
|
+
break;
|
|
1072
|
+
case "document_event":
|
|
1073
|
+
try {
|
|
1074
|
+
const parsedDocEvent = JSON.parse(content.trim());
|
|
1075
|
+
callbacks.onDocumentEventReceived?.(parsedDocEvent);
|
|
1076
|
+
}
|
|
1077
|
+
catch (error) {
|
|
1078
|
+
console.error("Error parsing document event:", error);
|
|
1079
|
+
}
|
|
1080
|
+
break;
|
|
1081
|
+
}
|
|
1082
|
+
// Remove the processed tag and its content from the chunk
|
|
1083
|
+
const tagAndContent = modifiedChunk.substring(tagStartIndex, tagStartIndex +
|
|
1084
|
+
tagStart.length +
|
|
1085
|
+
(nextTagIndex !== -1 ? nextTagIndex : content.length));
|
|
1086
|
+
modifiedChunk = modifiedChunk.replace(tagAndContent, "");
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
return { messageObject };
|
|
1090
|
+
}
|
|
1091
|
+
catch (error) {
|
|
1092
|
+
console.error("Error parsing chunk:", error);
|
|
1093
|
+
return { messageObject };
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
/**
|
|
1097
|
+
* Handle error responses from the API
|
|
1098
|
+
* @private
|
|
1099
|
+
*/
|
|
1100
|
+
async handleErrorResponse(response) {
|
|
1101
|
+
const error = await this.createErrorFromResponse(response);
|
|
1102
|
+
throw error;
|
|
1103
|
+
}
|
|
1104
|
+
/**
|
|
1105
|
+
* Create an error object from an HTTP response
|
|
1106
|
+
* @private
|
|
1107
|
+
*/
|
|
1108
|
+
async createErrorFromResponse(response) {
|
|
1109
|
+
// Only 401 expires the session; 403 (permission denied) must surface to the caller.
|
|
1110
|
+
if (response.status === 401 && typeof window !== "undefined") {
|
|
1111
|
+
window.dispatchEvent(new CustomEvent("sessionExpired", {
|
|
1112
|
+
detail: { status: response.status, url: response.url },
|
|
1113
|
+
}));
|
|
1114
|
+
}
|
|
1115
|
+
let errorMessage = response.statusText;
|
|
1116
|
+
let errorDetail;
|
|
1117
|
+
try {
|
|
1118
|
+
const errorData = await response.json();
|
|
1119
|
+
errorMessage = extractErrorMessage(errorData, errorMessage);
|
|
1120
|
+
errorDetail = errorData?.detail;
|
|
1121
|
+
}
|
|
1122
|
+
catch (e) {
|
|
1123
|
+
// If we can't parse the error response, use the status text
|
|
1124
|
+
}
|
|
1125
|
+
const error = new Error(`HTTP ${response.status}: ${errorMessage}`);
|
|
1126
|
+
const issueDiagnostic = response[Symbol.for("odin.issueDiagnostic")];
|
|
1127
|
+
if (issueDiagnostic) {
|
|
1128
|
+
Object.defineProperty(error, Symbol.for("odin.issueDiagnostic"), {
|
|
1129
|
+
configurable: true,
|
|
1130
|
+
value: issueDiagnostic,
|
|
1131
|
+
});
|
|
1132
|
+
}
|
|
1133
|
+
error.status = response.status;
|
|
1134
|
+
error.detail = errorDetail;
|
|
1135
|
+
return error;
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
/**
|
|
1140
|
+
* Voice SDK for ElevenLabs integration
|
|
1141
|
+
* Provides voice conversation capabilities with automatic chat integration
|
|
1142
|
+
*/
|
|
1143
|
+
class VoiceSDK extends BaseClient {
|
|
1144
|
+
constructor(config) {
|
|
1145
|
+
super(config);
|
|
1146
|
+
this.activeSessions = new Map();
|
|
1147
|
+
this.defaultAgentId = config.agentId;
|
|
1148
|
+
this.defaultVoiceSettings = config.defaultVoiceSettings;
|
|
1149
|
+
// Initialize ChatSDK for integration if we have the necessary config
|
|
1150
|
+
if (config.accessToken || (config.apiKey && config.apiSecret)) {
|
|
1151
|
+
this.chatSDK = new ChatSDK(config);
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
/**
|
|
1155
|
+
* Start a voice conversation session
|
|
1156
|
+
*/
|
|
1157
|
+
async startVoiceConversation(options = {}) {
|
|
1158
|
+
const sessionId = this.generateSessionId();
|
|
1159
|
+
// Create session record
|
|
1160
|
+
const session = {
|
|
1161
|
+
id: sessionId,
|
|
1162
|
+
chatId: options.existingChatId,
|
|
1163
|
+
startTime: Date.now(),
|
|
1164
|
+
messages: [],
|
|
1165
|
+
metadata: {
|
|
1166
|
+
agentId: options.agentId || this.defaultAgentId,
|
|
1167
|
+
voiceSettings: options.voiceSettings || this.defaultVoiceSettings,
|
|
1168
|
+
userInfo: options.userInfo,
|
|
1169
|
+
},
|
|
1170
|
+
};
|
|
1171
|
+
this.activeSessions.set(sessionId, session);
|
|
1172
|
+
// If we need to create a new chat for this voice conversation
|
|
1173
|
+
if (options.saveToChat && !options.existingChatId && this.chatSDK) {
|
|
1174
|
+
try {
|
|
1175
|
+
const chat = await this.chatSDK.createChat("Voice Conversation");
|
|
1176
|
+
session.chatId = chat.chat_id;
|
|
1177
|
+
options.callbacks?.onConversationSaved?.(chat.chat_id, "");
|
|
1178
|
+
}
|
|
1179
|
+
catch (error) {
|
|
1180
|
+
console.warn("Failed to create chat for voice conversation:", error);
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
// Set up enhanced callbacks that integrate with our session tracking
|
|
1184
|
+
const enhancedCallbacks = {
|
|
1185
|
+
...options.callbacks,
|
|
1186
|
+
onConnect: () => {
|
|
1187
|
+
options.callbacks?.onConnect?.();
|
|
1188
|
+
options.callbacks?.onSessionStart?.(sessionId);
|
|
1189
|
+
},
|
|
1190
|
+
onDisconnect: (details) => {
|
|
1191
|
+
options.callbacks?.onDisconnect?.(details);
|
|
1192
|
+
this.endVoiceSession(sessionId, details?.reason);
|
|
1193
|
+
},
|
|
1194
|
+
onMessage: (message) => {
|
|
1195
|
+
options.callbacks?.onMessage?.(message);
|
|
1196
|
+
this.handleVoiceMessage(sessionId, message);
|
|
1197
|
+
},
|
|
1198
|
+
onError: (error) => {
|
|
1199
|
+
options.callbacks?.onError?.(error);
|
|
1200
|
+
this.endVoiceSession(sessionId, error.message);
|
|
1201
|
+
},
|
|
1202
|
+
};
|
|
1203
|
+
// Store enhanced callbacks for this session
|
|
1204
|
+
session.metadata = {
|
|
1205
|
+
...session.metadata,
|
|
1206
|
+
enhancedCallbacks,
|
|
1207
|
+
};
|
|
1208
|
+
return sessionId;
|
|
1209
|
+
}
|
|
1210
|
+
/**
|
|
1211
|
+
* End a voice conversation session
|
|
1212
|
+
*/
|
|
1213
|
+
async endVoiceSession(sessionId, reason) {
|
|
1214
|
+
const session = this.activeSessions.get(sessionId);
|
|
1215
|
+
if (!session) {
|
|
1216
|
+
throw new Error(`Voice session ${sessionId} not found`);
|
|
1217
|
+
}
|
|
1218
|
+
session.endTime = Date.now();
|
|
1219
|
+
session.metadata = {
|
|
1220
|
+
...session.metadata,
|
|
1221
|
+
totalDuration: session.endTime - session.startTime,
|
|
1222
|
+
};
|
|
1223
|
+
// Save conversation to chat if configured
|
|
1224
|
+
if (session.chatId && this.chatSDK && session.messages.length > 0) {
|
|
1225
|
+
try {
|
|
1226
|
+
await this.saveVoiceConversationToChat(session);
|
|
1227
|
+
}
|
|
1228
|
+
catch (error) {
|
|
1229
|
+
console.warn("Failed to save voice conversation to chat:", error);
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
this.activeSessions.delete(sessionId);
|
|
1233
|
+
}
|
|
1234
|
+
/**
|
|
1235
|
+
* Get current voice conversation state
|
|
1236
|
+
*/
|
|
1237
|
+
getVoiceState(sessionId) {
|
|
1238
|
+
const session = this.activeSessions.get(sessionId);
|
|
1239
|
+
if (!session)
|
|
1240
|
+
return null;
|
|
1241
|
+
// This would integrate with the actual ElevenLabs hook state
|
|
1242
|
+
// For now, return a basic state structure
|
|
1243
|
+
return {
|
|
1244
|
+
sessionId,
|
|
1245
|
+
isActive: true,
|
|
1246
|
+
connectionStatus: "connected",
|
|
1247
|
+
volume: 50,
|
|
1248
|
+
micMuted: false,
|
|
1249
|
+
isSpeaking: false,
|
|
1250
|
+
};
|
|
1251
|
+
}
|
|
1252
|
+
/**
|
|
1253
|
+
* Update voice settings for a session
|
|
1254
|
+
*/
|
|
1255
|
+
async updateVoiceSettings(sessionId, settings) {
|
|
1256
|
+
const session = this.activeSessions.get(sessionId);
|
|
1257
|
+
if (!session) {
|
|
1258
|
+
throw new Error(`Voice session ${sessionId} not found`);
|
|
1259
|
+
}
|
|
1260
|
+
session.metadata = {
|
|
1261
|
+
...session.metadata,
|
|
1262
|
+
voiceSettings: { ...session.metadata?.voiceSettings, ...settings },
|
|
1263
|
+
};
|
|
1264
|
+
// Here you would call the actual ElevenLabs API to update settings
|
|
1265
|
+
// This is a placeholder for that functionality
|
|
1266
|
+
}
|
|
1267
|
+
/**
|
|
1268
|
+
* Mute/unmute microphone for a session
|
|
1269
|
+
*/
|
|
1270
|
+
async setMicrophoneMuted(sessionId, muted) {
|
|
1271
|
+
const session = this.activeSessions.get(sessionId);
|
|
1272
|
+
if (!session) {
|
|
1273
|
+
throw new Error(`Voice session ${sessionId} not found`);
|
|
1274
|
+
}
|
|
1275
|
+
// This would integrate with the actual ElevenLabs controls
|
|
1276
|
+
// For now, just track the state
|
|
1277
|
+
}
|
|
1278
|
+
/**
|
|
1279
|
+
* Set volume for a session
|
|
1280
|
+
*/
|
|
1281
|
+
async setVolume(sessionId, volume) {
|
|
1282
|
+
if (volume < 0 || volume > 100) {
|
|
1283
|
+
throw new Error("Volume must be between 0 and 100");
|
|
1284
|
+
}
|
|
1285
|
+
const session = this.activeSessions.get(sessionId);
|
|
1286
|
+
if (!session) {
|
|
1287
|
+
throw new Error(`Voice session ${sessionId} not found`);
|
|
1288
|
+
}
|
|
1289
|
+
// This would integrate with the actual ElevenLabs controls
|
|
1290
|
+
}
|
|
1291
|
+
/**
|
|
1292
|
+
* Get audio frequency data for visualization
|
|
1293
|
+
*/
|
|
1294
|
+
getAudioFrequencyData(sessionId) {
|
|
1295
|
+
const session = this.activeSessions.get(sessionId);
|
|
1296
|
+
if (!session)
|
|
1297
|
+
return null;
|
|
1298
|
+
// This would integrate with the actual ElevenLabs audio analysis
|
|
1299
|
+
// Return empty data for now
|
|
1300
|
+
return {};
|
|
1301
|
+
}
|
|
1302
|
+
/**
|
|
1303
|
+
* Send contextual information to enhance voice conversation
|
|
1304
|
+
*/
|
|
1305
|
+
async sendContextualUpdate(sessionId, context) {
|
|
1306
|
+
const session = this.activeSessions.get(sessionId);
|
|
1307
|
+
if (!session) {
|
|
1308
|
+
throw new Error(`Voice session ${sessionId} not found`);
|
|
1309
|
+
}
|
|
1310
|
+
// This would send context to the ElevenLabs agent
|
|
1311
|
+
// For now, just add it as a system message
|
|
1312
|
+
const contextMessage = {
|
|
1313
|
+
id: this.generateMessageId(),
|
|
1314
|
+
type: "system",
|
|
1315
|
+
text: `Context update: ${context}`,
|
|
1316
|
+
timestamp: Date.now(),
|
|
1317
|
+
};
|
|
1318
|
+
session.messages.push(contextMessage);
|
|
1319
|
+
}
|
|
1320
|
+
/**
|
|
1321
|
+
* Get conversation history for a session
|
|
1322
|
+
*/
|
|
1323
|
+
getConversationHistory(sessionId) {
|
|
1324
|
+
const session = this.activeSessions.get(sessionId);
|
|
1325
|
+
return session?.messages || [];
|
|
1326
|
+
}
|
|
1327
|
+
/**
|
|
1328
|
+
* Get all active voice sessions
|
|
1329
|
+
*/
|
|
1330
|
+
getActiveSessions() {
|
|
1331
|
+
return Array.from(this.activeSessions.values());
|
|
1332
|
+
}
|
|
1333
|
+
/**
|
|
1334
|
+
* Automatically save voice message to database via API
|
|
1335
|
+
* This is called internally when voice messages are processed
|
|
1336
|
+
*/
|
|
1337
|
+
async saveVoiceMessageToAPI(sessionId, userMessage, aiResponse, agentInfo) {
|
|
1338
|
+
const session = this.activeSessions.get(sessionId);
|
|
1339
|
+
if (!session || !session.chatId) {
|
|
1340
|
+
console.warn("Cannot save voice message: no session or chat ID");
|
|
1341
|
+
return;
|
|
1342
|
+
}
|
|
1343
|
+
try {
|
|
1344
|
+
// Get user information from session if available
|
|
1345
|
+
let userName = "Voice User";
|
|
1346
|
+
let userId = "voice-user";
|
|
1347
|
+
if (session.metadata?.userInfo) {
|
|
1348
|
+
userName = session.metadata.userInfo.name;
|
|
1349
|
+
userId = session.metadata.userInfo.id;
|
|
1350
|
+
}
|
|
1351
|
+
// Use the existing API endpoint to save voice messages
|
|
1352
|
+
await this.post("/elevenlabs/voice-message/save", {
|
|
1353
|
+
project_id: this.config.projectId,
|
|
1354
|
+
chat_id: session.chatId,
|
|
1355
|
+
message: userMessage,
|
|
1356
|
+
response: aiResponse,
|
|
1357
|
+
user_name: userName,
|
|
1358
|
+
user_id: userId,
|
|
1359
|
+
message_type: "complete",
|
|
1360
|
+
agent_id: agentInfo?.id || session.metadata?.agentId,
|
|
1361
|
+
agent_name: agentInfo?.name,
|
|
1362
|
+
conversation_id: sessionId,
|
|
1363
|
+
});
|
|
1364
|
+
console.log("Voice message automatically saved to database");
|
|
1365
|
+
}
|
|
1366
|
+
catch (error) {
|
|
1367
|
+
console.error("Failed to auto-save voice message:", error);
|
|
1368
|
+
// Don't throw - this shouldn't break the voice conversation
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
/**
|
|
1372
|
+
* Private helper methods
|
|
1373
|
+
*/
|
|
1374
|
+
generateSessionId() {
|
|
1375
|
+
return `voice_session_${Date.now()}_${Math.random()
|
|
1376
|
+
.toString(36)
|
|
1377
|
+
.substr(2, 9)}`;
|
|
1378
|
+
}
|
|
1379
|
+
generateMessageId() {
|
|
1380
|
+
return `voice_msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
1381
|
+
}
|
|
1382
|
+
handleVoiceMessage(sessionId, message) {
|
|
1383
|
+
const session = this.activeSessions.get(sessionId);
|
|
1384
|
+
if (!session)
|
|
1385
|
+
return;
|
|
1386
|
+
// Convert ElevenLabs message to our format
|
|
1387
|
+
const voiceMessage = {
|
|
1388
|
+
id: this.generateMessageId(),
|
|
1389
|
+
type: message.role === "user" ? "user_speech" : "ai_speech",
|
|
1390
|
+
text: message.content || message.text || "",
|
|
1391
|
+
timestamp: Date.now(),
|
|
1392
|
+
audioUrl: message.audioUrl,
|
|
1393
|
+
};
|
|
1394
|
+
session.messages.push(voiceMessage);
|
|
1395
|
+
// Auto-save voice messages when we have both user and AI messages
|
|
1396
|
+
this.autoSaveVoiceMessages(sessionId);
|
|
1397
|
+
// Update session metadata
|
|
1398
|
+
if (session.metadata) {
|
|
1399
|
+
const messageCount = session.messages.length;
|
|
1400
|
+
const totalTime = Date.now() - session.startTime;
|
|
1401
|
+
session.metadata.averageResponseTime = totalTime / messageCount;
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
/**
|
|
1405
|
+
* Auto-save voice messages when we have complete conversation pairs
|
|
1406
|
+
*/
|
|
1407
|
+
async autoSaveVoiceMessages(sessionId) {
|
|
1408
|
+
const session = this.activeSessions.get(sessionId);
|
|
1409
|
+
if (!session)
|
|
1410
|
+
return;
|
|
1411
|
+
// Look for unsaved message pairs (user + AI response)
|
|
1412
|
+
const messages = session.messages;
|
|
1413
|
+
let lastUserMessage = "";
|
|
1414
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
1415
|
+
const message = messages[i];
|
|
1416
|
+
if (message.type === "ai_speech" && lastUserMessage) {
|
|
1417
|
+
// We have a complete pair - save it
|
|
1418
|
+
try {
|
|
1419
|
+
await this.saveVoiceMessageToAPI(sessionId, lastUserMessage, message.text, {
|
|
1420
|
+
id: session.metadata?.agentId,
|
|
1421
|
+
name: session.metadata?.agentName,
|
|
1422
|
+
});
|
|
1423
|
+
// Mark these messages as saved to avoid duplicate saves
|
|
1424
|
+
message.saved = true;
|
|
1425
|
+
break;
|
|
1426
|
+
}
|
|
1427
|
+
catch (error) {
|
|
1428
|
+
console.error("Failed to auto-save voice message pair:", error);
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
else if (message.type === "user_speech" && !message.saved) {
|
|
1432
|
+
lastUserMessage = message.text;
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
async saveVoiceConversationToChat(session) {
|
|
1437
|
+
if (!this.chatSDK || !session.chatId)
|
|
1438
|
+
return;
|
|
1439
|
+
// Convert voice messages to chat format
|
|
1440
|
+
const conversationSummary = session.messages
|
|
1441
|
+
.filter((msg) => msg.type !== "system")
|
|
1442
|
+
.map((msg) => `${msg.type === "user_speech" ? "User" : "Assistant"}: ${msg.text}`)
|
|
1443
|
+
.join("\n");
|
|
1444
|
+
const duration = session.metadata?.totalDuration
|
|
1445
|
+
? Math.round(session.metadata.totalDuration / 1000 / 60)
|
|
1446
|
+
: 0;
|
|
1447
|
+
const summaryMessage = `Voice Conversation Summary (${duration} minutes):\n\n${conversationSummary}`;
|
|
1448
|
+
try {
|
|
1449
|
+
await this.chatSDK.sendMessage(summaryMessage, {
|
|
1450
|
+
chatId: session.chatId,
|
|
1451
|
+
metadata: {
|
|
1452
|
+
type: "voice_conversation_summary",
|
|
1453
|
+
sessionId: session.id,
|
|
1454
|
+
duration: session.metadata?.totalDuration,
|
|
1455
|
+
messageCount: session.messages.length,
|
|
1456
|
+
},
|
|
1457
|
+
});
|
|
1458
|
+
}
|
|
1459
|
+
catch (error) {
|
|
1460
|
+
console.error("Failed to save voice conversation to chat:", error);
|
|
1461
|
+
throw error;
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1466
|
+
/**
|
|
1467
|
+
* Enhanced useVoiceConversation hook with our SDK's chat integration and session management
|
|
1468
|
+
*/
|
|
1469
|
+
function useVoiceConversation(options = {}) {
|
|
1470
|
+
const { sdkConfig, sessionConfig, callbacks, ...elevenLabsOptions } = options;
|
|
1471
|
+
// State management
|
|
1472
|
+
const [voiceSDK, setVoiceSDK] = react.useState(null);
|
|
1473
|
+
const [currentSessionId, setCurrentSessionId] = react.useState(null);
|
|
1474
|
+
const [conversationState, setConversationState] = react.useState({
|
|
1475
|
+
isActive: false,
|
|
1476
|
+
connectionStatus: "disconnected",
|
|
1477
|
+
volume: 50,
|
|
1478
|
+
micMuted: false,
|
|
1479
|
+
isSpeaking: false,
|
|
1480
|
+
});
|
|
1481
|
+
// Refs for managing callbacks and cleanup
|
|
1482
|
+
const callbacksRef = react.useRef(callbacks);
|
|
1483
|
+
const sessionConfigRef = react.useRef(sessionConfig);
|
|
1484
|
+
// Update refs when options change
|
|
1485
|
+
react.useEffect(() => {
|
|
1486
|
+
callbacksRef.current = callbacks;
|
|
1487
|
+
sessionConfigRef.current = sessionConfig;
|
|
1488
|
+
}, [callbacks, sessionConfig]);
|
|
1489
|
+
// Initialize VoiceSDK lazily when needed
|
|
1490
|
+
const initializeVoiceSDK = react.useCallback(async (config) => {
|
|
1491
|
+
if (voiceSDK)
|
|
1492
|
+
return voiceSDK;
|
|
1493
|
+
try {
|
|
1494
|
+
const sdk = new VoiceSDK(config);
|
|
1495
|
+
setVoiceSDK(sdk);
|
|
1496
|
+
return sdk;
|
|
1497
|
+
}
|
|
1498
|
+
catch (error) {
|
|
1499
|
+
console.error("Failed to initialize VoiceSDK:", error);
|
|
1500
|
+
throw error;
|
|
1501
|
+
}
|
|
1502
|
+
}, [voiceSDK]);
|
|
1503
|
+
// Enhanced callbacks that integrate with our SDK
|
|
1504
|
+
const enhancedCallbacks = {
|
|
1505
|
+
...elevenLabsOptions,
|
|
1506
|
+
onConnect: react.useCallback(() => {
|
|
1507
|
+
setConversationState((prev) => ({
|
|
1508
|
+
...prev,
|
|
1509
|
+
connectionStatus: "connected",
|
|
1510
|
+
isActive: true,
|
|
1511
|
+
}));
|
|
1512
|
+
elevenLabsOptions.onConnect?.();
|
|
1513
|
+
callbacksRef.current?.onConnect?.();
|
|
1514
|
+
}, [elevenLabsOptions.onConnect]),
|
|
1515
|
+
onDisconnect: react.useCallback((details) => {
|
|
1516
|
+
setConversationState((prev) => ({
|
|
1517
|
+
...prev,
|
|
1518
|
+
connectionStatus: "disconnected",
|
|
1519
|
+
isActive: false,
|
|
1520
|
+
}));
|
|
1521
|
+
elevenLabsOptions.onDisconnect?.(details);
|
|
1522
|
+
callbacksRef.current?.onDisconnect?.(details);
|
|
1523
|
+
// End SDK session if active
|
|
1524
|
+
if (currentSessionId && voiceSDK) {
|
|
1525
|
+
voiceSDK.endVoiceSession(currentSessionId, details?.reason);
|
|
1526
|
+
setCurrentSessionId(null);
|
|
1527
|
+
}
|
|
1528
|
+
}, [currentSessionId, voiceSDK, elevenLabsOptions.onDisconnect]),
|
|
1529
|
+
onMessage: react.useCallback((message) => {
|
|
1530
|
+
elevenLabsOptions.onMessage?.(message);
|
|
1531
|
+
callbacksRef.current?.onMessage?.(message);
|
|
1532
|
+
// Handle transcription if available
|
|
1533
|
+
if (message.type === "user_speech" && message.text) {
|
|
1534
|
+
callbacksRef.current?.onTranscription?.(message.text, true);
|
|
1535
|
+
}
|
|
1536
|
+
}, [elevenLabsOptions.onMessage]),
|
|
1537
|
+
onError: react.useCallback((error) => {
|
|
1538
|
+
setConversationState((prev) => ({
|
|
1539
|
+
...prev,
|
|
1540
|
+
connectionStatus: "error",
|
|
1541
|
+
isActive: false,
|
|
1542
|
+
}));
|
|
1543
|
+
elevenLabsOptions.onError?.(error);
|
|
1544
|
+
callbacksRef.current?.onError?.(error);
|
|
1545
|
+
}, [elevenLabsOptions.onError]),
|
|
1546
|
+
onAudio: react.useCallback((audio) => {
|
|
1547
|
+
elevenLabsOptions.onAudio?.(audio);
|
|
1548
|
+
callbacksRef.current?.onSpeechGenerated?.(audio.url);
|
|
1549
|
+
}, [elevenLabsOptions.onAudio]),
|
|
1550
|
+
};
|
|
1551
|
+
// Initialize hook with enhanced callbacks
|
|
1552
|
+
const elevenLabsHook = react$1.useConversation(enhancedCallbacks);
|
|
1553
|
+
// Enhanced start session function
|
|
1554
|
+
const startSession = react.useCallback(async (config) => {
|
|
1555
|
+
const finalConfig = { ...sessionConfigRef.current, ...config };
|
|
1556
|
+
try {
|
|
1557
|
+
// Initialize SDK if needed and config is provided
|
|
1558
|
+
let sdk = voiceSDK;
|
|
1559
|
+
if (!sdk && finalConfig.sdkConfig) {
|
|
1560
|
+
sdk = await initializeVoiceSDK(finalConfig.sdkConfig);
|
|
1561
|
+
}
|
|
1562
|
+
if (!sdk) {
|
|
1563
|
+
throw new Error("VoiceSDK not initialized. Please provide sdkConfig.");
|
|
1564
|
+
}
|
|
1565
|
+
// Start SDK session first
|
|
1566
|
+
const sessionId = await sdk.startVoiceConversation({
|
|
1567
|
+
...finalConfig,
|
|
1568
|
+
callbacks: callbacksRef.current,
|
|
1569
|
+
});
|
|
1570
|
+
setCurrentSessionId(sessionId);
|
|
1571
|
+
// Then start ElevenLabs session
|
|
1572
|
+
const elevenLabsSessionId = await elevenLabsHook.startSession({
|
|
1573
|
+
agentId: finalConfig.agentId,
|
|
1574
|
+
...finalConfig,
|
|
1575
|
+
});
|
|
1576
|
+
return sessionId; // Return our SDK session ID
|
|
1577
|
+
}
|
|
1578
|
+
catch (error) {
|
|
1579
|
+
console.error("Failed to start voice session:", error);
|
|
1580
|
+
throw error;
|
|
1581
|
+
}
|
|
1582
|
+
}, [voiceSDK, elevenLabsHook.startSession, initializeVoiceSDK]);
|
|
1583
|
+
// Enhanced end session function
|
|
1584
|
+
const endSession = react.useCallback(async () => {
|
|
1585
|
+
try {
|
|
1586
|
+
// End ElevenLabs session first
|
|
1587
|
+
await elevenLabsHook.endSession();
|
|
1588
|
+
// Then end SDK session
|
|
1589
|
+
if (currentSessionId && voiceSDK) {
|
|
1590
|
+
await voiceSDK.endVoiceSession(currentSessionId);
|
|
1591
|
+
setCurrentSessionId(null);
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
catch (error) {
|
|
1595
|
+
console.error("Failed to end voice session:", error);
|
|
1596
|
+
throw error;
|
|
1597
|
+
}
|
|
1598
|
+
}, [currentSessionId, voiceSDK, elevenLabsHook.endSession]);
|
|
1599
|
+
// Volume control with SDK integration
|
|
1600
|
+
const setVolume = react.useCallback(({ volume }) => {
|
|
1601
|
+
elevenLabsHook.setVolume({ volume });
|
|
1602
|
+
setConversationState((prev) => ({ ...prev, volume }));
|
|
1603
|
+
if (currentSessionId && voiceSDK) {
|
|
1604
|
+
voiceSDK.setVolume(currentSessionId, volume);
|
|
1605
|
+
}
|
|
1606
|
+
}, [currentSessionId, voiceSDK, elevenLabsHook.setVolume]);
|
|
1607
|
+
// Audio data with SDK integration
|
|
1608
|
+
const getInputByteFrequencyData = react.useCallback(() => {
|
|
1609
|
+
const data = elevenLabsHook.getInputByteFrequencyData();
|
|
1610
|
+
// Update conversation state with audio data
|
|
1611
|
+
if (data && currentSessionId) {
|
|
1612
|
+
setConversationState((prev) => ({
|
|
1613
|
+
...prev,
|
|
1614
|
+
audioData: {
|
|
1615
|
+
...prev.audioData,
|
|
1616
|
+
inputFrequencyData: data,
|
|
1617
|
+
},
|
|
1618
|
+
}));
|
|
1619
|
+
}
|
|
1620
|
+
return data;
|
|
1621
|
+
}, [currentSessionId, elevenLabsHook.getInputByteFrequencyData]);
|
|
1622
|
+
const getOutputByteFrequencyData = react.useCallback(() => {
|
|
1623
|
+
const data = elevenLabsHook.getOutputByteFrequencyData();
|
|
1624
|
+
if (data && currentSessionId) {
|
|
1625
|
+
setConversationState((prev) => ({
|
|
1626
|
+
...prev,
|
|
1627
|
+
audioData: {
|
|
1628
|
+
...prev.audioData,
|
|
1629
|
+
outputFrequencyData: data,
|
|
1630
|
+
},
|
|
1631
|
+
}));
|
|
1632
|
+
}
|
|
1633
|
+
return data;
|
|
1634
|
+
}, [currentSessionId, elevenLabsHook.getOutputByteFrequencyData]);
|
|
1635
|
+
// Volume monitoring
|
|
1636
|
+
const getInputVolume = react.useCallback(() => {
|
|
1637
|
+
const volume = elevenLabsHook.getInputVolume();
|
|
1638
|
+
if (currentSessionId) {
|
|
1639
|
+
setConversationState((prev) => ({
|
|
1640
|
+
...prev,
|
|
1641
|
+
audioData: {
|
|
1642
|
+
...prev.audioData,
|
|
1643
|
+
inputVolume: volume,
|
|
1644
|
+
},
|
|
1645
|
+
}));
|
|
1646
|
+
}
|
|
1647
|
+
return volume;
|
|
1648
|
+
}, [currentSessionId, elevenLabsHook.getInputVolume]);
|
|
1649
|
+
const getOutputVolume = react.useCallback(() => {
|
|
1650
|
+
const volume = elevenLabsHook.getOutputVolume();
|
|
1651
|
+
if (currentSessionId) {
|
|
1652
|
+
setConversationState((prev) => ({
|
|
1653
|
+
...prev,
|
|
1654
|
+
audioData: {
|
|
1655
|
+
...prev.audioData,
|
|
1656
|
+
outputVolume: volume,
|
|
1657
|
+
},
|
|
1658
|
+
}));
|
|
1659
|
+
}
|
|
1660
|
+
return volume;
|
|
1661
|
+
}, [currentSessionId, elevenLabsHook.getOutputVolume]);
|
|
1662
|
+
// Context and message sending with SDK integration
|
|
1663
|
+
const sendContextualUpdate = react.useCallback((text) => {
|
|
1664
|
+
elevenLabsHook.sendContextualUpdate(text);
|
|
1665
|
+
if (currentSessionId && voiceSDK) {
|
|
1666
|
+
voiceSDK.sendContextualUpdate(currentSessionId, text);
|
|
1667
|
+
}
|
|
1668
|
+
}, [currentSessionId, voiceSDK, elevenLabsHook.sendContextualUpdate]);
|
|
1669
|
+
// SDK-specific methods
|
|
1670
|
+
const getConversationHistory = react.useCallback(() => {
|
|
1671
|
+
if (currentSessionId && voiceSDK) {
|
|
1672
|
+
return voiceSDK.getConversationHistory(currentSessionId);
|
|
1673
|
+
}
|
|
1674
|
+
return [];
|
|
1675
|
+
}, [currentSessionId, voiceSDK]);
|
|
1676
|
+
const getVoiceState = react.useCallback(() => {
|
|
1677
|
+
if (currentSessionId && voiceSDK) {
|
|
1678
|
+
return voiceSDK.getVoiceState(currentSessionId);
|
|
1679
|
+
}
|
|
1680
|
+
return conversationState;
|
|
1681
|
+
}, [currentSessionId, voiceSDK, conversationState]);
|
|
1682
|
+
// Update isSpeaking state
|
|
1683
|
+
react.useEffect(() => {
|
|
1684
|
+
setConversationState((prev) => ({
|
|
1685
|
+
...prev,
|
|
1686
|
+
isSpeaking: elevenLabsHook.isSpeaking,
|
|
1687
|
+
micMuted: elevenLabsHook.micMuted,
|
|
1688
|
+
}));
|
|
1689
|
+
}, [elevenLabsHook.isSpeaking, elevenLabsHook.micMuted]);
|
|
1690
|
+
// Cleanup active sessions on unmount
|
|
1691
|
+
react.useEffect(() => {
|
|
1692
|
+
return () => {
|
|
1693
|
+
if (voiceSDK) {
|
|
1694
|
+
voiceSDK.getActiveSessions().forEach((session) => {
|
|
1695
|
+
voiceSDK.endVoiceSession(session.id);
|
|
1696
|
+
});
|
|
1697
|
+
}
|
|
1698
|
+
};
|
|
1699
|
+
}, [voiceSDK]);
|
|
1700
|
+
return {
|
|
1701
|
+
// Core session management
|
|
1702
|
+
startSession,
|
|
1703
|
+
endSession,
|
|
1704
|
+
// Audio controls
|
|
1705
|
+
setVolume,
|
|
1706
|
+
getInputByteFrequencyData,
|
|
1707
|
+
getOutputByteFrequencyData,
|
|
1708
|
+
getInputVolume,
|
|
1709
|
+
getOutputVolume,
|
|
1710
|
+
// Communication
|
|
1711
|
+
sendContextualUpdate,
|
|
1712
|
+
sendUserMessage: elevenLabsHook.sendUserMessage,
|
|
1713
|
+
sendUserActivity: elevenLabsHook.sendUserActivity,
|
|
1714
|
+
sendMCPToolApprovalResult: elevenLabsHook.sendMCPToolApprovalResult,
|
|
1715
|
+
// Feedback
|
|
1716
|
+
sendFeedback: elevenLabsHook.sendFeedback,
|
|
1717
|
+
canSendFeedback: elevenLabsHook.canSendFeedback,
|
|
1718
|
+
// State
|
|
1719
|
+
status: elevenLabsHook.status,
|
|
1720
|
+
micMuted: elevenLabsHook.micMuted,
|
|
1721
|
+
isSpeaking: elevenLabsHook.isSpeaking,
|
|
1722
|
+
getId: elevenLabsHook.getId,
|
|
1723
|
+
// SDK-specific features
|
|
1724
|
+
currentSessionId,
|
|
1725
|
+
conversationState,
|
|
1726
|
+
getConversationHistory,
|
|
1727
|
+
getVoiceState,
|
|
1728
|
+
voiceSDK,
|
|
1729
|
+
};
|
|
1730
|
+
}
|
|
1731
|
+
|
|
1732
|
+
Object.defineProperty(exports, 'postOverallFeedback', {
|
|
1733
|
+
enumerable: true,
|
|
1734
|
+
get: function () { return client.postOverallFeedback; }
|
|
1735
|
+
});
|
|
1736
|
+
exports.useVoiceConversation = useVoiceConversation;
|
|
1737
|
+
//# sourceMappingURL=react.cjs.map
|