@odin-ai/sdk 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +106 -249
- package/dist/{src/BaseClient.d.ts → BaseClient.d.cts} +21 -2
- package/dist/BaseClient.d.ts +15 -1
- package/dist/BaseClient.d.ts.map +1 -1
- package/dist/{src/ChatSDK.d.ts → ChatSDK.d.cts} +52 -5
- package/dist/ChatSDK.d.ts +49 -3
- package/dist/ChatSDK.d.ts.map +1 -1
- package/dist/{src/SmartTablesSDK.d.ts → SmartTablesSDK.d.cts} +115 -9
- package/dist/SmartTablesSDK.d.ts +29 -7
- package/dist/SmartTablesSDK.d.ts.map +1 -1
- package/dist/VoiceSDK.d.cts +72 -0
- package/dist/VoiceSDK.d.ts +2 -2
- package/dist/VoiceSDK.d.ts.map +1 -1
- package/dist/{index.js → index.cjs} +651 -906
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +11 -0
- package/dist/index.d.ts +11 -13
- package/dist/index.d.ts.map +1 -1
- package/dist/index.esm.js +644 -900
- package/dist/index.esm.js.map +1 -1
- package/dist/react.cjs +1737 -0
- package/dist/react.cjs.map +1 -0
- package/dist/react.d.cts +3 -0
- package/dist/react.d.ts +4 -0
- package/dist/react.d.ts.map +1 -0
- package/dist/react.esm.js +1731 -0
- package/dist/react.esm.js.map +1 -0
- package/dist/resumableTurnStream.d.cts +57 -0
- package/dist/resumableTurnStream.d.ts +58 -0
- package/dist/resumableTurnStream.d.ts.map +1 -0
- package/dist/{src/types.d.ts → types.d.cts} +109 -111
- package/dist/types.d.ts +89 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/useVoiceConversation.d.cts +33 -0
- package/dist/useVoiceConversation.d.ts +5 -5
- package/dist/useVoiceConversation.d.ts.map +1 -1
- package/dist/voice-types.d.cts +168 -0
- package/dist/voice-types.d.ts +7 -7
- package/dist/voice-types.d.ts.map +1 -1
- package/package.json +53 -26
- package/LICENSE +0 -21
- package/dist/WorkflowSDK.d.ts +0 -188
- package/dist/WorkflowSDK.d.ts.map +0 -1
- package/dist/examples/basic-chat.d.ts +0 -2
- package/dist/examples/basic-chat.d.ts.map +0 -1
- package/dist/examples/react-integration.d.ts +0 -7
- package/dist/examples/react-integration.d.ts.map +0 -1
- package/dist/examples/smart-tables-basic.d.ts +0 -2
- package/dist/examples/smart-tables-basic.d.ts.map +0 -1
- package/dist/examples/smart-tables-comprehensive.d.ts +0 -2
- package/dist/examples/smart-tables-comprehensive.d.ts.map +0 -1
- package/dist/examples/smart-tables-demo.d.ts +0 -2
- package/dist/examples/smart-tables-demo.d.ts.map +0 -1
- package/dist/examples/smart-tables-import.d.ts +0 -2
- package/dist/examples/smart-tables-import.d.ts.map +0 -1
- package/dist/examples/streaming-chat.d.ts +0 -2
- package/dist/examples/streaming-chat.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/src/BaseClient.d.ts.map +0 -1
- package/dist/src/ChatSDK.d.ts.map +0 -1
- package/dist/src/SmartTablesSDK.d.ts.map +0 -1
- package/dist/src/components/MessageBubble.d.ts +0 -24
- package/dist/src/components/MessageBubble.d.ts.map +0 -1
- package/dist/src/components/MessageList.d.ts +0 -28
- package/dist/src/components/MessageList.d.ts.map +0 -1
- package/dist/src/components/index.d.ts +0 -4
- package/dist/src/components/index.d.ts.map +0 -1
- package/dist/src/index.d.ts +0 -10
- package/dist/src/index.d.ts.map +0 -1
- package/dist/src/types.d.ts.map +0 -1
- package/dist/workflow-types.d.ts +0 -431
- package/dist/workflow-types.d.ts.map +0 -1
package/dist/index.esm.js
CHANGED
|
@@ -1,7 +1,32 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Picks a human-readable string out of a parsed error response body.
|
|
3
|
+
*
|
|
4
|
+
* FastAPI wraps every raised `HTTPException` as `{"detail": ...}`. `detail`
|
|
5
|
+
* is a plain string for most errors, but structured blocks -- notably the
|
|
6
|
+
* credit gate's 402 (`{code, limit_type, message, limit, used, ...}`) -- send
|
|
7
|
+
* an object instead. Interpolating that object into the error message with a
|
|
8
|
+
* template literal used to stringify it via `String(detail)`, producing
|
|
9
|
+
* "HTTP 402: [object Object]" instead of the actual message. Preferring
|
|
10
|
+
* `detail.message` when `detail` is an object keeps that readable; the raw
|
|
11
|
+
* object is still preserved on `APIError.detail` for callers that want to
|
|
12
|
+
* branch on `code`/`limit_type` (see `parseCreditLimitError`).
|
|
13
|
+
*/
|
|
14
|
+
function extractErrorMessage(errorData, fallback) {
|
|
15
|
+
if (!errorData || typeof errorData !== "object")
|
|
16
|
+
return fallback;
|
|
17
|
+
const data = errorData;
|
|
18
|
+
if (typeof data.message === "string")
|
|
19
|
+
return data.message;
|
|
20
|
+
const { detail } = data;
|
|
21
|
+
if (typeof detail === "string")
|
|
22
|
+
return detail;
|
|
23
|
+
if (detail && typeof detail === "object") {
|
|
24
|
+
const nested = detail.message;
|
|
25
|
+
if (typeof nested === "string")
|
|
26
|
+
return nested;
|
|
27
|
+
}
|
|
28
|
+
return fallback;
|
|
29
|
+
}
|
|
5
30
|
/**
|
|
6
31
|
* Generic HTTP client for AI Content Creator SDKs
|
|
7
32
|
*/
|
|
@@ -10,39 +35,47 @@ class BaseClient {
|
|
|
10
35
|
this.config = config;
|
|
11
36
|
// Wrap fetch in an arrow function to preserve the correct 'this' context
|
|
12
37
|
// This prevents "Illegal invocation" errors when fetch is called
|
|
13
|
-
this.customFetch =
|
|
38
|
+
this.customFetch =
|
|
39
|
+
config.customFetch ||
|
|
40
|
+
((...args) => fetch(...args));
|
|
14
41
|
// Validate authentication configuration
|
|
15
|
-
const hasAccessToken = config.accessToken && config.accessToken.trim() !==
|
|
16
|
-
const hasApiKeys = config.apiKey &&
|
|
17
|
-
config.
|
|
42
|
+
const hasAccessToken = config.accessToken && config.accessToken.trim() !== "";
|
|
43
|
+
const hasApiKeys = config.apiKey &&
|
|
44
|
+
config.apiSecret &&
|
|
45
|
+
config.apiKey.trim() !== "" &&
|
|
46
|
+
config.apiSecret.trim() !== "";
|
|
18
47
|
if (!hasAccessToken && !hasApiKeys) {
|
|
19
|
-
throw new Error(
|
|
48
|
+
throw new Error("Authentication required: Provide either accessToken (for web app) or both apiKey and apiSecret (for external SDK)");
|
|
20
49
|
}
|
|
21
50
|
if (hasAccessToken && hasApiKeys) {
|
|
22
|
-
console.warn(
|
|
51
|
+
console.warn("Both accessToken and API keys provided. Using accessToken for authentication.");
|
|
23
52
|
}
|
|
24
53
|
// Support both API key authentication and access token authentication
|
|
25
54
|
if (hasAccessToken) {
|
|
26
55
|
// Web app authentication using access token
|
|
27
56
|
this.headers = {
|
|
28
|
-
|
|
29
|
-
|
|
57
|
+
"Content-Type": "application/json",
|
|
58
|
+
"access-token": config.accessToken,
|
|
59
|
+
"X-Project-Id": config.projectId,
|
|
30
60
|
};
|
|
31
61
|
}
|
|
32
62
|
else {
|
|
33
63
|
// External SDK authentication using API keys
|
|
34
64
|
this.headers = {
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
65
|
+
"Content-Type": "application/json",
|
|
66
|
+
"X-API-KEY": config.apiKey,
|
|
67
|
+
"X-API-SECRET": config.apiSecret,
|
|
68
|
+
"X-Project-Id": config.projectId,
|
|
38
69
|
};
|
|
39
70
|
}
|
|
40
71
|
}
|
|
41
72
|
/**
|
|
42
73
|
* Make an HTTP request with proper error handling
|
|
43
74
|
*/
|
|
44
|
-
async makeRequest(endpoint, method =
|
|
45
|
-
const url = endpoint.startsWith(
|
|
75
|
+
async makeRequest(endpoint, method = "GET", body, customHeaders) {
|
|
76
|
+
const url = endpoint.startsWith("http")
|
|
77
|
+
? endpoint
|
|
78
|
+
: `${this.config.baseUrl}${endpoint}`;
|
|
46
79
|
const requestOptions = {
|
|
47
80
|
method,
|
|
48
81
|
headers: {
|
|
@@ -53,12 +86,13 @@ class BaseClient {
|
|
|
53
86
|
if (body) {
|
|
54
87
|
if (body instanceof FormData) {
|
|
55
88
|
// Remove Content-Type header for FormData - browser will set it automatically
|
|
56
|
-
const {
|
|
89
|
+
const { "Content-Type": _, ...headersWithoutContentType } = requestOptions.headers;
|
|
57
90
|
requestOptions.headers = headersWithoutContentType;
|
|
58
91
|
requestOptions.body = body;
|
|
59
92
|
}
|
|
60
93
|
else {
|
|
61
|
-
requestOptions.body =
|
|
94
|
+
requestOptions.body =
|
|
95
|
+
typeof body === "string" ? body : JSON.stringify(body);
|
|
62
96
|
}
|
|
63
97
|
}
|
|
64
98
|
const response = await this.customFetch(url, requestOptions);
|
|
@@ -66,8 +100,8 @@ class BaseClient {
|
|
|
66
100
|
await this.handleErrorResponse(response);
|
|
67
101
|
}
|
|
68
102
|
// Handle empty responses
|
|
69
|
-
const contentType = response.headers.get(
|
|
70
|
-
if (contentType && contentType.includes(
|
|
103
|
+
const contentType = response.headers.get("content-type");
|
|
104
|
+
if (contentType && contentType.includes("application/json")) {
|
|
71
105
|
return response.json();
|
|
72
106
|
}
|
|
73
107
|
return response.text();
|
|
@@ -76,35 +110,34 @@ class BaseClient {
|
|
|
76
110
|
* Make a GET request
|
|
77
111
|
*/
|
|
78
112
|
async get(endpoint, headers) {
|
|
79
|
-
return this.makeRequest(endpoint,
|
|
113
|
+
return this.makeRequest(endpoint, "GET", null, headers);
|
|
80
114
|
}
|
|
81
115
|
/**
|
|
82
116
|
* Make a POST request
|
|
83
117
|
*/
|
|
84
118
|
async post(endpoint, body, headers) {
|
|
85
|
-
return this.makeRequest(endpoint,
|
|
119
|
+
return this.makeRequest(endpoint, "POST", body, headers);
|
|
86
120
|
}
|
|
87
121
|
/**
|
|
88
122
|
* Make a PUT request
|
|
89
123
|
*/
|
|
90
124
|
async put(endpoint, body, headers) {
|
|
91
|
-
return this.makeRequest(endpoint,
|
|
125
|
+
return this.makeRequest(endpoint, "PUT", body, headers);
|
|
92
126
|
}
|
|
93
127
|
/**
|
|
94
128
|
* Make a DELETE request
|
|
95
129
|
*/
|
|
96
130
|
async delete(endpoint, body, headers) {
|
|
97
|
-
return this.makeRequest(endpoint,
|
|
131
|
+
return this.makeRequest(endpoint, "DELETE", body, headers);
|
|
98
132
|
}
|
|
99
133
|
/**
|
|
100
134
|
* Handle error responses from the API
|
|
101
135
|
*/
|
|
102
136
|
async handleErrorResponse(response) {
|
|
103
|
-
//
|
|
104
|
-
if (
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
detail: { status: response.status, url: response.url }
|
|
137
|
+
// Only 401 expires the session; 403 (permission denied) must surface to the caller.
|
|
138
|
+
if (response.status === 401 && typeof window !== "undefined") {
|
|
139
|
+
window.dispatchEvent(new CustomEvent("sessionExpired", {
|
|
140
|
+
detail: { status: response.status, url: response.url },
|
|
108
141
|
}));
|
|
109
142
|
}
|
|
110
143
|
const error = await this.createErrorFromResponse(response);
|
|
@@ -118,7 +151,7 @@ class BaseClient {
|
|
|
118
151
|
let errorDetail;
|
|
119
152
|
try {
|
|
120
153
|
const errorData = await response.json();
|
|
121
|
-
errorMessage = errorData
|
|
154
|
+
errorMessage = extractErrorMessage(errorData, errorMessage);
|
|
122
155
|
errorDetail = errorData?.detail;
|
|
123
156
|
}
|
|
124
157
|
catch (e) {
|
|
@@ -133,18 +166,262 @@ class BaseClient {
|
|
|
133
166
|
* Update the access token at runtime. Useful when the application's session token is refreshed.
|
|
134
167
|
*/
|
|
135
168
|
setAccessToken(newAccessToken) {
|
|
136
|
-
if (!newAccessToken || newAccessToken.trim() ===
|
|
169
|
+
if (!newAccessToken || newAccessToken.trim() === "") {
|
|
137
170
|
return;
|
|
138
171
|
}
|
|
139
172
|
this.config.accessToken = newAccessToken;
|
|
140
173
|
// Ensure header reflects the latest token
|
|
141
174
|
this.headers = {
|
|
142
175
|
...this.headers,
|
|
143
|
-
|
|
176
|
+
"access-token": newAccessToken,
|
|
144
177
|
};
|
|
145
178
|
}
|
|
146
179
|
}
|
|
147
180
|
|
|
181
|
+
/**
|
|
182
|
+
* Reader for a resumable chat turn stream (POST /v4/chat/message with
|
|
183
|
+
* `X-Odin-Resumable-Stream: 1`, or GET /v4/chat/message/{id}/stream).
|
|
184
|
+
*
|
|
185
|
+
* The server follows every frame with `<turn_seq>N</turn_seq>` and ends the
|
|
186
|
+
* turn with `<turn_complete>status</turn_complete>`. Only text up to a seq
|
|
187
|
+
* marker is a complete frame, so this reader forwards exactly those, in
|
|
188
|
+
* order, and never twice. When the connection drops or goes silent (the
|
|
189
|
+
* server sends a keepalive marker every 15s), it reconnects from the last
|
|
190
|
+
* seq it forwarded, so the caller sees one uninterrupted stream.
|
|
191
|
+
*
|
|
192
|
+
* A response without `X-Turn-Id` comes from a server that does not journal
|
|
193
|
+
* turns; it is passed through unchanged and cannot be resumed.
|
|
194
|
+
*/
|
|
195
|
+
const SEQ_OPEN = "<turn_seq>";
|
|
196
|
+
const SEQ_CLOSE = "</turn_seq>";
|
|
197
|
+
const COMPLETE_OPEN = "<turn_complete>";
|
|
198
|
+
const COMPLETE_CLOSE = "</turn_complete>";
|
|
199
|
+
const MARKER_RE = /<turn_seq>(\d+)<\/turn_seq>|<turn_complete>([^<]*)<\/turn_complete>/g;
|
|
200
|
+
/** Where a marker that may complete in a later read starts, or -1. */
|
|
201
|
+
const partialMarkerAt = (text) => {
|
|
202
|
+
// Complete markers are already removed, so any "<turn_" left is unfinished.
|
|
203
|
+
const open = text.lastIndexOf("<turn_");
|
|
204
|
+
if (open !== -1)
|
|
205
|
+
return open;
|
|
206
|
+
const lt = text.lastIndexOf("<");
|
|
207
|
+
if (lt === -1)
|
|
208
|
+
return -1;
|
|
209
|
+
const tail = text.slice(lt);
|
|
210
|
+
return SEQ_OPEN.startsWith(tail) || COMPLETE_OPEN.startsWith(tail) ? lt : -1;
|
|
211
|
+
};
|
|
212
|
+
const RESUMABLE_STREAM_HEADER = "X-Odin-Resumable-Stream";
|
|
213
|
+
const CLIENT_TURN_ID_HEADER = "X-Client-Turn-Id";
|
|
214
|
+
const TURN_ID_HEADER = "X-Turn-Id";
|
|
215
|
+
class TurnStreamLostError extends Error {
|
|
216
|
+
constructor(message, turnId, lastSeq) {
|
|
217
|
+
super(message);
|
|
218
|
+
this.turnId = turnId;
|
|
219
|
+
this.lastSeq = lastSeq;
|
|
220
|
+
this.name = "TurnStreamLostError";
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
const newClientTurnId = () => typeof crypto !== "undefined" && "randomUUID" in crypto
|
|
224
|
+
? crypto.randomUUID()
|
|
225
|
+
: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
226
|
+
const backoffMs = (attempt) => {
|
|
227
|
+
const base = Math.min(8000, 500 * 2 ** (attempt - 1));
|
|
228
|
+
return base / 2 + Math.random() * (base / 2);
|
|
229
|
+
};
|
|
230
|
+
const isAbort = (error) => error?.name === "AbortError";
|
|
231
|
+
const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
232
|
+
if (signal?.aborted) {
|
|
233
|
+
reject(new DOMException("Aborted", "AbortError"));
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
const timer = setTimeout(() => {
|
|
237
|
+
signal?.removeEventListener("abort", onAbort);
|
|
238
|
+
resolve();
|
|
239
|
+
}, ms);
|
|
240
|
+
const onAbort = () => {
|
|
241
|
+
clearTimeout(timer);
|
|
242
|
+
reject(new DOMException("Aborted", "AbortError"));
|
|
243
|
+
};
|
|
244
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
245
|
+
});
|
|
246
|
+
async function readResumableTurn(options) {
|
|
247
|
+
const { signal, onText, stallTimeoutMs = 45000, maxReconnects = 6, } = options;
|
|
248
|
+
const turnId = options.turnId ?? options.response.headers.get(TURN_ID_HEADER) ?? null;
|
|
249
|
+
let lastSeq = options.fromSeq ?? 0;
|
|
250
|
+
const pump = async (response) => {
|
|
251
|
+
const outcome = { status: null, progressed: false };
|
|
252
|
+
if (!response.body)
|
|
253
|
+
return outcome;
|
|
254
|
+
const reader = response.body.getReader();
|
|
255
|
+
const decoder = new TextDecoder("utf-8");
|
|
256
|
+
let buffer = "";
|
|
257
|
+
const drain = () => {
|
|
258
|
+
// eslint-disable-next-line no-constant-condition
|
|
259
|
+
while (true) {
|
|
260
|
+
const seqAt = buffer.indexOf(SEQ_OPEN);
|
|
261
|
+
const completeAt = buffer.indexOf(COMPLETE_OPEN);
|
|
262
|
+
if (seqAt === -1 && completeAt === -1)
|
|
263
|
+
return false;
|
|
264
|
+
if (completeAt !== -1 && (seqAt === -1 || completeAt < seqAt)) {
|
|
265
|
+
const end = buffer.indexOf(COMPLETE_CLOSE, completeAt);
|
|
266
|
+
if (end === -1)
|
|
267
|
+
return false;
|
|
268
|
+
const text = buffer.slice(0, completeAt);
|
|
269
|
+
if (text)
|
|
270
|
+
onText(text);
|
|
271
|
+
outcome.status = buffer
|
|
272
|
+
.slice(completeAt + COMPLETE_OPEN.length, end)
|
|
273
|
+
.trim();
|
|
274
|
+
return true;
|
|
275
|
+
}
|
|
276
|
+
const end = buffer.indexOf(SEQ_CLOSE, seqAt);
|
|
277
|
+
if (end === -1)
|
|
278
|
+
return false;
|
|
279
|
+
const seq = Number(buffer.slice(seqAt + SEQ_OPEN.length, end));
|
|
280
|
+
const text = buffer.slice(0, seqAt);
|
|
281
|
+
buffer = buffer.slice(end + SEQ_CLOSE.length);
|
|
282
|
+
if (seq > lastSeq) {
|
|
283
|
+
if (text)
|
|
284
|
+
onText(text);
|
|
285
|
+
lastSeq = seq;
|
|
286
|
+
outcome.progressed = true;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
try {
|
|
291
|
+
// eslint-disable-next-line no-constant-condition
|
|
292
|
+
while (true) {
|
|
293
|
+
let stallTimer;
|
|
294
|
+
const stalled = new Promise((resolve) => {
|
|
295
|
+
stallTimer = setTimeout(() => resolve("stalled"), stallTimeoutMs);
|
|
296
|
+
});
|
|
297
|
+
const result = await Promise.race([reader.read(), stalled]);
|
|
298
|
+
clearTimeout(stallTimer);
|
|
299
|
+
if (result === "stalled") {
|
|
300
|
+
reader.cancel().catch(() => undefined);
|
|
301
|
+
return outcome;
|
|
302
|
+
}
|
|
303
|
+
if (result.done)
|
|
304
|
+
return outcome;
|
|
305
|
+
options.onActivity?.();
|
|
306
|
+
buffer += decoder.decode(result.value, { stream: true });
|
|
307
|
+
if (drain()) {
|
|
308
|
+
reader.cancel().catch(() => undefined);
|
|
309
|
+
return outcome;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
catch (error) {
|
|
314
|
+
if (isAbort(error) || signal?.aborted)
|
|
315
|
+
throw error;
|
|
316
|
+
return outcome;
|
|
317
|
+
}
|
|
318
|
+
finally {
|
|
319
|
+
try {
|
|
320
|
+
reader.releaseLock();
|
|
321
|
+
}
|
|
322
|
+
catch {
|
|
323
|
+
// already released by cancel()
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
// Without a turn id (an old server, or a cross-site caller that cannot read
|
|
328
|
+
// the header) the stream cannot be resumed, but it may still carry markers.
|
|
329
|
+
const passthrough = async (response) => {
|
|
330
|
+
if (!response.body)
|
|
331
|
+
return null;
|
|
332
|
+
const reader = response.body.getReader();
|
|
333
|
+
const decoder = new TextDecoder("utf-8");
|
|
334
|
+
let buffer = "";
|
|
335
|
+
let status = null;
|
|
336
|
+
const flush = (final) => {
|
|
337
|
+
buffer = buffer.replace(MARKER_RE, (_match, _seq, complete) => {
|
|
338
|
+
if (complete !== undefined)
|
|
339
|
+
status = complete.trim();
|
|
340
|
+
return "";
|
|
341
|
+
});
|
|
342
|
+
// Hold back a tail that could be the start of a marker split across reads.
|
|
343
|
+
const held = final ? -1 : partialMarkerAt(buffer);
|
|
344
|
+
const out = held === -1 ? buffer : buffer.slice(0, held);
|
|
345
|
+
buffer = held === -1 ? "" : buffer.slice(held);
|
|
346
|
+
if (out)
|
|
347
|
+
onText(out);
|
|
348
|
+
};
|
|
349
|
+
try {
|
|
350
|
+
// eslint-disable-next-line no-constant-condition
|
|
351
|
+
while (true) {
|
|
352
|
+
const { done, value } = await reader.read();
|
|
353
|
+
if (done) {
|
|
354
|
+
flush(true);
|
|
355
|
+
return status;
|
|
356
|
+
}
|
|
357
|
+
options.onActivity?.();
|
|
358
|
+
buffer += decoder.decode(value, { stream: true });
|
|
359
|
+
flush(false);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
finally {
|
|
363
|
+
reader.releaseLock();
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
if (!turnId) {
|
|
367
|
+
const status = await passthrough(options.response);
|
|
368
|
+
return { status, turnId: null, lastSeq };
|
|
369
|
+
}
|
|
370
|
+
let response = options.response;
|
|
371
|
+
let failures = 0;
|
|
372
|
+
// eslint-disable-next-line no-constant-condition
|
|
373
|
+
while (true) {
|
|
374
|
+
if (response) {
|
|
375
|
+
const outcome = await pump(response);
|
|
376
|
+
if (outcome.status)
|
|
377
|
+
return { status: outcome.status, turnId, lastSeq };
|
|
378
|
+
if (outcome.progressed)
|
|
379
|
+
failures = 0;
|
|
380
|
+
}
|
|
381
|
+
if (signal?.aborted)
|
|
382
|
+
throw new DOMException("Aborted", "AbortError");
|
|
383
|
+
failures += 1;
|
|
384
|
+
if (failures > maxReconnects) {
|
|
385
|
+
throw new TurnStreamLostError("Lost the connection to this response and could not reconnect.", turnId, lastSeq);
|
|
386
|
+
}
|
|
387
|
+
await sleep(backoffMs(failures), signal);
|
|
388
|
+
options.onReconnect?.(failures, lastSeq);
|
|
389
|
+
try {
|
|
390
|
+
response = await options.resume(turnId, lastSeq, signal);
|
|
391
|
+
}
|
|
392
|
+
catch (error) {
|
|
393
|
+
if (isAbort(error) || signal?.aborted)
|
|
394
|
+
throw error;
|
|
395
|
+
response = null;
|
|
396
|
+
continue;
|
|
397
|
+
}
|
|
398
|
+
if (response.status === 404) {
|
|
399
|
+
throw new TurnStreamLostError("This response can no longer be resumed.", turnId, lastSeq);
|
|
400
|
+
}
|
|
401
|
+
if (!response.ok)
|
|
402
|
+
response = null;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* POST a turn, retrying network failures with the same client turn id so the
|
|
407
|
+
* server attaches the retry to the turn the first attempt started.
|
|
408
|
+
*/
|
|
409
|
+
async function postTurnWithRetry(send, options = {}) {
|
|
410
|
+
const clientTurnId = options.clientTurnId || newClientTurnId();
|
|
411
|
+
const attempts = options.attempts ?? 3;
|
|
412
|
+
for (let attempt = 1;; attempt++) {
|
|
413
|
+
try {
|
|
414
|
+
return await send(clientTurnId);
|
|
415
|
+
}
|
|
416
|
+
catch (error) {
|
|
417
|
+
if (isAbort(error) || options.signal?.aborted || attempt >= attempts) {
|
|
418
|
+
throw error;
|
|
419
|
+
}
|
|
420
|
+
await sleep(backoffMs(attempt), options.signal);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
148
425
|
/**
|
|
149
426
|
* Main SDK class for interacting with the AI Content Creator chat system
|
|
150
427
|
*/
|
|
@@ -160,6 +437,14 @@ class ChatSDK extends BaseClient {
|
|
|
160
437
|
this.messageInitObject = null;
|
|
161
438
|
this.actionsMap = new Map();
|
|
162
439
|
this.hasCalledOnStart = false;
|
|
440
|
+
/** Unfinished tag payload from the previous TCP chunk (JSON split across reads). */
|
|
441
|
+
this.streamTagRemainder = "";
|
|
442
|
+
}
|
|
443
|
+
/**
|
|
444
|
+
* Get the project ID this SDK is configured for (for use when building requests elsewhere)
|
|
445
|
+
*/
|
|
446
|
+
getProjectId() {
|
|
447
|
+
return this.config.projectId;
|
|
163
448
|
}
|
|
164
449
|
/**
|
|
165
450
|
* Create a new chat in the project
|
|
@@ -187,6 +472,46 @@ class ChatSDK extends BaseClient {
|
|
|
187
472
|
});
|
|
188
473
|
return await this.get(`project/${this.config.projectId}/chat?${params}`);
|
|
189
474
|
}
|
|
475
|
+
/**
|
|
476
|
+
* Like `listChats`, but revalidates a page the caller already holds.
|
|
477
|
+
*
|
|
478
|
+
* Pass the `etag` from the last response for the same cursor and limit. The
|
|
479
|
+
* server answers 304 when the page has not changed, and then there is no
|
|
480
|
+
* body to parse: `notModified` is true and the caller keeps its copy.
|
|
481
|
+
* @returns The fresh page with its ETag, or `notModified: true`
|
|
482
|
+
*/
|
|
483
|
+
async listChatsIfChanged(cursor, limit = 30, etag) {
|
|
484
|
+
const params = new URLSearchParams({
|
|
485
|
+
limit: Math.min(limit, 100).toString(),
|
|
486
|
+
...(cursor && { cursor: cursor.toString() }),
|
|
487
|
+
});
|
|
488
|
+
const headers = { ...this.headers };
|
|
489
|
+
if (etag)
|
|
490
|
+
headers["If-None-Match"] = etag;
|
|
491
|
+
const response = await this.customFetch(`${this.config.baseUrl}project/${this.config.projectId}/chat?${params}`, { method: "GET", headers });
|
|
492
|
+
if (response.status === 304)
|
|
493
|
+
return { notModified: true };
|
|
494
|
+
if (!response.ok)
|
|
495
|
+
await this.handleErrorResponse(response);
|
|
496
|
+
return {
|
|
497
|
+
notModified: false,
|
|
498
|
+
data: (await response.json()),
|
|
499
|
+
etag: response.headers.get("etag"),
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Chats in the project with a turn running right now.
|
|
504
|
+
*
|
|
505
|
+
* Unlike the session list a client builds up locally, this includes turns
|
|
506
|
+
* started in another tab or device, or before a reload -- a turn's life is
|
|
507
|
+
* server-side, so this is the only way a client
|
|
508
|
+
* can tell. Poll it only while something is running.
|
|
509
|
+
* @returns Promise resolving to the running chats
|
|
510
|
+
*/
|
|
511
|
+
async listRunningChats() {
|
|
512
|
+
const response = await this.get(`v4/chat/turns/running?project_id=${encodeURIComponent(this.config.projectId)}`);
|
|
513
|
+
return response ?? { chats: [] };
|
|
514
|
+
}
|
|
190
515
|
/**
|
|
191
516
|
* Get a specific chat with its message history
|
|
192
517
|
* @param chatId The ID of the chat to retrieve
|
|
@@ -219,6 +544,19 @@ class ChatSDK extends BaseClient {
|
|
|
219
544
|
title: newName,
|
|
220
545
|
});
|
|
221
546
|
}
|
|
547
|
+
/** Get the current user's starred chat IDs for this project. */
|
|
548
|
+
async listStarredChatIds() {
|
|
549
|
+
const response = await this.get(`project/${this.config.projectId}/chat/stars`);
|
|
550
|
+
return Array.isArray(response?.chat_ids) ? response.chat_ids : [];
|
|
551
|
+
}
|
|
552
|
+
/** Star or unstar a chat for the current user. */
|
|
553
|
+
async setChatStarred(chatId, starred) {
|
|
554
|
+
await this.post("chat/star", {
|
|
555
|
+
project_id: this.config.projectId,
|
|
556
|
+
chat_id: chatId,
|
|
557
|
+
starred,
|
|
558
|
+
});
|
|
559
|
+
}
|
|
222
560
|
/**
|
|
223
561
|
* Send a message and get the response
|
|
224
562
|
* @param message The message text to send
|
|
@@ -237,7 +575,9 @@ class ChatSDK extends BaseClient {
|
|
|
237
575
|
agent_type: options.agentType || "chat_agent",
|
|
238
576
|
agent_id: options.agentId,
|
|
239
577
|
document_keys: documentKeysString,
|
|
240
|
-
|
|
578
|
+
// No fallback model: the agent resolves its own, and inventing one here
|
|
579
|
+
// only mislabelled the audit record.
|
|
580
|
+
model_name: options.modelName,
|
|
241
581
|
use_knowledgebase: options.useKnowledgebase ?? true,
|
|
242
582
|
is_test: options.isTest ?? false,
|
|
243
583
|
google_search: options.googleSearch ?? false,
|
|
@@ -276,66 +616,139 @@ class ChatSDK extends BaseClient {
|
|
|
276
616
|
}, {});
|
|
277
617
|
formData.append("multipart_document_keys", JSON.stringify(_documentKeys));
|
|
278
618
|
}
|
|
279
|
-
|
|
280
|
-
|
|
619
|
+
// Send an empty selection explicitly rather than omitting the field. The
|
|
620
|
+
// caller passes undefined when the agent has a single knowledge base (there
|
|
621
|
+
// is nothing to choose between) and an array when it has several, so an
|
|
622
|
+
// empty array means the user switched every one off. Dropping it here made
|
|
623
|
+
// that indistinguishable from "no selection sent", and the backend resolves
|
|
624
|
+
// those two cases differently: absent falls back to the agent's configured
|
|
625
|
+
// knowledge bases, whereas [] now searches none of them.
|
|
626
|
+
if (options.activeKnowledgeBases !== undefined) {
|
|
281
627
|
const activeKbJson = JSON.stringify(options.activeKnowledgeBases);
|
|
282
628
|
formData.append("active_knowledgebases", activeKbJson);
|
|
283
629
|
}
|
|
284
|
-
if (options.images) {
|
|
630
|
+
if (options.images && options.images.length > 0) {
|
|
285
631
|
options.images.forEach((image) => {
|
|
286
|
-
|
|
632
|
+
const file = image instanceof File
|
|
633
|
+
? image
|
|
634
|
+
: new File([image], "image.png", {
|
|
635
|
+
type: image.type || "image/png",
|
|
636
|
+
});
|
|
637
|
+
formData.append("images", file, file.name || "image.png");
|
|
287
638
|
});
|
|
288
639
|
}
|
|
289
|
-
|
|
290
|
-
|
|
640
|
+
const mergedMetadata = { ...(options.metadata || {}) };
|
|
641
|
+
if (options.targetProjectId) {
|
|
642
|
+
mergedMetadata.target_project_id = options.targetProjectId;
|
|
643
|
+
}
|
|
644
|
+
if (Object.keys(mergedMetadata).length > 0) {
|
|
645
|
+
formData.append("request_metadata", JSON.stringify(mergedMetadata));
|
|
291
646
|
}
|
|
292
647
|
formData.append("use_knowledgebase", String(options.useKnowledgebase ?? true));
|
|
293
648
|
formData.append("is_test", String(options.isTest ?? false));
|
|
294
649
|
formData.append("google_search", String(options.googleSearch ?? false));
|
|
295
650
|
formData.append("format_instructions", options.formatInstructions || "normal");
|
|
296
651
|
formData.append("ignore_chat_history", String(options.ignoreChatHistory ?? false));
|
|
652
|
+
if (options.environment) {
|
|
653
|
+
formData.append("environment", options.environment);
|
|
654
|
+
}
|
|
297
655
|
if (options.exampleJson) {
|
|
298
656
|
formData.append("example_json", options.exampleJson);
|
|
299
657
|
}
|
|
300
|
-
// Use customFetch for streaming (defaults to native fetch if not provided)
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
658
|
+
// Use customFetch for streaming (defaults to native fetch if not provided).
|
|
659
|
+
// A network failure before the response is retried with the same client
|
|
660
|
+
// turn id, which the server attaches to the turn already started.
|
|
661
|
+
let response;
|
|
662
|
+
try {
|
|
663
|
+
response = await postTurnWithRetry((clientTurnId) => this.customFetch(`${this.config.baseUrl}v4/chat/message`, {
|
|
664
|
+
method: "POST",
|
|
665
|
+
headers: {
|
|
666
|
+
...this.streamHeaders(),
|
|
667
|
+
[RESUMABLE_STREAM_HEADER]: "1",
|
|
668
|
+
[CLIENT_TURN_ID_HEADER]: clientTurnId,
|
|
669
|
+
},
|
|
670
|
+
body: formData,
|
|
671
|
+
signal: options.signal,
|
|
672
|
+
}), { signal: options.signal, clientTurnId: options.clientTurnId });
|
|
673
|
+
}
|
|
674
|
+
catch (error) {
|
|
675
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
676
|
+
options.onError?.(err);
|
|
677
|
+
throw err;
|
|
678
|
+
}
|
|
310
679
|
if (!response.ok) {
|
|
311
680
|
const error = await this.createErrorFromResponse(response);
|
|
312
681
|
options.onError?.(error);
|
|
313
682
|
throw error;
|
|
314
683
|
}
|
|
684
|
+
options.onResponseAccepted?.();
|
|
685
|
+
await this.consumeTurnStream(response, options);
|
|
686
|
+
}
|
|
687
|
+
/**
|
|
688
|
+
* Status of a streamed turn, so a reloaded page can reattach to one still
|
|
689
|
+
* running. Resolves to null once the turn is no longer resumable.
|
|
690
|
+
*/
|
|
691
|
+
async getTurnStatus(messageId) {
|
|
692
|
+
try {
|
|
693
|
+
return await this.get(`v4/chat/message/${encodeURIComponent(messageId)}/turn?project_id=${encodeURIComponent(this.config.projectId)}`);
|
|
694
|
+
}
|
|
695
|
+
catch (error) {
|
|
696
|
+
if (error?.status === 404)
|
|
697
|
+
return null;
|
|
698
|
+
throw error;
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
/**
|
|
702
|
+
* Reattach to a turn (e.g. after a page reload) and stream it from the
|
|
703
|
+
* start, with the same callbacks as `sendMessageStream`.
|
|
704
|
+
*/
|
|
705
|
+
async resumeTurnStream(messageId, options = {}) {
|
|
706
|
+
const response = await this.openTurnStream(messageId, 0, options.signal);
|
|
707
|
+
if (!response.ok) {
|
|
708
|
+
const error = await this.createErrorFromResponse(response);
|
|
709
|
+
options.onError?.(error);
|
|
710
|
+
throw error;
|
|
711
|
+
}
|
|
712
|
+
await this.consumeTurnStream(response, options, messageId);
|
|
713
|
+
}
|
|
714
|
+
streamHeaders() {
|
|
715
|
+
// Don't set Content-Type for FormData - browser will set it with boundary
|
|
716
|
+
return Object.fromEntries(Object.entries(this.headers).filter(([key]) => key !== "Content-Type"));
|
|
717
|
+
}
|
|
718
|
+
openTurnStream(messageId, fromSeq, signal) {
|
|
719
|
+
const query = new URLSearchParams({
|
|
720
|
+
project_id: this.config.projectId,
|
|
721
|
+
from_seq: String(fromSeq),
|
|
722
|
+
});
|
|
723
|
+
return this.customFetch(`${this.config.baseUrl}v4/chat/message/${encodeURIComponent(messageId)}/stream?${query.toString()}`, { method: "GET", headers: this.streamHeaders(), signal });
|
|
724
|
+
}
|
|
725
|
+
async consumeTurnStream(response, options, turnId) {
|
|
315
726
|
if (!response.body) {
|
|
316
727
|
const error = new Error("ReadableStream not supported in this environment");
|
|
317
728
|
options.onError?.(error);
|
|
318
729
|
throw error;
|
|
319
730
|
}
|
|
320
|
-
const reader = response.body.getReader();
|
|
321
|
-
const decoder = new TextDecoder("utf-8");
|
|
322
731
|
// Reset streaming state for new message
|
|
323
732
|
this.resetStreamingState();
|
|
324
733
|
try {
|
|
325
734
|
let messageObject = {};
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
}
|
|
735
|
+
const { status } = await readResumableTurn({
|
|
736
|
+
response,
|
|
737
|
+
turnId,
|
|
738
|
+
signal: options.signal,
|
|
739
|
+
resume: (id, fromSeq, signal) => this.openTurnStream(id, fromSeq, signal),
|
|
740
|
+
onReconnect: options.onReconnect,
|
|
741
|
+
onActivity: options.onActivity,
|
|
742
|
+
onText: (chunk) => {
|
|
743
|
+
const parsedData = this.parseStreamChunk(chunk, options);
|
|
744
|
+
if (parsedData.messageObject) {
|
|
745
|
+
messageObject = { ...messageObject, ...parsedData.messageObject };
|
|
746
|
+
}
|
|
747
|
+
},
|
|
748
|
+
});
|
|
749
|
+
if (status) {
|
|
750
|
+
const resumedBy = this.messageInitObject?.mi?.resumed_by;
|
|
751
|
+
options.onTurnStatus?.(status, typeof resumedBy === "string" && resumedBy ? { resumedBy } : undefined);
|
|
339
752
|
}
|
|
340
753
|
// Call completion callback with final message
|
|
341
754
|
if (options.onComplete) {
|
|
@@ -355,9 +768,6 @@ class ChatSDK extends BaseClient {
|
|
|
355
768
|
options.onError?.(err);
|
|
356
769
|
throw err;
|
|
357
770
|
}
|
|
358
|
-
finally {
|
|
359
|
-
reader.releaseLock();
|
|
360
|
-
}
|
|
361
771
|
}
|
|
362
772
|
/**
|
|
363
773
|
* Send user feedback for a message
|
|
@@ -384,6 +794,7 @@ class ChatSDK extends BaseClient {
|
|
|
384
794
|
this.messageInitObject = null;
|
|
385
795
|
this.actionsMap.clear();
|
|
386
796
|
this.hasCalledOnStart = false;
|
|
797
|
+
this.streamTagRemainder = "";
|
|
387
798
|
}
|
|
388
799
|
/**
|
|
389
800
|
* Parse streaming response chunks and trigger appropriate callbacks
|
|
@@ -392,7 +803,8 @@ class ChatSDK extends BaseClient {
|
|
|
392
803
|
parseStreamChunk(chunk, callbacks) {
|
|
393
804
|
let messageObject;
|
|
394
805
|
try {
|
|
395
|
-
let modifiedChunk = chunk;
|
|
806
|
+
let modifiedChunk = this.streamTagRemainder + chunk;
|
|
807
|
+
this.streamTagRemainder = "";
|
|
396
808
|
/**
|
|
397
809
|
* List of tags used to parse streaming response chunks.
|
|
398
810
|
* These tags act as delimiters in the streaming response, allowing the backend
|
|
@@ -409,6 +821,8 @@ class ChatSDK extends BaseClient {
|
|
|
409
821
|
* - sql: SQL query data - SQL query information as JSON
|
|
410
822
|
* - document_event: Document event notifications - events related to document processing
|
|
411
823
|
* - meta: Message identity - provides chat_id and message_id for precise updates
|
|
824
|
+
* - msg_discard: Take back streamed text - a model call that failed partway
|
|
825
|
+
* is being retried, so its partial text ({"text": ...}) must be removed
|
|
412
826
|
*/
|
|
413
827
|
const tags = [
|
|
414
828
|
"msg_chunk",
|
|
@@ -421,7 +835,19 @@ class ChatSDK extends BaseClient {
|
|
|
421
835
|
"sql",
|
|
422
836
|
"document_event",
|
|
423
837
|
"meta",
|
|
838
|
+
"msg_discard",
|
|
424
839
|
];
|
|
840
|
+
const jsonPayloadTags = new Set([
|
|
841
|
+
"mi",
|
|
842
|
+
"msg_object",
|
|
843
|
+
"ui_form",
|
|
844
|
+
"ma",
|
|
845
|
+
"meta",
|
|
846
|
+
"msmro",
|
|
847
|
+
"sql",
|
|
848
|
+
"document_event",
|
|
849
|
+
"msg_discard",
|
|
850
|
+
]);
|
|
425
851
|
// Process the chunk as long as it contains tags
|
|
426
852
|
let stillHasTags = true;
|
|
427
853
|
while (stillHasTags) {
|
|
@@ -437,6 +863,12 @@ class ChatSDK extends BaseClient {
|
|
|
437
863
|
firstTag = tag;
|
|
438
864
|
}
|
|
439
865
|
}
|
|
866
|
+
if (firstTagIndex === -1) {
|
|
867
|
+
if (modifiedChunk.length > 0) {
|
|
868
|
+
this.streamTagRemainder = modifiedChunk;
|
|
869
|
+
}
|
|
870
|
+
break;
|
|
871
|
+
}
|
|
440
872
|
// If a tag was found, process it
|
|
441
873
|
if (firstTagIndex !== -1) {
|
|
442
874
|
stillHasTags = true;
|
|
@@ -457,14 +889,61 @@ class ChatSDK extends BaseClient {
|
|
|
457
889
|
const content = nextTagIndex !== -1
|
|
458
890
|
? afterTagStart.substring(0, nextTagIndex)
|
|
459
891
|
: afterTagStart;
|
|
892
|
+
if (jsonPayloadTags.has(firstTag) && nextTagIndex === -1) {
|
|
893
|
+
try {
|
|
894
|
+
JSON.parse(content.trim());
|
|
895
|
+
}
|
|
896
|
+
catch {
|
|
897
|
+
this.streamTagRemainder = modifiedChunk.substring(tagStartIndex);
|
|
898
|
+
break;
|
|
899
|
+
}
|
|
900
|
+
}
|
|
460
901
|
// Process the content based on the tag
|
|
461
902
|
switch (firstTag) {
|
|
462
903
|
case "msg_chunk":
|
|
463
904
|
this.messageChunkString += content;
|
|
464
905
|
callbacks.onChunk?.(content);
|
|
465
906
|
break;
|
|
907
|
+
case "msg_discard":
|
|
908
|
+
try {
|
|
909
|
+
const { text } = JSON.parse(content.trim());
|
|
910
|
+
if (typeof text === "string" &&
|
|
911
|
+
text &&
|
|
912
|
+
this.messageChunkString.endsWith(text)) {
|
|
913
|
+
this.messageChunkString = this.messageChunkString.slice(0, -text.length);
|
|
914
|
+
callbacks.onDiscard?.(text);
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
catch (error) {
|
|
918
|
+
console.error("Error parsing msg_discard:", error);
|
|
919
|
+
}
|
|
920
|
+
break;
|
|
466
921
|
case "msmro":
|
|
467
|
-
|
|
922
|
+
try {
|
|
923
|
+
const parsed = JSON.parse(content.trim());
|
|
924
|
+
if (parsed.message) {
|
|
925
|
+
this.messageInitObject = {
|
|
926
|
+
...this.messageInitObject,
|
|
927
|
+
mi: {
|
|
928
|
+
...(this.messageInitObject?.mi || {}),
|
|
929
|
+
...parsed.message,
|
|
930
|
+
},
|
|
931
|
+
msg_object: {
|
|
932
|
+
...(this.messageInitObject?.msg_object || {}),
|
|
933
|
+
...parsed.message,
|
|
934
|
+
},
|
|
935
|
+
};
|
|
936
|
+
messageObject = {
|
|
937
|
+
...messageObject,
|
|
938
|
+
...parsed.message,
|
|
939
|
+
...(parsed.chat_id && { chat_id: parsed.chat_id }),
|
|
940
|
+
...(parsed.message_id && { message_id: parsed.message_id }),
|
|
941
|
+
};
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
catch {
|
|
945
|
+
// msmro may not always contain valid JSON
|
|
946
|
+
}
|
|
468
947
|
callbacks.onMessageEnd?.();
|
|
469
948
|
break;
|
|
470
949
|
case "meta":
|
|
@@ -621,10 +1100,8 @@ class ChatSDK extends BaseClient {
|
|
|
621
1100
|
* @private
|
|
622
1101
|
*/
|
|
623
1102
|
async createErrorFromResponse(response) {
|
|
624
|
-
//
|
|
625
|
-
if (
|
|
626
|
-
typeof window !== "undefined") {
|
|
627
|
-
// Dispatch custom event immediately for session expiration
|
|
1103
|
+
// Only 401 expires the session; 403 (permission denied) must surface to the caller.
|
|
1104
|
+
if (response.status === 401 && typeof window !== "undefined") {
|
|
628
1105
|
window.dispatchEvent(new CustomEvent("sessionExpired", {
|
|
629
1106
|
detail: { status: response.status, url: response.url },
|
|
630
1107
|
}));
|
|
@@ -633,13 +1110,20 @@ class ChatSDK extends BaseClient {
|
|
|
633
1110
|
let errorDetail;
|
|
634
1111
|
try {
|
|
635
1112
|
const errorData = await response.json();
|
|
636
|
-
errorMessage = errorData
|
|
1113
|
+
errorMessage = extractErrorMessage(errorData, errorMessage);
|
|
637
1114
|
errorDetail = errorData?.detail;
|
|
638
1115
|
}
|
|
639
1116
|
catch (e) {
|
|
640
1117
|
// If we can't parse the error response, use the status text
|
|
641
1118
|
}
|
|
642
1119
|
const error = new Error(`HTTP ${response.status}: ${errorMessage}`);
|
|
1120
|
+
const issueDiagnostic = response[Symbol.for("odin.issueDiagnostic")];
|
|
1121
|
+
if (issueDiagnostic) {
|
|
1122
|
+
Object.defineProperty(error, Symbol.for("odin.issueDiagnostic"), {
|
|
1123
|
+
configurable: true,
|
|
1124
|
+
value: issueDiagnostic,
|
|
1125
|
+
});
|
|
1126
|
+
}
|
|
643
1127
|
error.status = response.status;
|
|
644
1128
|
error.detail = errorDetail;
|
|
645
1129
|
return error;
|
|
@@ -679,33 +1163,10 @@ class SmartTablesSDK extends BaseClient {
|
|
|
679
1163
|
return await this.delete(`project/${project_id}/data-types/${data_type_id}`);
|
|
680
1164
|
}
|
|
681
1165
|
async getKbDataTypeForView(project_id, data_type_id, filters = [], pagination) {
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
queryParams.append(filter.column, String(filter.value));
|
|
687
|
-
});
|
|
688
|
-
}
|
|
689
|
-
// Add pagination parameters
|
|
690
|
-
if (pagination) {
|
|
691
|
-
if (pagination.page !== undefined) {
|
|
692
|
-
queryParams.append("page", pagination.page.toString());
|
|
693
|
-
}
|
|
694
|
-
if (pagination.limit !== undefined) {
|
|
695
|
-
queryParams.append("limit", pagination.limit.toString());
|
|
696
|
-
}
|
|
697
|
-
if (pagination.search) {
|
|
698
|
-
queryParams.append("search", pagination.search);
|
|
699
|
-
}
|
|
700
|
-
if (pagination.sort_column) {
|
|
701
|
-
queryParams.append("sort_column", pagination.sort_column);
|
|
702
|
-
}
|
|
703
|
-
if (pagination.sort_direction) {
|
|
704
|
-
queryParams.append("sort_direction", pagination.sort_direction);
|
|
705
|
-
}
|
|
706
|
-
}
|
|
707
|
-
const endpoint = `project/${project_id}/data-types/${data_type_id}/view${queryParams.toString() ? "?" + queryParams.toString() : ""}`;
|
|
708
|
-
return await this.get(endpoint);
|
|
1166
|
+
return await this.post(`project/${project_id}/data-types/${data_type_id}/view`, {
|
|
1167
|
+
filters,
|
|
1168
|
+
pagination,
|
|
1169
|
+
});
|
|
709
1170
|
}
|
|
710
1171
|
async addDataTypeRow(projectId, dataTypeId, metadata = {}) {
|
|
711
1172
|
return await this.post(`project/${projectId}/data-type/${dataTypeId}/row`, {
|
|
@@ -751,34 +1212,40 @@ class SmartTablesSDK extends BaseClient {
|
|
|
751
1212
|
async getDataTypeExampleJson(project_id, data_type_id) {
|
|
752
1213
|
return await this.get(`project/${project_id}/data-types/${data_type_id}/json`);
|
|
753
1214
|
}
|
|
754
|
-
async importSmartTable(projectId, title, description, columnMappings, file) {
|
|
1215
|
+
async importSmartTable(projectId, title, description, columnMappings, file, needsDecryption) {
|
|
755
1216
|
const formData = new FormData();
|
|
756
1217
|
formData.append("title", title);
|
|
757
1218
|
formData.append("description", description);
|
|
758
1219
|
formData.append("column_mappings", JSON.stringify(columnMappings));
|
|
759
1220
|
formData.append("file", file);
|
|
1221
|
+
if (needsDecryption) {
|
|
1222
|
+
formData.append("needs_decryption", "true");
|
|
1223
|
+
}
|
|
760
1224
|
try {
|
|
761
1225
|
return await this.post(`project/${projectId}/import-table`, formData);
|
|
762
1226
|
}
|
|
763
1227
|
catch (error) {
|
|
764
1228
|
// Extract the detailed error message if available
|
|
765
1229
|
let errorMessage = "Failed to import table";
|
|
766
|
-
if (typeof error ===
|
|
1230
|
+
if (typeof error === "object" && error !== null) {
|
|
767
1231
|
// Try to extract the detail field which often contains the specific error
|
|
768
|
-
if (
|
|
1232
|
+
if ("detail" in error && typeof error.detail === "string") {
|
|
769
1233
|
errorMessage = error.detail;
|
|
770
1234
|
}
|
|
771
|
-
else if (
|
|
1235
|
+
else if ("message" in error && typeof error.message === "string") {
|
|
772
1236
|
errorMessage = error.message;
|
|
773
1237
|
}
|
|
774
1238
|
else {
|
|
775
1239
|
// Try to find any error-related fields
|
|
776
1240
|
const errorStr = JSON.stringify(error);
|
|
777
|
-
if (errorStr.includes(
|
|
778
|
-
|
|
1241
|
+
if (errorStr.includes("InvalidDatetimeFormat") ||
|
|
1242
|
+
errorStr.includes("invalid input syntax")) {
|
|
1243
|
+
errorMessage =
|
|
1244
|
+
"Data type mismatch: One or more values don't match the column data type. Check for date/time format issues.";
|
|
779
1245
|
}
|
|
780
|
-
else if (errorStr.includes(
|
|
781
|
-
errorMessage =
|
|
1246
|
+
else if (errorStr.includes("duplicate key value")) {
|
|
1247
|
+
errorMessage =
|
|
1248
|
+
"Duplicate key error: The table already contains some of these records.";
|
|
782
1249
|
}
|
|
783
1250
|
}
|
|
784
1251
|
}
|
|
@@ -841,7 +1308,7 @@ class SmartTablesSDK extends BaseClient {
|
|
|
841
1308
|
project_id: this.config.projectId,
|
|
842
1309
|
data_type_id: tableId,
|
|
843
1310
|
title,
|
|
844
|
-
description: description ||
|
|
1311
|
+
description: description || "",
|
|
845
1312
|
metadata,
|
|
846
1313
|
});
|
|
847
1314
|
}
|
|
@@ -863,7 +1330,7 @@ class SmartTablesSDK extends BaseClient {
|
|
|
863
1330
|
async queryTable(tableId, options = {}) {
|
|
864
1331
|
const fullInfo = await this.getTableFullInfo(tableId, options);
|
|
865
1332
|
// Debug logging to understand response structure
|
|
866
|
-
console.log(
|
|
1333
|
+
console.log("🔍 SDK queryTable response:", {
|
|
867
1334
|
hasDataView: !!fullInfo.data_view,
|
|
868
1335
|
dataViewLength: fullInfo.data_view?.length || 0,
|
|
869
1336
|
hasTotalCount: !!fullInfo.total_count,
|
|
@@ -891,7 +1358,7 @@ class SmartTablesSDK extends BaseClient {
|
|
|
891
1358
|
dataTypeId: tableId,
|
|
892
1359
|
columnName: column.name,
|
|
893
1360
|
columnType: column.type,
|
|
894
|
-
description: column.description ||
|
|
1361
|
+
description: column.description || "",
|
|
895
1362
|
options: column.options || {},
|
|
896
1363
|
defaultValue: column.defaultValue !== null && column.defaultValue !== undefined
|
|
897
1364
|
? String(column.defaultValue)
|
|
@@ -969,10 +1436,11 @@ class SmartTablesSDK extends BaseClient {
|
|
|
969
1436
|
* @returns Promise resolving to complete table information
|
|
970
1437
|
*/
|
|
971
1438
|
async getTableFullInfo(tableId, options = {}) {
|
|
972
|
-
const filters = (options.filters || []).map(f => ({
|
|
1439
|
+
const filters = (options.filters || []).map((f) => ({
|
|
973
1440
|
column: f.column,
|
|
974
1441
|
operator: f.operator,
|
|
975
1442
|
value: f.value,
|
|
1443
|
+
...(f.logicalOperator ? { logicalOperator: f.logicalOperator } : {}),
|
|
976
1444
|
}));
|
|
977
1445
|
const pagination = {
|
|
978
1446
|
page: options.pagination?.page || 1,
|
|
@@ -1026,19 +1494,6 @@ class SmartTablesSDK extends BaseClient {
|
|
|
1026
1494
|
data_schema.sort((a, b) => (a.order || 0) - (b.order || 0));
|
|
1027
1495
|
}
|
|
1028
1496
|
}
|
|
1029
|
-
// Debug logging to understand response structure
|
|
1030
|
-
console.log('🔍 SDK queryTableWithSchema response:', {
|
|
1031
|
-
hasDataView: !!fullInfo.data_view,
|
|
1032
|
-
dataViewLength: fullInfo.data_view?.length || 0,
|
|
1033
|
-
hasTotalCount: !!fullInfo.total_count,
|
|
1034
|
-
totalCount: fullInfo.total_count,
|
|
1035
|
-
schemaColumns: data_schema?.length || 0,
|
|
1036
|
-
views: fullInfo.views?.length || 0,
|
|
1037
|
-
defaultView,
|
|
1038
|
-
defaultViewOptions: defaultView?.options,
|
|
1039
|
-
hasDashboardLayout: !!defaultView?.options?.dashboardLayout,
|
|
1040
|
-
rawFullInfo: fullInfo,
|
|
1041
|
-
});
|
|
1042
1497
|
return {
|
|
1043
1498
|
data: fullInfo.data_view || [],
|
|
1044
1499
|
total: fullInfo.total_count || 0,
|
|
@@ -1057,36 +1512,13 @@ class SmartTablesSDK extends BaseClient {
|
|
|
1057
1512
|
* @returns Promise resolving to grouped data and schema
|
|
1058
1513
|
*/
|
|
1059
1514
|
async queryGroupedTableWithSchema(tableId, options) {
|
|
1060
|
-
const
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
queryParams.append(filter.column, String(filter.value));
|
|
1068
|
-
});
|
|
1069
|
-
}
|
|
1070
|
-
// Add sort
|
|
1071
|
-
if (options.sort && options.sort.length > 0) {
|
|
1072
|
-
const sort = options.sort[0]; // Take the first sort for now
|
|
1073
|
-
queryParams.append("sort_column", sort.column);
|
|
1074
|
-
queryParams.append("sort_direction", sort.direction);
|
|
1075
|
-
}
|
|
1076
|
-
// Add pagination
|
|
1077
|
-
if (options.pagination) {
|
|
1078
|
-
if (options.pagination.page !== undefined) {
|
|
1079
|
-
queryParams.append("page", options.pagination.page.toString());
|
|
1080
|
-
}
|
|
1081
|
-
if (options.pagination.limit !== undefined) {
|
|
1082
|
-
queryParams.append("limit", options.pagination.limit.toString());
|
|
1083
|
-
}
|
|
1084
|
-
if (options.pagination.search) {
|
|
1085
|
-
queryParams.append("search", options.pagination.search);
|
|
1086
|
-
}
|
|
1087
|
-
}
|
|
1088
|
-
const url = `project/${this.config.projectId}/data-types/${tableId}/view/grouped${queryParams.toString() ? "?" + queryParams.toString() : ""}`;
|
|
1089
|
-
const response = await this.get(url);
|
|
1515
|
+
const response = await this.post(`project/${this.config.projectId}/data-types/${tableId}/view/grouped`, {
|
|
1516
|
+
group_column: options.groupColumn,
|
|
1517
|
+
group_column_type: options.groupColumnType,
|
|
1518
|
+
filters: options.filters || [],
|
|
1519
|
+
sort: options.sort || [],
|
|
1520
|
+
pagination: options.pagination,
|
|
1521
|
+
});
|
|
1090
1522
|
return {
|
|
1091
1523
|
grouped_data: response.grouped_data || [],
|
|
1092
1524
|
total_count: response.total_count || 0,
|
|
@@ -1145,10 +1577,12 @@ class SmartTablesSDK extends BaseClient {
|
|
|
1145
1577
|
* @param description Description for the new table
|
|
1146
1578
|
* @param columnMappings Array of column mappings
|
|
1147
1579
|
* @param file File to import
|
|
1580
|
+
* @param needsDecryption True when the file is encrypted by an external DRM /
|
|
1581
|
+
* envelope encryption scheme; the server decrypts it before parsing
|
|
1148
1582
|
* @returns Promise resolving to import result
|
|
1149
1583
|
*/
|
|
1150
|
-
async importTable(title, description, columnMappings, file) {
|
|
1151
|
-
const response = await this.importSmartTable(this.config.projectId, title, description, columnMappings, file);
|
|
1584
|
+
async importTable(title, description, columnMappings, file, needsDecryption) {
|
|
1585
|
+
const response = await this.importSmartTable(this.config.projectId, title, description, columnMappings, file, needsDecryption);
|
|
1152
1586
|
return {
|
|
1153
1587
|
data_type_id: response.data_type_id || response.id,
|
|
1154
1588
|
rows_imported: response.rows_imported || 0,
|
|
@@ -1211,9 +1645,9 @@ class SmartTablesSDK extends BaseClient {
|
|
|
1211
1645
|
async listJobs(dataTypeId, options = {}) {
|
|
1212
1646
|
const params = new URLSearchParams();
|
|
1213
1647
|
if (options.limit)
|
|
1214
|
-
params.append(
|
|
1648
|
+
params.append("limit", options.limit.toString());
|
|
1215
1649
|
if (options.offset)
|
|
1216
|
-
params.append(
|
|
1650
|
+
params.append("offset", options.offset.toString());
|
|
1217
1651
|
return await this.get(`project/${this.config.projectId}/data-type/${dataTypeId}/compute-column/jobs?${params.toString()}`);
|
|
1218
1652
|
}
|
|
1219
1653
|
/**
|
|
@@ -1233,6 +1667,15 @@ class SmartTablesSDK extends BaseClient {
|
|
|
1233
1667
|
async computeAllRows(dataTypeId) {
|
|
1234
1668
|
return await this.post(`project/${this.config.projectId}/data-type/${dataTypeId}/compute-all-rows`, {});
|
|
1235
1669
|
}
|
|
1670
|
+
/**
|
|
1671
|
+
* Cancel a running compute-all-rows job (EN-3633).
|
|
1672
|
+
* @param dataTypeId The ID of the data type
|
|
1673
|
+
* @param executionId The execution ID returned from computeAllRows
|
|
1674
|
+
* @returns Promise resolving when cancellation is requested
|
|
1675
|
+
*/
|
|
1676
|
+
async cancelAllRowsJob(dataTypeId, executionId) {
|
|
1677
|
+
return await this.post(`project/${this.config.projectId}/data-type/${dataTypeId}/compute-all-rows/cancel/${executionId}`, {});
|
|
1678
|
+
}
|
|
1236
1679
|
/**
|
|
1237
1680
|
* Normalize table data from API response
|
|
1238
1681
|
* @private
|
|
@@ -1241,451 +1684,16 @@ class SmartTablesSDK extends BaseClient {
|
|
|
1241
1684
|
return {
|
|
1242
1685
|
id: data.id || data.data_type_id,
|
|
1243
1686
|
project_id: data.project_id || this.config.projectId,
|
|
1244
|
-
title: data.title || data.name ||
|
|
1245
|
-
description: data.description ||
|
|
1687
|
+
title: data.title || data.name || "",
|
|
1688
|
+
description: data.description || "",
|
|
1246
1689
|
schema: data.schema || [],
|
|
1247
|
-
table_name: data.table_name ||
|
|
1690
|
+
table_name: data.table_name || "",
|
|
1248
1691
|
created_at: data.created_at,
|
|
1249
1692
|
updated_at: data.updated_at,
|
|
1250
1693
|
};
|
|
1251
1694
|
}
|
|
1252
1695
|
}
|
|
1253
1696
|
|
|
1254
|
-
/**
|
|
1255
|
-
* SDK for interacting with the Odin AI Workflow system.
|
|
1256
|
-
*
|
|
1257
|
-
* Allows you to:
|
|
1258
|
-
* - List and retrieve workflows
|
|
1259
|
-
* - Execute workflows programmatically
|
|
1260
|
-
* - Stream real-time execution updates
|
|
1261
|
-
* - View execution history
|
|
1262
|
-
*
|
|
1263
|
-
* @example
|
|
1264
|
-
* ```typescript
|
|
1265
|
-
* import { WorkflowSDK } from '@odin-ai/sdk';
|
|
1266
|
-
*
|
|
1267
|
-
* const sdk = new WorkflowSDK({
|
|
1268
|
-
* baseUrl: 'https://api.odin.ai/',
|
|
1269
|
-
* projectId: 'your-project-id',
|
|
1270
|
-
* apiKey: 'your-api-key',
|
|
1271
|
-
* apiSecret: 'your-api-secret',
|
|
1272
|
-
* });
|
|
1273
|
-
*
|
|
1274
|
-
* // List workflows
|
|
1275
|
-
* const { tools: workflows } = await sdk.listWorkflows();
|
|
1276
|
-
*
|
|
1277
|
-
* // Execute with streaming
|
|
1278
|
-
* const session = await sdk.executeWorkflowStream(workflowId, {
|
|
1279
|
-
* inputs: { name: 'John' },
|
|
1280
|
-
* onNodeCompleted: (event) => console.log(`Node ${event.node_id} completed`),
|
|
1281
|
-
* onExecutionCompleted: (event) => console.log('Done!', event.result),
|
|
1282
|
-
* });
|
|
1283
|
-
* ```
|
|
1284
|
-
*/
|
|
1285
|
-
class WorkflowSDK extends BaseClient {
|
|
1286
|
-
/**
|
|
1287
|
-
* Initialize the Workflow SDK
|
|
1288
|
-
* @param config Configuration object with API credentials and settings
|
|
1289
|
-
*/
|
|
1290
|
-
constructor(config) {
|
|
1291
|
-
super(config);
|
|
1292
|
-
}
|
|
1293
|
-
/**
|
|
1294
|
-
* List all workflows in the project
|
|
1295
|
-
* @param limit Maximum number of workflows to return (default: 50)
|
|
1296
|
-
* @param offset Pagination offset (default: 0)
|
|
1297
|
-
* @returns Promise resolving to list of workflows
|
|
1298
|
-
*/
|
|
1299
|
-
async listWorkflows(limit = 50, offset = 0) {
|
|
1300
|
-
const params = new URLSearchParams({
|
|
1301
|
-
project_id: this.config.projectId,
|
|
1302
|
-
limit: limit.toString(),
|
|
1303
|
-
offset: offset.toString(),
|
|
1304
|
-
});
|
|
1305
|
-
return await this.get(`tools/custom?${params}`);
|
|
1306
|
-
}
|
|
1307
|
-
/**
|
|
1308
|
-
* Get a specific workflow by ID
|
|
1309
|
-
* @param workflowId The ID of the workflow to retrieve
|
|
1310
|
-
* @returns Promise resolving to the workflow details
|
|
1311
|
-
*/
|
|
1312
|
-
async getWorkflow(workflowId) {
|
|
1313
|
-
return await this.get(`tools/custom/${workflowId}`);
|
|
1314
|
-
}
|
|
1315
|
-
/**
|
|
1316
|
-
* Get a specific published version of a workflow
|
|
1317
|
-
* @param workflowId The ID of the workflow
|
|
1318
|
-
* @param version The version string (e.g., "1.0.0")
|
|
1319
|
-
* @returns Promise resolving to the workflow version details
|
|
1320
|
-
*/
|
|
1321
|
-
async getWorkflowVersion(workflowId, version) {
|
|
1322
|
-
return await this.get(`tools/custom/${workflowId}/version/${version}`);
|
|
1323
|
-
}
|
|
1324
|
-
/**
|
|
1325
|
-
* List all published versions of a workflow
|
|
1326
|
-
* @param workflowId The ID of the workflow
|
|
1327
|
-
* @param limit Maximum number of versions to return (default: 20)
|
|
1328
|
-
* @param offset Pagination offset (default: 0)
|
|
1329
|
-
* @returns Promise resolving to list of workflow versions
|
|
1330
|
-
*/
|
|
1331
|
-
async listWorkflowVersions(workflowId, limit = 20, offset = 0) {
|
|
1332
|
-
const params = new URLSearchParams({
|
|
1333
|
-
limit: limit.toString(),
|
|
1334
|
-
offset: offset.toString(),
|
|
1335
|
-
});
|
|
1336
|
-
return await this.get(`tools/custom/${workflowId}/versions?${params}`);
|
|
1337
|
-
}
|
|
1338
|
-
/**
|
|
1339
|
-
* Execute a workflow and wait for the result
|
|
1340
|
-
*
|
|
1341
|
-
* For real-time updates during execution, use `executeWorkflowStream` instead.
|
|
1342
|
-
*
|
|
1343
|
-
* @param workflowId The ID of the workflow to execute
|
|
1344
|
-
* @param options Execution options including inputs
|
|
1345
|
-
* @returns Promise resolving to the execution result
|
|
1346
|
-
*/
|
|
1347
|
-
async executeWorkflow(workflowId, options = {}) {
|
|
1348
|
-
return await this.post('tools/execute-workflow', {
|
|
1349
|
-
project_id: this.config.projectId,
|
|
1350
|
-
tool_id: workflowId,
|
|
1351
|
-
inputs: options.inputs || {},
|
|
1352
|
-
execution_mode: options.executionMode || 'workflow',
|
|
1353
|
-
mode: options.triggerMode || 'manual',
|
|
1354
|
-
chat_id: options.chatId,
|
|
1355
|
-
message_id: options.messageId,
|
|
1356
|
-
return_response: true,
|
|
1357
|
-
});
|
|
1358
|
-
}
|
|
1359
|
-
/**
|
|
1360
|
-
* Execute a workflow with real-time streaming updates via SSE.
|
|
1361
|
-
*
|
|
1362
|
-
* This method provides callbacks for real-time execution events:
|
|
1363
|
-
* - `onExecutionStarted`: Fired when execution begins
|
|
1364
|
-
* - `onNodeStarted`: Fired when each node begins executing
|
|
1365
|
-
* - `onNodeCompleted`: Fired when each node finishes
|
|
1366
|
-
* - `onNodeError`: Fired if a node encounters an error
|
|
1367
|
-
* - `onNodeSkipped`: Fired when a node is skipped (e.g., conditional branch)
|
|
1368
|
-
* - `onExecutionCompleted`: Fired when the entire workflow completes
|
|
1369
|
-
* - `onExecutionError`: Fired if the workflow fails
|
|
1370
|
-
* - `onAgentChunk`: Fired when an AI agent streams text
|
|
1371
|
-
* - `onAgentThinking`: Fired for AI agent reasoning/thinking updates
|
|
1372
|
-
*
|
|
1373
|
-
* @param workflowId The ID of the workflow to execute
|
|
1374
|
-
* @param options Execution options
|
|
1375
|
-
* @param callbacks Event callbacks for streaming updates
|
|
1376
|
-
* @returns Promise resolving to an execution session for control
|
|
1377
|
-
*
|
|
1378
|
-
* @example
|
|
1379
|
-
* ```typescript
|
|
1380
|
-
* const session = await sdk.executeWorkflowStream(
|
|
1381
|
-
* 'workflow-123',
|
|
1382
|
-
* { inputs: { name: 'John' } },
|
|
1383
|
-
* {
|
|
1384
|
-
* onNodeStarted: (e) => console.log(`Starting ${e.node_id}`),
|
|
1385
|
-
* onNodeCompleted: (e) => console.log(`Completed ${e.node_id}`),
|
|
1386
|
-
* onExecutionCompleted: (e) => {
|
|
1387
|
-
* console.log('Workflow complete!', e.result);
|
|
1388
|
-
* },
|
|
1389
|
-
* onError: (err) => console.error('Error:', err),
|
|
1390
|
-
* }
|
|
1391
|
-
* );
|
|
1392
|
-
*
|
|
1393
|
-
* // Later, to cancel execution:
|
|
1394
|
-
* session.close();
|
|
1395
|
-
* ```
|
|
1396
|
-
*/
|
|
1397
|
-
async executeWorkflowStream(workflowId, options = {}) {
|
|
1398
|
-
// Extract callbacks from options
|
|
1399
|
-
const { inputs, executionMode, triggerMode, chatId, messageId, onExecutionStarted, onNodeStarted, onNodeCompleted, onNodeError, onNodeSkipped, onExecutionCompleted, onExecutionError, onAgentChunk, onAgentThinking, onResponseCard, onRawEvent, onError, onClose, } = options;
|
|
1400
|
-
// Step 1: Prepare execution by storing inputs in Redis
|
|
1401
|
-
const prepareResponse = await this.prepareWorkflowExecution(workflowId, {
|
|
1402
|
-
inputs,
|
|
1403
|
-
executionMode,
|
|
1404
|
-
triggerMode,
|
|
1405
|
-
chatId,
|
|
1406
|
-
messageId,
|
|
1407
|
-
});
|
|
1408
|
-
const executionId = prepareResponse.execution_id;
|
|
1409
|
-
// Step 2: Get access token for SSE connection
|
|
1410
|
-
const accessToken = await this.getAccessTokenForSSE();
|
|
1411
|
-
// Step 3: Connect to SSE stream
|
|
1412
|
-
const streamUrl = new URL('tools/execute-workflow-stream', this.config.baseUrl);
|
|
1413
|
-
streamUrl.searchParams.set('execution_id', executionId);
|
|
1414
|
-
streamUrl.searchParams.set('access_token', accessToken);
|
|
1415
|
-
const eventSource = new EventSource(streamUrl.toString());
|
|
1416
|
-
// Track connection state
|
|
1417
|
-
let isOpen = true;
|
|
1418
|
-
// Create session object
|
|
1419
|
-
const session = {
|
|
1420
|
-
executionId,
|
|
1421
|
-
close: () => {
|
|
1422
|
-
isOpen = false;
|
|
1423
|
-
eventSource.close();
|
|
1424
|
-
},
|
|
1425
|
-
isOpen: () => isOpen && eventSource.readyState !== EventSource.CLOSED,
|
|
1426
|
-
};
|
|
1427
|
-
// Handle SSE events
|
|
1428
|
-
eventSource.onmessage = (event) => {
|
|
1429
|
-
try {
|
|
1430
|
-
const data = this.parseSSEEvent(event.data);
|
|
1431
|
-
if (!data)
|
|
1432
|
-
return;
|
|
1433
|
-
// Call raw event callback
|
|
1434
|
-
onRawEvent?.(data);
|
|
1435
|
-
// Call specific event callbacks based on type
|
|
1436
|
-
this.dispatchEvent(data, {
|
|
1437
|
-
onExecutionStarted,
|
|
1438
|
-
onNodeStarted,
|
|
1439
|
-
onNodeCompleted,
|
|
1440
|
-
onNodeError,
|
|
1441
|
-
onNodeSkipped,
|
|
1442
|
-
onExecutionCompleted,
|
|
1443
|
-
onExecutionError,
|
|
1444
|
-
onAgentChunk,
|
|
1445
|
-
onAgentThinking,
|
|
1446
|
-
onResponseCard,
|
|
1447
|
-
});
|
|
1448
|
-
// Close connection on completion or error
|
|
1449
|
-
if (data.type === 'execution_completed' || data.type === 'execution_error') {
|
|
1450
|
-
session.close();
|
|
1451
|
-
}
|
|
1452
|
-
}
|
|
1453
|
-
catch (err) {
|
|
1454
|
-
console.error('Error parsing SSE event:', err);
|
|
1455
|
-
onError?.(err instanceof Error ? err : new Error(String(err)));
|
|
1456
|
-
}
|
|
1457
|
-
};
|
|
1458
|
-
eventSource.onerror = (event) => {
|
|
1459
|
-
console.error('SSE connection error:', event);
|
|
1460
|
-
isOpen = false;
|
|
1461
|
-
onError?.(new Error('SSE connection error'));
|
|
1462
|
-
eventSource.close();
|
|
1463
|
-
};
|
|
1464
|
-
eventSource.addEventListener('close', () => {
|
|
1465
|
-
isOpen = false;
|
|
1466
|
-
onClose?.();
|
|
1467
|
-
});
|
|
1468
|
-
return session;
|
|
1469
|
-
}
|
|
1470
|
-
/**
|
|
1471
|
-
* Get execution history for a workflow
|
|
1472
|
-
* @param workflowId The ID of the workflow (optional - if not provided, returns all project executions)
|
|
1473
|
-
* @param page Page number (1-based, default: 1)
|
|
1474
|
-
* @param pageSize Number of results per page (default: 20, max: 100)
|
|
1475
|
-
* @returns Promise resolving to execution history
|
|
1476
|
-
*/
|
|
1477
|
-
async getExecutionHistory(workflowId, page = 1, pageSize = 20) {
|
|
1478
|
-
const params = new URLSearchParams({
|
|
1479
|
-
project_id: this.config.projectId,
|
|
1480
|
-
page: page.toString(),
|
|
1481
|
-
page_size: Math.min(pageSize, 100).toString(),
|
|
1482
|
-
});
|
|
1483
|
-
if (workflowId) {
|
|
1484
|
-
params.set('tool_id', workflowId);
|
|
1485
|
-
}
|
|
1486
|
-
return await this.get(`tools/execution-history?${params}`);
|
|
1487
|
-
}
|
|
1488
|
-
/**
|
|
1489
|
-
* Get details of a specific execution
|
|
1490
|
-
* @param executionId The ID of the execution
|
|
1491
|
-
* @returns Promise resolving to execution details
|
|
1492
|
-
*/
|
|
1493
|
-
async getExecution(executionId) {
|
|
1494
|
-
return await this.get(`tools/execution/${executionId}`);
|
|
1495
|
-
}
|
|
1496
|
-
/**
|
|
1497
|
-
* Prepare workflow execution by storing inputs in Redis.
|
|
1498
|
-
* This is an internal method used by executeWorkflowStream.
|
|
1499
|
-
* @private
|
|
1500
|
-
*/
|
|
1501
|
-
async prepareWorkflowExecution(workflowId, options = {}) {
|
|
1502
|
-
return await this.post('tools/prepare-workflow-execution', {
|
|
1503
|
-
project_id: this.config.projectId,
|
|
1504
|
-
tool_id: workflowId,
|
|
1505
|
-
inputs: options.inputs || {},
|
|
1506
|
-
execution_mode: options.executionMode || 'workflow',
|
|
1507
|
-
mode: options.triggerMode || 'manual',
|
|
1508
|
-
chat_id: options.chatId,
|
|
1509
|
-
message_id: options.messageId,
|
|
1510
|
-
});
|
|
1511
|
-
}
|
|
1512
|
-
/**
|
|
1513
|
-
* Get access token for SSE connection.
|
|
1514
|
-
* Uses the configured access token or generates one from API keys.
|
|
1515
|
-
* @private
|
|
1516
|
-
*/
|
|
1517
|
-
async getAccessTokenForSSE() {
|
|
1518
|
-
// If we have an access token configured, use it
|
|
1519
|
-
if (this.config.accessToken) {
|
|
1520
|
-
return this.config.accessToken;
|
|
1521
|
-
}
|
|
1522
|
-
// Otherwise, we need to exchange API keys for an access token
|
|
1523
|
-
// This endpoint should be implemented on the backend if not already
|
|
1524
|
-
const response = await this.post('auth/api-key-token', {
|
|
1525
|
-
api_key: this.config.apiKey,
|
|
1526
|
-
api_secret: this.config.apiSecret,
|
|
1527
|
-
});
|
|
1528
|
-
return response.access_token;
|
|
1529
|
-
}
|
|
1530
|
-
/**
|
|
1531
|
-
* Parse SSE event data into a typed event object.
|
|
1532
|
-
* @private
|
|
1533
|
-
*/
|
|
1534
|
-
parseSSEEvent(data) {
|
|
1535
|
-
try {
|
|
1536
|
-
// Handle different SSE event formats
|
|
1537
|
-
const parsed = JSON.parse(data);
|
|
1538
|
-
// Normalize event format
|
|
1539
|
-
if (parsed.event_type) {
|
|
1540
|
-
return {
|
|
1541
|
-
type: parsed.event_type,
|
|
1542
|
-
...parsed,
|
|
1543
|
-
};
|
|
1544
|
-
}
|
|
1545
|
-
if (parsed.type) {
|
|
1546
|
-
return parsed;
|
|
1547
|
-
}
|
|
1548
|
-
// Handle legacy format with specific field names
|
|
1549
|
-
if (parsed.node_id && parsed.status === 'started') {
|
|
1550
|
-
return {
|
|
1551
|
-
type: 'node_started',
|
|
1552
|
-
node_id: parsed.node_id,
|
|
1553
|
-
node_label: parsed.node_label,
|
|
1554
|
-
node_type: parsed.node_type,
|
|
1555
|
-
};
|
|
1556
|
-
}
|
|
1557
|
-
if (parsed.node_id && parsed.status === 'completed') {
|
|
1558
|
-
return {
|
|
1559
|
-
type: 'node_completed',
|
|
1560
|
-
node_id: parsed.node_id,
|
|
1561
|
-
result: parsed.result,
|
|
1562
|
-
execution_time_ms: parsed.execution_time_ms,
|
|
1563
|
-
};
|
|
1564
|
-
}
|
|
1565
|
-
if (parsed.execution_completed || parsed.final_result) {
|
|
1566
|
-
return {
|
|
1567
|
-
type: 'execution_completed',
|
|
1568
|
-
result: parsed.final_result || parsed.result,
|
|
1569
|
-
};
|
|
1570
|
-
}
|
|
1571
|
-
if (parsed.chunk && parsed.node_id) {
|
|
1572
|
-
return {
|
|
1573
|
-
type: 'agent_chunk',
|
|
1574
|
-
node_id: parsed.node_id,
|
|
1575
|
-
chunk: parsed.chunk,
|
|
1576
|
-
};
|
|
1577
|
-
}
|
|
1578
|
-
// Return raw data if we can't categorize it
|
|
1579
|
-
return {
|
|
1580
|
-
type: 'execution_started',
|
|
1581
|
-
workflow_id: parsed.workflow_id || parsed.tool_id || '',
|
|
1582
|
-
execution_id: parsed.execution_id || '',
|
|
1583
|
-
...parsed,
|
|
1584
|
-
};
|
|
1585
|
-
}
|
|
1586
|
-
catch (err) {
|
|
1587
|
-
// If it's not JSON, it might be a text chunk
|
|
1588
|
-
if (typeof data === 'string' && data.trim()) {
|
|
1589
|
-
console.warn('Non-JSON SSE data received:', data);
|
|
1590
|
-
}
|
|
1591
|
-
return null;
|
|
1592
|
-
}
|
|
1593
|
-
}
|
|
1594
|
-
/**
|
|
1595
|
-
* Dispatch event to appropriate callback.
|
|
1596
|
-
* @private
|
|
1597
|
-
*/
|
|
1598
|
-
dispatchEvent(event, callbacks) {
|
|
1599
|
-
switch (event.type) {
|
|
1600
|
-
case 'execution_started':
|
|
1601
|
-
callbacks.onExecutionStarted?.(event);
|
|
1602
|
-
break;
|
|
1603
|
-
case 'node_started':
|
|
1604
|
-
callbacks.onNodeStarted?.(event);
|
|
1605
|
-
break;
|
|
1606
|
-
case 'node_completed':
|
|
1607
|
-
callbacks.onNodeCompleted?.(event);
|
|
1608
|
-
break;
|
|
1609
|
-
case 'node_error':
|
|
1610
|
-
callbacks.onNodeError?.(event);
|
|
1611
|
-
break;
|
|
1612
|
-
case 'node_skipped':
|
|
1613
|
-
callbacks.onNodeSkipped?.(event);
|
|
1614
|
-
break;
|
|
1615
|
-
case 'execution_completed':
|
|
1616
|
-
callbacks.onExecutionCompleted?.(event);
|
|
1617
|
-
break;
|
|
1618
|
-
case 'execution_error':
|
|
1619
|
-
callbacks.onExecutionError?.(event);
|
|
1620
|
-
break;
|
|
1621
|
-
case 'agent_chunk':
|
|
1622
|
-
callbacks.onAgentChunk?.(event);
|
|
1623
|
-
break;
|
|
1624
|
-
case 'agent_thinking':
|
|
1625
|
-
callbacks.onAgentThinking?.(event);
|
|
1626
|
-
break;
|
|
1627
|
-
case 'response_card':
|
|
1628
|
-
callbacks.onResponseCard?.(event);
|
|
1629
|
-
break;
|
|
1630
|
-
}
|
|
1631
|
-
}
|
|
1632
|
-
/**
|
|
1633
|
-
* Upload a file for use with file upload trigger workflows.
|
|
1634
|
-
* Returns a temporary file reference to use with executeWorkflowStream.
|
|
1635
|
-
*
|
|
1636
|
-
* @param file The file to upload
|
|
1637
|
-
* @returns Promise resolving to file reference info
|
|
1638
|
-
*/
|
|
1639
|
-
async uploadWorkflowFile(file) {
|
|
1640
|
-
const formData = new FormData();
|
|
1641
|
-
formData.append('file', file);
|
|
1642
|
-
formData.append('project_id', this.config.projectId);
|
|
1643
|
-
return await this.post('tools/upload-workflow-file', formData);
|
|
1644
|
-
}
|
|
1645
|
-
/**
|
|
1646
|
-
* Upload multiple files for use with file upload trigger workflows.
|
|
1647
|
-
* Returns a temporary file reference to use with executeWorkflowStream.
|
|
1648
|
-
*
|
|
1649
|
-
* @param files Array of files to upload
|
|
1650
|
-
* @returns Promise resolving to file reference info
|
|
1651
|
-
*/
|
|
1652
|
-
async uploadWorkflowFiles(files) {
|
|
1653
|
-
const formData = new FormData();
|
|
1654
|
-
files.forEach((file, index) => {
|
|
1655
|
-
formData.append('files', file);
|
|
1656
|
-
});
|
|
1657
|
-
formData.append('project_id', this.config.projectId);
|
|
1658
|
-
formData.append('multiple_files', 'true');
|
|
1659
|
-
return await this.post('tools/upload-workflow-file', formData);
|
|
1660
|
-
}
|
|
1661
|
-
/**
|
|
1662
|
-
* Execute a workflow with file upload trigger.
|
|
1663
|
-
* This is a convenience method that handles file upload and execution in one call.
|
|
1664
|
-
*
|
|
1665
|
-
* @param workflowId The ID of the workflow to execute
|
|
1666
|
-
* @param file File(s) to upload
|
|
1667
|
-
* @param options Additional execution options
|
|
1668
|
-
* @returns Promise resolving to the execution result
|
|
1669
|
-
*/
|
|
1670
|
-
async executeWorkflowWithFile(workflowId, file, options = {}) {
|
|
1671
|
-
const formData = new FormData();
|
|
1672
|
-
formData.append('project_id', this.config.projectId);
|
|
1673
|
-
formData.append('tool_id', workflowId);
|
|
1674
|
-
if (Array.isArray(file)) {
|
|
1675
|
-
file.forEach((f) => formData.append('files', f));
|
|
1676
|
-
formData.append('multiple_files', 'true');
|
|
1677
|
-
}
|
|
1678
|
-
else {
|
|
1679
|
-
formData.append('file', file);
|
|
1680
|
-
formData.append('multiple_files', 'false');
|
|
1681
|
-
}
|
|
1682
|
-
if (options.inputs) {
|
|
1683
|
-
formData.append('runtime_inputs', JSON.stringify(options.inputs));
|
|
1684
|
-
}
|
|
1685
|
-
return await this.post('tools/execute-workflow-file-upload', formData);
|
|
1686
|
-
}
|
|
1687
|
-
}
|
|
1688
|
-
|
|
1689
1697
|
/**
|
|
1690
1698
|
* Voice SDK for ElevenLabs integration
|
|
1691
1699
|
* Provides voice conversation capabilities with automatic chat integration
|
|
@@ -1716,18 +1724,18 @@ class VoiceSDK extends BaseClient {
|
|
|
1716
1724
|
agentId: options.agentId || this.defaultAgentId,
|
|
1717
1725
|
voiceSettings: options.voiceSettings || this.defaultVoiceSettings,
|
|
1718
1726
|
userInfo: options.userInfo,
|
|
1719
|
-
}
|
|
1727
|
+
},
|
|
1720
1728
|
};
|
|
1721
1729
|
this.activeSessions.set(sessionId, session);
|
|
1722
1730
|
// If we need to create a new chat for this voice conversation
|
|
1723
1731
|
if (options.saveToChat && !options.existingChatId && this.chatSDK) {
|
|
1724
1732
|
try {
|
|
1725
|
-
const chat = await this.chatSDK.createChat(
|
|
1733
|
+
const chat = await this.chatSDK.createChat("Voice Conversation");
|
|
1726
1734
|
session.chatId = chat.chat_id;
|
|
1727
|
-
options.callbacks?.onConversationSaved?.(chat.chat_id,
|
|
1735
|
+
options.callbacks?.onConversationSaved?.(chat.chat_id, "");
|
|
1728
1736
|
}
|
|
1729
1737
|
catch (error) {
|
|
1730
|
-
console.warn(
|
|
1738
|
+
console.warn("Failed to create chat for voice conversation:", error);
|
|
1731
1739
|
}
|
|
1732
1740
|
}
|
|
1733
1741
|
// Set up enhanced callbacks that integrate with our session tracking
|
|
@@ -1748,12 +1756,12 @@ class VoiceSDK extends BaseClient {
|
|
|
1748
1756
|
onError: (error) => {
|
|
1749
1757
|
options.callbacks?.onError?.(error);
|
|
1750
1758
|
this.endVoiceSession(sessionId, error.message);
|
|
1751
|
-
}
|
|
1759
|
+
},
|
|
1752
1760
|
};
|
|
1753
1761
|
// Store enhanced callbacks for this session
|
|
1754
1762
|
session.metadata = {
|
|
1755
1763
|
...session.metadata,
|
|
1756
|
-
enhancedCallbacks
|
|
1764
|
+
enhancedCallbacks,
|
|
1757
1765
|
};
|
|
1758
1766
|
return sessionId;
|
|
1759
1767
|
}
|
|
@@ -1768,7 +1776,7 @@ class VoiceSDK extends BaseClient {
|
|
|
1768
1776
|
session.endTime = Date.now();
|
|
1769
1777
|
session.metadata = {
|
|
1770
1778
|
...session.metadata,
|
|
1771
|
-
totalDuration: session.endTime - session.startTime
|
|
1779
|
+
totalDuration: session.endTime - session.startTime,
|
|
1772
1780
|
};
|
|
1773
1781
|
// Save conversation to chat if configured
|
|
1774
1782
|
if (session.chatId && this.chatSDK && session.messages.length > 0) {
|
|
@@ -1776,7 +1784,7 @@ class VoiceSDK extends BaseClient {
|
|
|
1776
1784
|
await this.saveVoiceConversationToChat(session);
|
|
1777
1785
|
}
|
|
1778
1786
|
catch (error) {
|
|
1779
|
-
console.warn(
|
|
1787
|
+
console.warn("Failed to save voice conversation to chat:", error);
|
|
1780
1788
|
}
|
|
1781
1789
|
}
|
|
1782
1790
|
this.activeSessions.delete(sessionId);
|
|
@@ -1793,7 +1801,7 @@ class VoiceSDK extends BaseClient {
|
|
|
1793
1801
|
return {
|
|
1794
1802
|
sessionId,
|
|
1795
1803
|
isActive: true,
|
|
1796
|
-
connectionStatus:
|
|
1804
|
+
connectionStatus: "connected",
|
|
1797
1805
|
volume: 50,
|
|
1798
1806
|
micMuted: false,
|
|
1799
1807
|
isSpeaking: false,
|
|
@@ -1809,7 +1817,7 @@ class VoiceSDK extends BaseClient {
|
|
|
1809
1817
|
}
|
|
1810
1818
|
session.metadata = {
|
|
1811
1819
|
...session.metadata,
|
|
1812
|
-
voiceSettings: { ...session.metadata?.voiceSettings, ...settings }
|
|
1820
|
+
voiceSettings: { ...session.metadata?.voiceSettings, ...settings },
|
|
1813
1821
|
};
|
|
1814
1822
|
// Here you would call the actual ElevenLabs API to update settings
|
|
1815
1823
|
// This is a placeholder for that functionality
|
|
@@ -1830,7 +1838,7 @@ class VoiceSDK extends BaseClient {
|
|
|
1830
1838
|
*/
|
|
1831
1839
|
async setVolume(sessionId, volume) {
|
|
1832
1840
|
if (volume < 0 || volume > 100) {
|
|
1833
|
-
throw new Error(
|
|
1841
|
+
throw new Error("Volume must be between 0 and 100");
|
|
1834
1842
|
}
|
|
1835
1843
|
const session = this.activeSessions.get(sessionId);
|
|
1836
1844
|
if (!session) {
|
|
@@ -1861,7 +1869,7 @@ class VoiceSDK extends BaseClient {
|
|
|
1861
1869
|
// For now, just add it as a system message
|
|
1862
1870
|
const contextMessage = {
|
|
1863
1871
|
id: this.generateMessageId(),
|
|
1864
|
-
type:
|
|
1872
|
+
type: "system",
|
|
1865
1873
|
text: `Context update: ${context}`,
|
|
1866
1874
|
timestamp: Date.now(),
|
|
1867
1875
|
};
|
|
@@ -1887,34 +1895,34 @@ class VoiceSDK extends BaseClient {
|
|
|
1887
1895
|
async saveVoiceMessageToAPI(sessionId, userMessage, aiResponse, agentInfo) {
|
|
1888
1896
|
const session = this.activeSessions.get(sessionId);
|
|
1889
1897
|
if (!session || !session.chatId) {
|
|
1890
|
-
console.warn(
|
|
1898
|
+
console.warn("Cannot save voice message: no session or chat ID");
|
|
1891
1899
|
return;
|
|
1892
1900
|
}
|
|
1893
1901
|
try {
|
|
1894
1902
|
// Get user information from session if available
|
|
1895
|
-
let userName =
|
|
1896
|
-
let userId =
|
|
1903
|
+
let userName = "Voice User";
|
|
1904
|
+
let userId = "voice-user";
|
|
1897
1905
|
if (session.metadata?.userInfo) {
|
|
1898
1906
|
userName = session.metadata.userInfo.name;
|
|
1899
1907
|
userId = session.metadata.userInfo.id;
|
|
1900
1908
|
}
|
|
1901
1909
|
// Use the existing API endpoint to save voice messages
|
|
1902
|
-
await this.post(
|
|
1910
|
+
await this.post("/elevenlabs/voice-message/save", {
|
|
1903
1911
|
project_id: this.config.projectId,
|
|
1904
1912
|
chat_id: session.chatId,
|
|
1905
1913
|
message: userMessage,
|
|
1906
1914
|
response: aiResponse,
|
|
1907
1915
|
user_name: userName,
|
|
1908
1916
|
user_id: userId,
|
|
1909
|
-
message_type:
|
|
1917
|
+
message_type: "complete",
|
|
1910
1918
|
agent_id: agentInfo?.id || session.metadata?.agentId,
|
|
1911
1919
|
agent_name: agentInfo?.name,
|
|
1912
1920
|
conversation_id: sessionId,
|
|
1913
1921
|
});
|
|
1914
|
-
console.log(
|
|
1922
|
+
console.log("Voice message automatically saved to database");
|
|
1915
1923
|
}
|
|
1916
1924
|
catch (error) {
|
|
1917
|
-
console.error(
|
|
1925
|
+
console.error("Failed to auto-save voice message:", error);
|
|
1918
1926
|
// Don't throw - this shouldn't break the voice conversation
|
|
1919
1927
|
}
|
|
1920
1928
|
}
|
|
@@ -1922,7 +1930,9 @@ class VoiceSDK extends BaseClient {
|
|
|
1922
1930
|
* Private helper methods
|
|
1923
1931
|
*/
|
|
1924
1932
|
generateSessionId() {
|
|
1925
|
-
return `voice_session_${Date.now()}_${Math.random()
|
|
1933
|
+
return `voice_session_${Date.now()}_${Math.random()
|
|
1934
|
+
.toString(36)
|
|
1935
|
+
.substr(2, 9)}`;
|
|
1926
1936
|
}
|
|
1927
1937
|
generateMessageId() {
|
|
1928
1938
|
return `voice_msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
@@ -1934,8 +1944,8 @@ class VoiceSDK extends BaseClient {
|
|
|
1934
1944
|
// Convert ElevenLabs message to our format
|
|
1935
1945
|
const voiceMessage = {
|
|
1936
1946
|
id: this.generateMessageId(),
|
|
1937
|
-
type: message.role ===
|
|
1938
|
-
text: message.content || message.text ||
|
|
1947
|
+
type: message.role === "user" ? "user_speech" : "ai_speech",
|
|
1948
|
+
text: message.content || message.text || "",
|
|
1939
1949
|
timestamp: Date.now(),
|
|
1940
1950
|
audioUrl: message.audioUrl,
|
|
1941
1951
|
};
|
|
@@ -1958,25 +1968,25 @@ class VoiceSDK extends BaseClient {
|
|
|
1958
1968
|
return;
|
|
1959
1969
|
// Look for unsaved message pairs (user + AI response)
|
|
1960
1970
|
const messages = session.messages;
|
|
1961
|
-
let lastUserMessage =
|
|
1971
|
+
let lastUserMessage = "";
|
|
1962
1972
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
1963
1973
|
const message = messages[i];
|
|
1964
|
-
if (message.type ===
|
|
1974
|
+
if (message.type === "ai_speech" && lastUserMessage) {
|
|
1965
1975
|
// We have a complete pair - save it
|
|
1966
1976
|
try {
|
|
1967
1977
|
await this.saveVoiceMessageToAPI(sessionId, lastUserMessage, message.text, {
|
|
1968
1978
|
id: session.metadata?.agentId,
|
|
1969
|
-
name: session.metadata?.agentName
|
|
1979
|
+
name: session.metadata?.agentName,
|
|
1970
1980
|
});
|
|
1971
1981
|
// Mark these messages as saved to avoid duplicate saves
|
|
1972
1982
|
message.saved = true;
|
|
1973
1983
|
break;
|
|
1974
1984
|
}
|
|
1975
1985
|
catch (error) {
|
|
1976
|
-
console.error(
|
|
1986
|
+
console.error("Failed to auto-save voice message pair:", error);
|
|
1977
1987
|
}
|
|
1978
1988
|
}
|
|
1979
|
-
else if (message.type ===
|
|
1989
|
+
else if (message.type === "user_speech" && !message.saved) {
|
|
1980
1990
|
lastUserMessage = message.text;
|
|
1981
1991
|
}
|
|
1982
1992
|
}
|
|
@@ -1986,296 +1996,30 @@ class VoiceSDK extends BaseClient {
|
|
|
1986
1996
|
return;
|
|
1987
1997
|
// Convert voice messages to chat format
|
|
1988
1998
|
const conversationSummary = session.messages
|
|
1989
|
-
.filter(msg => msg.type !==
|
|
1990
|
-
.map(msg => `${msg.type ===
|
|
1991
|
-
.join(
|
|
1999
|
+
.filter((msg) => msg.type !== "system")
|
|
2000
|
+
.map((msg) => `${msg.type === "user_speech" ? "User" : "Assistant"}: ${msg.text}`)
|
|
2001
|
+
.join("\n");
|
|
1992
2002
|
const duration = session.metadata?.totalDuration
|
|
1993
|
-
? Math.round(
|
|
2003
|
+
? Math.round(session.metadata.totalDuration / 1000 / 60)
|
|
1994
2004
|
: 0;
|
|
1995
2005
|
const summaryMessage = `Voice Conversation Summary (${duration} minutes):\n\n${conversationSummary}`;
|
|
1996
2006
|
try {
|
|
1997
2007
|
await this.chatSDK.sendMessage(summaryMessage, {
|
|
1998
2008
|
chatId: session.chatId,
|
|
1999
2009
|
metadata: {
|
|
2000
|
-
type:
|
|
2010
|
+
type: "voice_conversation_summary",
|
|
2001
2011
|
sessionId: session.id,
|
|
2002
2012
|
duration: session.metadata?.totalDuration,
|
|
2003
2013
|
messageCount: session.messages.length,
|
|
2004
|
-
}
|
|
2014
|
+
},
|
|
2005
2015
|
});
|
|
2006
2016
|
}
|
|
2007
2017
|
catch (error) {
|
|
2008
|
-
console.error(
|
|
2018
|
+
console.error("Failed to save voice conversation to chat:", error);
|
|
2009
2019
|
throw error;
|
|
2010
2020
|
}
|
|
2011
2021
|
}
|
|
2012
2022
|
}
|
|
2013
2023
|
|
|
2014
|
-
|
|
2015
|
-
* Enhanced useVoiceConversation hook with our SDK's chat integration and session management
|
|
2016
|
-
*/
|
|
2017
|
-
function useVoiceConversation(options = {}) {
|
|
2018
|
-
const { sdkConfig, sessionConfig, callbacks, ...elevenLabsOptions } = options;
|
|
2019
|
-
// State management
|
|
2020
|
-
const [voiceSDK, setVoiceSDK] = useState(null);
|
|
2021
|
-
const [currentSessionId, setCurrentSessionId] = useState(null);
|
|
2022
|
-
const [conversationState, setConversationState] = useState({
|
|
2023
|
-
isActive: false,
|
|
2024
|
-
connectionStatus: 'disconnected',
|
|
2025
|
-
volume: 50,
|
|
2026
|
-
micMuted: false,
|
|
2027
|
-
isSpeaking: false,
|
|
2028
|
-
});
|
|
2029
|
-
// Refs for managing callbacks and cleanup
|
|
2030
|
-
const callbacksRef = useRef(callbacks);
|
|
2031
|
-
const sessionConfigRef = useRef(sessionConfig);
|
|
2032
|
-
// Update refs when options change
|
|
2033
|
-
useEffect(() => {
|
|
2034
|
-
callbacksRef.current = callbacks;
|
|
2035
|
-
sessionConfigRef.current = sessionConfig;
|
|
2036
|
-
}, [callbacks, sessionConfig]);
|
|
2037
|
-
// Initialize VoiceSDK lazily when needed
|
|
2038
|
-
const initializeVoiceSDK = useCallback(async (config) => {
|
|
2039
|
-
if (voiceSDK)
|
|
2040
|
-
return voiceSDK;
|
|
2041
|
-
try {
|
|
2042
|
-
const sdk = new VoiceSDK(config);
|
|
2043
|
-
setVoiceSDK(sdk);
|
|
2044
|
-
return sdk;
|
|
2045
|
-
}
|
|
2046
|
-
catch (error) {
|
|
2047
|
-
console.error('Failed to initialize VoiceSDK:', error);
|
|
2048
|
-
throw error;
|
|
2049
|
-
}
|
|
2050
|
-
}, [voiceSDK]);
|
|
2051
|
-
// Enhanced callbacks that integrate with our SDK
|
|
2052
|
-
const enhancedCallbacks = {
|
|
2053
|
-
...elevenLabsOptions,
|
|
2054
|
-
onConnect: useCallback(() => {
|
|
2055
|
-
setConversationState(prev => ({
|
|
2056
|
-
...prev,
|
|
2057
|
-
connectionStatus: 'connected',
|
|
2058
|
-
isActive: true
|
|
2059
|
-
}));
|
|
2060
|
-
elevenLabsOptions.onConnect?.();
|
|
2061
|
-
callbacksRef.current?.onConnect?.();
|
|
2062
|
-
}, [elevenLabsOptions.onConnect]),
|
|
2063
|
-
onDisconnect: useCallback((details) => {
|
|
2064
|
-
setConversationState(prev => ({
|
|
2065
|
-
...prev,
|
|
2066
|
-
connectionStatus: 'disconnected',
|
|
2067
|
-
isActive: false
|
|
2068
|
-
}));
|
|
2069
|
-
elevenLabsOptions.onDisconnect?.(details);
|
|
2070
|
-
callbacksRef.current?.onDisconnect?.(details);
|
|
2071
|
-
// End SDK session if active
|
|
2072
|
-
if (currentSessionId && voiceSDK) {
|
|
2073
|
-
voiceSDK.endVoiceSession(currentSessionId, details?.reason);
|
|
2074
|
-
setCurrentSessionId(null);
|
|
2075
|
-
}
|
|
2076
|
-
}, [currentSessionId, voiceSDK, elevenLabsOptions.onDisconnect]),
|
|
2077
|
-
onMessage: useCallback((message) => {
|
|
2078
|
-
elevenLabsOptions.onMessage?.(message);
|
|
2079
|
-
callbacksRef.current?.onMessage?.(message);
|
|
2080
|
-
// Handle transcription if available
|
|
2081
|
-
if (message.type === 'user_speech' && message.text) {
|
|
2082
|
-
callbacksRef.current?.onTranscription?.(message.text, true);
|
|
2083
|
-
}
|
|
2084
|
-
}, [elevenLabsOptions.onMessage]),
|
|
2085
|
-
onError: useCallback((error) => {
|
|
2086
|
-
setConversationState(prev => ({
|
|
2087
|
-
...prev,
|
|
2088
|
-
connectionStatus: 'error',
|
|
2089
|
-
isActive: false
|
|
2090
|
-
}));
|
|
2091
|
-
elevenLabsOptions.onError?.(error);
|
|
2092
|
-
callbacksRef.current?.onError?.(error);
|
|
2093
|
-
}, [elevenLabsOptions.onError]),
|
|
2094
|
-
onAudio: useCallback((audio) => {
|
|
2095
|
-
elevenLabsOptions.onAudio?.(audio);
|
|
2096
|
-
callbacksRef.current?.onSpeechGenerated?.(audio.url);
|
|
2097
|
-
}, [elevenLabsOptions.onAudio]),
|
|
2098
|
-
};
|
|
2099
|
-
// Initialize hook with enhanced callbacks
|
|
2100
|
-
const elevenLabsHook = useConversation(enhancedCallbacks);
|
|
2101
|
-
// Enhanced start session function
|
|
2102
|
-
const startSession = useCallback(async (config) => {
|
|
2103
|
-
const finalConfig = { ...sessionConfigRef.current, ...config };
|
|
2104
|
-
try {
|
|
2105
|
-
// Initialize SDK if needed and config is provided
|
|
2106
|
-
let sdk = voiceSDK;
|
|
2107
|
-
if (!sdk && finalConfig.sdkConfig) {
|
|
2108
|
-
sdk = await initializeVoiceSDK(finalConfig.sdkConfig);
|
|
2109
|
-
}
|
|
2110
|
-
if (!sdk) {
|
|
2111
|
-
throw new Error('VoiceSDK not initialized. Please provide sdkConfig.');
|
|
2112
|
-
}
|
|
2113
|
-
// Start SDK session first
|
|
2114
|
-
const sessionId = await sdk.startVoiceConversation({
|
|
2115
|
-
...finalConfig,
|
|
2116
|
-
callbacks: callbacksRef.current,
|
|
2117
|
-
});
|
|
2118
|
-
setCurrentSessionId(sessionId);
|
|
2119
|
-
// Then start ElevenLabs session
|
|
2120
|
-
const elevenLabsSessionId = await elevenLabsHook.startSession({
|
|
2121
|
-
agentId: finalConfig.agentId,
|
|
2122
|
-
...finalConfig,
|
|
2123
|
-
});
|
|
2124
|
-
return sessionId; // Return our SDK session ID
|
|
2125
|
-
}
|
|
2126
|
-
catch (error) {
|
|
2127
|
-
console.error('Failed to start voice session:', error);
|
|
2128
|
-
throw error;
|
|
2129
|
-
}
|
|
2130
|
-
}, [voiceSDK, elevenLabsHook.startSession, initializeVoiceSDK]);
|
|
2131
|
-
// Enhanced end session function
|
|
2132
|
-
const endSession = useCallback(async () => {
|
|
2133
|
-
try {
|
|
2134
|
-
// End ElevenLabs session first
|
|
2135
|
-
await elevenLabsHook.endSession();
|
|
2136
|
-
// Then end SDK session
|
|
2137
|
-
if (currentSessionId && voiceSDK) {
|
|
2138
|
-
await voiceSDK.endVoiceSession(currentSessionId);
|
|
2139
|
-
setCurrentSessionId(null);
|
|
2140
|
-
}
|
|
2141
|
-
}
|
|
2142
|
-
catch (error) {
|
|
2143
|
-
console.error('Failed to end voice session:', error);
|
|
2144
|
-
throw error;
|
|
2145
|
-
}
|
|
2146
|
-
}, [currentSessionId, voiceSDK, elevenLabsHook.endSession]);
|
|
2147
|
-
// Volume control with SDK integration
|
|
2148
|
-
const setVolume = useCallback(({ volume }) => {
|
|
2149
|
-
elevenLabsHook.setVolume({ volume });
|
|
2150
|
-
setConversationState(prev => ({ ...prev, volume }));
|
|
2151
|
-
if (currentSessionId && voiceSDK) {
|
|
2152
|
-
voiceSDK.setVolume(currentSessionId, volume);
|
|
2153
|
-
}
|
|
2154
|
-
}, [currentSessionId, voiceSDK, elevenLabsHook.setVolume]);
|
|
2155
|
-
// Audio data with SDK integration
|
|
2156
|
-
const getInputByteFrequencyData = useCallback(() => {
|
|
2157
|
-
const data = elevenLabsHook.getInputByteFrequencyData();
|
|
2158
|
-
// Update conversation state with audio data
|
|
2159
|
-
if (data && currentSessionId) {
|
|
2160
|
-
setConversationState(prev => ({
|
|
2161
|
-
...prev,
|
|
2162
|
-
audioData: {
|
|
2163
|
-
...prev.audioData,
|
|
2164
|
-
inputFrequencyData: data,
|
|
2165
|
-
}
|
|
2166
|
-
}));
|
|
2167
|
-
}
|
|
2168
|
-
return data;
|
|
2169
|
-
}, [currentSessionId, elevenLabsHook.getInputByteFrequencyData]);
|
|
2170
|
-
const getOutputByteFrequencyData = useCallback(() => {
|
|
2171
|
-
const data = elevenLabsHook.getOutputByteFrequencyData();
|
|
2172
|
-
if (data && currentSessionId) {
|
|
2173
|
-
setConversationState(prev => ({
|
|
2174
|
-
...prev,
|
|
2175
|
-
audioData: {
|
|
2176
|
-
...prev.audioData,
|
|
2177
|
-
outputFrequencyData: data,
|
|
2178
|
-
}
|
|
2179
|
-
}));
|
|
2180
|
-
}
|
|
2181
|
-
return data;
|
|
2182
|
-
}, [currentSessionId, elevenLabsHook.getOutputByteFrequencyData]);
|
|
2183
|
-
// Volume monitoring
|
|
2184
|
-
const getInputVolume = useCallback(() => {
|
|
2185
|
-
const volume = elevenLabsHook.getInputVolume();
|
|
2186
|
-
if (currentSessionId) {
|
|
2187
|
-
setConversationState(prev => ({
|
|
2188
|
-
...prev,
|
|
2189
|
-
audioData: {
|
|
2190
|
-
...prev.audioData,
|
|
2191
|
-
inputVolume: volume,
|
|
2192
|
-
}
|
|
2193
|
-
}));
|
|
2194
|
-
}
|
|
2195
|
-
return volume;
|
|
2196
|
-
}, [currentSessionId, elevenLabsHook.getInputVolume]);
|
|
2197
|
-
const getOutputVolume = useCallback(() => {
|
|
2198
|
-
const volume = elevenLabsHook.getOutputVolume();
|
|
2199
|
-
if (currentSessionId) {
|
|
2200
|
-
setConversationState(prev => ({
|
|
2201
|
-
...prev,
|
|
2202
|
-
audioData: {
|
|
2203
|
-
...prev.audioData,
|
|
2204
|
-
outputVolume: volume,
|
|
2205
|
-
}
|
|
2206
|
-
}));
|
|
2207
|
-
}
|
|
2208
|
-
return volume;
|
|
2209
|
-
}, [currentSessionId, elevenLabsHook.getOutputVolume]);
|
|
2210
|
-
// Context and message sending with SDK integration
|
|
2211
|
-
const sendContextualUpdate = useCallback((text) => {
|
|
2212
|
-
elevenLabsHook.sendContextualUpdate(text);
|
|
2213
|
-
if (currentSessionId && voiceSDK) {
|
|
2214
|
-
voiceSDK.sendContextualUpdate(currentSessionId, text);
|
|
2215
|
-
}
|
|
2216
|
-
}, [currentSessionId, voiceSDK, elevenLabsHook.sendContextualUpdate]);
|
|
2217
|
-
// SDK-specific methods
|
|
2218
|
-
const getConversationHistory = useCallback(() => {
|
|
2219
|
-
if (currentSessionId && voiceSDK) {
|
|
2220
|
-
return voiceSDK.getConversationHistory(currentSessionId);
|
|
2221
|
-
}
|
|
2222
|
-
return [];
|
|
2223
|
-
}, [currentSessionId, voiceSDK]);
|
|
2224
|
-
const getVoiceState = useCallback(() => {
|
|
2225
|
-
if (currentSessionId && voiceSDK) {
|
|
2226
|
-
return voiceSDK.getVoiceState(currentSessionId);
|
|
2227
|
-
}
|
|
2228
|
-
return conversationState;
|
|
2229
|
-
}, [currentSessionId, voiceSDK, conversationState]);
|
|
2230
|
-
// Update isSpeaking state
|
|
2231
|
-
useEffect(() => {
|
|
2232
|
-
setConversationState(prev => ({
|
|
2233
|
-
...prev,
|
|
2234
|
-
isSpeaking: elevenLabsHook.isSpeaking,
|
|
2235
|
-
micMuted: elevenLabsHook.micMuted,
|
|
2236
|
-
}));
|
|
2237
|
-
}, [elevenLabsHook.isSpeaking, elevenLabsHook.micMuted]);
|
|
2238
|
-
// Cleanup active sessions on unmount
|
|
2239
|
-
useEffect(() => {
|
|
2240
|
-
return () => {
|
|
2241
|
-
if (voiceSDK) {
|
|
2242
|
-
voiceSDK.getActiveSessions().forEach(session => {
|
|
2243
|
-
voiceSDK.endVoiceSession(session.id);
|
|
2244
|
-
});
|
|
2245
|
-
}
|
|
2246
|
-
};
|
|
2247
|
-
}, [voiceSDK]);
|
|
2248
|
-
return {
|
|
2249
|
-
// Core session management
|
|
2250
|
-
startSession,
|
|
2251
|
-
endSession,
|
|
2252
|
-
// Audio controls
|
|
2253
|
-
setVolume,
|
|
2254
|
-
getInputByteFrequencyData,
|
|
2255
|
-
getOutputByteFrequencyData,
|
|
2256
|
-
getInputVolume,
|
|
2257
|
-
getOutputVolume,
|
|
2258
|
-
// Communication
|
|
2259
|
-
sendContextualUpdate,
|
|
2260
|
-
sendUserMessage: elevenLabsHook.sendUserMessage,
|
|
2261
|
-
sendUserActivity: elevenLabsHook.sendUserActivity,
|
|
2262
|
-
sendMCPToolApprovalResult: elevenLabsHook.sendMCPToolApprovalResult,
|
|
2263
|
-
// Feedback
|
|
2264
|
-
sendFeedback: elevenLabsHook.sendFeedback,
|
|
2265
|
-
canSendFeedback: elevenLabsHook.canSendFeedback,
|
|
2266
|
-
// State
|
|
2267
|
-
status: elevenLabsHook.status,
|
|
2268
|
-
micMuted: elevenLabsHook.micMuted,
|
|
2269
|
-
isSpeaking: elevenLabsHook.isSpeaking,
|
|
2270
|
-
getId: elevenLabsHook.getId,
|
|
2271
|
-
// SDK-specific features
|
|
2272
|
-
currentSessionId,
|
|
2273
|
-
conversationState,
|
|
2274
|
-
getConversationHistory,
|
|
2275
|
-
getVoiceState,
|
|
2276
|
-
voiceSDK,
|
|
2277
|
-
};
|
|
2278
|
-
}
|
|
2279
|
-
|
|
2280
|
-
export { BaseClient, ChatSDK, SmartTablesSDK, VoiceSDK, WorkflowSDK, ChatSDK as default, useVoiceConversation };
|
|
2024
|
+
export { BaseClient, CLIENT_TURN_ID_HEADER, ChatSDK, RESUMABLE_STREAM_HEADER, SmartTablesSDK, TURN_ID_HEADER, TurnStreamLostError, VoiceSDK, ChatSDK as default, newClientTurnId, postTurnWithRetry, readResumableTurn };
|
|
2281
2025
|
//# sourceMappingURL=index.esm.js.map
|