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