@oryksa/react-native 1.1.3 → 1.1.4
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/CHANGELOG.md +44 -37
- package/README.es.md +181 -161
- package/README.fr.md +181 -161
- package/README.md +181 -161
- package/README.pt.md +181 -161
- package/package.json +69 -69
- package/src/client.js +307 -267
- package/src/index.d.ts +257 -237
package/src/client.js
CHANGED
|
@@ -1,267 +1,307 @@
|
|
|
1
|
-
/*!
|
|
2
|
-
* @oryksa/react-native - in-app client. Uses a short-lived session token (oryk_cs_...)
|
|
3
|
-
* created by YOUR server with POST /v1/sessions. The secret API key never goes into the app.
|
|
4
|
-
* Docs: https://developer.oryksa.com License: MIT
|
|
5
|
-
*/
|
|
6
|
-
"use strict";
|
|
7
|
-
|
|
8
|
-
const DEFAULT_BASE = "https://api.oryksa.com/v1";
|
|
9
|
-
const VERSION = "1.1.
|
|
10
|
-
|
|
11
|
-
class OryksaError extends Error {
|
|
12
|
-
constructor(status, code, message, extra) {
|
|
13
|
-
super(message);
|
|
14
|
-
this.name = "OryksaError";
|
|
15
|
-
this.status = status;
|
|
16
|
-
this.code = code;
|
|
17
|
-
Object.assign(this, extra || {});
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
async function request(base, token, method, path, body, fetchImpl, timeoutMs) {
|
|
22
|
-
const f = fetchImpl || globalThis.fetch;
|
|
23
|
-
const ctrl = typeof AbortController !== "undefined" ? new AbortController() : null;
|
|
24
|
-
const timer = ctrl ? setTimeout(() => ctrl.abort(), timeoutMs) : null;
|
|
25
|
-
let res;
|
|
26
|
-
try {
|
|
27
|
-
res = await f(base + path, {
|
|
28
|
-
method,
|
|
29
|
-
headers: Object.assign(
|
|
30
|
-
{ Authorization: "Bearer " + token, Accept: "application/json", "X-ORYKSA-SDK": "react-native/" + VERSION },
|
|
31
|
-
body !== undefined ? { "Content-Type": "application/json" } : {}
|
|
32
|
-
),
|
|
33
|
-
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
34
|
-
signal: ctrl ? ctrl.signal : undefined,
|
|
35
|
-
});
|
|
36
|
-
} catch (e) {
|
|
37
|
-
throw new OryksaError(0, "network_error", "Could not reach ORYKSA: " + (e && e.message));
|
|
38
|
-
} finally {
|
|
39
|
-
if (timer) clearTimeout(timer);
|
|
40
|
-
}
|
|
41
|
-
let data = null;
|
|
42
|
-
try { data = await res.json(); } catch (_) { data = null; }
|
|
43
|
-
if (!res.ok && res.status !== 202) {
|
|
44
|
-
const e = (data && data.error) || {};
|
|
45
|
-
const extra = Object.assign({}, e);
|
|
46
|
-
delete extra.code; delete extra.message;
|
|
47
|
-
throw new OryksaError(res.status, e.code || "http_" + res.status, e.message || "Request failed with HTTP " + res.status, extra);
|
|
48
|
-
}
|
|
49
|
-
return data || {};
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/** One raw exchange (used for the voice: MP3 back, WAV up). Returns the Response. */
|
|
53
|
-
async function rawFetch(base, token, path, init, fetchImpl, timeoutMs) {
|
|
54
|
-
const f = fetchImpl || globalThis.fetch;
|
|
55
|
-
const ctrl = typeof AbortController !== "undefined" ? new AbortController() : null;
|
|
56
|
-
const timer = ctrl ? setTimeout(() => ctrl.abort(), timeoutMs) : null;
|
|
57
|
-
let res;
|
|
58
|
-
try {
|
|
59
|
-
res = await f(base + path, Object.assign({}, init, {
|
|
60
|
-
headers: Object.assign({ Authorization: "Bearer " + token, "X-ORYKSA-SDK": "react-native/" + VERSION }, init.headers || {}),
|
|
61
|
-
signal: ctrl ? ctrl.signal : undefined,
|
|
62
|
-
}));
|
|
63
|
-
} catch (e) {
|
|
64
|
-
throw new OryksaError(0, "network_error", "Could not reach ORYKSA: " + (e && e.message));
|
|
65
|
-
} finally {
|
|
66
|
-
if (timer) clearTimeout(timer);
|
|
67
|
-
}
|
|
68
|
-
if (!res.ok) {
|
|
69
|
-
let data = null;
|
|
70
|
-
try { data = await res.json(); } catch (_) { data = null; }
|
|
71
|
-
const e = (data && data.error) || {};
|
|
72
|
-
throw new OryksaError(res.status, e.code || "http_" + res.status, e.message || "Request failed with HTTP " + res.status);
|
|
73
|
-
}
|
|
74
|
-
return res;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
function utf8(str) {
|
|
78
|
-
if (typeof TextEncoder !== "undefined") return new TextEncoder().encode(str);
|
|
79
|
-
const out = [];
|
|
80
|
-
for (let i = 0; i < str.length; i++) out.push(str.charCodeAt(i) & 0xff); // ASCII only (multipart headers)
|
|
81
|
-
return new Uint8Array(out);
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
/** multipart/form-data body with one file field `file` (built by hand: works in React Native and Node). */
|
|
85
|
-
function multipart(bytes, filename, type) {
|
|
86
|
-
const boundary = "oryksa-" + Date.now().toString(36) + Math.random().toString(36).slice(2);
|
|
87
|
-
const head = utf8("--" + boundary + '\r\nContent-Disposition: form-data; name="file"; filename="' + filename + '"\r\nContent-Type: ' + type + "\r\n\r\n");
|
|
88
|
-
const tail = utf8("\r\n--" + boundary + "--\r\n");
|
|
89
|
-
const body = new Uint8Array(head.length + bytes.length + tail.length);
|
|
90
|
-
body.set(head, 0);
|
|
91
|
-
body.set(bytes, head.length);
|
|
92
|
-
body.set(tail, head.length + bytes.length);
|
|
93
|
-
return { body, contentType: "multipart/form-data; boundary=" + boundary };
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
class OryksaClient {
|
|
97
|
-
/**
|
|
98
|
-
* @param {{token?: string, getToken?: () => Promise<string>, baseUrl?: string, fetch?: Function, timeoutMs?: number}} opts
|
|
99
|
-
*/
|
|
100
|
-
constructor(opts) {
|
|
101
|
-
const o = opts || {};
|
|
102
|
-
if (!o.token && !o.getToken) throw new Error("OryksaClient needs { token } or { getToken }.");
|
|
103
|
-
if (o.token && String(o.token).startsWith("oryk_live_")) throw new Error("Never use the secret API key in an app. Use a session token (oryk_cs_...).");
|
|
104
|
-
this._token = o.token || null;
|
|
105
|
-
this._getToken = o.getToken || null;
|
|
106
|
-
this._base = String(o.baseUrl || DEFAULT_BASE).replace(/\/$/, "");
|
|
107
|
-
this._fetch = o.fetch;
|
|
108
|
-
this._timeout = o.timeoutMs || 60000;
|
|
109
|
-
this._previews = new Map();
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
async _tok(force) {
|
|
113
|
-
if ((!this._token || force) && this._getToken) this._token = await this._getToken();
|
|
114
|
-
if (!this._token) throw new OryksaError(401, "no_token", "No session token.");
|
|
115
|
-
return this._token;
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
async _req(method, path, body) {
|
|
119
|
-
try {
|
|
120
|
-
return await request(this._base, await this._tok(false), method, path, body, this._fetch, this._timeout);
|
|
121
|
-
} catch (e) {
|
|
122
|
-
if (e instanceof OryksaError && (e.code === "session_expired" || e.status === 401) && this._getToken) {
|
|
123
|
-
return request(this._base, await this._tok(true), method, path, body, this._fetch, this._timeout);
|
|
124
|
-
}
|
|
125
|
-
throw e;
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
/** Name, photo, greeting and suggestions of the AI employee. */
|
|
130
|
-
agent() { return this._req("GET", "/client/agent"); }
|
|
131
|
-
|
|
132
|
-
/**
|
|
133
|
-
* Title and picture of a link the AI gave, for the card under her reply:
|
|
134
|
-
* { object: "link_preview", url, title, image, site, price }. Only the pages of the business's own
|
|
135
|
-
* site (its website chat domains) get a title and a picture. Resolves null when it cannot be read;
|
|
136
|
-
* never throws. Kept in memory for this client.
|
|
137
|
-
*/
|
|
138
|
-
async linkPreview(url) {
|
|
139
|
-
const key = String(url || "");
|
|
140
|
-
if (this._previews.has(key)) return this._previews.get(key);
|
|
141
|
-
try {
|
|
142
|
-
const d = await this._req("GET", "/client/link-preview?url=" + encodeURIComponent(key));
|
|
143
|
-
const str = (v) => (v === null || v === undefined ? "" : String(v));
|
|
144
|
-
const p = { object: "link_preview", url: str(d.url), title: str(d.title), image: str(d.image), site: str(d.site), price: str(d.price) };
|
|
145
|
-
if (this._previews.size > 200) this._previews.clear();
|
|
146
|
-
this._previews.set(key, p);
|
|
147
|
-
return p;
|
|
148
|
-
} catch (_) {
|
|
149
|
-
return null;
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
/**
|
|
154
|
-
* Sends a message. status is "pending" when the AI needs a few more seconds: use sendAndWait.
|
|
155
|
-
* @param {string} message
|
|
156
|
-
* @param {{appContext?: {screen?: string, title?: string, items?: string[]}, voice?: boolean, whisper?: boolean, voiceStats?: object,
|
|
157
|
-
* image?: {base64: string, mime?: string}, file?: {base64: string, name: string, mime?: string}}} [opts]
|
|
158
|
-
* appContext: the screen the customer is on inside your app, so the AI answers about it.
|
|
159
|
-
* voice: the reply will be heard (it also carries a short `speech`). whisper: the customer whispered.
|
|
160
|
-
* image: a photo from the customer, the AI looks at it (up to 2 MB).
|
|
161
|
-
* file: a document from the customer (PDF, Word, text, CSV), the AI reads it (up to 8 MB).
|
|
162
|
-
*/
|
|
163
|
-
send(message, opts) {
|
|
164
|
-
return this._req("POST", "/client/chat", chatBody(message, opts));
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
/**
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
async
|
|
211
|
-
try {
|
|
212
|
-
const
|
|
213
|
-
|
|
214
|
-
const
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
if (
|
|
256
|
-
if (
|
|
257
|
-
if (
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
1
|
+
/*!
|
|
2
|
+
* @oryksa/react-native - in-app client. Uses a short-lived session token (oryk_cs_...)
|
|
3
|
+
* created by YOUR server with POST /v1/sessions. The secret API key never goes into the app.
|
|
4
|
+
* Docs: https://developer.oryksa.com License: MIT
|
|
5
|
+
*/
|
|
6
|
+
"use strict";
|
|
7
|
+
|
|
8
|
+
const DEFAULT_BASE = "https://api.oryksa.com/v1";
|
|
9
|
+
const VERSION = "1.1.4";
|
|
10
|
+
|
|
11
|
+
class OryksaError extends Error {
|
|
12
|
+
constructor(status, code, message, extra) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = "OryksaError";
|
|
15
|
+
this.status = status;
|
|
16
|
+
this.code = code;
|
|
17
|
+
Object.assign(this, extra || {});
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function request(base, token, method, path, body, fetchImpl, timeoutMs) {
|
|
22
|
+
const f = fetchImpl || globalThis.fetch;
|
|
23
|
+
const ctrl = typeof AbortController !== "undefined" ? new AbortController() : null;
|
|
24
|
+
const timer = ctrl ? setTimeout(() => ctrl.abort(), timeoutMs) : null;
|
|
25
|
+
let res;
|
|
26
|
+
try {
|
|
27
|
+
res = await f(base + path, {
|
|
28
|
+
method,
|
|
29
|
+
headers: Object.assign(
|
|
30
|
+
{ Authorization: "Bearer " + token, Accept: "application/json", "X-ORYKSA-SDK": "react-native/" + VERSION },
|
|
31
|
+
body !== undefined ? { "Content-Type": "application/json" } : {}
|
|
32
|
+
),
|
|
33
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
34
|
+
signal: ctrl ? ctrl.signal : undefined,
|
|
35
|
+
});
|
|
36
|
+
} catch (e) {
|
|
37
|
+
throw new OryksaError(0, "network_error", "Could not reach ORYKSA: " + (e && e.message));
|
|
38
|
+
} finally {
|
|
39
|
+
if (timer) clearTimeout(timer);
|
|
40
|
+
}
|
|
41
|
+
let data = null;
|
|
42
|
+
try { data = await res.json(); } catch (_) { data = null; }
|
|
43
|
+
if (!res.ok && res.status !== 202) {
|
|
44
|
+
const e = (data && data.error) || {};
|
|
45
|
+
const extra = Object.assign({}, e);
|
|
46
|
+
delete extra.code; delete extra.message;
|
|
47
|
+
throw new OryksaError(res.status, e.code || "http_" + res.status, e.message || "Request failed with HTTP " + res.status, extra);
|
|
48
|
+
}
|
|
49
|
+
return data || {};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** One raw exchange (used for the voice: MP3 back, WAV up). Returns the Response. */
|
|
53
|
+
async function rawFetch(base, token, path, init, fetchImpl, timeoutMs) {
|
|
54
|
+
const f = fetchImpl || globalThis.fetch;
|
|
55
|
+
const ctrl = typeof AbortController !== "undefined" ? new AbortController() : null;
|
|
56
|
+
const timer = ctrl ? setTimeout(() => ctrl.abort(), timeoutMs) : null;
|
|
57
|
+
let res;
|
|
58
|
+
try {
|
|
59
|
+
res = await f(base + path, Object.assign({}, init, {
|
|
60
|
+
headers: Object.assign({ Authorization: "Bearer " + token, "X-ORYKSA-SDK": "react-native/" + VERSION }, init.headers || {}),
|
|
61
|
+
signal: ctrl ? ctrl.signal : undefined,
|
|
62
|
+
}));
|
|
63
|
+
} catch (e) {
|
|
64
|
+
throw new OryksaError(0, "network_error", "Could not reach ORYKSA: " + (e && e.message));
|
|
65
|
+
} finally {
|
|
66
|
+
if (timer) clearTimeout(timer);
|
|
67
|
+
}
|
|
68
|
+
if (!res.ok) {
|
|
69
|
+
let data = null;
|
|
70
|
+
try { data = await res.json(); } catch (_) { data = null; }
|
|
71
|
+
const e = (data && data.error) || {};
|
|
72
|
+
throw new OryksaError(res.status, e.code || "http_" + res.status, e.message || "Request failed with HTTP " + res.status);
|
|
73
|
+
}
|
|
74
|
+
return res;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function utf8(str) {
|
|
78
|
+
if (typeof TextEncoder !== "undefined") return new TextEncoder().encode(str);
|
|
79
|
+
const out = [];
|
|
80
|
+
for (let i = 0; i < str.length; i++) out.push(str.charCodeAt(i) & 0xff); // ASCII only (multipart headers)
|
|
81
|
+
return new Uint8Array(out);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** multipart/form-data body with one file field `file` (built by hand: works in React Native and Node). */
|
|
85
|
+
function multipart(bytes, filename, type) {
|
|
86
|
+
const boundary = "oryksa-" + Date.now().toString(36) + Math.random().toString(36).slice(2);
|
|
87
|
+
const head = utf8("--" + boundary + '\r\nContent-Disposition: form-data; name="file"; filename="' + filename + '"\r\nContent-Type: ' + type + "\r\n\r\n");
|
|
88
|
+
const tail = utf8("\r\n--" + boundary + "--\r\n");
|
|
89
|
+
const body = new Uint8Array(head.length + bytes.length + tail.length);
|
|
90
|
+
body.set(head, 0);
|
|
91
|
+
body.set(bytes, head.length);
|
|
92
|
+
body.set(tail, head.length + bytes.length);
|
|
93
|
+
return { body, contentType: "multipart/form-data; boundary=" + boundary };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
class OryksaClient {
|
|
97
|
+
/**
|
|
98
|
+
* @param {{token?: string, getToken?: () => Promise<string>, baseUrl?: string, fetch?: Function, timeoutMs?: number}} opts
|
|
99
|
+
*/
|
|
100
|
+
constructor(opts) {
|
|
101
|
+
const o = opts || {};
|
|
102
|
+
if (!o.token && !o.getToken) throw new Error("OryksaClient needs { token } or { getToken }.");
|
|
103
|
+
if (o.token && String(o.token).startsWith("oryk_live_")) throw new Error("Never use the secret API key in an app. Use a session token (oryk_cs_...).");
|
|
104
|
+
this._token = o.token || null;
|
|
105
|
+
this._getToken = o.getToken || null;
|
|
106
|
+
this._base = String(o.baseUrl || DEFAULT_BASE).replace(/\/$/, "");
|
|
107
|
+
this._fetch = o.fetch;
|
|
108
|
+
this._timeout = o.timeoutMs || 60000;
|
|
109
|
+
this._previews = new Map();
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async _tok(force) {
|
|
113
|
+
if ((!this._token || force) && this._getToken) this._token = await this._getToken();
|
|
114
|
+
if (!this._token) throw new OryksaError(401, "no_token", "No session token.");
|
|
115
|
+
return this._token;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async _req(method, path, body) {
|
|
119
|
+
try {
|
|
120
|
+
return await request(this._base, await this._tok(false), method, path, body, this._fetch, this._timeout);
|
|
121
|
+
} catch (e) {
|
|
122
|
+
if (e instanceof OryksaError && (e.code === "session_expired" || e.status === 401) && this._getToken) {
|
|
123
|
+
return request(this._base, await this._tok(true), method, path, body, this._fetch, this._timeout);
|
|
124
|
+
}
|
|
125
|
+
throw e;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Name, photo, greeting and suggestions of the AI employee. */
|
|
130
|
+
agent() { return this._req("GET", "/client/agent"); }
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Title and picture of a link the AI gave, for the card under her reply:
|
|
134
|
+
* { object: "link_preview", url, title, image, site, price }. Only the pages of the business's own
|
|
135
|
+
* site (its website chat domains) get a title and a picture. Resolves null when it cannot be read;
|
|
136
|
+
* never throws. Kept in memory for this client.
|
|
137
|
+
*/
|
|
138
|
+
async linkPreview(url) {
|
|
139
|
+
const key = String(url || "");
|
|
140
|
+
if (this._previews.has(key)) return this._previews.get(key);
|
|
141
|
+
try {
|
|
142
|
+
const d = await this._req("GET", "/client/link-preview?url=" + encodeURIComponent(key));
|
|
143
|
+
const str = (v) => (v === null || v === undefined ? "" : String(v));
|
|
144
|
+
const p = { object: "link_preview", url: str(d.url), title: str(d.title), image: str(d.image), site: str(d.site), price: str(d.price) };
|
|
145
|
+
if (this._previews.size > 200) this._previews.clear();
|
|
146
|
+
this._previews.set(key, p);
|
|
147
|
+
return p;
|
|
148
|
+
} catch (_) {
|
|
149
|
+
return null;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Sends a message. status is "pending" when the AI needs a few more seconds: use sendAndWait.
|
|
155
|
+
* @param {string} message
|
|
156
|
+
* @param {{appContext?: {screen?: string, title?: string, items?: string[]}, voice?: boolean, whisper?: boolean, voiceStats?: object,
|
|
157
|
+
* image?: {base64: string, mime?: string}, file?: {base64: string, name: string, mime?: string}}} [opts]
|
|
158
|
+
* appContext: the screen the customer is on inside your app, so the AI answers about it.
|
|
159
|
+
* voice: the reply will be heard (it also carries a short `speech`). whisper: the customer whispered.
|
|
160
|
+
* image: a photo from the customer, the AI looks at it (up to 2 MB).
|
|
161
|
+
* file: a document from the customer (PDF, Word, text, CSV), the AI reads it (up to 8 MB).
|
|
162
|
+
*/
|
|
163
|
+
send(message, opts) {
|
|
164
|
+
return this._req("POST", "/client/chat", chatBody(message, opts));
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* An AI task of your own app, counted as ORYKSA interactions (1 per answer): read a photo, extract data,
|
|
169
|
+
* classify, translate, write. It never creates a conversation in the business's inbox and never acts on
|
|
170
|
+
* the account. Your prompt (instructions) and your JSON Schema (schema) live in your app.
|
|
171
|
+
* @param {{instructions?: string, input?: string, images?: {base64: string, mime?: string}[], schema?: object,
|
|
172
|
+
* maxTokens?: number, temperature?: number}} opts images: up to 4 photos (about 1.5 MB each; resize to 1600 px).
|
|
173
|
+
* @returns {Promise<{text: string, json: object|null, interactionsSpent: number, interactionsRemaining: number|null}>}
|
|
174
|
+
*/
|
|
175
|
+
async ai(opts) {
|
|
176
|
+
const d = await this._req("POST", "/client/ai", aiBody(opts));
|
|
177
|
+
return aiResult(d);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Like sendAndWait, but returns the whole reply object ({ status, reply, speech, whisper }). */
|
|
181
|
+
async sendAndWaitReply(message, opts) {
|
|
182
|
+
const o = opts || {};
|
|
183
|
+
const r = await this.send(message, o);
|
|
184
|
+
if (!r || r.status !== "pending") return r || {};
|
|
185
|
+
const end = Date.now() + (o.maxWaitMs || 40000);
|
|
186
|
+
while (Date.now() < end) {
|
|
187
|
+
await new Promise((ok) => setTimeout(ok, 1500));
|
|
188
|
+
const h = await this.messages();
|
|
189
|
+
const last = ((h && h.messages) || []).slice(-1)[0];
|
|
190
|
+
if (last && last.role === "assistant") return { status: "replied", reply: last.content, whisper: !!o.whisper };
|
|
191
|
+
}
|
|
192
|
+
return r;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async _raw(path, init) {
|
|
196
|
+
try {
|
|
197
|
+
return await rawFetch(this._base, await this._tok(false), path, init, this._fetch, this._timeout);
|
|
198
|
+
} catch (e) {
|
|
199
|
+
if (e instanceof OryksaError && (e.code === "session_expired" || e.status === 401) && this._getToken) {
|
|
200
|
+
return rawFetch(this._base, await this._tok(true), path, init, this._fetch, this._timeout);
|
|
201
|
+
}
|
|
202
|
+
throw e;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* The AI's voice (ElevenLabs, the voice chosen in ORYKSA) for one reply of this conversation, as MP3
|
|
208
|
+
* bytes (Uint8Array). Resolves null when the voice is not available: then show the text only.
|
|
209
|
+
*/
|
|
210
|
+
async tts(text, opts) {
|
|
211
|
+
try {
|
|
212
|
+
const body = { text };
|
|
213
|
+
if (opts && opts.whisper) body.whisper = true;
|
|
214
|
+
const res = await this._raw("/client/tts", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
|
215
|
+
const buf = new Uint8Array(await res.arrayBuffer());
|
|
216
|
+
return buf.length ? buf : null;
|
|
217
|
+
} catch (_) {
|
|
218
|
+
return null;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Customer voice to text. wav: Uint8Array, 16 kHz mono PCM16 WAV, up to 15 s. "" = nothing said, null = failed. */
|
|
223
|
+
async transcribe(wav) {
|
|
224
|
+
try {
|
|
225
|
+
const mp = multipart(wav, "voice.wav", "audio/wav");
|
|
226
|
+
const res = await this._raw("/client/transcribe", { method: "POST", headers: { "Content-Type": mp.contentType, Accept: "application/json" }, body: mp.body });
|
|
227
|
+
const d = await res.json();
|
|
228
|
+
return String((d && d.text) || "").trim();
|
|
229
|
+
} catch (_) {
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Reports a voice turn that produced no message (nothing heard, a cut with nothing said). */
|
|
235
|
+
async voiceStats(stats) {
|
|
236
|
+
try { await this._req("POST", "/client/voice-stats", { platform: "rn", voice_stats: stats }); } catch (_) { /* telemetry only */ }
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Messages of this conversation: { messages: [{ role, content }] }. */
|
|
240
|
+
messages() { return this._req("GET", "/client/messages"); }
|
|
241
|
+
|
|
242
|
+
/** Sends a message and waits for the reply text. opts: { appContext } (or a number = maxWaitMs, as in 1.0). */
|
|
243
|
+
async sendAndWait(message, opts) {
|
|
244
|
+
const o = typeof opts === "number" ? { maxWaitMs: opts } : (opts || {});
|
|
245
|
+
const r = await this.sendAndWaitReply(message, o);
|
|
246
|
+
return (r && r.reply) || null;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** The JSON of POST /v1/client/chat. */
|
|
251
|
+
function chatBody(message, opts) {
|
|
252
|
+
const o = opts || {};
|
|
253
|
+
const body = { message };
|
|
254
|
+
if (o.appContext) body.app_context = appContextJson(o.appContext);
|
|
255
|
+
if (o.voice) body.voice = true;
|
|
256
|
+
if (o.whisper) body.whisper = true;
|
|
257
|
+
if (o.voiceStats) { body.platform = "rn"; body.voice_stats = o.voiceStats; }
|
|
258
|
+
if (o.image && o.image.base64) { body.image_base64 = o.image.base64; body.image_mime = o.image.mime || "image/jpeg"; }
|
|
259
|
+
if (o.file && typeof o.file.base64 === "string") {
|
|
260
|
+
body.file_base64 = o.file.base64; body.file_name = o.file.name || "file"; body.file_mime = o.file.mime || "application/octet-stream";
|
|
261
|
+
}
|
|
262
|
+
return body;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** The JSON of POST /v1/client/ai. */
|
|
266
|
+
function aiBody(opts) {
|
|
267
|
+
const o = opts || {};
|
|
268
|
+
const images = Array.isArray(o.images) ? o.images : [];
|
|
269
|
+
if (!o.instructions && !o.input && !images.length) throw new Error("ai() needs instructions, input or an image.");
|
|
270
|
+
if (images.length > 4) throw new Error("ai() takes at most 4 images.");
|
|
271
|
+
const body = { platform: "rn" };
|
|
272
|
+
if (o.instructions) body.instructions = String(o.instructions);
|
|
273
|
+
if (o.input) body.input = String(o.input);
|
|
274
|
+
if (images.length) body.images = images.map((i) => ({ base64: i.base64, mime: i.mime || "image/jpeg" }));
|
|
275
|
+
if (o.schema) body.schema = o.schema;
|
|
276
|
+
if (o.maxTokens != null) body.max_tokens = o.maxTokens;
|
|
277
|
+
if (o.temperature != null) body.temperature = o.temperature;
|
|
278
|
+
return body;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Reads an ai_result answer. */
|
|
282
|
+
function aiResult(d) {
|
|
283
|
+
const use = (d && d.oryksa) || {};
|
|
284
|
+
return {
|
|
285
|
+
text: (d && d.text) || "",
|
|
286
|
+
json: d && d.json && typeof d.json === "object" ? d.json : null,
|
|
287
|
+
interactionsSpent: use.interactions_spent || 0,
|
|
288
|
+
interactionsRemaining: use.interactions_remaining == null ? null : use.interactions_remaining,
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** JSON of an app context: { screen, title, items (up to 20) }. */
|
|
293
|
+
function appContextJson(c) {
|
|
294
|
+
const o = {};
|
|
295
|
+
if (c.screen) o.screen = String(c.screen);
|
|
296
|
+
if (c.title) o.title = String(c.title);
|
|
297
|
+
if (Array.isArray(c.items) && c.items.length) o.items = c.items.slice(0, 20).map(String);
|
|
298
|
+
return o;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Picks the text for a language with fallbacks (br uses pt, then en). */
|
|
302
|
+
function pick(map, lang) {
|
|
303
|
+
if (!map || typeof map !== "object") return undefined;
|
|
304
|
+
return map[lang] || (lang === "br" ? map.pt : undefined) || map.en || Object.values(map)[0];
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
module.exports = { OryksaClient, OryksaError, pick, appContextJson, chatBody, aiBody, aiResult, multipart, VERSION, DEFAULT_BASE };
|