@oryksa/react-native 1.0.0 → 1.1.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/CHANGELOG.md +16 -0
- package/README.md +123 -98
- package/package.json +49 -9
- package/src/chat.js +225 -163
- package/src/client.js +133 -14
- package/src/index.d.ts +151 -53
- package/src/index.js +28 -18
- package/src/profanity.js +60 -0
- package/src/vad.js +264 -0
- package/src/voice-screen.js +141 -0
- package/src/voice.js +338 -0
package/src/chat.js
CHANGED
|
@@ -1,163 +1,225 @@
|
|
|
1
|
-
/*!
|
|
2
|
-
* @oryksa/react-native - the ORYKSA chat for React Native
|
|
3
|
-
* ORYKSA
|
|
4
|
-
* License: MIT
|
|
5
|
-
*/
|
|
6
|
-
"use strict";
|
|
7
|
-
|
|
8
|
-
const React = require("react");
|
|
9
|
-
const RN = require("react-native");
|
|
10
|
-
const { pick } = require("./client");
|
|
11
|
-
|
|
12
|
-
const
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
}, [
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
h(Text, { style: s.
|
|
104
|
-
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
});
|
|
162
|
-
|
|
163
|
-
|
|
1
|
+
/*!
|
|
2
|
+
* @oryksa/react-native - the ORYKSA chat for React Native: name and photo of the AI from
|
|
3
|
+
* the ORYKSA account, with voice (the same behaviour as the ORYKSA app).
|
|
4
|
+
* License: MIT
|
|
5
|
+
*/
|
|
6
|
+
"use strict";
|
|
7
|
+
|
|
8
|
+
const React = require("react");
|
|
9
|
+
const RN = require("react-native");
|
|
10
|
+
const { pick } = require("./client");
|
|
11
|
+
const { OryksaVoiceScreen, MicIcon } = require("./voice-screen");
|
|
12
|
+
const { createDefaultAudio } = require("./voice");
|
|
13
|
+
const profanity = require("./profanity");
|
|
14
|
+
|
|
15
|
+
const h = React.createElement;
|
|
16
|
+
const { View, Text, TextInput, Image, Pressable, FlatList, Modal, KeyboardAvoidingView, Platform, StyleSheet, SafeAreaView, useWindowDimensions } = RN;
|
|
17
|
+
|
|
18
|
+
const TX = {
|
|
19
|
+
en: { talk: "Talk to", ph: "Type your question", send: "Send", err: "Sorry, something went wrong. Try again.", voice: "Talk by voice", copy: "Copy" },
|
|
20
|
+
pt: { talk: "Falar com", ph: "Escreve a tua pergunta", send: "Enviar", err: "Desculpa, algo correu mal. Tenta de novo.", voice: "Falar por voz", copy: "Copiar" },
|
|
21
|
+
br: { talk: "Falar com", ph: "Digite sua pergunta", send: "Enviar", err: "Desculpe, algo deu errado. Tente de novo.", voice: "Falar por voz", copy: "Copiar" },
|
|
22
|
+
es: { talk: "Hablar con", ph: "Escribe tu pregunta", send: "Enviar", err: "Lo siento, algo salió mal. Inténtalo de nuevo.", voice: "Hablar por voz", copy: "Copiar" },
|
|
23
|
+
};
|
|
24
|
+
const DEFAULT_THEME = { accent: "#5B57E0", ink: "#161B3D", soft: "#EEEBFB", background: "#FFFFFF", muted: "#6B7280" };
|
|
25
|
+
const FALLBACK_AVATAR = "https://oryksa.com/assets/img/avatar_official_oryksa.png";
|
|
26
|
+
const L = (lang) => (TX[lang] ? lang : "en");
|
|
27
|
+
|
|
28
|
+
/** Text with **bold** parts (the server marks them, the app only draws them). */
|
|
29
|
+
function bold(text, style) {
|
|
30
|
+
const parts = String(text).split("**");
|
|
31
|
+
if (parts.length < 3) return text;
|
|
32
|
+
return parts.map((p, i) => (p ? (i % 2 === 1 ? h(Text, { key: i, style: [style, { fontWeight: "700" }] }, p) : p) : null));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The chat panel: header with the photo and name of the AI, messages, suggestions, input and (when
|
|
37
|
+
* the plan has voice and an audio adapter is available) the microphone that opens the voice screen.
|
|
38
|
+
* Props: client, lang, theme, onClose, appContext (() => ({ screen, title, items })), voice (default
|
|
39
|
+
* true), audio (adapter; default: react-native-live-audio-stream + react-native-sound + react-native-fs).
|
|
40
|
+
*/
|
|
41
|
+
function OryksaChat(props) {
|
|
42
|
+
const { client, lang = "en", theme, onClose, appContext, voice = true } = props;
|
|
43
|
+
const audio = React.useMemo(() => props.audio || createDefaultAudio(), [props.audio]);
|
|
44
|
+
const [voiceOpen, setVoiceOpen] = React.useState(false);
|
|
45
|
+
const th = Object.assign({}, DEFAULT_THEME, theme || {});
|
|
46
|
+
const tx = TX[L(lang)];
|
|
47
|
+
const [agent, setAgent] = React.useState(null);
|
|
48
|
+
const [msgs, setMsgs] = React.useState([]);
|
|
49
|
+
const [sug, setSug] = React.useState([]);
|
|
50
|
+
const [text, setText] = React.useState("");
|
|
51
|
+
const [busy, setBusy] = React.useState(false);
|
|
52
|
+
const listRef = React.useRef(null);
|
|
53
|
+
|
|
54
|
+
const [, setProfReady] = React.useState(0);
|
|
55
|
+
React.useEffect(() => {
|
|
56
|
+
// Swear words the customer types show as asterisks (one list for every ORYKSA chat).
|
|
57
|
+
profanity.load(L(lang)).then(() => setProfReady((n) => n + 1));
|
|
58
|
+
}, [lang]);
|
|
59
|
+
|
|
60
|
+
React.useEffect(() => {
|
|
61
|
+
let alive = true;
|
|
62
|
+
(async () => {
|
|
63
|
+
try {
|
|
64
|
+
const a = await client.agent();
|
|
65
|
+
const hist = await client.messages().catch(() => ({ messages: [] }));
|
|
66
|
+
if (!alive) return;
|
|
67
|
+
setAgent(a);
|
|
68
|
+
const past = (hist && hist.messages) || [];
|
|
69
|
+
if (past.length) {
|
|
70
|
+
setMsgs(past.map((m, i) => ({ id: "h" + i, role: m.role === "user" ? "user" : "assistant", text: m.content })));
|
|
71
|
+
} else {
|
|
72
|
+
const g = pick(a.greeting, L(lang));
|
|
73
|
+
if (g) setMsgs([{ id: "g", role: "assistant", text: g }]);
|
|
74
|
+
setSug((pick(a.suggestions, L(lang)) || []).slice(0, 4));
|
|
75
|
+
}
|
|
76
|
+
} catch (_) {
|
|
77
|
+
if (alive) setAgent({ name: "ORYKSA", avatar: FALLBACK_AVATAR });
|
|
78
|
+
}
|
|
79
|
+
})();
|
|
80
|
+
return () => { alive = false; };
|
|
81
|
+
}, [client, lang]);
|
|
82
|
+
|
|
83
|
+
const send = React.useCallback(async (value) => {
|
|
84
|
+
const q = String(value || "").trim();
|
|
85
|
+
if (!q || busy) return;
|
|
86
|
+
setBusy(true); setSug([]); setText("");
|
|
87
|
+
const id = String(Date.now());
|
|
88
|
+
setMsgs((m) => m.concat([{ id: id + "u", role: "user", text: q }, { id: id + "t", role: "typing", text: "..." }]));
|
|
89
|
+
let reply = null;
|
|
90
|
+
try { reply = await client.sendAndWait(q, { appContext: appContext ? appContext() : undefined }); } catch (_) { reply = null; }
|
|
91
|
+
setMsgs((m) => m.filter((x) => x.role !== "typing").concat([{ id: id + "a", role: "assistant", text: reply || tx.err }]));
|
|
92
|
+
setBusy(false);
|
|
93
|
+
}, [busy, client, tx]);
|
|
94
|
+
|
|
95
|
+
const name = (agent && agent.name) || "";
|
|
96
|
+
const sub = agent ? (pick(agent.subtitle, L(lang)) || agent.business || "") : "";
|
|
97
|
+
|
|
98
|
+
return h(View, { style: [s.panel, { backgroundColor: th.background }] },
|
|
99
|
+
h(View, { style: s.hd },
|
|
100
|
+
h(Image, { source: { uri: (agent && agent.avatar) || FALLBACK_AVATAR }, style: s.hdImg }),
|
|
101
|
+
h(View, { style: { flex: 1 } },
|
|
102
|
+
h(Text, { style: [s.hdName, { color: th.ink }], numberOfLines: 1 }, name.toUpperCase()),
|
|
103
|
+
sub ? h(Text, { style: [s.hdSub, { color: th.muted }], numberOfLines: 1 }, sub) : null),
|
|
104
|
+
onClose ? h(Pressable, { onPress: onClose, accessibilityRole: "button", accessibilityLabel: "close", hitSlop: 10 },
|
|
105
|
+
h(Text, { style: [s.close, { color: th.muted }] }, "×")) : null),
|
|
106
|
+
h(FlatList, {
|
|
107
|
+
ref: listRef,
|
|
108
|
+
data: msgs,
|
|
109
|
+
keyExtractor: (m) => m.id,
|
|
110
|
+
contentContainerStyle: { padding: 16 },
|
|
111
|
+
onContentSizeChange: () => listRef.current && listRef.current.scrollToEnd({ animated: true }),
|
|
112
|
+
renderItem: ({ item }) => {
|
|
113
|
+
const mine = item.role === "user";
|
|
114
|
+
const bubble = h(View, { style: [s.bubble, mine ? [s.me, { backgroundColor: th.accent }] : [s.ai, { backgroundColor: th.soft }], item.role === "typing" ? { opacity: 0.6 } : null] },
|
|
115
|
+
h(Text, { selectable: true, style: { color: mine ? "#fff" : th.ink, fontSize: 14, lineHeight: 21 } }, bold(mine ? profanity.mask(item.text, L(lang)) : item.text, { color: mine ? "#fff" : th.ink })));
|
|
116
|
+
if (mine || item.role === "typing" || !String(item.text || "").trim()) return bubble;
|
|
117
|
+
// Copy button under each reply of the AI (same as the ORYKSA apps and extension).
|
|
118
|
+
return h(View, null, bubble, h(CopyButton, { text: String(item.text).replace(/\*\*/g, ""), label: tx.copy, color: th.muted }));
|
|
119
|
+
},
|
|
120
|
+
}),
|
|
121
|
+
sug.length ? h(View, { style: s.sug }, sug.map((q) =>
|
|
122
|
+
h(Pressable, { key: q, onPress: () => send(q), style: s.chip }, h(Text, { style: { color: th.accent, fontSize: 12.5 } }, q)))) : null,
|
|
123
|
+
h(View, { style: s.form },
|
|
124
|
+
h(TextInput, {
|
|
125
|
+
value: text, onChangeText: setText, placeholder: tx.ph, placeholderTextColor: "#9CA3AF", maxLength: 2000,
|
|
126
|
+
style: [s.input, { color: th.ink }], returnKeyType: "send", onSubmitEditing: () => send(text),
|
|
127
|
+
}),
|
|
128
|
+
voice && audio && agent && agent.voice_replies && !text.trim()
|
|
129
|
+
? h(Pressable, { onPress: () => setVoiceOpen(true), disabled: busy, accessibilityRole: "button", accessibilityLabel: tx.voice, style: s.micBtn },
|
|
130
|
+
h(MicIcon, { color: th.accent }))
|
|
131
|
+
: null,
|
|
132
|
+
h(Pressable, { onPress: () => send(text), disabled: busy, style: [s.sendBtn, { backgroundColor: th.accent, opacity: busy ? 0.6 : 1 }] },
|
|
133
|
+
h(Text, { style: s.sendTxt }, tx.send.toUpperCase()))),
|
|
134
|
+
h(Text, { style: s.pw }, "POWERED BY ", h(Text, { style: { color: th.accent, fontWeight: "800" } }, "ORYKSA")),
|
|
135
|
+
voiceOpen ? h(OryksaVoiceScreen, {
|
|
136
|
+
client, agent, visible: true, lang: L(lang), theme: th, appContext, audio,
|
|
137
|
+
onClose: () => setVoiceOpen(false),
|
|
138
|
+
onUserText: (t) => { setSug([]); setMsgs((m) => m.concat([{ id: "v" + Date.now() + "u", role: "user", text: t }])); },
|
|
139
|
+
onReply: (t) => setMsgs((m) => m.concat([{ id: "v" + Date.now() + "a", role: "assistant", text: t }])),
|
|
140
|
+
}) : null);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Full-screen (phone) or floating (tablet) modal with the chat. */
|
|
144
|
+
function OryksaChatModal(props) {
|
|
145
|
+
const { visible, onClose } = props;
|
|
146
|
+
const { width } = useWindowDimensions();
|
|
147
|
+
const wide = width >= 600;
|
|
148
|
+
return h(Modal, { visible: !!visible, animationType: "slide", transparent: wide, onRequestClose: onClose },
|
|
149
|
+
h(KeyboardAvoidingView, { style: wide ? s.wideWrap : { flex: 1 }, behavior: Platform.OS === "ios" ? "padding" : undefined },
|
|
150
|
+
h(SafeAreaView, { style: wide ? s.wideCard : { flex: 1 } }, h(OryksaChat, Object.assign({}, props, { onClose })))));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Floating "Talk to name" button with the photo of the AI. Opens the chat. */
|
|
154
|
+
function OryksaChatButton(props) {
|
|
155
|
+
const { client, lang = "en", theme, position = "right", style, appContext, voice, audio } = props;
|
|
156
|
+
const th = Object.assign({}, DEFAULT_THEME, theme || {});
|
|
157
|
+
const [agent, setAgent] = React.useState(null);
|
|
158
|
+
const [open, setOpen] = React.useState(false);
|
|
159
|
+
React.useEffect(() => {
|
|
160
|
+
let alive = true;
|
|
161
|
+
client.agent().then((a) => { if (alive) setAgent(a); }).catch(() => {});
|
|
162
|
+
return () => { alive = false; };
|
|
163
|
+
}, [client]);
|
|
164
|
+
const tx = TX[L(lang)];
|
|
165
|
+
return h(React.Fragment, null,
|
|
166
|
+
h(Pressable, {
|
|
167
|
+
onPress: () => setOpen(true), accessibilityRole: "button",
|
|
168
|
+
style: [s.fab, position === "left" ? { left: 18 } : { right: 18 }, { backgroundColor: th.accent }, style],
|
|
169
|
+
},
|
|
170
|
+
h(Image, { source: { uri: (agent && agent.avatar) || FALLBACK_AVATAR }, style: s.fabImg }),
|
|
171
|
+
h(Text, { style: s.fabTxt }, (tx.talk + " " + ((agent && agent.name) || "ORYKSA")).toUpperCase())),
|
|
172
|
+
h(OryksaChatModal, { client, lang, theme, appContext, voice, audio, visible: open, onClose: () => setOpen(false) }));
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Copies text: @react-native-clipboard/clipboard when installed, else the Clipboard of older React Native. */
|
|
176
|
+
function copyText(t) {
|
|
177
|
+
try { const C = require("@react-native-clipboard/clipboard"); (C.default || C).setString(t); return true; } catch (e) {}
|
|
178
|
+
try { if (RN.Clipboard && RN.Clipboard.setString) { RN.Clipboard.setString(t); return true; } } catch (e) {}
|
|
179
|
+
return false;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Copy icon drawn with views (no icon font): two rounded squares; a check after copying. */
|
|
183
|
+
function CopyGlyph({ color, done }) {
|
|
184
|
+
if (done) return h(View, { style: { width: 14, height: 14, alignItems: "center", justifyContent: "center" } },
|
|
185
|
+
h(View, { style: { width: 11, height: 6, borderLeftWidth: 2, borderBottomWidth: 2, borderColor: color, transform: [{ rotate: "-45deg" }], marginTop: -3 } }));
|
|
186
|
+
return h(View, { style: { width: 14, height: 14 } },
|
|
187
|
+
h(View, { style: { position: "absolute", left: 0, top: 0, width: 9, height: 9, borderWidth: 1.6, borderColor: color, borderRadius: 2, borderRightWidth: 0, borderBottomWidth: 0 } }),
|
|
188
|
+
h(View, { style: { position: "absolute", left: 4, top: 4, width: 10, height: 10, borderWidth: 1.6, borderColor: color, borderRadius: 2 } }));
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Small copy button under a reply: copies the text and shows a check for a moment. */
|
|
192
|
+
function CopyButton({ text, label, color }) {
|
|
193
|
+
const [done, setDone] = React.useState(false);
|
|
194
|
+
React.useEffect(() => { if (!done) return undefined; const t = setTimeout(() => setDone(false), 1200); return () => clearTimeout(t); }, [done]);
|
|
195
|
+
return h(Pressable, { onPress: () => { if (copyText(text)) setDone(true); }, accessibilityRole: "button", accessibilityLabel: label, hitSlop: 8, style: s.copy },
|
|
196
|
+
h(CopyGlyph, { color, done }));
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const s = StyleSheet.create({
|
|
200
|
+
panel: { flex: 1 },
|
|
201
|
+
hd: { flexDirection: "row", alignItems: "center", gap: 12, paddingHorizontal: 16, paddingVertical: 14, borderBottomWidth: 1, borderBottomColor: "#ECEEF6" },
|
|
202
|
+
hdImg: { width: 46, height: 46, borderRadius: 23 },
|
|
203
|
+
hdName: { fontSize: 14, fontWeight: "800", letterSpacing: 2 },
|
|
204
|
+
hdSub: { fontSize: 12 },
|
|
205
|
+
close: { fontSize: 26, paddingHorizontal: 6 },
|
|
206
|
+
bubble: { maxWidth: "82%", paddingHorizontal: 14, paddingVertical: 10, borderRadius: 16, marginBottom: 10 },
|
|
207
|
+
copy: { alignSelf: "flex-start", padding: 6, marginTop: -6, marginBottom: 6, borderRadius: 7 },
|
|
208
|
+
ai: { alignSelf: "flex-start", borderBottomLeftRadius: 6 },
|
|
209
|
+
me: { alignSelf: "flex-end", borderBottomRightRadius: 6 },
|
|
210
|
+
sug: { flexDirection: "row", flexWrap: "wrap", gap: 8, paddingHorizontal: 16, paddingBottom: 10 },
|
|
211
|
+
chip: { borderWidth: 1, borderColor: "#DCDCF5", borderRadius: 999, paddingHorizontal: 12, paddingVertical: 7, backgroundColor: "#fff" },
|
|
212
|
+
form: { flexDirection: "row", borderTopWidth: 1, borderTopColor: "#ECEEF6" },
|
|
213
|
+
input: { flex: 1, paddingHorizontal: 16, paddingVertical: 14, fontSize: 14 },
|
|
214
|
+
sendBtn: { justifyContent: "center", paddingHorizontal: 18 },
|
|
215
|
+
sendTxt: { color: "#fff", fontWeight: "800", letterSpacing: 1.2 },
|
|
216
|
+
micBtn: { justifyContent: "center", paddingHorizontal: 12 },
|
|
217
|
+
pw: { textAlign: "center", fontSize: 10.5, letterSpacing: 1.3, color: "#9CA3AF", paddingTop: 6, paddingBottom: 8 },
|
|
218
|
+
wideWrap: { flex: 1, alignItems: "flex-end", justifyContent: "flex-end", padding: 22, paddingBottom: 92 },
|
|
219
|
+
wideCard: { width: 380, height: 560, borderRadius: 20, overflow: "hidden", backgroundColor: "#fff", elevation: 16, shadowColor: "#161B3D", shadowOpacity: 0.25, shadowRadius: 30, shadowOffset: { width: 0, height: 12 } },
|
|
220
|
+
fab: { position: "absolute", bottom: 22, flexDirection: "row", alignItems: "center", gap: 10, borderRadius: 999, paddingLeft: 8, paddingRight: 18, paddingVertical: 8, elevation: 8, shadowColor: "#161B3D", shadowOpacity: 0.28, shadowRadius: 15, shadowOffset: { width: 0, height: 6 } },
|
|
221
|
+
fabImg: { width: 42, height: 42, borderRadius: 21, borderWidth: 2, borderColor: "#fff" },
|
|
222
|
+
fabTxt: { color: "#fff", fontWeight: "800", fontSize: 13, letterSpacing: 1 },
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
module.exports = { OryksaChat, OryksaChatModal, OryksaChatButton, DEFAULT_THEME };
|
package/src/client.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
"use strict";
|
|
7
7
|
|
|
8
8
|
const DEFAULT_BASE = "https://api.oryksa.com/v1";
|
|
9
|
-
const VERSION = "1.
|
|
9
|
+
const VERSION = "1.1.1";
|
|
10
10
|
|
|
11
11
|
class OryksaError extends Error {
|
|
12
12
|
constructor(status, code, message, extra) {
|
|
@@ -49,6 +49,50 @@ async function request(base, token, method, path, body, fetchImpl, timeoutMs) {
|
|
|
49
49
|
return data || {};
|
|
50
50
|
}
|
|
51
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
|
+
|
|
52
96
|
class OryksaClient {
|
|
53
97
|
/**
|
|
54
98
|
* @param {{token?: string, getToken?: () => Promise<string>, baseUrl?: string, fetch?: Function, timeoutMs?: number}} opts
|
|
@@ -84,25 +128,100 @@ class OryksaClient {
|
|
|
84
128
|
/** Name, photo, greeting and suggestions of the AI employee. */
|
|
85
129
|
agent() { return this._req("GET", "/client/agent"); }
|
|
86
130
|
|
|
87
|
-
/**
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
131
|
+
/**
|
|
132
|
+
* Sends a message. status is "pending" when the AI needs a few more seconds: use sendAndWait.
|
|
133
|
+
* @param {string} message
|
|
134
|
+
* @param {{appContext?: {screen?: string, title?: string, items?: string[]}, voice?: boolean, whisper?: boolean, voiceStats?: object}} [opts]
|
|
135
|
+
* appContext: the screen the customer is on inside your app, so the AI answers about it.
|
|
136
|
+
* voice: the reply will be heard (it also carries a short `speech`). whisper: the customer whispered.
|
|
137
|
+
*/
|
|
138
|
+
send(message, opts) {
|
|
139
|
+
const o = opts || {};
|
|
140
|
+
const body = { message };
|
|
141
|
+
if (o.appContext) body.app_context = appContextJson(o.appContext);
|
|
142
|
+
if (o.voice) body.voice = true;
|
|
143
|
+
if (o.whisper) body.whisper = true;
|
|
144
|
+
if (o.voiceStats) { body.platform = "rn"; body.voice_stats = o.voiceStats; }
|
|
145
|
+
return this._req("POST", "/client/chat", body);
|
|
146
|
+
}
|
|
92
147
|
|
|
93
|
-
/**
|
|
94
|
-
async
|
|
95
|
-
const
|
|
96
|
-
|
|
97
|
-
|
|
148
|
+
/** Like sendAndWait, but returns the whole reply object ({ status, reply, speech, whisper }). */
|
|
149
|
+
async sendAndWaitReply(message, opts) {
|
|
150
|
+
const o = opts || {};
|
|
151
|
+
const r = await this.send(message, o);
|
|
152
|
+
if (!r || r.status !== "pending") return r || {};
|
|
153
|
+
const end = Date.now() + (o.maxWaitMs || 40000);
|
|
98
154
|
while (Date.now() < end) {
|
|
99
155
|
await new Promise((ok) => setTimeout(ok, 1500));
|
|
100
156
|
const h = await this.messages();
|
|
101
157
|
const last = ((h && h.messages) || []).slice(-1)[0];
|
|
102
|
-
if (last && last.role === "assistant") return last.content;
|
|
158
|
+
if (last && last.role === "assistant") return { status: "replied", reply: last.content, whisper: !!o.whisper };
|
|
103
159
|
}
|
|
104
|
-
return
|
|
160
|
+
return r;
|
|
105
161
|
}
|
|
162
|
+
|
|
163
|
+
async _raw(path, init) {
|
|
164
|
+
try {
|
|
165
|
+
return await rawFetch(this._base, await this._tok(false), path, init, this._fetch, this._timeout);
|
|
166
|
+
} catch (e) {
|
|
167
|
+
if (e instanceof OryksaError && (e.code === "session_expired" || e.status === 401) && this._getToken) {
|
|
168
|
+
return rawFetch(this._base, await this._tok(true), path, init, this._fetch, this._timeout);
|
|
169
|
+
}
|
|
170
|
+
throw e;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* The AI's voice (ElevenLabs, the voice chosen in ORYKSA) for one reply of this conversation, as MP3
|
|
176
|
+
* bytes (Uint8Array). Resolves null when the voice is not available: then show the text only.
|
|
177
|
+
*/
|
|
178
|
+
async tts(text, opts) {
|
|
179
|
+
try {
|
|
180
|
+
const body = { text };
|
|
181
|
+
if (opts && opts.whisper) body.whisper = true;
|
|
182
|
+
const res = await this._raw("/client/tts", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
|
183
|
+
const buf = new Uint8Array(await res.arrayBuffer());
|
|
184
|
+
return buf.length ? buf : null;
|
|
185
|
+
} catch (_) {
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Customer voice to text. wav: Uint8Array, 16 kHz mono PCM16 WAV, up to 15 s. "" = nothing said, null = failed. */
|
|
191
|
+
async transcribe(wav) {
|
|
192
|
+
try {
|
|
193
|
+
const mp = multipart(wav, "voice.wav", "audio/wav");
|
|
194
|
+
const res = await this._raw("/client/transcribe", { method: "POST", headers: { "Content-Type": mp.contentType, Accept: "application/json" }, body: mp.body });
|
|
195
|
+
const d = await res.json();
|
|
196
|
+
return String((d && d.text) || "").trim();
|
|
197
|
+
} catch (_) {
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Reports a voice turn that produced no message (nothing heard, a cut with nothing said). */
|
|
203
|
+
async voiceStats(stats) {
|
|
204
|
+
try { await this._req("POST", "/client/voice-stats", { platform: "rn", voice_stats: stats }); } catch (_) { /* telemetry only */ }
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Messages of this conversation: { messages: [{ role, content }] }. */
|
|
208
|
+
messages() { return this._req("GET", "/client/messages"); }
|
|
209
|
+
|
|
210
|
+
/** Sends a message and waits for the reply text. opts: { appContext } (or a number = maxWaitMs, as in 1.0). */
|
|
211
|
+
async sendAndWait(message, opts) {
|
|
212
|
+
const o = typeof opts === "number" ? { maxWaitMs: opts } : (opts || {});
|
|
213
|
+
const r = await this.sendAndWaitReply(message, o);
|
|
214
|
+
return (r && r.reply) || null;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** JSON of an app context: { screen, title, items (up to 20) }. */
|
|
219
|
+
function appContextJson(c) {
|
|
220
|
+
const o = {};
|
|
221
|
+
if (c.screen) o.screen = String(c.screen);
|
|
222
|
+
if (c.title) o.title = String(c.title);
|
|
223
|
+
if (Array.isArray(c.items) && c.items.length) o.items = c.items.slice(0, 20).map(String);
|
|
224
|
+
return o;
|
|
106
225
|
}
|
|
107
226
|
|
|
108
227
|
/** Picks the text for a language with fallbacks (br uses pt, then en). */
|
|
@@ -111,4 +230,4 @@ function pick(map, lang) {
|
|
|
111
230
|
return map[lang] || (lang === "br" ? map.pt : undefined) || map.en || Object.values(map)[0];
|
|
112
231
|
}
|
|
113
232
|
|
|
114
|
-
module.exports = { OryksaClient, OryksaError, pick, VERSION, DEFAULT_BASE };
|
|
233
|
+
module.exports = { OryksaClient, OryksaError, pick, appContextJson, multipart, VERSION, DEFAULT_BASE };
|