@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
@@ -2,10 +2,35 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var react = require('react');
6
- var react$1 = require('@elevenlabs/react');
7
- var client = require('@elevenlabs/client');
8
-
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
+ }
9
34
  /**
10
35
  * Generic HTTP client for AI Content Creator SDKs
11
36
  */
@@ -14,39 +39,47 @@ class BaseClient {
14
39
  this.config = config;
15
40
  // Wrap fetch in an arrow function to preserve the correct 'this' context
16
41
  // This prevents "Illegal invocation" errors when fetch is called
17
- this.customFetch = config.customFetch || ((...args) => fetch(...args));
42
+ this.customFetch =
43
+ config.customFetch ||
44
+ ((...args) => fetch(...args));
18
45
  // Validate authentication configuration
19
- const hasAccessToken = config.accessToken && config.accessToken.trim() !== '';
20
- const hasApiKeys = config.apiKey && config.apiSecret &&
21
- config.apiKey.trim() !== '' && config.apiSecret.trim() !== '';
46
+ const hasAccessToken = config.accessToken && config.accessToken.trim() !== "";
47
+ const hasApiKeys = config.apiKey &&
48
+ config.apiSecret &&
49
+ config.apiKey.trim() !== "" &&
50
+ config.apiSecret.trim() !== "";
22
51
  if (!hasAccessToken && !hasApiKeys) {
23
- throw new Error('Authentication required: Provide either accessToken (for web app) or both apiKey and apiSecret (for external SDK)');
52
+ throw new Error("Authentication required: Provide either accessToken (for web app) or both apiKey and apiSecret (for external SDK)");
24
53
  }
25
54
  if (hasAccessToken && hasApiKeys) {
26
- console.warn('Both accessToken and API keys provided. Using accessToken for authentication.');
55
+ console.warn("Both accessToken and API keys provided. Using accessToken for authentication.");
27
56
  }
28
57
  // Support both API key authentication and access token authentication
29
58
  if (hasAccessToken) {
30
59
  // Web app authentication using access token
31
60
  this.headers = {
32
- 'Content-Type': 'application/json',
33
- 'access-token': config.accessToken,
61
+ "Content-Type": "application/json",
62
+ "access-token": config.accessToken,
63
+ "X-Project-Id": config.projectId,
34
64
  };
35
65
  }
36
66
  else {
37
67
  // External SDK authentication using API keys
38
68
  this.headers = {
39
- 'Content-Type': 'application/json',
40
- 'X-API-KEY': config.apiKey,
41
- 'X-API-SECRET': config.apiSecret,
69
+ "Content-Type": "application/json",
70
+ "X-API-KEY": config.apiKey,
71
+ "X-API-SECRET": config.apiSecret,
72
+ "X-Project-Id": config.projectId,
42
73
  };
43
74
  }
44
75
  }
45
76
  /**
46
77
  * Make an HTTP request with proper error handling
47
78
  */
