@guideai/react-native 0.3.0 → 0.7.0

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/dist/voice.cjs CHANGED
@@ -2,17 +2,109 @@
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const React = require("react");
4
4
  const expoAudio = require("expo-audio");
5
- const setup = require("./setup-Bl0ZLz8B.cjs");
6
- const MIC_REFUSED = "Allow microphone access in Settings to talk to the assistant.";
7
- const START_FAILED = "The microphone didn't start. Please try again.";
8
- function profileLanguage() {
9
- var _a;
10
- const language = (_a = setup.requireConfigured().profile) == null ? void 0 : _a.language;
11
- return typeof language === "string" && language.trim() ? language.trim() : void 0;
5
+ const useConversations = require("./useConversations-CTbQBTz-.cjs");
6
+ const expoFileSystem = require("expo-file-system");
7
+ const jsxRuntime = require("react/jsx-runtime");
8
+ const GuideAIChat = require("./GuideAIChat-CxyWFl_o.cjs");
9
+ const DEFAULT_VOICE_LANGUAGES = [
10
+ { code: "en", label: "English" },
11
+ { code: "fr", label: "Français" },
12
+ { code: "ha", label: "Hausa" },
13
+ { code: "yo", label: "Yorùbá" },
14
+ { code: "sw", label: "Kiswahili" },
15
+ { code: "ar", label: "العربية" },
16
+ { code: "pt", label: "Português" },
17
+ { code: "es", label: "Español" }
18
+ ];
19
+ const KEY = "guideai_voice_language";
20
+ let state = { code: null, choosing: false, asker: null, resume: null };
21
+ let loadedFor = null;
22
+ const listeners = /* @__PURE__ */ new Set();
23
+ function set(next) {
24
+ state = { ...state, ...next };
25
+ for (const listener of listeners) listener();
26
+ }
27
+ function load() {
28
+ if (!useConversations.GuideAI.isConfigured()) return;
29
+ const configured = useConversations.requireConfigured();
30
+ if (loadedFor === configured && state.code) return;
31
+ loadedFor = configured;
32
+ let saved = null;
33
+ try {
34
+ saved = configured.storage.getItem(KEY);
35
+ } catch {
36
+ saved = null;
37
+ }
38
+ if (saved && saved !== state.code) set({ code: saved });
12
39
  }
40
+ const subscribe = (listener) => {
41
+ listeners.add(listener);
42
+ return () => {
43
+ listeners.delete(listener);
44
+ };
45
+ };
46
+ const snapshot = () => state;
47
+ function useVoiceLanguage(options, me, onResume) {
48
+ var _a, _b, _c;
49
+ const current = React.useSyncExternalStore(subscribe, snapshot, snapshot);
50
+ const languages = ((_a = options.languages) == null ? void 0 : _a.length) ? options.languages : DEFAULT_VOICE_LANGUAGES;
51
+ React.useEffect(() => {
52
+ load();
53
+ if (state.code || options.languageCode) return void 0;
54
+ const timer = setInterval(() => {
55
+ load();
56
+ if (state.code) clearInterval(timer);
57
+ }, 500);
58
+ const giveUp = setTimeout(() => clearInterval(timer), 5e3);
59
+ return () => {
60
+ clearInterval(timer);
61
+ clearTimeout(giveUp);
62
+ };
63
+ }, [options.languageCode]);
64
+ React.useEffect(() => {
65
+ var _a2;
66
+ if (((_a2 = current.resume) == null ? void 0 : _a2.who) !== me) return;
67
+ set({ resume: null });
68
+ onResume();
69
+ }, [current.resume, me, onResume]);
70
+ const code = (_b = options.languageCode) != null ? _b : current.code;
71
+ const language = code ? (_c = languages.find((entry) => entry.code === code)) != null ? _c : { code, label: code } : null;
72
+ return {
73
+ code,
74
+ language,
75
+ languages,
76
+ choosingLanguage: current.choosing,
77
+ ask: React.useCallback(() => set({ choosing: true, asker: me }), [me]),
78
+ chooseLanguage: React.useCallback(async (chosen) => {
79
+ var _a2, _b2;
80
+ try {
81
+ useConversations.requireConfigured().storage.setItem(KEY, chosen);
82
+ } catch {
83
+ }
84
+ const asker = state.asker;
85
+ set({
86
+ code: chosen,
87
+ choosing: false,
88
+ asker: null,
89
+ resume: asker ? { who: asker, n: ((_b2 = (_a2 = state.resume) == null ? void 0 : _a2.n) != null ? _b2 : 0) + 1 } : null
90
+ });
91
+ }, []),
92
+ changeLanguage: React.useCallback(() => set({ choosing: true, asker: null }), []),
93
+ cancelLanguage: React.useCallback(() => set({ choosing: false, asker: null }), [])
94
+ };
95
+ }
96
+ const MIC_REFUSED$1 = "Allow microphone access in Settings to talk to the assistant.";
97
+ const START_FAILED$1 = "The microphone didn't start. Please try again.";
13
98
  function useVoiceInput(chat, options = {}) {
14
99
  var _a;
15
100
  const recorder = expoAudio.useAudioRecorder(expoAudio.RecordingPresets.HIGH_QUALITY);
101
+ const me = React.useRef({}).current;
102
+ const startRef = React.useRef(async () => false);
103
+ const resume = React.useCallback(() => {
104
+ void startRef.current();
105
+ }, []);
106
+ const lang = useVoiceLanguage(options, me, resume);
107
+ const languageCode = lang.code;
16
108
  const [recording, setRecording] = React.useState(false);
17
109
  const [error, setError] = React.useState(null);
18
110
  const limit = React.useRef(null);
@@ -39,9 +131,13 @@ function useVoiceInput(chat, options = {}) {
39
131
  const start = React.useCallback(async () => {
40
132
  if (recording || chat.busy || chat.transcribing) return false;
41
133
  setError(null);
134
+ if (!languageCode) {
135
+ lang.ask();
136
+ return false;
137
+ }
42
138
  const permission = await expoAudio.requestRecordingPermissionsAsync().catch(() => null);
43
139
  if (!(permission == null ? void 0 : permission.granted)) {
44
- if (mounted.current) setError(MIC_REFUSED);
140
+ if (mounted.current) setError(MIC_REFUSED$1);
45
141
  return false;
46
142
  }
47
143
  try {
@@ -50,7 +146,7 @@ function useVoiceInput(chat, options = {}) {
50
146
  recorder.record();
51
147
  } catch (cause) {
52
148
  console.log("[GuideAI] ✗ microphone did not start:", cause);
53
- if (mounted.current) setError(START_FAILED);
149
+ if (mounted.current) setError(START_FAILED$1);
54
150
  return false;
55
151
  }
56
152
  if (mounted.current) setRecording(true);
@@ -58,9 +154,10 @@ function useVoiceInput(chat, options = {}) {
58
154
  void stopRef.current();
59
155
  }, maxSeconds * 1e3);
60
156
  return true;
61
- }, [recording, chat.busy, chat.transcribing, recorder, maxSeconds]);
157
+ }, [recording, chat.busy, chat.transcribing, recorder, maxSeconds, languageCode, lang]);
158
+ startRef.current = start;
62
159
  const stop = React.useCallback(async () => {
63
- var _a2, _b;
160
+ var _a2;
64
161
  let uri = null;
65
162
  try {
66
163
  uri = await finish();
@@ -70,11 +167,11 @@ function useVoiceInput(chat, options = {}) {
70
167
  if (!uri) return null;
71
168
  const result = await chat.sendVoice({
72
169
  uri,
73
- languageCode: (_a2 = options.languageCode) != null ? _a2 : profileLanguage()
170
+ languageCode: languageCode != null ? languageCode : void 0
74
171
  });
75
- if (mounted.current) setError((_b = result.error) != null ? _b : null);
172
+ if (mounted.current) setError((_a2 = result.error) != null ? _a2 : null);
76
173
  return result.text;
77
- }, [finish, chat, options.languageCode]);
174
+ }, [finish, chat, languageCode]);
78
175
  stopRef.current = stop;
79
176
  const cancel = React.useCallback(async () => {
80
177
  await finish().catch(() => null);
@@ -83,7 +180,361 @@ function useVoiceInput(chat, options = {}) {
83
180
  if (recording) await stop();
84
181
  else await start();
85
182
  }, [recording, start, stop]);
86
- return { recording, transcribing: chat.transcribing, error, start, stop, cancel, toggle };
183
+ return {
184
+ recording,
185
+ transcribing: chat.transcribing,
186
+ error,
187
+ start,
188
+ stop,
189
+ cancel,
190
+ toggle,
191
+ language: lang.language,
192
+ languages: lang.languages,
193
+ choosingLanguage: lang.choosingLanguage,
194
+ chooseLanguage: lang.chooseLanguage,
195
+ changeLanguage: lang.changeLanguage,
196
+ cancelLanguage: lang.cancelLanguage
197
+ };
198
+ }
199
+ const MAX_LINE_CHARS = 230;
200
+ function mathWords(tex) {
201
+ let s = tex;
202
+ for (let i = 0; i < 4; i += 1) {
203
+ s = s.replace(/\\[dt]?frac\{([^{}]*)\}\{([^{}]*)\}/g, " $1 over $2 ").replace(/\\sqrt\{([^{}]*)\}/g, " the square root of $1 ").replace(/\\text\{([^{}]*)\}/g, " $1 ").replace(/\\mathrm\{([^{}]*)\}/g, " $1 ");
204
+ }
205
+ return s.replace(/\^\{?2\}?/g, " squared ").replace(/\^\{?3\}?/g, " cubed ").replace(/\^\{([^{}]*)\}/g, " to the power $1 ").replace(/\^(\w)/g, " to the power $1 ").replace(/_\{([^{}]*)\}/g, " $1 ").replace(/\\times|\\cdot/g, " times ").replace(/\\div/g, " divided by ").replace(/\\pm/g, " plus or minus ").replace(/\\leq?/g, " less than or equal to ").replace(/\\geq?/g, " greater than or equal to ").replace(/\\neq?/g, " not equal to ").replace(/\\approx/g, " approximately ").replace(/\\pi/g, " pi ").replace(/\\theta/g, " theta ").replace(/\\(right|left)arrow|\\to/g, " gives ").replace(/\\[a-zA-Z]+/g, " ").replace(/[{}]/g, " ").replace(/\s*=\s*/g, " equals ").replace(/(\d)\s*-\s*(\d)/g, "$1 minus $2").replace(/\s+-\s+/g, " minus ").replace(/\s*\+\s*/g, " plus ");
206
+ }
207
+ function toSpeakable(markdown) {
208
+ return markdown.replace(/```[\s\S]*?(```|$)/g, " ").replace(/!\[[^\]]*\]\([^)]*\)/g, " ").replace(/\[([^\]]+)\]\([^)]*\)/g, "$1").replace(/\\\[([\s\S]*?)\\\]/g, (_, tex) => `. ${mathWords(tex)}. `).replace(/\\\(([\s\S]*?)\\\)/g, (_, tex) => mathWords(tex)).replace(/\$\$([\s\S]*?)\$\$/g, (_, tex) => `. ${mathWords(tex)}. `).replace(/`([^`]*)`/g, "$1").replace(/^\s*\|?[\s:|-]+\|[\s:|-]*$/gm, " ").replace(/\|/g, ", ").replace(/^#{1,6}\s*/gm, "").replace(/^\s*[-*•]\s+/gm, "").replace(/(\*\*|__)(.*?)\1/g, "$2").replace(/(^|\s)[*_](\S[^*_]*?)[*_](?=\s|[.,!?]|$)/g, "$1$2").replace(/\n{2,}/g, ". ").replace(/\n/g, " ").replace(/\s+([.,!?;:])/g, "$1").replace(/([.!?])(\s*[.!?])+/g, "$1").replace(/\s{2,}/g, " ").trim();
209
+ }
210
+ function speechLines(text, max = MAX_LINE_CHARS) {
211
+ var _a, _b;
212
+ const sentences = (_b = (_a = text.match(/[^.!?]+[.!?]*/g)) == null ? void 0 : _a.map((s) => s.trim()).filter(Boolean)) != null ? _b : [];
213
+ const lines = [];
214
+ let current = "";
215
+ const push = (piece) => {
216
+ if (!piece) return;
217
+ if (piece.length > max) {
218
+ let rest = piece;
219
+ while (rest.length > max) {
220
+ const cut = Math.max(rest.lastIndexOf(", ", max), rest.lastIndexOf(" ", max));
221
+ const at = cut > max / 2 ? cut + 1 : max;
222
+ lines.push(rest.slice(0, at).trim());
223
+ rest = rest.slice(at).trim();
224
+ }
225
+ if (rest) lines.push(rest);
226
+ return;
227
+ }
228
+ lines.push(piece);
229
+ };
230
+ for (const sentence of sentences) {
231
+ if (!current) current = sentence;
232
+ else if (current.length + 1 + sentence.length <= max) current = `${current} ${sentence}`;
233
+ else {
234
+ push(current);
235
+ current = sentence;
236
+ }
237
+ }
238
+ push(current);
239
+ return lines;
240
+ }
241
+ const MIN_HEARD_MS = 400;
242
+ const MAX_LINE_MS = 6e4;
243
+ function wavFromPcm(pcm, sampleRate) {
244
+ const out = new Uint8Array(44 + pcm.length);
245
+ const view = new DataView(out.buffer);
246
+ const text = (at, s) => {
247
+ for (let i = 0; i < s.length; i += 1) out[at + i] = s.charCodeAt(i);
248
+ };
249
+ text(0, "RIFF");
250
+ view.setUint32(4, 36 + pcm.length, true);
251
+ text(8, "WAVE");
252
+ text(12, "fmt ");
253
+ view.setUint32(16, 16, true);
254
+ view.setUint16(20, 1, true);
255
+ view.setUint16(22, 1, true);
256
+ view.setUint32(24, sampleRate, true);
257
+ view.setUint32(28, sampleRate * 2, true);
258
+ view.setUint16(32, 2, true);
259
+ view.setUint16(34, 16, true);
260
+ text(36, "data");
261
+ view.setUint32(40, pcm.length, true);
262
+ out.set(pcm, 44);
263
+ return out;
264
+ }
265
+ async function fetchLine(text) {
266
+ var _a;
267
+ const audio = await useConversations.requireConfigured().api.postForAudio(useConversations.EP.coachSpeech(), { text }, 3e4);
268
+ const wav = audio.contentType.includes("L16") || audio.contentType.includes("pcm") ? wavFromPcm(audio.bytes, (_a = audio.sampleRate) != null ? _a : 24e3) : audio.bytes;
269
+ const file = new expoFileSystem.File(expoFileSystem.Paths.cache, `guideai-line-${Date.now()}-${Math.random().toString(36).slice(2, 6)}.wav`);
270
+ file.write(wav);
271
+ return file;
272
+ }
273
+ function forget(file) {
274
+ try {
275
+ file == null ? void 0 : file.delete();
276
+ } catch {
277
+ }
278
+ }
279
+ function createSpeech() {
280
+ let player = null;
281
+ let finish = null;
282
+ let session = 0;
283
+ const silence = () => {
284
+ const done = finish;
285
+ finish = null;
286
+ if (player) {
287
+ try {
288
+ player.pause();
289
+ player.remove();
290
+ } catch {
291
+ }
292
+ player = null;
293
+ }
294
+ done == null ? void 0 : done();
295
+ };
296
+ const stop = () => {
297
+ session += 1;
298
+ silence();
299
+ };
300
+ const play = (file, mine) => new Promise((resolve) => {
301
+ if (mine !== session) {
302
+ resolve();
303
+ return;
304
+ }
305
+ const current = expoAudio.createAudioPlayer({ uri: file.uri });
306
+ player = current;
307
+ const timer = setTimeout(() => {
308
+ if (player === current) silence();
309
+ }, MAX_LINE_MS);
310
+ finish = () => {
311
+ clearTimeout(timer);
312
+ resolve();
313
+ };
314
+ current.addListener("playbackStatusUpdate", (status) => {
315
+ if (status.didJustFinish && player === current) silence();
316
+ });
317
+ current.play();
318
+ });
319
+ const say = async (text) => {
320
+ stop();
321
+ const mine = session;
322
+ const lines = speechLines(text.trim());
323
+ if (!lines.length) return false;
324
+ await expoAudio.setAudioModeAsync({ playsInSilentMode: true, allowsRecording: false }).catch(() => void 0);
325
+ const started = Date.now();
326
+ let next = fetchLine(lines[0]).catch((error) => {
327
+ console.log("[GuideAI] ✗ could not say a line:", error);
328
+ return null;
329
+ });
330
+ for (let i = 0; i < lines.length; i += 1) {
331
+ const file = await next;
332
+ if (mine !== session) {
333
+ forget(file);
334
+ break;
335
+ }
336
+ next = i + 1 < lines.length ? fetchLine(lines[i + 1]).catch(() => null) : Promise.resolve(null);
337
+ if (file) {
338
+ await play(file, mine);
339
+ forget(file);
340
+ }
341
+ }
342
+ if (mine !== session) void next.then(forget);
343
+ return Date.now() - started >= MIN_HEARD_MS;
344
+ };
345
+ return { say, stop };
346
+ }
347
+ const RECORDING = { ...expoAudio.RecordingPresets.HIGH_QUALITY, isMeteringEnabled: true };
348
+ const POLL_MS = 100;
349
+ const OVER_NOISE_DB = 12;
350
+ const SPEECH_FLOOR_DB = -45;
351
+ const MIN_SPEECH_MS = 350;
352
+ const MAX_TURN_MS = 45e3;
353
+ const MIC_REFUSED = "Allow microphone access in Settings to talk to the assistant.";
354
+ const START_FAILED = "The microphone didn't start. Please try again.";
355
+ const IDLE = "I stopped listening because I didn't hear anything. Tap to talk again.";
356
+ let fallbackSpeech = null;
357
+ function voice() {
358
+ const configured = useConversations.requireConfigured().speech;
359
+ if (configured) return configured;
360
+ fallbackSpeech != null ? fallbackSpeech : fallbackSpeech = createSpeech();
361
+ return fallbackSpeech;
362
+ }
363
+ const sleep = (ms) => new Promise((resolve) => {
364
+ setTimeout(resolve, ms);
365
+ });
366
+ function useLiveVoice(chat, options = {}) {
367
+ var _a, _b;
368
+ const recorder = expoAudio.useAudioRecorder(RECORDING);
369
+ const [state2, setState] = React.useState("off");
370
+ const [level, setLevel] = React.useState(0);
371
+ const [error, setError] = React.useState(null);
372
+ const call = React.useRef(0);
373
+ const mounted = React.useRef(true);
374
+ const chatRef = React.useRef(chat);
375
+ chatRef.current = chat;
376
+ const me = React.useRef({}).current;
377
+ const startRef = React.useRef(async () => false);
378
+ const resume = React.useCallback(() => {
379
+ void startRef.current();
380
+ }, []);
381
+ const lang = useVoiceLanguage(options, me, resume);
382
+ const languageRef = React.useRef(lang.code);
383
+ languageRef.current = lang.code;
384
+ const idleMs = ((_a = options.idleSeconds) != null ? _a : 30) * 1e3;
385
+ const pauseMs = ((_b = options.pauseSeconds) != null ? _b : 1.2) * 1e3;
386
+ const show = React.useCallback((next) => {
387
+ if (mounted.current) setState(next);
388
+ }, []);
389
+ const stopRecorder = React.useCallback(async () => {
390
+ try {
391
+ if (recorder.isRecording) await recorder.stop();
392
+ } catch {
393
+ }
394
+ }, [recorder]);
395
+ const stop = React.useCallback(() => {
396
+ call.current += 1;
397
+ voice().stop();
398
+ void stopRecorder();
399
+ void expoAudio.setAudioModeAsync({ allowsRecording: false }).catch(() => void 0);
400
+ show("off");
401
+ if (mounted.current) setLevel(0);
402
+ }, [show, stopRecorder]);
403
+ React.useEffect(() => () => {
404
+ mounted.current = false;
405
+ call.current += 1;
406
+ voice().stop();
407
+ }, []);
408
+ const listen = React.useCallback(async (mine) => {
409
+ var _a2, _b2;
410
+ await expoAudio.setAudioModeAsync({ allowsRecording: true, playsInSilentMode: true });
411
+ await recorder.prepareToRecordAsync();
412
+ recorder.record();
413
+ show("listening");
414
+ const began = Date.now();
415
+ let noise = null;
416
+ let speechSince = null;
417
+ let quietSince = null;
418
+ let spoke = false;
419
+ while (mine === call.current) {
420
+ await sleep(POLL_MS);
421
+ if (mine !== call.current) break;
422
+ const db = (_a2 = recorder.getStatus().metering) != null ? _a2 : -160;
423
+ const now = Date.now();
424
+ if (now - began < 500) {
425
+ noise = noise === null ? db : Math.max(noise, db);
426
+ continue;
427
+ }
428
+ const threshold = Math.max(SPEECH_FLOOR_DB, (noise != null ? noise : -60) + OVER_NOISE_DB);
429
+ if (mounted.current) setLevel(Math.max(0, Math.min(1, (db + 60) / 50)));
430
+ if (db >= threshold) {
431
+ speechSince != null ? speechSince : speechSince = now;
432
+ quietSince = null;
433
+ if (!spoke && now - speechSince >= MIN_SPEECH_MS) {
434
+ spoke = true;
435
+ show("hearing");
436
+ }
437
+ } else {
438
+ if (!spoke) speechSince = null;
439
+ quietSince != null ? quietSince : quietSince = now;
440
+ }
441
+ if (spoke && quietSince !== null && now - quietSince >= pauseMs) break;
442
+ if (spoke && speechSince !== null && now - speechSince >= MAX_TURN_MS) break;
443
+ if (!spoke && now - began >= idleMs) {
444
+ await stopRecorder();
445
+ return "idle";
446
+ }
447
+ }
448
+ await stopRecorder();
449
+ if (mounted.current) setLevel(0);
450
+ if (mine !== call.current) return null;
451
+ return (_b2 = recorder.uri) != null ? _b2 : null;
452
+ }, [recorder, show, stopRecorder, idleMs, pauseMs]);
453
+ const start = React.useCallback(async () => {
454
+ if (state2 !== "off") return true;
455
+ setError(null);
456
+ if (!languageRef.current) {
457
+ lang.ask();
458
+ return false;
459
+ }
460
+ const permission = await expoAudio.requestRecordingPermissionsAsync().catch(() => null);
461
+ if (!(permission == null ? void 0 : permission.granted)) {
462
+ if (mounted.current) setError(MIC_REFUSED);
463
+ return false;
464
+ }
465
+ call.current += 1;
466
+ const mine = call.current;
467
+ void (async () => {
468
+ var _a2;
469
+ while (mine === call.current) {
470
+ let heard;
471
+ try {
472
+ heard = await listen(mine);
473
+ } catch (cause) {
474
+ console.log("[GuideAI] ✗ live voice: microphone failed:", cause);
475
+ if (mine === call.current) {
476
+ setError(START_FAILED);
477
+ stop();
478
+ }
479
+ return;
480
+ }
481
+ if (mine !== call.current) return;
482
+ if (heard === "idle") {
483
+ setError(IDLE);
484
+ stop();
485
+ return;
486
+ }
487
+ if (!heard) continue;
488
+ show("thinking");
489
+ await expoAudio.setAudioModeAsync({ allowsRecording: false }).catch(() => void 0);
490
+ const result = await chatRef.current.sendVoice({ uri: heard, languageCode: (_a2 = languageRef.current) != null ? _a2 : void 0 });
491
+ if (mine !== call.current) return;
492
+ if (!result.text) continue;
493
+ if (result.answer) {
494
+ show("speaking");
495
+ await voice().say(toSpeakable(result.answer));
496
+ }
497
+ }
498
+ })();
499
+ return true;
500
+ }, [state2, lang, listen, show, stop]);
501
+ startRef.current = start;
502
+ const interrupt = React.useCallback(() => {
503
+ voice().stop();
504
+ }, []);
505
+ return {
506
+ state: state2,
507
+ active: state2 !== "off",
508
+ level,
509
+ error,
510
+ start,
511
+ stop,
512
+ interrupt,
513
+ language: lang.language,
514
+ languages: lang.languages,
515
+ choosingLanguage: lang.choosingLanguage,
516
+ chooseLanguage: lang.chooseLanguage,
517
+ changeLanguage: lang.changeLanguage,
518
+ cancelLanguage: lang.cancelLanguage
519
+ };
520
+ }
521
+ function useChatVoice(chat) {
522
+ return { mic: useVoiceInput(chat), live: useLiveVoice(chat) };
523
+ }
524
+ function GuideAIVoiceChat(props) {
525
+ var _a;
526
+ const configured = useConversations.requireConfigured();
527
+ (_a = configured.speech) != null ? _a : configured.speech = createSpeech();
528
+ return /* @__PURE__ */ jsxRuntime.jsx(GuideAIChat.GuideAIChat, { ...props, useVoice: useChatVoice });
87
529
  }
530
+ exports.DEFAULT_LANGUAGE_PICKER_LABELS = GuideAIChat.DEFAULT_LANGUAGE_PICKER_LABELS;
531
+ exports.DEFAULT_LIVE_VOICE_LABELS = GuideAIChat.DEFAULT_LIVE_VOICE_LABELS;
532
+ exports.GuideAILanguagePicker = GuideAIChat.GuideAILanguagePicker;
533
+ exports.GuideAILiveVoice = GuideAIChat.GuideAILiveVoice;
534
+ exports.DEFAULT_VOICE_LANGUAGES = DEFAULT_VOICE_LANGUAGES;
535
+ exports.GuideAIVoiceChat = GuideAIVoiceChat;
536
+ exports.createSpeech = createSpeech;
537
+ exports.toSpeakable = toSpeakable;
538
+ exports.useLiveVoice = useLiveVoice;
88
539
  exports.useVoiceInput = useVoiceInput;
89
540
  //# sourceMappingURL=voice.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"voice.cjs","sources":["../src/voice/useVoiceInput.ts"],"sourcesContent":["// ============================================================\n// @guideai/react-native/voice — push-to-talk\n// ============================================================\n//\n// The whole mic for a host's chat: permission, recording, transcription\n// and sending the words as the next message. The host draws a button and\n// reads `recording` / `transcribing` / `error`; nothing else.\n//\n// Its own entry point because it needs expo-audio (an optional peer): an\n// app that never imports '@guideai/react-native/voice' never needs it.\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport {\n RecordingPresets,\n requestRecordingPermissionsAsync,\n setAudioModeAsync,\n useAudioRecorder,\n} from 'expo-audio';\nimport type { UseGuideAIResult } from '../react/useGuideAI';\nimport { requireConfigured } from '../setup';\n\nexport interface UseVoiceInputOptions {\n /** BCP-47 language spoken, e.g. 'en-NG'. Defaults to the user profile's language. */\n languageCode?: string;\n /** A recording stops and is sent after this long. Default 60 s. */\n maxSeconds?: number;\n}\n\nexport interface UseVoiceInputResult {\n /** The mic is on. */\n recording: boolean;\n /** What was said is being turned into text (then sent). */\n transcribing: boolean;\n /** Why the last attempt failed, in words to show the user; null when it didn't. */\n error: string | null;\n /** Start recording. False when the microphone was refused or is busy. */\n start(): Promise<boolean>;\n /** Stop, transcribe and send. Resolves with what was heard, or null. */\n stop(): Promise<string | null>;\n /** Stop and throw the recording away. */\n cancel(): Promise<void>;\n /** Start when idle, stop and send when recording: one mic button. */\n toggle(): Promise<void>;\n}\n\nconst MIC_REFUSED = 'Allow microphone access in Settings to talk to the assistant.';\nconst START_FAILED = \"The microphone didn't start. Please try again.\";\n\n/** The user profile's language as a recognizer code ('fr' → 'fr'), when set. */\nfunction profileLanguage(): string | undefined {\n const language = requireConfigured().profile?.language;\n return typeof language === 'string' && language.trim() ? language.trim() : undefined;\n}\n\n/**\n * Push-to-talk for a chat from `useGuideAI()`:\n *\n * const chat = useGuideAI();\n * const mic = useVoiceInput(chat);\n * <Button onPress={mic.toggle} title={mic.recording ? 'Send' : 'Talk'} />\n */\nexport function useVoiceInput(\n chat: Pick<UseGuideAIResult, 'sendVoice' | 'transcribing' | 'busy'>,\n options: UseVoiceInputOptions = {},\n): UseVoiceInputResult {\n const recorder = useAudioRecorder(RecordingPresets.HIGH_QUALITY);\n const [recording, setRecording] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const limit = useRef<ReturnType<typeof setTimeout> | null>(null);\n const mounted = useRef(true);\n const stopRef = useRef<() => Promise<string | null>>(async () => null);\n const maxSeconds = options.maxSeconds ?? 60;\n\n useEffect(() => () => {\n mounted.current = false;\n if (limit.current) clearTimeout(limit.current);\n }, []);\n\n const finish = useCallback(async (): Promise<string | null> => {\n if (limit.current) clearTimeout(limit.current);\n limit.current = null;\n if (!recorder.isRecording) {\n if (mounted.current) setRecording(false);\n return null;\n }\n await recorder.stop();\n if (mounted.current) setRecording(false);\n // Back to playback, or iOS keeps replies on the earpiece.\n await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);\n return recorder.uri ?? null;\n }, [recorder]);\n\n const start = useCallback(async () => {\n if (recording || chat.busy || chat.transcribing) return false;\n setError(null);\n const permission = await requestRecordingPermissionsAsync().catch(() => null);\n if (!permission?.granted) {\n if (mounted.current) setError(MIC_REFUSED);\n return false;\n }\n try {\n await setAudioModeAsync({ allowsRecording: true, playsInSilentMode: true });\n await recorder.prepareToRecordAsync();\n recorder.record();\n } catch (cause) {\n console.log('[GuideAI] ✗ microphone did not start:', cause);\n if (mounted.current) setError(START_FAILED);\n return false;\n }\n if (mounted.current) setRecording(true);\n limit.current = setTimeout(() => { void stopRef.current(); }, maxSeconds * 1000);\n return true;\n }, [recording, chat.busy, chat.transcribing, recorder, maxSeconds]);\n\n const stop = useCallback(async () => {\n let uri: string | null = null;\n try {\n uri = await finish();\n } catch (cause) {\n console.log('[GuideAI] ✗ recording did not stop:', cause);\n }\n if (!uri) return null;\n const result = await chat.sendVoice({\n uri,\n languageCode: options.languageCode ?? profileLanguage(),\n });\n if (mounted.current) setError(result.error ?? null);\n return result.text;\n }, [finish, chat, options.languageCode]);\n stopRef.current = stop;\n\n const cancel = useCallback(async () => {\n await finish().catch(() => null);\n }, [finish]);\n\n const toggle = useCallback(async () => {\n if (recording) await stop();\n else await start();\n }, [recording, start, stop]);\n\n return { recording, transcribing: chat.transcribing, error, start, stop, cancel, toggle };\n}\n"],"names":["requireConfigured","useAudioRecorder","RecordingPresets","useState","useRef","useEffect","useCallback","setAudioModeAsync","_a","requestRecordingPermissionsAsync"],"mappings":";;;;;AA6CA,MAAM,cAAc;AACpB,MAAM,eAAe;AAGrB,SAAS,kBAAsC;;AAC7C,QAAM,YAAWA,WAAAA,oBAAoB,YAApBA,mBAA6B;AAC9C,SAAO,OAAO,aAAa,YAAY,SAAS,SAAS,SAAS,SAAS;AAC7E;AASO,SAAS,cACd,MACA,UAAgC,IACX;;AACrB,QAAM,WAAWC,UAAAA,iBAAiBC,UAAAA,iBAAiB,YAAY;AAC/D,QAAM,CAAC,WA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1D,UAAI,QAAQ,QAAS,UAAS,YAAY;AAC1C,aAAO;AAAA,IACT;AACA,QAAI,QAAQ,QAAS,cAAa,IAAI;AACtC,UAAM,UAAU,WAAW,MAAM;AAAE,WAAK,QAAQ,QAAA;AAAA,IAAW,GAAG,aAAa,GAAI;AAC/E,WAAO;AAAA,EACT,GAAG,CAAC,WAAW,KAAK,MAAM,KAAK,cAAc,UAAU,UAAU,CAAC;AAElE,QAAM,OAAOD,MAAAA,YAAY,YAAY;;AACnC,QAAI,MAAqB;AACzB,QAAI;AACF,YAAM,MAAM,OAAA;AAAA,IACd,SAAS,OAAO;AACd,cAAQ,IAAI,uCAAuC,KAAK;AAAA,IAC1D;AACA,QAAI,CAAC,IAAK,QAAO;AACjB,UAAM,SAAS,MAAM,KAAK,UAAU;AAAA,MAClC;AAAA,MACA,eAAcE,MAAA,QAAQ,iBAAR,OAAAA,MAAwB,gBAAA;AAAA,IAAgB,CACvD;AACD,QAAI,QAAQ,QAAS,WAAS,YAAO,UAAP,YAAgB,IAAI;AAClD,WAAO,OAAO;AAAA,EAChB,GAAG,CAAC,QAAQ,MAAM,QAAQ,YAAY,CAAC;AACvC,UAAQ,UAAU;AAElB,QAAM,SAASF,MAAAA,YAAY,YAAY;AACrC,UAAM,OAAA,EAAS,MAAM,MAAM,IAAI;AAAA,EACjC,GAAG,CAAC,MAAM,CAAC;AAEX,QAAM,SAASA,MAAAA,YAAY,YAAY;AACrC,QAAI,iBAAiB,KAAA;AAAA,eACV,MAAA;AAAA,EACb,GAAG,CAAC,WAAW,OAAO,IAAI,CAAC;AAE3B,SAAO,EAAE,WAAW,cAAc,KAAK,cAAc,OAAO,OAAO,MAAM,QAAQ,OAAA;AACnF;;"}
1
+ {"version":3,"file":"voice.cjs","sources":["../src/voice/language.ts","../src/voice/useVoiceInput.ts","../src/voice/speakable.ts","../src/voice/speech.ts","../src/voice/useLiveVoice.ts","../src/voice/GuideAIVoiceChat.tsx"],"sourcesContent":["// ============================================================\n// @guideai/react-native/voice — the language the user speaks\n// ============================================================\n//\n// Recognizing speech in the wrong language gives nonsense, so the first\n// time the mic (or live voice) is used, the user is asked. One choice for\n// the whole app, remembered in the library's storage; push-to-talk and\n// live voice share it, and share one picker: whichever asked is the one\n// that starts once a language is chosen.\n\nimport { useCallback, useEffect, useSyncExternalStore } from 'react';\nimport { GuideAI, requireConfigured } from '../setup';\n\n/** A language the user can speak in, as the picker shows it. */\nexport interface VoiceLanguage {\n /** Code the recognizer takes, e.g. 'en', 'fr', 'yo'. */\n code: string;\n /** Its name in that language, e.g. 'Français'. */\n label: string;\n}\n\n/** Offered when the app gives no list. */\nexport const DEFAULT_VOICE_LANGUAGES: VoiceLanguage[] = [\n { code: 'en', label: 'English' },\n { code: 'fr', label: 'Français' },\n { code: 'ha', label: 'Hausa' },\n { code: 'yo', label: 'Yorùbá' },\n { code: 'sw', label: 'Kiswahili' },\n { code: 'ar', label: 'العربية' },\n { code: 'pt', label: 'Português' },\n { code: 'es', label: 'Español' },\n];\n\nconst KEY = 'guideai_voice_language';\n\ninterface State {\n code: string | null;\n choosing: boolean;\n /** Who opened the picker by trying to listen; it starts once chosen. */\n asker: object | null;\n /** Who should start now, and a counter so the same one can start again. */\n resume: { who: object; n: number } | null;\n}\n\nlet state: State = { code: null, choosing: false, asker: null, resume: null };\nlet loadedFor: unknown = null;\nconst listeners = new Set<() => void>();\n\nfunction set(next: Partial<State>): void {\n state = { ...state, ...next };\n for (const listener of listeners) listener();\n}\n\n/** The saved choice, read again (the store may still have been loading). */\nfunction load(): void {\n if (!GuideAI.isConfigured()) return;\n const configured = requireConfigured();\n if (loadedFor === configured && state.code) return;\n loadedFor = configured;\n let saved: string | null = null;\n try { saved = configured.storage.getItem(KEY); } catch { saved = null; }\n if (saved && saved !== state.code) set({ code: saved });\n}\n\nconst subscribe = (listener: () => void) => {\n listeners.add(listener);\n return () => { listeners.delete(listener); };\n};\nconst snapshot = () => state;\n\nexport interface VoiceLanguageOptions {\n /** The language spoken, fixed by the app. Given, the user is never asked. */\n languageCode?: string;\n /** Languages the picker offers. Defaults to DEFAULT_VOICE_LANGUAGES. */\n languages?: VoiceLanguage[];\n}\n\nexport interface VoiceLanguageFields {\n /** The language the user speaks; null until they chose one. */\n language: VoiceLanguage | null;\n /** The languages to offer. */\n languages: VoiceLanguage[];\n /**\n * Show the language picker (one for the app): the mic or live voice was\n * started before a language was chosen, or `changeLanguage()` was called.\n * Draw `languages`; a tap calls `chooseLanguage(code)`.\n */\n choosingLanguage: boolean;\n /** Pick the language (remembered). Whatever asked for it then starts. */\n chooseLanguage(code: string): Promise<void>;\n /** Open the picker to change the language. */\n changeLanguage(): void;\n /** Close the picker without choosing. */\n cancelLanguage(): void;\n}\n\n/**\n * The shared language, for a voice hook. `ask(me)` opens the picker on\n * behalf of `me`; `onResume` is called for `me` once a language is chosen.\n */\nexport function useVoiceLanguage(\n options: VoiceLanguageOptions,\n me: object,\n onResume: () => void,\n): VoiceLanguageFields & { code: string | null; ask(): void } {\n const current = useSyncExternalStore(subscribe, snapshot, snapshot);\n const languages = options.languages?.length ? options.languages : DEFAULT_VOICE_LANGUAGES;\n\n // Saved earlier, perhaps still loading from AsyncStorage: look a few times.\n useEffect(() => {\n load();\n if (state.code || options.languageCode) return undefined;\n const timer = setInterval(() => { load(); if (state.code) clearInterval(timer); }, 500);\n const giveUp = setTimeout(() => clearInterval(timer), 5_000);\n return () => { clearInterval(timer); clearTimeout(giveUp); };\n }, [options.languageCode]);\n\n useEffect(() => {\n if (current.resume?.who !== me) return;\n set({ resume: null });\n onResume();\n }, [current.resume, me, onResume]);\n\n const code = options.languageCode ?? current.code;\n const language = code\n ? languages.find((entry) => entry.code === code) ?? { code, label: code }\n : null;\n\n return {\n code,\n language,\n languages,\n choosingLanguage: current.choosing,\n ask: useCallback(() => set({ choosing: true, asker: me }), [me]),\n chooseLanguage: useCallback(async (chosen: string) => {\n try { requireConfigured().storage.setItem(KEY, chosen); } catch { /* kept for this session */ }\n const asker = state.asker;\n set({\n code: chosen,\n choosing: false,\n asker: null,\n resume: asker ? { who: asker, n: (state.resume?.n ?? 0) + 1 } : null,\n });\n }, []),\n changeLanguage: useCallback(() => set({ choosing: true, asker: null }), []),\n cancelLanguage: useCallback(() => set({ choosing: false, asker: null }), []),\n };\n}\n","// ============================================================\n// @guideai/react-native/voice — push-to-talk\n// ============================================================\n//\n// The whole mic for a host's chat: permission, recording, transcription\n// and sending the words as the next message. The host draws a button and\n// reads `recording` / `transcribing` / `error`; nothing else.\n//\n// Its own entry point because it needs expo-audio (an optional peer): an\n// app that never imports '@guideai/react-native/voice' never needs it.\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport {\n RecordingPresets,\n requestRecordingPermissionsAsync,\n setAudioModeAsync,\n useAudioRecorder,\n} from 'expo-audio';\nimport type { UseGuideAIResult } from '../react/useGuideAI';\nimport {\n useVoiceLanguage,\n type VoiceLanguageFields,\n type VoiceLanguageOptions,\n} from './language';\n\nexport { DEFAULT_VOICE_LANGUAGES } from './language';\nexport type { VoiceLanguage } from './language';\n\nexport interface UseVoiceInputOptions extends VoiceLanguageOptions {\n /** A recording stops and is sent after this long. Default 60 s. */\n maxSeconds?: number;\n}\n\nexport interface UseVoiceInputResult extends VoiceLanguageFields {\n /** The mic is on. */\n recording: boolean;\n /** What was said is being turned into text (then sent). */\n transcribing: boolean;\n /** Why the last attempt failed, in words to show the user; null when it didn't. */\n error: string | null;\n /** Start recording. False when the microphone was refused or is busy. */\n start(): Promise<boolean>;\n /** Stop, transcribe and send. Resolves with what was heard, or null. */\n stop(): Promise<string | null>;\n /** Stop and throw the recording away. */\n cancel(): Promise<void>;\n /** Start when idle, stop and send when recording: one mic button. */\n toggle(): Promise<void>;\n}\n\nconst MIC_REFUSED = 'Allow microphone access in Settings to talk to the assistant.';\nconst START_FAILED = \"The microphone didn't start. Please try again.\";\n\n/**\n * Push-to-talk for a chat from `useGuideAI()`:\n *\n * const chat = useGuideAI();\n * const mic = useVoiceInput(chat);\n * <Button onPress={mic.toggle} title={mic.recording ? 'Send' : 'Talk'} />\n */\nexport function useVoiceInput(\n chat: Pick<UseGuideAIResult, 'sendVoice' | 'transcribing' | 'busy'>,\n options: UseVoiceInputOptions = {},\n): UseVoiceInputResult {\n const recorder = useAudioRecorder(RecordingPresets.HIGH_QUALITY);\n const me = useRef({}).current;\n const startRef = useRef<() => Promise<boolean>>(async () => false);\n const resume = useCallback(() => { void startRef.current(); }, []);\n const lang = useVoiceLanguage(options, me, resume);\n const languageCode = lang.code;\n const [recording, setRecording] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const limit = useRef<ReturnType<typeof setTimeout> | null>(null);\n const mounted = useRef(true);\n const stopRef = useRef<() => Promise<string | null>>(async () => null);\n const maxSeconds = options.maxSeconds ?? 60;\n\n useEffect(() => () => {\n mounted.current = false;\n if (limit.current) clearTimeout(limit.current);\n }, []);\n\n const finish = useCallback(async (): Promise<string | null> => {\n if (limit.current) clearTimeout(limit.current);\n limit.current = null;\n if (!recorder.isRecording) {\n if (mounted.current) setRecording(false);\n return null;\n }\n await recorder.stop();\n if (mounted.current) setRecording(false);\n // Back to playback, or iOS keeps replies on the earpiece.\n await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);\n return recorder.uri ?? null;\n }, [recorder]);\n\n const start = useCallback(async () => {\n if (recording || chat.busy || chat.transcribing) return false;\n setError(null);\n // Recognizing in the wrong language gives nonsense: ask first.\n if (!languageCode) {\n lang.ask();\n return false;\n }\n const permission = await requestRecordingPermissionsAsync().catch(() => null);\n if (!permission?.granted) {\n if (mounted.current) setError(MIC_REFUSED);\n return false;\n }\n try {\n await setAudioModeAsync({ allowsRecording: true, playsInSilentMode: true });\n await recorder.prepareToRecordAsync();\n recorder.record();\n } catch (cause) {\n console.log('[GuideAI] ✗ microphone did not start:', cause);\n if (mounted.current) setError(START_FAILED);\n return false;\n }\n if (mounted.current) setRecording(true);\n limit.current = setTimeout(() => { void stopRef.current(); }, maxSeconds * 1000);\n return true;\n }, [recording, chat.busy, chat.transcribing, recorder, maxSeconds, languageCode, lang]);\n startRef.current = start;\n\n const stop = useCallback(async () => {\n let uri: string | null = null;\n try {\n uri = await finish();\n } catch (cause) {\n console.log('[GuideAI] ✗ recording did not stop:', cause);\n }\n if (!uri) return null;\n const result = await chat.sendVoice({\n uri,\n languageCode: languageCode ?? undefined,\n });\n if (mounted.current) setError(result.error ?? null);\n return result.text;\n }, [finish, chat, languageCode]);\n stopRef.current = stop;\n\n const cancel = useCallback(async () => {\n await finish().catch(() => null);\n }, [finish]);\n\n const toggle = useCallback(async () => {\n if (recording) await stop();\n else await start();\n }, [recording, start, stop]);\n\n return {\n recording, transcribing: chat.transcribing, error, start, stop, cancel, toggle,\n language: lang.language,\n languages: lang.languages,\n choosingLanguage: lang.choosingLanguage,\n chooseLanguage: lang.chooseLanguage,\n changeLanguage: lang.changeLanguage,\n cancelLanguage: lang.cancelLanguage,\n };\n}\n","// ============================================================\n// @guideai/react-native/voice — what an answer sounds like\n// ============================================================\n//\n// Answers are Markdown with LaTeX maths. Read as typed, a voice says\n// \"backslash frac open brace\". This keeps the words, reads simple maths\n// the way a teacher says it, and drops what has no sound (code, images,\n// table rules). Then it cuts the text into lines the speech endpoint takes.\n\n/** The speech endpoint's limit is 240 characters a line. */\nexport const MAX_LINE_CHARS = 230;\n\n/** A LaTeX expression as words. */\nfunction mathWords(tex: string): string {\n let s = tex;\n // Innermost first, a few rounds for nesting.\n for (let i = 0; i < 4; i += 1) {\n s = s\n .replace(/\\\\[dt]?frac\\{([^{}]*)\\}\\{([^{}]*)\\}/g, ' $1 over $2 ')\n .replace(/\\\\sqrt\\{([^{}]*)\\}/g, ' the square root of $1 ')\n .replace(/\\\\text\\{([^{}]*)\\}/g, ' $1 ')\n .replace(/\\\\mathrm\\{([^{}]*)\\}/g, ' $1 ');\n }\n return s\n .replace(/\\^\\{?2\\}?/g, ' squared ')\n .replace(/\\^\\{?3\\}?/g, ' cubed ')\n .replace(/\\^\\{([^{}]*)\\}/g, ' to the power $1 ')\n .replace(/\\^(\\w)/g, ' to the power $1 ')\n .replace(/_\\{([^{}]*)\\}/g, ' $1 ')\n .replace(/\\\\times|\\\\cdot/g, ' times ')\n .replace(/\\\\div/g, ' divided by ')\n .replace(/\\\\pm/g, ' plus or minus ')\n .replace(/\\\\leq?/g, ' less than or equal to ')\n .replace(/\\\\geq?/g, ' greater than or equal to ')\n .replace(/\\\\neq?/g, ' not equal to ')\n .replace(/\\\\approx/g, ' approximately ')\n .replace(/\\\\pi/g, ' pi ')\n .replace(/\\\\theta/g, ' theta ')\n .replace(/\\\\(right|left)arrow|\\\\to/g, ' gives ')\n .replace(/\\\\[a-zA-Z]+/g, ' ')\n .replace(/[{}]/g, ' ')\n .replace(/\\s*=\\s*/g, ' equals ')\n .replace(/(\\d)\\s*-\\s*(\\d)/g, '$1 minus $2')\n .replace(/\\s+-\\s+/g, ' minus ')\n .replace(/\\s*\\+\\s*/g, ' plus ');\n}\n\n/** The answer as plain words to say. */\nexport function toSpeakable(markdown: string): string {\n return markdown\n .replace(/```[\\s\\S]*?(```|$)/g, ' ')\n .replace(/!\\[[^\\]]*\\]\\([^)]*\\)/g, ' ')\n .replace(/\\[([^\\]]+)\\]\\([^)]*\\)/g, '$1')\n .replace(/\\\\\\[([\\s\\S]*?)\\\\\\]/g, (_, tex: string) => `. ${mathWords(tex)}. `)\n .replace(/\\\\\\(([\\s\\S]*?)\\\\\\)/g, (_, tex: string) => mathWords(tex))\n .replace(/\\$\\$([\\s\\S]*?)\\$\\$/g, (_, tex: string) => `. ${mathWords(tex)}. `)\n .replace(/`([^`]*)`/g, '$1')\n .replace(/^\\s*\\|?[\\s:|-]+\\|[\\s:|-]*$/gm, ' ')\n .replace(/\\|/g, ', ')\n .replace(/^#{1,6}\\s*/gm, '')\n .replace(/^\\s*[-*•]\\s+/gm, '')\n .replace(/(\\*\\*|__)(.*?)\\1/g, '$2')\n .replace(/(^|\\s)[*_](\\S[^*_]*?)[*_](?=\\s|[.,!?]|$)/g, '$1$2')\n .replace(/\\n{2,}/g, '. ')\n .replace(/\\n/g, ' ')\n .replace(/\\s+([.,!?;:])/g, '$1')\n .replace(/([.!?])(\\s*[.!?])+/g, '$1')\n .replace(/\\s{2,}/g, ' ')\n .trim();\n}\n\n/** Lines of at most `max` characters, cut at sentence ends where possible. */\nexport function speechLines(text: string, max = MAX_LINE_CHARS): string[] {\n const sentences = text.match(/[^.!?]+[.!?]*/g)?.map((s) => s.trim()).filter(Boolean) ?? [];\n const lines: string[] = [];\n let current = '';\n const push = (piece: string) => {\n if (!piece) return;\n if (piece.length > max) {\n // One long sentence: cut at commas, then at spaces.\n let rest = piece;\n while (rest.length > max) {\n const cut = Math.max(rest.lastIndexOf(', ', max), rest.lastIndexOf(' ', max));\n const at = cut > max / 2 ? cut + 1 : max;\n lines.push(rest.slice(0, at).trim());\n rest = rest.slice(at).trim();\n }\n if (rest) lines.push(rest);\n return;\n }\n lines.push(piece);\n };\n for (const sentence of sentences) {\n if (!current) current = sentence;\n else if (current.length + 1 + sentence.length <= max) current = `${current} ${sentence}`;\n else { push(current); current = sentence; }\n }\n push(current);\n return lines;\n}\n","// ============================================================\n// @guideai/react-native/voice — speech\n// ============================================================\n//\n// The assistant's voice on a phone: GuideAI's natural voice (the same line\n// endpoint the web whiteboard and coach use), played with expo-audio.\n//\n// GuideAI.configure({ ..., speech: createSpeech() });\n//\n// The server answers a new line as raw 16-bit PCM and a line it has said\n// before as WAV. expo-audio plays files, not PCM, so a PCM line gets a WAV\n// header and both are written to the cache directory and played from there.\n\nimport { createAudioPlayer, setAudioModeAsync, type AudioPlayer } from 'expo-audio';\nimport { File, Paths } from 'expo-file-system';\nimport { EP } from '@guideai/core';\nimport { requireConfigured, type GuideAISpeech } from '../setup';\nimport { speechLines } from './speakable';\n\n/** A line that played for less than this was not really heard. */\nconst MIN_HEARD_MS = 400;\n/** A line that never reports finishing is given up on after this long. */\nconst MAX_LINE_MS = 60_000;\n\n/** A WAV file around raw 16-bit little-endian mono PCM. */\nexport function wavFromPcm(pcm: Uint8Array, sampleRate: number): Uint8Array {\n const out = new Uint8Array(44 + pcm.length);\n const view = new DataView(out.buffer);\n const text = (at: number, s: string) => { for (let i = 0; i < s.length; i += 1) out[at + i] = s.charCodeAt(i); };\n text(0, 'RIFF');\n view.setUint32(4, 36 + pcm.length, true);\n text(8, 'WAVE');\n text(12, 'fmt ');\n view.setUint32(16, 16, true);\n view.setUint16(20, 1, true); // PCM\n view.setUint16(22, 1, true); // mono\n view.setUint32(24, sampleRate, true);\n view.setUint32(28, sampleRate * 2, true);\n view.setUint16(32, 2, true);\n view.setUint16(34, 16, true);\n text(36, 'data');\n view.setUint32(40, pcm.length, true);\n out.set(pcm, 44);\n return out;\n}\n\n/** A line fetched and written to a file, ready to play. */\nasync function fetchLine(text: string): Promise<File> {\n const audio = await requireConfigured().api.postForAudio(EP.coachSpeech(), { text }, 30_000);\n const wav = audio.contentType.includes('L16') || audio.contentType.includes('pcm')\n ? wavFromPcm(audio.bytes, audio.sampleRate ?? 24_000)\n : audio.bytes;\n const file = new File(Paths.cache, `guideai-line-${Date.now()}-${Math.random().toString(36).slice(2, 6)}.wav`);\n file.write(wav);\n return file;\n}\n\nfunction forget(file: File | null | undefined): void {\n try { file?.delete(); } catch { /* the system clears the cache anyway */ }\n}\n\n/**\n * GuideAI's natural voice, played on the device. `say` takes any length:\n * it is cut into lines the endpoint takes, and the next line is fetched\n * while the current one plays.\n */\nexport function createSpeech(): GuideAISpeech {\n let player: AudioPlayer | null = null;\n let finish: (() => void) | null = null;\n let session = 0;\n\n const silence = () => {\n const done = finish;\n finish = null;\n if (player) {\n try { player.pause(); player.remove(); } catch { /* already gone */ }\n player = null;\n }\n done?.();\n };\n\n const stop = () => {\n session += 1;\n silence();\n };\n\n const play = (file: File, mine: number) => new Promise<void>((resolve) => {\n if (mine !== session) { resolve(); return; }\n const current = createAudioPlayer({ uri: file.uri });\n player = current;\n const timer = setTimeout(() => { if (player === current) silence(); }, MAX_LINE_MS);\n finish = () => { clearTimeout(timer); resolve(); };\n current.addListener('playbackStatusUpdate', (status) => {\n if (status.didJustFinish && player === current) silence();\n });\n current.play();\n });\n\n const say = async (text: string): Promise<boolean> => {\n stop();\n const mine = session;\n const lines = speechLines(text.trim());\n if (!lines.length) return false;\n await setAudioModeAsync({ playsInSilentMode: true, allowsRecording: false }).catch(() => undefined);\n const started = Date.now();\n let next: Promise<File | null> = fetchLine(lines[0]).catch((error) => {\n console.log('[GuideAI] ✗ could not say a line:', error);\n return null;\n });\n for (let i = 0; i < lines.length; i += 1) {\n const file = await next;\n if (mine !== session) { forget(file); break; }\n // Ask for the next line while this one plays.\n next = i + 1 < lines.length\n ? fetchLine(lines[i + 1]).catch(() => null)\n : Promise.resolve(null);\n if (file) {\n await play(file, mine);\n forget(file);\n }\n }\n if (mine !== session) void next.then(forget);\n return Date.now() - started >= MIN_HEARD_MS;\n };\n\n return { say, stop };\n}\n","// ============================================================\n// @guideai/react-native/voice — live voice (a hands-free conversation)\n// ============================================================\n//\n// Talk to the assistant like a call: it listens, hears when you have\n// finished (the mic level drops for a moment), sends what you said, reads\n// the answer aloud, then listens again, until you stop it. The words and\n// answers land in the same conversation as typed ones.\n//\n// Built on expo-audio and expo-file-system alone, which Expo apps already\n// ship, so it needs no new native module: the mic records to a file and is\n// cut when you stop speaking, rather than streamed. The host draws a call\n// button from `state` and `level`.\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport {\n RecordingPresets,\n requestRecordingPermissionsAsync,\n setAudioModeAsync,\n useAudioRecorder,\n type RecordingOptions,\n} from 'expo-audio';\nimport type { UseGuideAIResult } from '../react/useGuideAI';\nimport { requireConfigured, type GuideAISpeech } from '../setup';\nimport { createSpeech } from './speech';\nimport { toSpeakable } from './speakable';\nimport {\n useVoiceLanguage,\n type VoiceLanguageFields,\n type VoiceLanguageOptions,\n} from './language';\n\nexport type LiveVoiceState =\n /** Not in a call. */\n | 'off'\n /** Waiting for the user to speak. */\n | 'listening'\n /** The user is speaking. */\n | 'hearing'\n /** What they said is being understood and answered. */\n | 'thinking'\n /** The answer is being read aloud. */\n | 'speaking';\n\nexport interface UseLiveVoiceOptions extends VoiceLanguageOptions {\n /** A call with nobody speaking ends after this long. Default 30 s. */\n idleSeconds?: number;\n /** Silence that ends what the user is saying. Default 1.2 s. */\n pauseSeconds?: number;\n}\n\nexport interface UseLiveVoiceResult extends VoiceLanguageFields {\n state: LiveVoiceState;\n /** In a call (any state but 'off'). */\n active: boolean;\n /** Mic level 0–1 while listening, for a pulsing button. */\n level: number;\n /** Why the call stopped or a turn failed, in words to show; null otherwise. */\n error: string | null;\n /** Start the call. False when the microphone was refused or no language is chosen yet. */\n start(): Promise<boolean>;\n /** End the call. */\n stop(): void;\n /** Cut the answer short and listen again. */\n interrupt(): void;\n}\n\nconst RECORDING: RecordingOptions = { ...RecordingPresets.HIGH_QUALITY, isMeteringEnabled: true };\nconst POLL_MS = 100;\n/** Speech is this many dB over the room's own noise… */\nconst OVER_NOISE_DB = 12;\n/** …and at least this loud. */\nconst SPEECH_FLOOR_DB = -45;\n/** Sound shorter than this is a cough or a tap, not a turn. */\nconst MIN_SPEECH_MS = 350;\n/** One turn is cut here even if the user keeps talking. */\nconst MAX_TURN_MS = 45_000;\n\nconst MIC_REFUSED = 'Allow microphone access in Settings to talk to the assistant.';\nconst START_FAILED = \"The microphone didn't start. Please try again.\";\nconst IDLE = \"I stopped listening because I didn't hear anything. Tap to talk again.\";\n\nlet fallbackSpeech: GuideAISpeech | null = null;\nfunction voice(): GuideAISpeech {\n const configured = requireConfigured().speech;\n if (configured) return configured;\n fallbackSpeech ??= createSpeech();\n return fallbackSpeech;\n}\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => { setTimeout(resolve, ms); });\n\n/**\n * A live voice call for a chat from `useGuideAI()`:\n *\n * const chat = useGuideAI();\n * const live = useLiveVoice(chat);\n * <Button onPress={live.active ? live.stop : live.start} title={live.active ? 'End' : 'Talk'} />\n */\nexport function useLiveVoice(\n chat: Pick<UseGuideAIResult, 'sendVoice' | 'busy' | 'transcribing'>,\n options: UseLiveVoiceOptions = {},\n): UseLiveVoiceResult {\n const recorder = useAudioRecorder(RECORDING);\n const [state, setState] = useState<LiveVoiceState>('off');\n const [level, setLevel] = useState(0);\n const [error, setError] = useState<string | null>(null);\n const call = useRef(0);\n const mounted = useRef(true);\n const chatRef = useRef(chat);\n chatRef.current = chat;\n const me = useRef({}).current;\n const startRef = useRef<() => Promise<boolean>>(async () => false);\n const resume = useCallback(() => { void startRef.current(); }, []);\n const lang = useVoiceLanguage(options, me, resume);\n const languageRef = useRef(lang.code);\n languageRef.current = lang.code;\n const idleMs = (options.idleSeconds ?? 30) * 1000;\n const pauseMs = (options.pauseSeconds ?? 1.2) * 1000;\n\n const show = useCallback((next: LiveVoiceState) => { if (mounted.current) setState(next); }, []);\n\n const stopRecorder = useCallback(async () => {\n try { if (recorder.isRecording) await recorder.stop(); } catch { /* already stopped */ }\n }, [recorder]);\n\n const stop = useCallback(() => {\n call.current += 1;\n voice().stop();\n void stopRecorder();\n void setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);\n show('off');\n if (mounted.current) setLevel(0);\n }, [show, stopRecorder]);\n\n useEffect(() => () => {\n mounted.current = false;\n call.current += 1;\n voice().stop();\n }, []);\n\n /**\n * One turn: record until the user has spoken and paused. Resolves with\n * the file, or null when the call ended or nobody spoke for `idleMs`.\n */\n const listen = useCallback(async (mine: number): Promise<string | null | 'idle'> => {\n await setAudioModeAsync({ allowsRecording: true, playsInSilentMode: true });\n await recorder.prepareToRecordAsync();\n recorder.record();\n show('listening');\n const began = Date.now();\n let noise: number | null = null;\n let speechSince: number | null = null;\n let quietSince: number | null = null;\n let spoke = false;\n while (mine === call.current) {\n await sleep(POLL_MS);\n if (mine !== call.current) break;\n const db = recorder.getStatus().metering ?? -160;\n const now = Date.now();\n // The room's own noise, learnt in the first half-second.\n if (now - began < 500) {\n noise = noise === null ? db : Math.max(noise, db);\n continue;\n }\n const threshold = Math.max(SPEECH_FLOOR_DB, (noise ?? -60) + OVER_NOISE_DB);\n if (mounted.current) setLevel(Math.max(0, Math.min(1, (db + 60) / 50)));\n if (db >= threshold) {\n speechSince ??= now;\n quietSince = null;\n if (!spoke && now - speechSince >= MIN_SPEECH_MS) {\n spoke = true;\n show('hearing');\n }\n } else {\n if (!spoke) speechSince = null;\n quietSince ??= now;\n }\n if (spoke && quietSince !== null && now - quietSince >= pauseMs) break;\n if (spoke && speechSince !== null && now - speechSince >= MAX_TURN_MS) break;\n if (!spoke && now - began >= idleMs) {\n await stopRecorder();\n return 'idle';\n }\n }\n await stopRecorder();\n if (mounted.current) setLevel(0);\n if (mine !== call.current) return null;\n return recorder.uri ?? null;\n }, [recorder, show, stopRecorder, idleMs, pauseMs]);\n\n const start = useCallback(async (): Promise<boolean> => {\n if (state !== 'off') return true;\n setError(null);\n if (!languageRef.current) {\n lang.ask();\n return false;\n }\n const permission = await requestRecordingPermissionsAsync().catch(() => null);\n if (!permission?.granted) {\n if (mounted.current) setError(MIC_REFUSED);\n return false;\n }\n call.current += 1;\n const mine = call.current;\n\n void (async () => {\n while (mine === call.current) {\n let heard: string | null | 'idle';\n try {\n heard = await listen(mine);\n } catch (cause) {\n console.log('[GuideAI] ✗ live voice: microphone failed:', cause);\n if (mine === call.current) { setError(START_FAILED); stop(); }\n return;\n }\n if (mine !== call.current) return;\n if (heard === 'idle') { setError(IDLE); stop(); return; }\n if (!heard) continue;\n\n show('thinking');\n await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);\n const result = await chatRef.current.sendVoice({ uri: heard, languageCode: languageRef.current ?? undefined });\n if (mine !== call.current) return;\n if (!result.text) continue; // nothing understood: listen again\n if (result.answer) {\n show('speaking');\n await voice().say(toSpeakable(result.answer));\n }\n }\n })();\n return true;\n }, [state, lang, listen, show, stop]);\n startRef.current = start;\n\n const interrupt = useCallback(() => {\n // The loop goes on to listen once the answer stops.\n voice().stop();\n }, []);\n\n return {\n state,\n active: state !== 'off',\n level,\n error,\n start,\n stop,\n interrupt,\n language: lang.language,\n languages: lang.languages,\n choosingLanguage: lang.choosingLanguage,\n chooseLanguage: lang.chooseLanguage,\n changeLanguage: lang.changeLanguage,\n cancelLanguage: lang.cancelLanguage,\n };\n}\n","// ============================================================\n// @guideai/react-native/voice — the default chat, with voice\n// ============================================================\n//\n// <GuideAIChat> with its mic, live voice and the whiteboard's voice\n// switched on. Everything else is the same component:\n//\n// GuideAI.configure({ apiKey, origin, storage: AsyncStorage });\n// <GuideAIVoiceChat />\n\nimport React from 'react';\nimport { GuideAIChat, type GuideAIChatProps, type GuideAIChatVoice } from '../ui/GuideAIChat';\nimport type { UseGuideAIResult } from '../react/useGuideAI';\nimport { requireConfigured } from '../setup';\nimport { createSpeech } from './speech';\nimport { useVoiceInput } from './useVoiceInput';\nimport { useLiveVoice } from './useLiveVoice';\n\nfunction useChatVoice(chat: UseGuideAIResult): GuideAIChatVoice {\n return { mic: useVoiceInput(chat), live: useLiveVoice(chat) };\n}\n\nexport type GuideAIVoiceChatProps = Omit<GuideAIChatProps, 'useVoice'>;\n\nexport function GuideAIVoiceChat(props: GuideAIVoiceChatProps): React.ReactElement {\n // The whiteboard reads aloud too, unless the app chose its own voice.\n const configured = requireConfigured();\n configured.speech ??= createSpeech();\n return <GuideAIChat {...props} useVoice={useChatVoice} />;\n}\n"],"names":["GuideAI","requireConfigured","useSyncExternalStore","useEffect","_a","useCallback","_b","MIC_REFUSED","START_FAILED","useAudioRecorder","RecordingPresets","useRef","useState","setAudioModeAsync","requestRecordingPermissionsAsync","EP","File","Paths","createAudioPlayer","state","jsx","GuideAIChat"],"mappings":";;;;;;;;AAsBO,MAAM,0BAA2C;AAAA,EACtD,EAAE,MAAM,MAAM,OAAO,UAAA;AAAA,EACrB,EAAE,MAAM,MAAM,OAAO,WAAA;AAAA,EACrB,EAAE,MAAM,MAAM,OAAO,QAAA;AAAA,EACrB,EAAE,MAAM,MAAM,OAAO,SAAA;AAAA,EACrB,EAAE,MAAM,MAAM,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