48
- async makeRequest(endpoint, method = 'GET', body, customHeaders) {
49
- const url = endpoint.startsWith('http') ? endpoint : `${this.config.baseUrl}${endpoint}`;
79
+ async makeRequest(endpoint, method = "GET", body, customHeaders) {
80
+ const url = endpoint.startsWith("http")
81
+ ? endpoint
82
+ : `${this.config.baseUrl}${endpoint}`;
50
83
  const requestOptions = {
51
84
  method,
52
85
  headers: {
@@ -57,12 +90,13 @@ class BaseClient {
57
90
  if (body) {
58
91
  if (body instanceof FormData) {
59
92
  // Remove Content-Type header for FormData - browser will set it automatically
60
- const { 'Content-Type': _, ...headersWithoutContentType } = requestOptions.headers;
93
+ const { "Content-Type": _, ...headersWithoutContentType } = requestOptions.headers;
61
94
  requestOptions.headers = headersWithoutContentType;
62
95
  requestOptions.body = body;
63
96
  }
64
97
  else {
65
- requestOptions.body = typeof body === 'string' ? body : JSON.stringify(body);
98
+ requestOptions.body =
99
+ typeof body === "string" ? body : JSON.stringify(body);
66
100
  }
67
101
  }
68
102
  const response = await this.customFetch(url, requestOptions);
@@ -70,8 +104,8 @@ class BaseClient {
70
104
  await this.handleErrorResponse(response);
71
105
  }
72
106
  // Handle empty responses
73
- const contentType = response.headers.get('content-type');
74
- if (contentType && contentType.includes('application/json')) {
107
+ const contentType = response.headers.get("content-type");
108
+ if (contentType && contentType.includes("application/json")) {
75
109
  return response.json();
76
110
  }
77
111
  return response.text();
@@ -80,35 +114,34 @@ class BaseClient {
80
114
  * Make a GET request
81
115
  */
82
116
  async get(endpoint, headers) {
83
- return this.makeRequest(endpoint, 'GET', null, headers);
117
+ return this.makeRequest(endpoint, "GET", null, headers);
84
118
  }
85
119
  /**
86
120
  * Make a POST request
87
121
  */
88
122
  async post(endpoint, body, headers) {
89
- return this.makeRequest(endpoint, 'POST', body, headers);
123
+ return this.makeRequest(endpoint, "POST", body, headers);
90
124
  }
91
125
  /**
92
126
  * Make a PUT request
93
127
  */
94
128
  async put(endpoint, body, headers) {
95
- return this.makeRequest(endpoint, 'PUT', body, headers);
129
+ return this.makeRequest(endpoint, "PUT", body, headers);
96
130
  }
97
131
  /**
98
132
  * Make a DELETE request
99
133
  */
100
134
  async delete(endpoint, body, headers) {
101
- return this.makeRequest(endpoint, 'DELETE', body, headers);
135
+ return this.makeRequest(endpoint, "DELETE", body, headers);
102
136
  }
103
137
  /**
104
138
  * Handle error responses from the API
105
139
  */
106
140
  async handleErrorResponse(response) {
107
- // Check for session expiration and dispatch custom event
108
- if ((response.status === 401 || response.status === 403) && typeof window !== 'undefined') {
109
- // Dispatch custom event immediately for session expiration
110
- window.dispatchEvent(new CustomEvent('sessionExpired', {
111
- detail: { status: response.status, url: response.url }
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 },
112
145
  }));
113
146
  }
114
147
  const error = await this.createErrorFromResponse(response);
@@ -122,7 +155,7 @@ class BaseClient {
122
155
  let errorDetail;
123
156
  try {
124
157
  const errorData = await response.json();
125
- errorMessage = errorData?.message || errorData?.detail || errorMessage;
158
+ errorMessage = extractErrorMessage(errorData, errorMessage);
126
159
  errorDetail = errorData?.detail;
127
160
  }
128
161
  catch (e) {
@@ -137,15 +170,259 @@ class BaseClient {
137
170
  * Update the access token at runtime. Useful when the application's session token is refreshed.
138
171
  */
139
172
  setAccessToken(newAccessToken) {
140
- if (!newAccessToken || newAccessToken.trim() === '') {
173
+ if (!newAccessToken || newAccessToken.trim() === "") {
141
174
  return;
142
175
  }
143
176
  this.config.accessToken = newAccessToken;
144
177
  // Ensure header reflects the latest token
145
178
  this.headers = {
146
179
  ...this.headers,
147
- 'access-token': newAccessToken,
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);
148
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
+ }
149
426
  }
150
427
  }
151
428
 
@@ -164,6 +441,14 @@ class ChatSDK extends BaseClient {
164
441
  this.messageInitObject = null;
165
442
  this.actionsMap = new Map();
166
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;
167
452
  }
168
453
  /**
169
454
  * Create a new chat in the project
@@ -191,6 +476,46 @@ class ChatSDK extends BaseClient {
191
476
  });
192
477
  return await this.get(`project/${this.config.projectId}/chat?${params}`);
193
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
+ }
194
519
  /**
195
520
  * Get a specific chat with its message history
196
521
  * @param chatId The ID of the chat to retrieve
@@ -223,6 +548,19 @@ class ChatSDK extends BaseClient {
223
548
  title: newName,
224
549
  });
225
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
+ }
226
564
  /**
227
565
  * Send a message and get the response
228
566
  * @param message The message text to send
@@ -241,7 +579,9 @@ class ChatSDK extends BaseClient {
241
579
  agent_type: options.agentType || "chat_agent",
242
580
  agent_id: options.agentId,
243
581
  document_keys: documentKeysString,
244
- model_name: options.modelName || "gpt-4o-mini",
582
+ // No fallback model: the agent resolves its own, and inventing one here
583
+ // only mislabelled the audit record.
584
+ model_name: options.modelName,
245
585
  use_knowledgebase: options.useKnowledgebase ?? true,
246
586
  is_test: options.isTest ?? false,
247
587
  google_search: options.googleSearch ?? false,
@@ -280,66 +620,139 @@ class ChatSDK extends BaseClient {
280
620
  }, {});
281
621
  formData.append("multipart_document_keys", JSON.stringify(_documentKeys));
282
622
  }
283
- if (options.activeKnowledgeBases &&
284
- options.activeKnowledgeBases.length > 0) {
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) {
285
631
  const activeKbJson = JSON.stringify(options.activeKnowledgeBases);
286
632
  formData.append("active_knowledgebases", activeKbJson);
287
633
  }
288
- if (options.images) {
634
+ if (options.images && options.images.length > 0) {
289
635
  options.images.forEach((image) => {
290
- formData.append("images", 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");
291
642
  });
292
643
  }
293
- if (options.metadata) {
294
- formData.append("request_metadata", JSON.stringify(options.metadata));
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));
295
650
  }
296
651
  formData.append("use_knowledgebase", String(options.useKnowledgebase ?? true));
297
652
  formData.append("is_test", String(options.isTest ?? false));
298
653
  formData.append("google_search", String(options.googleSearch ?? false));
299
654
  formData.append("format_instructions", options.formatInstructions || "normal");
300
655
  formData.append("ignore_chat_history", String(options.ignoreChatHistory ?? false));
656
+ if (options.environment) {
657
+ formData.append("environment", options.environment);
658
+ }
301
659
  if (options.exampleJson) {
302
660
  formData.append("example_json", options.exampleJson);
303
661
  }
304
- // Use customFetch for streaming (defaults to native fetch if not provided)
305
- const response = await this.customFetch(`${this.config.baseUrl}v3/chat/message`, {
306
- method: "POST",
307
- headers: {
308
- // Use the same authentication headers as other methods
309
- ...Object.fromEntries(Object.entries(this.headers).filter(([key]) => key !== "Content-Type")),
310
- // Don't set Content-Type for FormData - browser will set it with boundary
311
- },
312
- body: formData,
313
- });
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
+ }
314
683
  if (!response.ok) {
315
684
  const error = await this.createErrorFromResponse(response);
316
685
  options.onError?.(error);
317
686
  throw error;
318
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) {
319
730
  if (!response.body) {
320
731
  const error = new Error("ReadableStream not supported in this environment");
321
732
  options.onError?.(error);
322
733
  throw error;
323
734
  }
324
- const reader = response.body.getReader();
325
- const decoder = new TextDecoder("utf-8");
326
735
  // Reset streaming state for new message
327
736
  this.resetStreamingState();
328
737
  try {
329
738
  let messageObject = {};
330
- let fullMessage = "";
331
- // eslint-disable-next-line no-constant-condition
332
- while (true) {
333
- const { done, value } = await reader.read();
334
- if (done)
335
- break;
336
- const chunk = decoder.decode(value, { stream: true });
337
- fullMessage += chunk;
338
- // Parse streaming chunks
339
- const parsedData = this.parseStreamChunk(chunk, options);
340
- if (parsedData.messageObject) {
341
- messageObject = { ...messageObject, ...parsedData.messageObject };
342
- }
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);
343
756
  }
344
757
  // Call completion callback with final message
345
758
  if (options.onComplete) {
@@ -359,9 +772,6 @@ class ChatSDK extends BaseClient {
359
772
  options.onError?.(err);
360
773
  throw err;
361
774
  }
362
- finally {
363
- reader.releaseLock();
364
- }
365
775
  }
366
776
  /**
367
777
  * Send user feedback for a message
@@ -388,6 +798,7 @@ class ChatSDK extends BaseClient {
388
798
  this.messageInitObject = null;
389
799
  this.actionsMap.clear();
390
800
  this.hasCalledOnStart = false;
801
+ this.streamTagRemainder = "";
391
802
  }
392
803
  /**
393
804
  * Parse streaming response chunks and trigger appropriate callbacks
@@ -396,7 +807,8 @@ class ChatSDK extends BaseClient {
396
807
  parseStreamChunk(chunk, callbacks) {
397
808
  let messageObject;
398
809
  try {
399
- let modifiedChunk = chunk;
810
+ let modifiedChunk = this.streamTagRemainder + chunk;
811
+ this.streamTagRemainder = "";
400
812
  /**
401
813
  * List of tags used to parse streaming response chunks.
402
814
  * These tags act as delimiters in the streaming response, allowing the backend
@@ -413,6 +825,8 @@ class ChatSDK extends BaseClient {
413
825
  * - sql: SQL query data - SQL query information as JSON
414
826
  * - document_event: Document event notifications - events related to document processing
415
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
416
830
  */
417
831
  const tags = [
418
832
  "msg_chunk",
@@ -425,7 +839,19 @@ class ChatSDK extends BaseClient {
425
839
  "sql",
426
840
  "document_event",
427
841
  "meta",
842
+ "msg_discard",
428
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
+ ]);
429
855
  // Process the chunk as long as it contains tags
430
856
  let stillHasTags = true;
431
857
  while (stillHasTags) {
@@ -441,6 +867,12 @@ class ChatSDK extends BaseClient {
441
867
  firstTag = tag;
442
868
  }
443
869
  }
870
+ if (firstTagIndex === -1) {
871
+ if (modifiedChunk.length > 0) {
872
+ this.streamTagRemainder = modifiedChunk;
873
+ }
874
+ break;
875
+ }
444
876
  // If a tag was found, process it
445
877
  if (firstTagIndex !== -1) {
446
878
  stillHasTags = true;
@@ -461,14 +893,61 @@ class ChatSDK extends BaseClient {
461
893
  const content = nextTagIndex !== -1
462
894
  ? afterTagStart.substring(0, nextTagIndex)
463
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
+ }
464
905
  // Process the content based on the tag
465
906
  switch (firstTag) {
466
907
  case "msg_chunk":
467
908
  this.messageChunkString += content;
468
909
  callbacks.onChunk?.(content);
469
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;
470
925
  case "msmro":
471
- // Message end signal
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
+ }
472
951
  callbacks.onMessageEnd?.();
473
952
  break;
474
953
  case "meta":
@@ -625,10 +1104,8 @@ class ChatSDK extends BaseClient {
625
1104
  * @private
626
1105
  */
627
1106
  async createErrorFromResponse(response) {
628
- // Check for session expiration and dispatch custom event
629
- if ((response.status === 401 || response.status === 403) &&
630
- typeof window !== "undefined") {
631
- // Dispatch custom event immediately for session expiration
1107
+ // Only 401 expires the session; 403 (permission denied) must surface to the caller.
1108
+ if (response.status === 401 && typeof window !== "undefined") {
632
1109
  window.dispatchEvent(new CustomEvent("sessionExpired", {
633
1110
  detail: { status: response.status, url: response.url },
634
1111
  }));
@@ -637,13 +1114,20 @@ class ChatSDK extends BaseClient {
637
1114
  let errorDetail;
638
1115
  try {
639
1116
  const errorData = await response.json();
640
- errorMessage = errorData?.message || errorData?.detail || errorMessage;
1117
+ errorMessage = extractErrorMessage(errorData, errorMessage);
641
1118
  errorDetail = errorData?.detail;
642
1119
  }
643
1120
  catch (e) {
644
1121
  // If we can't parse the error response, use the status text
645
1122
  }
646
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
+ }
647
1131
  error.status = response.status;
648
1132
  error.detail = errorDetail;
649
1133
  return error;
@@ -683,33 +1167,10 @@ class SmartTablesSDK extends BaseClient {
683
1167
  return await this.delete(`project/${project_id}/data-types/${data_type_id}`);
684
1168
  }
685
1169
  async getKbDataTypeForView(project_id, data_type_id, filters = [], pagination) {
686
- const queryParams = new URLSearchParams();
687
- // Add filter parameters
688
- if (filters.length > 0) {
689
- filters.forEach((filter) => {
690
- queryParams.append(filter.column, String(filter.value));
691
- });
692
- }
693
- // Add pagination parameters
694
- if (pagination) {
695
- if (pagination.page !== undefined) {
696
- queryParams.append("page", pagination.page.toString());
697
- }
698
- if (pagination.limit !== undefined) {
699
- queryParams.append("limit", pagination.limit.toString());
700
- }
701
- if (pagination.search) {
702
- queryParams.append("search", pagination.search);
703
- }
704
- if (pagination.sort_column) {
705
- queryParams.append("sort_column", pagination.sort_column);
706
- }
707
- if (pagination.sort_direction) {
708
- queryParams.append("sort_direction", pagination.sort_direction);
709
- }
710
- }
711
- const endpoint = `project/${project_id}/data-types/${data_type_id}/view${queryParams.toString() ? "?" + queryParams.toString() : ""}`;
712
- return await this.get(endpoint);
1170
+ return await this.post(`project/${project_id}/data-types/${data_type_id}/view`, {
1171
+ filters,
1172
+ pagination,
1173
+ });
713
1174
  }
714
1175
  async addDataTypeRow(projectId, dataTypeId, metadata = {}) {
715
1176
  return await this.post(`project/${projectId}/data-type/${dataTypeId}/row`, {
@@ -755,34 +1216,40 @@ class SmartTablesSDK extends BaseClient {
755
1216
  async getDataTypeExampleJson(project_id, data_type_id) {
756
1217
  return await this.get(`project/${project_id}/data-types/${data_type_id}/json`);
757
1218
  }
758
- async importSmartTable(projectId, title, description, columnMappings, file) {
1219
+ async importSmartTable(projectId, title, description, columnMappings, file, needsDecryption) {
759
1220
  const formData = new FormData();
760
1221
  formData.append("title", title);
761
1222
  formData.append("description", description);
762
1223
  formData.append("column_mappings", JSON.stringify(columnMappings));
763
1224
  formData.append("file", file);
1225
+ if (needsDecryption) {
1226
+ formData.append("needs_decryption", "true");
1227
+ }
764
1228
  try {
765
1229
  return await this.post(`project/${projectId}/import-table`, formData);
766
1230
  }
767
1231
  catch (error) {
768
1232
  // Extract the detailed error message if available
769
1233
  let errorMessage = "Failed to import table";
770
- if (typeof error === 'object' && error !== null) {
1234
+ if (typeof error === "object" && error !== null) {
771
1235
  // Try to extract the detail field which often contains the specific error
772
- if ('detail' in error && typeof error.detail === 'string') {
1236
+ if ("detail" in error && typeof error.detail === "string") {
773
1237
  errorMessage = error.detail;
774
1238
  }
775
- else if ('message' in error && typeof error.message === 'string') {
1239
+ else if ("message" in error && typeof error.message === "string") {
776
1240
  errorMessage = error.message;
777
1241
  }
778
1242
  else {
779
1243
  // Try to find any error-related fields
780
1244
  const errorStr = JSON.stringify(error);
781
- if (errorStr.includes('InvalidDatetimeFormat') || errorStr.includes('invalid input syntax')) {
782
- errorMessage = "Data type mismatch: One or more values don't match the column data type. Check for date/time format issues.";
1245
+ if (errorStr.includes("InvalidDatetimeFormat") ||
1246
+ errorStr.includes("invalid input syntax")) {
1247
+ errorMessage =
1248
+ "Data type mismatch: One or more values don't match the column data type. Check for date/time format issues.";
783
1249
  }
784
- else if (errorStr.includes('duplicate key value')) {
785
- errorMessage = "Duplicate key error: The table already contains some of these records.";
1250
+ else if (errorStr.includes("duplicate key value")) {
1251
+ errorMessage =
1252
+ "Duplicate key error: The table already contains some of these records.";
786
1253
  }
787
1254
  }
788
1255
  }
@@ -845,7 +1312,7 @@ class SmartTablesSDK extends BaseClient {
845
1312
  project_id: this.config.projectId,
846
1313
  data_type_id: tableId,
847
1314
  title,
848
- description: description || '',
1315
+ description: description || "",
849
1316
  metadata,
850
1317
  });
851
1318
  }
@@ -867,7 +1334,7 @@ class SmartTablesSDK extends BaseClient {
867
1334
  async queryTable(tableId, options = {}) {
868
1335
  const fullInfo = await this.getTableFullInfo(tableId, options);
869
1336
  // Debug logging to understand response structure
870
- console.log('🔍 SDK queryTable response:', {
1337
+ console.log("🔍 SDK queryTable response:", {
871
1338
  hasDataView: !!fullInfo.data_view,
872
1339
  dataViewLength: fullInfo.data_view?.length || 0,
873
1340
  hasTotalCount: !!fullInfo.total_count,
@@ -895,7 +1362,7 @@ class SmartTablesSDK extends BaseClient {
895
1362
  dataTypeId: tableId,
896
1363
  columnName: column.name,
897
1364
  columnType: column.type,
898
- description: column.description || '',
1365
+ description: column.description || "",
899
1366
  options: column.options || {},
900
1367
  defaultValue: column.defaultValue !== null && column.defaultValue !== undefined
901
1368
  ? String(column.defaultValue)
@@ -973,10 +1440,11 @@ class SmartTablesSDK extends BaseClient {
973
1440
  * @returns Promise resolving to complete table information
974
1441
  */
975
1442
  async getTableFullInfo(tableId, options = {}) {
976
- const filters = (options.filters || []).map(f => ({
1443
+ const filters = (options.filters || []).map((f) => ({
977
1444
  column: f.column,
978
1445
  operator: f.operator,
979
1446
  value: f.value,
1447
+ ...(f.logicalOperator ? { logicalOperator: f.logicalOperator } : {}),
980
1448
  }));
981
1449
  const pagination = {
982
1450
  page: options.pagination?.page || 1,
@@ -1030,19 +1498,6 @@ class SmartTablesSDK extends BaseClient {
1030
1498
  data_schema.sort((a, b) => (a.order || 0) - (b.order || 0));
1031
1499
  }
1032
1500
  }
1033
- // Debug logging to understand response structure
1034
- console.log('🔍 SDK queryTableWithSchema response:', {
1035
- hasDataView: !!fullInfo.data_view,
1036
- dataViewLength: fullInfo.data_view?.length || 0,
1037
- hasTotalCount: !!fullInfo.total_count,
1038
- totalCount: fullInfo.total_count,
1039
- schemaColumns: data_schema?.length || 0,
1040
- views: fullInfo.views?.length || 0,
1041
- defaultView,
1042
- defaultViewOptions: defaultView?.options,
1043
- hasDashboardLayout: !!defaultView?.options?.dashboardLayout,
1044
- rawFullInfo: fullInfo,
1045
- });
1046
1501
  return {
1047
1502
  data: fullInfo.data_view || [],
1048
1503
  total: fullInfo.total_count || 0,
@@ -1061,36 +1516,13 @@ class SmartTablesSDK extends BaseClient {
1061
1516
  * @returns Promise resolving to grouped data and schema
1062
1517
  */
1063
1518
  async queryGroupedTableWithSchema(tableId, options) {
1064
- const queryParams = new URLSearchParams();
1065
- // Add grouping parameters
1066
- queryParams.append("group_column", options.groupColumn);
1067
- queryParams.append("group_column_type", options.groupColumnType);
1068
- // Add filters
1069
- if (options.filters && options.filters.length > 0) {
1070
- options.filters.forEach((filter) => {
1071
- queryParams.append(filter.column, String(filter.value));
1072
- });
1073
- }
1074
- // Add sort
1075
- if (options.sort && options.sort.length > 0) {
1076
- const sort = options.sort[0]; // Take the first sort for now
1077
- queryParams.append("sort_column", sort.column);
1078
- queryParams.append("sort_direction", sort.direction);
1079
- }
1080
- // Add pagination
1081
- if (options.pagination) {
1082
- if (options.pagination.page !== undefined) {
1083
- queryParams.append("page", options.pagination.page.toString());
1084
- }
1085
- if (options.pagination.limit !== undefined) {
1086
- queryParams.append("limit", options.pagination.limit.toString());
1087
- }
1088
- if (options.pagination.search) {
1089
- queryParams.append("search", options.pagination.search);
1090
- }
1091
- }
1092
- const url = `project/${this.config.projectId}/data-types/${tableId}/view/grouped${queryParams.toString() ? "?" + queryParams.toString() : ""}`;
1093
- const response = await this.get(url);
1519
+ const response = await this.post(`project/${this.config.projectId}/data-types/${tableId}/view/grouped`, {
1520
+ group_column: options.groupColumn,
1521
+ group_column_type: options.groupColumnType,
1522
+ filters: options.filters || [],
1523
+ sort: options.sort || [],
1524
+ pagination: options.pagination,
1525
+ });
1094
1526
  return {
1095
1527
  grouped_data: response.grouped_data || [],
1096
1528
  total_count: response.total_count || 0,
@@ -1149,10 +1581,12 @@ class SmartTablesSDK extends BaseClient {
1149
1581
  * @param description Description for the new table
1150
1582
  * @param columnMappings Array of column mappings
1151
1583
  * @param file File to import
1584
+ * @param needsDecryption True when the file is encrypted by an external DRM /
1585
+ * envelope encryption scheme; the server decrypts it before parsing
1152
1586
  * @returns Promise resolving to import result
1153
1587
  */
1154
- async importTable(title, description, columnMappings, file) {
1155
- const response = await this.importSmartTable(this.config.projectId, title, description, columnMappings, file);
1588
+ async importTable(title, description, columnMappings, file, needsDecryption) {
1589
+ const response = await this.importSmartTable(this.config.projectId, title, description, columnMappings, file, needsDecryption);
1156
1590
  return {
1157
1591
  data_type_id: response.data_type_id || response.id,
1158
1592
  rows_imported: response.rows_imported || 0,
@@ -1215,9 +1649,9 @@ class SmartTablesSDK extends BaseClient {
1215
1649
  async listJobs(dataTypeId, options = {}) {
1216
1650
  const params = new URLSearchParams();
1217
1651
  if (options.limit)
1218
- params.append('limit', options.limit.toString());
1652
+ params.append("limit", options.limit.toString());
1219
1653
  if (options.offset)
1220
- params.append('offset', options.offset.toString());
1654
+ params.append("offset", options.offset.toString());
1221
1655
  return await this.get(`project/${this.config.projectId}/data-type/${dataTypeId}/compute-column/jobs?${params.toString()}`);
1222
1656
  }
1223
1657
  /**
@@ -1237,6 +1671,15 @@ class SmartTablesSDK extends BaseClient {
1237
1671
  async computeAllRows(dataTypeId) {
1238
1672
  return await this.post(`project/${this.config.projectId}/data-type/${dataTypeId}/compute-all-rows`, {});
1239
1673
  }
1674
+ /**
1675
+ * Cancel a running compute-all-rows job (EN-3633).
1676
+ * @param dataTypeId The ID of the data type
1677
+ * @param executionId The execution ID returned from computeAllRows
1678
+ * @returns Promise resolving when cancellation is requested
1679
+ */
1680
+ async cancelAllRowsJob(dataTypeId, executionId) {
1681
+ return await this.post(`project/${this.config.projectId}/data-type/${dataTypeId}/compute-all-rows/cancel/${executionId}`, {});
1682
+ }
1240
1683
  /**
1241
1684
  * Normalize table data from API response
1242
1685
  * @private
@@ -1245,451 +1688,16 @@ class SmartTablesSDK extends BaseClient {
1245
1688
  return {
1246
1689
  id: data.id || data.data_type_id,
1247
1690
  project_id: data.project_id || this.config.projectId,
1248
- title: data.title || data.name || '',
1249
- description: data.description || '',
1691
+ title: data.title || data.name || "",
1692
+ description: data.description || "",
1250
1693
  schema: data.schema || [],
1251
- table_name: data.table_name || '',
1694
+ table_name: data.table_name || "",
1252
1695
  created_at: data.created_at,
1253
1696
  updated_at: data.updated_at,
1254
1697
  };
1255
1698
  }
1256
1699
  }
1257
1700
 
1258
- /**
1259
- * SDK for interacting with the Odin AI Workflow system.
1260
- *
1261
- * Allows you to:
1262
- * - List and retrieve workflows
1263
- * - Execute workflows programmatically
1264
- * - Stream real-time execution updates
1265
- * - View execution history
1266
- *
1267
- * @example
1268
- * ```typescript
1269
- * import { WorkflowSDK } from '@odin-ai/sdk';
1270
- *
1271
- * const sdk = new WorkflowSDK({
1272
- * baseUrl: 'https://api.odin.ai/',
1273
- * projectId: 'your-project-id',
1274
- * apiKey: 'your-api-key',
1275
- * apiSecret: 'your-api-secret',
1276
- * });
1277
- *
1278
- * // List workflows
1279
- * const { tools: workflows } = await sdk.listWorkflows();
1280
- *
1281
- * // Execute with streaming
1282
- * const session = await sdk.executeWorkflowStream(workflowId, {
1283
- * inputs: { name: 'John' },
1284
- * onNodeCompleted: (event) => console.log(`Node ${event.node_id} completed`),
1285
- * onExecutionCompleted: (event) => console.log('Done!', event.result),
1286
- * });
1287
- * ```
1288
- */
1289
- class WorkflowSDK extends BaseClient {
1290
- /**
1291
- * Initialize the Workflow SDK
1292
- * @param config Configuration object with API credentials and settings
1293
- */
1294
- constructor(config) {
1295
- super(config);
1296
- }
1297
- /**
1298
- * List all workflows in the project
1299
- * @param limit Maximum number of workflows to return (default: 50)
1300
- * @param offset Pagination offset (default: 0)
1301
- * @returns Promise resolving to list of workflows
1302
- */
1303
- async listWorkflows(limit = 50, offset = 0) {
1304
- const params = new URLSearchParams({
1305
- project_id: this.config.projectId,
1306
- limit: limit.toString(),
1307
- offset: offset.toString(),
1308
- });
1309
- return await this.get(`tools/custom?${params}`);
1310
- }
1311
- /**
1312
- * Get a specific workflow by ID
1313
- * @param workflowId The ID of the workflow to retrieve
1314
- * @returns Promise resolving to the workflow details
1315
- */
1316
- async getWorkflow(workflowId) {
1317
- return await this.get(`tools/custom/${workflowId}`);
1318
- }
1319
- /**
1320
- * Get a specific published version of a workflow
1321
- * @param workflowId The ID of the workflow
1322
- * @param version The version string (e.g., "1.0.0")
1323
- * @returns Promise resolving to the workflow version details
1324
- */
1325
- async getWorkflowVersion(workflowId, version) {
1326
- return await this.get(`tools/custom/${workflowId}/version/${version}`);
1327
- }
1328
- /**
1329
- * List all published versions of a workflow
1330
- * @param workflowId The ID of the workflow
1331
- * @param limit Maximum number of versions to return (default: 20)
1332
- * @param offset Pagination offset (default: 0)
1333
- * @returns Promise resolving to list of workflow versions
1334
- */
1335
- async listWorkflowVersions(workflowId, limit = 20, offset = 0) {
1336
- const params = new URLSearchParams({
1337
- limit: limit.toString(),
1338
- offset: offset.toString(),
1339
- });
1340
- return await this.get(`tools/custom/${workflowId}/versions?${params}`);
1341
- }
1342
- /**
1343
- * Execute a workflow and wait for the result
1344
- *
1345
- * For real-time updates during execution, use `executeWorkflowStream` instead.
1346
- *
1347
- * @param workflowId The ID of the workflow to execute
1348
- * @param options Execution options including inputs
1349
- * @returns Promise resolving to the execution result
1350
- */
1351
- async executeWorkflow(workflowId, options = {}) {
1352
- return await this.post('tools/execute-workflow', {
1353
- project_id: this.config.projectId,
1354
- tool_id: workflowId,
1355
- inputs: options.inputs || {},
1356
- execution_mode: options.executionMode || 'workflow',
1357
- mode: options.triggerMode || 'manual',
1358
- chat_id: options.chatId,
1359
- message_id: options.messageId,
1360
- return_response: true,
1361
- });
1362
- }
1363
- /**
1364
- * Execute a workflow with real-time streaming updates via SSE.
1365
- *
1366
- * This method provides callbacks for real-time execution events:
1367
- * - `onExecutionStarted`: Fired when execution begins
1368
- * - `onNodeStarted`: Fired when each node begins executing
1369
- * - `onNodeCompleted`: Fired when each node finishes
1370
- * - `onNodeError`: Fired if a node encounters an error
1371
- * - `onNodeSkipped`: Fired when a node is skipped (e.g., conditional branch)
1372
- * - `onExecutionCompleted`: Fired when the entire workflow completes
1373
- * - `onExecutionError`: Fired if the workflow fails
1374
- * - `onAgentChunk`: Fired when an AI agent streams text
1375
- * - `onAgentThinking`: Fired for AI agent reasoning/thinking updates
1376
- *
1377
- * @param workflowId The ID of the workflow to execute
1378
- * @param options Execution options
1379
- * @param callbacks Event callbacks for streaming updates
1380
- * @returns Promise resolving to an execution session for control
1381
- *
1382
- * @example
1383
- * ```typescript
1384
- * const session = await sdk.executeWorkflowStream(
1385
- * 'workflow-123',
1386
- * { inputs: { name: 'John' } },
1387
- * {
1388
- * onNodeStarted: (e) => console.log(`Starting ${e.node_id}`),
1389
- * onNodeCompleted: (e) => console.log(`Completed ${e.node_id}`),
1390
- * onExecutionCompleted: (e) => {
1391
- * console.log('Workflow complete!', e.result);
1392
- * },
1393
- * onError: (err) => console.error('Error:', err),
1394
- * }
1395
- * );
1396
- *
1397
- * // Later, to cancel execution:
1398
- * session.close();
1399
- * ```
1400
- */
1401
- async executeWorkflowStream(workflowId, options = {}) {
1402
- // Extract callbacks from options
1403
- const { inputs, executionMode, triggerMode, chatId, messageId, onExecutionStarted, onNodeStarted, onNodeCompleted, onNodeError, onNodeSkipped, onExecutionCompleted, onExecutionError, onAgentChunk, onAgentThinking, onResponseCard, onRawEvent, onError, onClose, } = options;
1404
- // Step 1: Prepare execution by storing inputs in Redis
1405
- const prepareResponse = await this.prepareWorkflowExecution(workflowId, {
1406
- inputs,
1407
- executionMode,
1408
- triggerMode,
1409
- chatId,
1410
- messageId,
1411
- });
1412
- const executionId = prepareResponse.execution_id;
1413
- // Step 2: Get access token for SSE connection
1414
- const accessToken = await this.getAccessTokenForSSE();
1415
- // Step 3: Connect to SSE stream
1416
- const streamUrl = new URL('tools/execute-workflow-stream', this.config.baseUrl);
1417
- streamUrl.searchParams.set('execution_id', executionId);
1418
- streamUrl.searchParams.set('access_token', accessToken);
1419
- const eventSource = new EventSource(streamUrl.toString());
1420
- // Track connection state
1421
- let isOpen = true;
1422
- // Create session object
1423
- const session = {
1424
- executionId,
1425
- close: () => {
1426
- isOpen = false;
1427
- eventSource.close();
1428
- },
1429
- isOpen: () => isOpen && eventSource.readyState !== EventSource.CLOSED,
1430
- };
1431
- // Handle SSE events
1432
- eventSource.onmessage = (event) => {
1433
- try {
1434
- const data = this.parseSSEEvent(event.data);
1435
- if (!data)
1436
- return;
1437
- // Call raw event callback
1438
- onRawEvent?.(data);
1439
- // Call specific event callbacks based on type
1440
- this.dispatchEvent(data, {
1441
- onExecutionStarted,
1442
- onNodeStarted,
1443
- onNodeCompleted,
1444
- onNodeError,
1445
- onNodeSkipped,
1446
- onExecutionCompleted,
1447
- onExecutionError,
1448
- onAgentChunk,
1449
- onAgentThinking,
1450
- onResponseCard,
1451
- });
1452
- // Close connection on completion or error
1453
- if (data.type === 'execution_completed' || data.type === 'execution_error') {
1454
- session.close();
1455
- }
1456
- }
1457
- catch (err) {
1458
- console.error('Error parsing SSE event:', err);
1459
- onError?.(err instanceof Error ? err : new Error(String(err)));
1460
- }
1461
- };
1462
- eventSource.onerror = (event) => {
1463
- console.error('SSE connection error:', event);
1464
- isOpen = false;
1465
- onError?.(new Error('SSE connection error'));
1466
- eventSource.close();
1467
- };
1468
- eventSource.addEventListener('close', () => {
1469
- isOpen = false;
1470
- onClose?.();
1471
- });
1472
- return session;
1473
- }
1474
- /**
1475
- * Get execution history for a workflow
1476
- * @param workflowId The ID of the workflow (optional - if not provided, returns all project executions)
1477
- * @param page Page number (1-based, default: 1)
1478
- * @param pageSize Number of results per page (default: 20, max: 100)
1479
- * @returns Promise resolving to execution history
1480
- */
1481
- async getExecutionHistory(workflowId, page = 1, pageSize = 20) {
1482
- const params = new URLSearchParams({
1483
- project_id: this.config.projectId,
1484
- page: page.toString(),
1485
- page_size: Math.min(pageSize, 100).toString(),
1486
- });
1487
- if (workflowId) {
1488
- params.set('tool_id', workflowId);
1489
- }
1490
- return await this.get(`tools/execution-history?${params}`);
1491
- }
1492
- /**
1493
- * Get details of a specific execution
1494
- * @param executionId The ID of the execution
1495
- * @returns Promise resolving to execution details
1496
- */
1497
- async getExecution(executionId) {
1498
- return await this.get(`tools/execution/${executionId}`);
1499
- }
1500
- /**
1501
- * Prepare workflow execution by storing inputs in Redis.
1502
- * This is an internal method used by executeWorkflowStream.
1503
- * @private
1504
- */
1505
- async prepareWorkflowExecution(workflowId, options = {}) {
1506
- return await this.post('tools/prepare-workflow-execution', {
1507
- project_id: this.config.projectId,
1508
- tool_id: workflowId,
1509
- inputs: options.inputs || {},
1510
- execution_mode: options.executionMode || 'workflow',
1511
- mode: options.triggerMode || 'manual',
1512
- chat_id: options.chatId,
1513
- message_id: options.messageId,
1514
- });
1515
- }
1516
- /**
1517
- * Get access token for SSE connection.
1518
- * Uses the configured access token or generates one from API keys.
1519
- * @private
1520
- */
1521
- async getAccessTokenForSSE() {
1522
- // If we have an access token configured, use it
1523
- if (this.config.accessToken) {
1524
- return this.config.accessToken;
1525
- }
1526
- // Otherwise, we need to exchange API keys for an access token
1527
- // This endpoint should be implemented on the backend if not already
1528
- const response = await this.post('auth/api-key-token', {
1529
- api_key: this.config.apiKey,
1530
- api_secret: this.config.apiSecret,
1531
- });
1532
- return response.access_token;
1533
- }
1534
- /**
1535
- * Parse SSE event data into a typed event object.
1536
- * @private
1537
- */
1538
- parseSSEEvent(data) {
1539
- try {
1540
- // Handle different SSE event formats
1541
- const parsed = JSON.parse(data);
1542
- // Normalize event format
1543
- if (parsed.event_type) {
1544
- return {
1545
- type: parsed.event_type,
1546
- ...parsed,
1547
- };
1548
- }
1549
- if (parsed.type) {
1550
- return parsed;
1551
- }
1552
- // Handle legacy format with specific field names
1553
- if (parsed.node_id && parsed.status === 'started') {
1554
- return {
1555
- type: 'node_started',
1556
- node_id: parsed.node_id,
1557
- node_label: parsed.node_label,
1558
- node_type: parsed.node_type,
1559
- };
1560
- }
1561
- if (parsed.node_id && parsed.status === 'completed') {
1562
- return {
1563
- type: 'node_completed',
1564
- node_id: parsed.node_id,
1565
- result: parsed.result,
1566
- execution_time_ms: parsed.execution_time_ms,
1567
- };
1568
- }
1569
- if (parsed.execution_completed || parsed.final_result) {
1570
- return {
1571
- type: 'execution_completed',
1572
- result: parsed.final_result || parsed.result,
1573
- };
1574
- }
1575
- if (parsed.chunk && parsed.node_id) {
1576
- return {
1577
- type: 'agent_chunk',
1578
- node_id: parsed.node_id,
1579
- chunk: parsed.chunk,
1580
- };
1581
- }
1582
- // Return raw data if we can't categorize it
1583
- return {
1584
- type: 'execution_started',
1585
- workflow_id: parsed.workflow_id || parsed.tool_id || '',
1586
- execution_id: parsed.execution_id || '',
1587
- ...parsed,
1588
- };
1589
- }
1590
- catch (err) {
1591
- // If it's not JSON, it might be a text chunk
1592
- if (typeof data === 'string' && data.trim()) {
1593
- console.warn('Non-JSON SSE data received:', data);
1594
- }
1595
- return null;
1596
- }
1597
- }
1598
- /**
1599
- * Dispatch event to appropriate callback.
1600
- * @private
1601
- */
1602
- dispatchEvent(event, callbacks) {
1603
- switch (event.type) {
1604
- case 'execution_started':
1605
- callbacks.onExecutionStarted?.(event);
1606
- break;
1607
- case 'node_started':
1608
- callbacks.onNodeStarted?.(event);
1609
- break;
1610
- case 'node_completed':
1611
- callbacks.onNodeCompleted?.(event);
1612
- break;
1613
- case 'node_error':
1614
- callbacks.onNodeError?.(event);
1615
- break;
1616
- case 'node_skipped':
1617
- callbacks.onNodeSkipped?.(event);
1618
- break;
1619
- case 'execution_completed':
1620
- callbacks.onExecutionCompleted?.(event);
1621
- break;
1622
- case 'execution_error':
1623
- callbacks.onExecutionError?.(event);
1624
- break;
1625
- case 'agent_chunk':
1626
- callbacks.onAgentChunk?.(event);
1627
- break;
1628
- case 'agent_thinking':
1629
- callbacks.onAgentThinking?.(event);
1630
- break;
1631
- case 'response_card':
1632
- callbacks.onResponseCard?.(event);
1633
- break;
1634
- }
1635
- }
1636
- /**
1637
- * Upload a file for use with file upload trigger workflows.
1638
- * Returns a temporary file reference to use with executeWorkflowStream.
1639
- *
1640
- * @param file The file to upload
1641
- * @returns Promise resolving to file reference info
1642
- */
1643
- async uploadWorkflowFile(file) {
1644
- const formData = new FormData();
1645
- formData.append('file', file);
1646
- formData.append('project_id', this.config.projectId);
1647
- return await this.post('tools/upload-workflow-file', formData);
1648
- }
1649
- /**
1650
- * Upload multiple files for use with file upload trigger workflows.
1651
- * Returns a temporary file reference to use with executeWorkflowStream.
1652
- *
1653
- * @param files Array of files to upload
1654
- * @returns Promise resolving to file reference info
1655
- */
1656
- async uploadWorkflowFiles(files) {
1657
- const formData = new FormData();
1658
- files.forEach((file, index) => {
1659
- formData.append('files', file);
1660
- });
1661
- formData.append('project_id', this.config.projectId);
1662
- formData.append('multiple_files', 'true');
1663
- return await this.post('tools/upload-workflow-file', formData);
1664
- }
1665
- /**
1666
- * Execute a workflow with file upload trigger.
1667
- * This is a convenience method that handles file upload and execution in one call.
1668
- *
1669
- * @param workflowId The ID of the workflow to execute
1670
- * @param file File(s) to upload
1671
- * @param options Additional execution options
1672
- * @returns Promise resolving to the execution result
1673
- */
1674
- async executeWorkflowWithFile(workflowId, file, options = {}) {
1675
- const formData = new FormData();
1676
- formData.append('project_id', this.config.projectId);
1677
- formData.append('tool_id', workflowId);
1678
- if (Array.isArray(file)) {
1679
- file.forEach((f) => formData.append('files', f));
1680
- formData.append('multiple_files', 'true');
1681
- }
1682
- else {
1683
- formData.append('file', file);
1684
- formData.append('multiple_files', 'false');
1685
- }
1686
- if (options.inputs) {
1687
- formData.append('runtime_inputs', JSON.stringify(options.inputs));
1688
- }
1689
- return await this.post('tools/execute-workflow-file-upload', formData);
1690
- }
1691
- }
1692
-
1693
1701
  /**
1694
1702
  * Voice SDK for ElevenLabs integration
1695
1703
  * Provides voice conversation capabilities with automatic chat integration
@@ -1720,18 +1728,18 @@ class VoiceSDK extends BaseClient {
1720
1728
  agentId: options.agentId || this.defaultAgentId,
1721
1729
  voiceSettings: options.voiceSettings || this.defaultVoiceSettings,
1722
1730
  userInfo: options.userInfo,
1723
- }
1731
+ },
1724
1732
  };
1725
1733
  this.activeSessions.set(sessionId, session);
1726
1734
  // If we need to create a new chat for this voice conversation
1727
1735
  if (options.saveToChat && !options.existingChatId && this.chatSDK) {
1728
1736
  try {
1729
- const chat = await this.chatSDK.createChat('Voice Conversation');
1737
+ const chat = await this.chatSDK.createChat("Voice Conversation");
1730
1738
  session.chatId = chat.chat_id;
1731
- options.callbacks?.onConversationSaved?.(chat.chat_id, '');
1739
+ options.callbacks?.onConversationSaved?.(chat.chat_id, "");
1732
1740
  }
1733
1741
  catch (error) {
1734
- console.warn('Failed to create chat for voice conversation:', error);
1742
+ console.warn("Failed to create chat for voice conversation:", error);
1735
1743
  }
1736
1744
  }
1737
1745
  // Set up enhanced callbacks that integrate with our session tracking
@@ -1752,12 +1760,12 @@ class VoiceSDK extends BaseClient {
1752
1760
  onError: (error) => {
1753
1761
  options.callbacks?.onError?.(error);
1754
1762
  this.endVoiceSession(sessionId, error.message);
1755
- }
1763
+ },
1756
1764
  };
1757
1765
  // Store enhanced callbacks for this session
1758
1766
  session.metadata = {
1759
1767
  ...session.metadata,
1760
- enhancedCallbacks
1768
+ enhancedCallbacks,
1761
1769
  };
1762
1770
  return sessionId;
1763
1771
  }
@@ -1772,7 +1780,7 @@ class VoiceSDK extends BaseClient {
1772
1780
  session.endTime = Date.now();
1773
1781
  session.metadata = {
1774
1782
  ...session.metadata,
1775
- totalDuration: session.endTime - session.startTime
1783
+ totalDuration: session.endTime - session.startTime,
1776
1784
  };
1777
1785
  // Save conversation to chat if configured
1778
1786
  if (session.chatId && this.chatSDK && session.messages.length > 0) {
@@ -1780,7 +1788,7 @@ class VoiceSDK extends BaseClient {
1780
1788
  await this.saveVoiceConversationToChat(session);
1781
1789
  }
1782
1790
  catch (error) {
1783
- console.warn('Failed to save voice conversation to chat:', error);
1791
+ console.warn("Failed to save voice conversation to chat:", error);
1784
1792
  }
1785
1793
  }
1786
1794
  this.activeSessions.delete(sessionId);
@@ -1797,7 +1805,7 @@ class VoiceSDK extends BaseClient {
1797
1805
  return {
1798
1806
  sessionId,
1799
1807
  isActive: true,
1800
- connectionStatus: 'connected',
1808
+ connectionStatus: "connected",
1801
1809
  volume: 50,
1802
1810
  micMuted: false,
1803
1811
  isSpeaking: false,
@@ -1813,7 +1821,7 @@ class VoiceSDK extends BaseClient {
1813
1821
  }
1814
1822
  session.metadata = {
1815
1823
  ...session.metadata,
1816
- voiceSettings: { ...session.metadata?.voiceSettings, ...settings }
1824
+ voiceSettings: { ...session.metadata?.voiceSettings, ...settings },
1817
1825
  };
1818
1826
  // Here you would call the actual ElevenLabs API to update settings
1819
1827
  // This is a placeholder for that functionality
@@ -1834,7 +1842,7 @@ class VoiceSDK extends BaseClient {
1834
1842
  */
1835
1843
  async setVolume(sessionId, volume) {
1836
1844
  if (volume < 0 || volume > 100) {
1837
- throw new Error('Volume must be between 0 and 100');
1845
+ throw new Error("Volume must be between 0 and 100");
1838
1846
  }
1839
1847
  const session = this.activeSessions.get(sessionId);
1840
1848
  if (!session) {
@@ -1865,7 +1873,7 @@ class VoiceSDK extends BaseClient {
1865
1873
  // For now, just add it as a system message
1866
1874
  const contextMessage = {
1867
1875
  id: this.generateMessageId(),
1868
- type: 'system',
1876
+ type: "system",
1869
1877
  text: `Context update: ${context}`,
1870
1878
  timestamp: Date.now(),
1871
1879
  };
@@ -1891,34 +1899,34 @@ class VoiceSDK extends BaseClient {
1891
1899
  async saveVoiceMessageToAPI(sessionId, userMessage, aiResponse, agentInfo) {
1892
1900
  const session = this.activeSessions.get(sessionId);
1893
1901
  if (!session || !session.chatId) {
1894
- console.warn('Cannot save voice message: no session or chat ID');
1902
+ console.warn("Cannot save voice message: no session or chat ID");
1895
1903
  return;
1896
1904
  }
1897
1905
  try {
1898
1906
  // Get user information from session if available
1899
- let userName = 'Voice User';
1900
- let userId = 'voice-user';
1907
+ let userName = "Voice User";
1908
+ let userId = "voice-user";
1901
1909
  if (session.metadata?.userInfo) {
1902
1910
  userName = session.metadata.userInfo.name;
1903
1911
  userId = session.metadata.userInfo.id;
1904
1912
  }
1905
1913
  // Use the existing API endpoint to save voice messages
1906
- await this.post('/elevenlabs/voice-message/save', {
1914
+ await this.post("/elevenlabs/voice-message/save", {
1907
1915
  project_id: this.config.projectId,
1908
1916
  chat_id: session.chatId,
1909
1917
  message: userMessage,
1910
1918
  response: aiResponse,
1911
1919
  user_name: userName,
1912
1920
  user_id: userId,
1913
- message_type: 'complete',
1921
+ message_type: "complete",
1914
1922
  agent_id: agentInfo?.id || session.metadata?.agentId,
1915
1923
  agent_name: agentInfo?.name,
1916
1924
  conversation_id: sessionId,
1917
1925
  });
1918
- console.log('Voice message automatically saved to database');
1926
+ console.log("Voice message automatically saved to database");
1919
1927
  }
1920
1928
  catch (error) {
1921
- console.error('Failed to auto-save voice message:', error);
1929
+ console.error("Failed to auto-save voice message:", error);
1922
1930
  // Don't throw - this shouldn't break the voice conversation
1923
1931
  }
1924
1932
  }
@@ -1926,7 +1934,9 @@ class VoiceSDK extends BaseClient {
1926
1934
  * Private helper methods
1927
1935
  */
1928
1936
  generateSessionId() {
1929
- return `voice_session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
1937
+ return `voice_session_${Date.now()}_${Math.random()
1938
+ .toString(36)
1939
+ .substr(2, 9)}`;
1930
1940
  }
1931
1941
  generateMessageId() {
1932
1942
  return `voice_msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
@@ -1938,8 +1948,8 @@ class VoiceSDK extends BaseClient {
1938
1948
  // Convert ElevenLabs message to our format
1939
1949
  const voiceMessage = {
1940
1950
  id: this.generateMessageId(),
1941
- type: message.role === 'user' ? 'user_speech' : 'ai_speech',
1942
- text: message.content || message.text || '',
1951
+ type: message.role === "user" ? "user_speech" : "ai_speech",
1952
+ text: message.content || message.text || "",
1943
1953
  timestamp: Date.now(),
1944
1954
  audioUrl: message.audioUrl,
1945
1955
  };
@@ -1962,25 +1972,25 @@ class VoiceSDK extends BaseClient {
1962
1972
  return;
1963
1973
  // Look for unsaved message pairs (user + AI response)
1964
1974
  const messages = session.messages;
1965
- let lastUserMessage = '';
1975
+ let lastUserMessage = "";
1966
1976
  for (let i = messages.length - 1; i >= 0; i--) {
1967
1977
  const message = messages[i];
1968
- if (message.type === 'ai_speech' && lastUserMessage) {
1978
+ if (message.type === "ai_speech" && lastUserMessage) {
1969
1979
  // We have a complete pair - save it
1970
1980
  try {
1971
1981
  await this.saveVoiceMessageToAPI(sessionId, lastUserMessage, message.text, {
1972
1982
  id: session.metadata?.agentId,
1973
- name: session.metadata?.agentName
1983
+ name: session.metadata?.agentName,
1974
1984
  });
1975
1985
  // Mark these messages as saved to avoid duplicate saves
1976
1986
  message.saved = true;
1977
1987
  break;
1978
1988
  }
1979
1989
  catch (error) {
1980
- console.error('Failed to auto-save voice message pair:', error);
1990
+ console.error("Failed to auto-save voice message pair:", error);
1981
1991
  }
1982
1992
  }
1983
- else if (message.type === 'user_speech' && !message.saved) {
1993
+ else if (message.type === "user_speech" && !message.saved) {
1984
1994
  lastUserMessage = message.text;
1985
1995
  }
1986
1996
  }
@@ -1990,306 +2000,41 @@ class VoiceSDK extends BaseClient {
1990
2000
  return;
1991
2001
  // Convert voice messages to chat format
1992
2002
  const conversationSummary = session.messages
1993
- .filter(msg => msg.type !== 'system')
1994
- .map(msg => `${msg.type === 'user_speech' ? 'User' : 'Assistant'}: ${msg.text}`)
1995
- .join('\n');
2003
+ .filter((msg) => msg.type !== "system")
2004
+ .map((msg) => `${msg.type === "user_speech" ? "User" : "Assistant"}: ${msg.text}`)
2005
+ .join("\n");
1996
2006
  const duration = session.metadata?.totalDuration
1997
- ? Math.round((session.metadata.totalDuration / 1000) / 60)
2007
+ ? Math.round(session.metadata.totalDuration / 1000 / 60)
1998
2008
  : 0;
1999
2009
  const summaryMessage = `Voice Conversation Summary (${duration} minutes):\n\n${conversationSummary}`;
2000
2010
  try {
2001
2011
  await this.chatSDK.sendMessage(summaryMessage, {
2002
2012
  chatId: session.chatId,
2003
2013
  metadata: {
2004
- type: 'voice_conversation_summary',
2014
+ type: "voice_conversation_summary",
2005
2015
  sessionId: session.id,
2006
2016
  duration: session.metadata?.totalDuration,
2007
2017
  messageCount: session.messages.length,
2008
- }
2018
+ },
2009
2019
  });
2010
2020
  }
2011
2021
  catch (error) {
2012
- console.error('Failed to save voice conversation to chat:', error);
2022
+ console.error("Failed to save voice conversation to chat:", error);
2013
2023
  throw error;
2014
2024
  }
2015
2025
  }
2016
2026
  }
2017
2027
 
2018
- /**
2019
- * Enhanced useVoiceConversation hook with our SDK's chat integration and session management
2020
- */
2021
- function useVoiceConversation(options = {}) {
2022
- const { sdkConfig, sessionConfig, callbacks, ...elevenLabsOptions } = options;
2023
- // State management
2024
- const [voiceSDK, setVoiceSDK] = react.useState(null);
2025
- const [currentSessionId, setCurrentSessionId] = react.useState(null);
2026
- const [conversationState, setConversationState] = react.useState({
2027
- isActive: false,
2028
- connectionStatus: 'disconnected',
2029
- volume: 50,
2030
- micMuted: false,
2031
- isSpeaking: false,
2032
- });
2033
- // Refs for managing callbacks and cleanup
2034
- const callbacksRef = react.useRef(callbacks);
2035
- const sessionConfigRef = react.useRef(sessionConfig);
2036
- // Update refs when options change
2037
- react.useEffect(() => {
2038
- callbacksRef.current = callbacks;
2039
- sessionConfigRef.current = sessionConfig;
2040
- }, [callbacks, sessionConfig]);
2041
- // Initialize VoiceSDK lazily when needed
2042
- const initializeVoiceSDK = react.useCallback(async (config) => {
2043
- if (voiceSDK)
2044
- return voiceSDK;
2045
- try {
2046
- const sdk = new VoiceSDK(config);
2047
- setVoiceSDK(sdk);
2048
- return sdk;
2049
- }
2050
- catch (error) {
2051
- console.error('Failed to initialize VoiceSDK:', error);
2052
- throw error;
2053
- }
2054
- }, [voiceSDK]);
2055
- // Enhanced callbacks that integrate with our SDK
2056
- const enhancedCallbacks = {
2057
- ...elevenLabsOptions,
2058
- onConnect: react.useCallback(() => {
2059
- setConversationState(prev => ({
2060
- ...prev,
2061
- connectionStatus: 'connected',
2062
- isActive: true
2063
- }));
2064
- elevenLabsOptions.onConnect?.();
2065
- callbacksRef.current?.onConnect?.();
2066
- }, [elevenLabsOptions.onConnect]),
2067
- onDisconnect: react.useCallback((details) => {
2068
- setConversationState(prev => ({
2069
- ...prev,
2070
- connectionStatus: 'disconnected',
2071
- isActive: false
2072
- }));
2073
- elevenLabsOptions.onDisconnect?.(details);
2074
- callbacksRef.current?.onDisconnect?.(details);
2075
- // End SDK session if active
2076
- if (currentSessionId && voiceSDK) {
2077
- voiceSDK.endVoiceSession(currentSessionId, details?.reason);
2078
- setCurrentSessionId(null);
2079
- }
2080
- }, [currentSessionId, voiceSDK, elevenLabsOptions.onDisconnect]),
2081
- onMessage: react.useCallback((message) => {
2082
- elevenLabsOptions.onMessage?.(message);
2083
- callbacksRef.current?.onMessage?.(message);
2084
- // Handle transcription if available
2085
- if (message.type === 'user_speech' && message.text) {
2086
- callbacksRef.current?.onTranscription?.(message.text, true);
2087
- }
2088
- }, [elevenLabsOptions.onMessage]),
2089
- onError: react.useCallback((error) => {
2090
- setConversationState(prev => ({
2091
- ...prev,
2092
- connectionStatus: 'error',
2093
- isActive: false
2094
- }));
2095
- elevenLabsOptions.onError?.(error);
2096
- callbacksRef.current?.onError?.(error);
2097
- }, [elevenLabsOptions.onError]),
2098
- onAudio: react.useCallback((audio) => {
2099
- elevenLabsOptions.onAudio?.(audio);
2100
- callbacksRef.current?.onSpeechGenerated?.(audio.url);
2101
- }, [elevenLabsOptions.onAudio]),
2102
- };
2103
- // Initialize hook with enhanced callbacks
2104
- const elevenLabsHook = react$1.useConversation(enhancedCallbacks);
2105
- // Enhanced start session function
2106
- const startSession = react.useCallback(async (config) => {
2107
- const finalConfig = { ...sessionConfigRef.current, ...config };
2108
- try {
2109
- // Initialize SDK if needed and config is provided
2110
- let sdk = voiceSDK;
2111
- if (!sdk && finalConfig.sdkConfig) {
2112
- sdk = await initializeVoiceSDK(finalConfig.sdkConfig);
2113
- }
2114
- if (!sdk) {
2115
- throw new Error('VoiceSDK not initialized. Please provide sdkConfig.');
2116
- }
2117
- // Start SDK session first
2118
- const sessionId = await sdk.startVoiceConversation({
2119
- ...finalConfig,
2120
- callbacks: callbacksRef.current,
2121
- });
2122
- setCurrentSessionId(sessionId);
2123
- // Then start ElevenLabs session
2124
- const elevenLabsSessionId = await elevenLabsHook.startSession({
2125
- agentId: finalConfig.agentId,
2126
- ...finalConfig,
2127
- });
2128
- return sessionId; // Return our SDK session ID
2129
- }
2130
- catch (error) {
2131
- console.error('Failed to start voice session:', error);
2132
- throw error;
2133
- }
2134
- }, [voiceSDK, elevenLabsHook.startSession, initializeVoiceSDK]);
2135
- // Enhanced end session function
2136
- const endSession = react.useCallback(async () => {
2137
- try {
2138
- // End ElevenLabs session first
2139
- await elevenLabsHook.endSession();
2140
- // Then end SDK session
2141
- if (currentSessionId && voiceSDK) {
2142
- await voiceSDK.endVoiceSession(currentSessionId);
2143
- setCurrentSessionId(null);
2144
- }
2145
- }
2146
- catch (error) {
2147
- console.error('Failed to end voice session:', error);
2148
- throw error;
2149
- }
2150
- }, [currentSessionId, voiceSDK, elevenLabsHook.endSession]);
2151
- // Volume control with SDK integration
2152
- const setVolume = react.useCallback(({ volume }) => {
2153
- elevenLabsHook.setVolume({ volume });
2154
- setConversationState(prev => ({ ...prev, volume }));
2155
- if (currentSessionId && voiceSDK) {
2156
- voiceSDK.setVolume(currentSessionId, volume);
2157
- }
2158
- }, [currentSessionId, voiceSDK, elevenLabsHook.setVolume]);
2159
- // Audio data with SDK integration
2160
- const getInputByteFrequencyData = react.useCallback(() => {
2161
- const data = elevenLabsHook.getInputByteFrequencyData();
2162
- // Update conversation state with audio data
2163
- if (data && currentSessionId) {
2164
- setConversationState(prev => ({
2165
- ...prev,
2166
- audioData: {
2167
- ...prev.audioData,
2168
- inputFrequencyData: data,
2169
- }
2170
- }));
2171
- }
2172
- return data;
2173
- }, [currentSessionId, elevenLabsHook.getInputByteFrequencyData]);
2174
- const getOutputByteFrequencyData = react.useCallback(() => {
2175
- const data = elevenLabsHook.getOutputByteFrequencyData();
2176
- if (data && currentSessionId) {
2177
- setConversationState(prev => ({
2178
- ...prev,
2179
- audioData: {
2180
- ...prev.audioData,
2181
- outputFrequencyData: data,
2182
- }
2183
- }));
2184
- }
2185
- return data;
2186
- }, [currentSessionId, elevenLabsHook.getOutputByteFrequencyData]);
2187
- // Volume monitoring
2188
- const getInputVolume = react.useCallback(() => {
2189
- const volume = elevenLabsHook.getInputVolume();
2190
- if (currentSessionId) {
2191
- setConversationState(prev => ({
2192
- ...prev,
2193
- audioData: {
2194
- ...prev.audioData,
2195
- inputVolume: volume,
2196
- }
2197
- }));
2198
- }
2199
- return volume;
2200
- }, [currentSessionId, elevenLabsHook.getInputVolume]);
2201
- const getOutputVolume = react.useCallback(() => {
2202
- const volume = elevenLabsHook.getOutputVolume();
2203
- if (currentSessionId) {
2204
- setConversationState(prev => ({
2205
- ...prev,
2206
- audioData: {
2207
- ...prev.audioData,
2208
- outputVolume: volume,
2209
- }
2210
- }));
2211
- }
2212
- return volume;
2213
- }, [currentSessionId, elevenLabsHook.getOutputVolume]);
2214
- // Context and message sending with SDK integration
2215
- const sendContextualUpdate = react.useCallback((text) => {
2216
- elevenLabsHook.sendContextualUpdate(text);
2217
- if (currentSessionId && voiceSDK) {
2218
- voiceSDK.sendContextualUpdate(currentSessionId, text);
2219
- }
2220
- }, [currentSessionId, voiceSDK, elevenLabsHook.sendContextualUpdate]);
2221
- // SDK-specific methods
2222
- const getConversationHistory = react.useCallback(() => {
2223
- if (currentSessionId && voiceSDK) {
2224
- return voiceSDK.getConversationHistory(currentSessionId);
2225
- }
2226
- return [];
2227
- }, [currentSessionId, voiceSDK]);
2228
- const getVoiceState = react.useCallback(() => {
2229
- if (currentSessionId && voiceSDK) {
2230
- return voiceSDK.getVoiceState(currentSessionId);
2231
- }
2232
- return conversationState;
2233
- }, [currentSessionId, voiceSDK, conversationState]);
2234
- // Update isSpeaking state
2235
- react.useEffect(() => {
2236
- setConversationState(prev => ({
2237
- ...prev,
2238
- isSpeaking: elevenLabsHook.isSpeaking,
2239
- micMuted: elevenLabsHook.micMuted,
2240
- }));
2241
- }, [elevenLabsHook.isSpeaking, elevenLabsHook.micMuted]);
2242
- // Cleanup active sessions on unmount
2243
- react.useEffect(() => {
2244
- return () => {
2245
- if (voiceSDK) {
2246
- voiceSDK.getActiveSessions().forEach(session => {
2247
- voiceSDK.endVoiceSession(session.id);
2248
- });
2249
- }
2250
- };
2251
- }, [voiceSDK]);
2252
- return {
2253
- // Core session management
2254
- startSession,
2255
- endSession,
2256
- // Audio controls
2257
- setVolume,
2258
- getInputByteFrequencyData,
2259
- getOutputByteFrequencyData,
2260
- getInputVolume,
2261
- getOutputVolume,
2262
- // Communication
2263
- sendContextualUpdate,
2264
- sendUserMessage: elevenLabsHook.sendUserMessage,
2265
- sendUserActivity: elevenLabsHook.sendUserActivity,
2266
- sendMCPToolApprovalResult: elevenLabsHook.sendMCPToolApprovalResult,
2267
- // Feedback
2268
- sendFeedback: elevenLabsHook.sendFeedback,
2269
- canSendFeedback: elevenLabsHook.canSendFeedback,
2270
- // State
2271
- status: elevenLabsHook.status,
2272
- micMuted: elevenLabsHook.micMuted,
2273
- isSpeaking: elevenLabsHook.isSpeaking,
2274
- getId: elevenLabsHook.getId,
2275
- // SDK-specific features
2276
- currentSessionId,
2277
- conversationState,
2278
- getConversationHistory,
2279
- getVoiceState,
2280
- voiceSDK,
2281
- };
2282
- }
2283
-
2284
- Object.defineProperty(exports, 'postOverallFeedback', {
2285
- enumerable: true,
2286
- get: function () { return client.postOverallFeedback; }
2287
- });
2288
2028
  exports.BaseClient = BaseClient;
2029
+ exports.CLIENT_TURN_ID_HEADER = CLIENT_TURN_ID_HEADER;
2289
2030
  exports.ChatSDK = ChatSDK;
2031
+ exports.RESUMABLE_STREAM_HEADER = RESUMABLE_STREAM_HEADER;
2290
2032
  exports.SmartTablesSDK = SmartTablesSDK;
2033
+ exports.TURN_ID_HEADER = TURN_ID_HEADER;
2034
+ exports.TurnStreamLostError = TurnStreamLostError;
2291
2035
  exports.VoiceSDK = VoiceSDK;
2292
- exports.WorkflowSDK = WorkflowSDK;
2293
2036
  exports.default = ChatSDK;
2294
- exports.useVoiceConversation = useVoiceConversation;
2295
- //# sourceMappingURL=index.js.map
2037
+ exports.newClientTurnId = newClientTurnId;
2038
+ exports.postTurnWithRetry = postTurnWithRetry;
2039
+ exports.readResumableTurn = readResumableTurn;
2040
+ //# sourceMappingURL=index.cjs.map