yaver-feedback-react-native 0.8.13 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/app.plugin.js +126 -9
  2. package/dist/BlackBox.js +9 -1
  3. package/dist/DeployPanel.js +65 -0
  4. package/dist/Discovery.js +13 -2
  5. package/dist/FeedbackModal.js +477 -66
  6. package/dist/MachinePickerScreen.js +14 -5
  7. package/dist/P2PClient.d.ts +94 -1
  8. package/dist/P2PClient.js +281 -2
  9. package/dist/ShakeDetector.js +2 -0
  10. package/dist/VibeChatScreen.d.ts +6 -1
  11. package/dist/VibeChatScreen.js +204 -1
  12. package/dist/YaverFeedback.d.ts +98 -0
  13. package/dist/YaverFeedback.js +509 -46
  14. package/dist/__tests__/BlackBox.relayPassword.test.d.ts +1 -0
  15. package/dist/__tests__/BlackBox.relayPassword.test.js +105 -0
  16. package/dist/__tests__/BlackBoxAutoStart.test.d.ts +1 -0
  17. package/dist/__tests__/BlackBoxAutoStart.test.js +91 -0
  18. package/dist/__tests__/BlackBoxAutoStartColdStart.test.d.ts +1 -0
  19. package/dist/__tests__/BlackBoxAutoStartColdStart.test.js +156 -0
  20. package/dist/__tests__/BrowserLaneIcon.test.d.ts +3 -0
  21. package/dist/__tests__/BrowserLaneIcon.test.js +80 -0
  22. package/dist/__tests__/P2PClient.test.js +2 -2
  23. package/dist/__tests__/ReportIdentity.test.d.ts +1 -0
  24. package/dist/__tests__/ReportIdentity.test.js +168 -0
  25. package/dist/__tests__/SDKToken.test.js +1 -1
  26. package/dist/__tests__/ShakeToggle.test.d.ts +1 -0
  27. package/dist/__tests__/ShakeToggle.test.js +121 -0
  28. package/dist/__tests__/pickTargetDevice.test.d.ts +1 -0
  29. package/dist/__tests__/pickTargetDevice.test.js +89 -0
  30. package/dist/__tests__/reloadActions.test.d.ts +1 -0
  31. package/dist/__tests__/reloadActions.test.js +129 -0
  32. package/dist/__tests__/reloadActionsParity.test.d.ts +1 -0
  33. package/dist/__tests__/reloadActionsParity.test.js +42 -0
  34. package/dist/__tests__/types.test.js +5 -5
  35. package/dist/_core/device.d.ts +19 -9
  36. package/dist/_core/device.js +20 -14
  37. package/dist/capture.d.ts +6 -0
  38. package/dist/capture.js +53 -0
  39. package/dist/index.d.ts +4 -0
  40. package/dist/index.js +11 -1
  41. package/dist/reloadActions.d.ts +88 -0
  42. package/dist/reloadActions.js +200 -0
  43. package/dist/storeShots.d.ts +67 -0
  44. package/dist/storeShots.js +137 -0
  45. package/dist/types.d.ts +215 -3
  46. package/dist/voice.d.ts +61 -0
  47. package/dist/voice.js +246 -0
  48. package/package.json +14 -3
  49. package/src/BlackBox.ts +10 -1
  50. package/src/DeployPanel.tsx +74 -0
  51. package/src/Discovery.ts +13 -2
  52. package/src/FeedbackModal.tsx +563 -87
  53. package/src/MachinePickerScreen.tsx +12 -3
  54. package/src/P2PClient.ts +314 -2
  55. package/src/ShakeDetector.ts +1 -0
  56. package/src/VibeChatScreen.tsx +219 -0
  57. package/src/YaverFeedback.ts +498 -46
  58. package/src/__tests__/BlackBox.relayPassword.test.ts +129 -0
  59. package/src/__tests__/BlackBoxAutoStart.test.ts +111 -0
  60. package/src/__tests__/BlackBoxAutoStartColdStart.test.ts +191 -0
  61. package/src/__tests__/BrowserLaneIcon.test.ts +85 -0
  62. package/src/__tests__/P2PClient.test.ts +2 -2
  63. package/src/__tests__/ReportIdentity.test.ts +203 -0
  64. package/src/__tests__/SDKToken.test.ts +1 -1
  65. package/src/__tests__/ShakeToggle.test.ts +153 -0
  66. package/src/__tests__/pickTargetDevice.test.ts +101 -0
  67. package/src/__tests__/reloadActions.test.ts +171 -0
  68. package/src/__tests__/reloadActionsParity.test.ts +49 -0
  69. package/src/__tests__/types.test.ts +5 -5
  70. package/src/_core/device.ts +20 -14
  71. package/src/capture.ts +51 -0
  72. package/src/index.ts +21 -0
  73. package/src/reloadActions.ts +273 -0
  74. package/src/storeShots.ts +189 -0
  75. package/src/types.ts +217 -3
  76. package/src/voice.ts +270 -0
package/src/types.ts CHANGED
@@ -1,3 +1,7 @@
1
+ // Type-only: BlackBox.ts already imports from this module, so a value import
2
+ // would close a cycle. `import type` is erased at compile time.
3
+ import type { BlackBoxConfig } from './BlackBox';
4
+
1
5
  /**
2
6
  * Remote browser-style sign-in session for a coding-agent CLI on the
3
7
  * connected yaver host. Mirrors runnerBrowserAuthSession on the agent
@@ -20,6 +24,49 @@ export interface RunnerBrowserAuthSession {
20
24
  completedAt?: number;
21
25
  }
22
26
 
27
+ export interface RunnerAuthStatusRow {
28
+ id: string;
29
+ name: string;
30
+ installed: boolean;
31
+ ready: boolean;
32
+ authConfigured: boolean;
33
+ authSource?: string;
34
+ warning?: string;
35
+ error?: string;
36
+ path?: string;
37
+ detail?: string;
38
+ version?: string;
39
+ }
40
+
41
+ export interface OpenCodeProviderSummary {
42
+ id: string;
43
+ name?: string;
44
+ hasApiKey?: boolean;
45
+ baseUrl?: string;
46
+ models?: Array<{ id: string; name?: string; provider?: string }>;
47
+ }
48
+
49
+ export interface OpenCodeAgentSummary {
50
+ name: string;
51
+ model?: string;
52
+ description?: string;
53
+ isBuiltin?: boolean;
54
+ }
55
+
56
+ export interface OpenCodeConfigSummary {
57
+ path: string;
58
+ exists: boolean;
59
+ defaultAgent?: string;
60
+ model?: string;
61
+ smallModel?: string;
62
+ buildModel?: string;
63
+ planModel?: string;
64
+ providers?: OpenCodeProviderSummary[];
65
+ models?: Array<{ id: string; name?: string; provider?: string }>;
66
+ agents?: OpenCodeAgentSummary[];
67
+ diagnostics?: string[];
68
+ }
69
+
23
70
  export interface IncidentEvent {
24
71
  id: string;
25
72
  timestamp: number;
@@ -79,9 +126,33 @@ export interface CapabilitySnapshot {
79
126
  targets: Record<string, CapabilityTargetReadiness>;
80
127
  }
81
128
 
129
+ /**
130
+ * Opt-in config for the overlay's "App Store screenshots" action and the
131
+ * `capture_store_shots` remote command. When set, the SDK can walk the
132
+ * app's routes on-device, screenshot each, and upload them to the agent
133
+ * (which runs the App Store Connect backend).
134
+ */
135
+ export interface StoreShotsConfig {
136
+ /** Ordered routes to visit + screenshot (e.g. ['/(tabs)/home', ...]). */
137
+ routes: string[];
138
+ /** Navigation handle: a react-navigation ref or expo-router `router`. */
139
+ navigationRef?: any;
140
+ /** Also set metadata + attempt submit-for-review after upload. */
141
+ submit?: boolean;
142
+ /** Optional per-route screenshot names (defaults to NN_<route>). */
143
+ screens?: string[];
144
+ }
145
+
82
146
  export interface FeedbackConfig {
83
147
  /** URL of the Yaver agent (e.g. "http://192.168.1.10:18080"). If omitted, auto-discovery is used. */
84
148
  agentUrl?: string;
149
+ /**
150
+ * Enables the overlay's "App Store screenshots" action + the
151
+ * `capture_store_shots` remote command. The host supplies the route
152
+ * list (and a navigation ref) once; the SDK captures the real running
153
+ * app — no simulator needed.
154
+ */
155
+ storeShots?: StoreShotsConfig;
85
156
  /**
86
157
  * Auth token for the Yaver agent. Optional in 0.5+: if omitted, the SDK
87
158
  * will hydrate one from AsyncStorage or show its in-app login screen
@@ -121,6 +192,39 @@ export interface FeedbackConfig {
121
192
  * If omitted with convexUrl, connects to the first online device.
122
193
  */
123
194
  preferredDeviceId?: string;
195
+ /**
196
+ * Identity of the app this SDK instance reports for. Both fields are
197
+ * resolved automatically from expo-constants / native modules when
198
+ * omitted, so most apps never set them.
199
+ *
200
+ * Set them when the ambient answer would be wrong — above all when the
201
+ * app's JS is pushed into Yaver's container as a Hermes guest. There the
202
+ * runtime IS Yaver: `expo-constants` and `SettingsManager` describe the
203
+ * host (`Yaver` / `io.yaver.mobile`), not the guest, so auto-resolution
204
+ * would file every report against Yaver's own repo and the fix task would
205
+ * edit the SDK instead of the app. Declaring identity here is the only
206
+ * answer that holds in both a standalone build and a guest bundle.
207
+ *
208
+ * `bundleId` is the key that actually routes: the agent matches it against
209
+ * each project's pbxproj / build.gradle / app.json. `projectName` is a
210
+ * fallback for platforms with no bundle id.
211
+ */
212
+ projectName?: string;
213
+ bundleId?: string;
214
+ /** Primary Yaver product surface for this app/package. */
215
+ surface?: YaverSurface;
216
+ /** All product surfaces this app/package owns. */
217
+ surfaces?: YaverSurface[];
218
+ /** Canonical development stack labels, e.g. react-native-expo, yaver-xml. */
219
+ stack?: string;
220
+ stacks?: string[];
221
+ /** Yaver preview/runtime targets that can exercise this app. */
222
+ testSurfaces?: string[];
223
+ feedbackSdk?: string;
224
+ feedbackTransport?: string;
225
+ voiceCapabilities?: string[];
226
+ sttProvider?: string;
227
+ ttsProvider?: string;
124
228
  /** How feedback collection is triggered */
125
229
  trigger?: 'shake' | 'floating-button' | 'manual';
126
230
  /**
@@ -161,6 +265,22 @@ export interface FeedbackConfig {
161
265
  * Calling `BlackBox.start()` manually is still safe — it's idempotent.
162
266
  */
163
267
  autoStartBlackBox?: boolean;
268
+ /**
269
+ * Config handed to BlackBox when the SDK auto-starts it.
270
+ *
271
+ * Without this there was no way to configure the flight recorder at all.
272
+ * The obvious move — and the one the README's own snippet makes — is:
273
+ *
274
+ * YaverFeedback.init({ trigger: 'shake' });
275
+ * BlackBox.start({ appName: 'my-app' });
276
+ *
277
+ * but that start() early-returns, because a zero-config init has no
278
+ * agentUrl yet (discovery resolves it asynchronously). The auto-start then
279
+ * fires ~500ms later once the agent and token exist and calls `start()`
280
+ * with NO arguments — so the host's config is silently dropped and appName
281
+ * is ''. Pass it here instead and the auto-start will honour it.
282
+ */
283
+ blackBox?: BlackBoxConfig;
164
284
  /**
165
285
  * Small tap-to-open icon that floats above the app so the user
166
286
  * doesn't have to shake every time they want to open feedback.
@@ -246,6 +366,26 @@ export interface FeedbackConfig {
246
366
  * Bugsnag, or any other error tracking tool.
247
367
  */
248
368
  maxCapturedErrors?: number;
369
+ /**
370
+ * Crash-aware reporting/fixing. Defaults to disabled.
371
+ *
372
+ * - enabled: records fatal errors into the SDK error buffer and enables
373
+ * explicit `YaverFeedback.reportCrash(error)`.
374
+ * - installGlobalHandler: opt-in only. Wraps React Native's global ErrorUtils
375
+ * handler without suppressing the existing handler. Leave false when Sentry,
376
+ * Crashlytics, Bugsnag, or another crash tool owns the global handler.
377
+ * - autoFix: after uploading a crash report, ask the connected Yaver agent to
378
+ * create a fix task. The normal BlackBox command stream can then deliver a
379
+ * reload/reload_bundle command after the agent rebuilds.
380
+ * - captureScreenshot: attach a best-effort screenshot to the crash report.
381
+ */
382
+ crashReporting?: {
383
+ enabled?: boolean;
384
+ installGlobalHandler?: boolean;
385
+ autoFix?: boolean;
386
+ captureScreenshot?: boolean;
387
+ metadata?: Record<string, unknown>;
388
+ };
249
389
  /**
250
390
  * Which platforms the Build button targets.
251
391
  * - 'ios' — build iOS only
@@ -361,9 +501,36 @@ export interface CapturedError {
361
501
 
362
502
  export interface FeedbackMetadata {
363
503
  timestamp: string;
364
- device: DeviceInfo;
504
+ /**
505
+ * Wire key is `deviceInfo`, matching the Flutter + web SDKs and the
506
+ * agent's `FeedbackReport.DeviceInfo` (`json:"deviceInfo"`). This was
507
+ * `device` until 0.9.2 — a key the agent never read, so the whole block
508
+ * (platform, model, and the app name the fix router needs) was silently
509
+ * dropped on every React Native report. The agent still accepts the old
510
+ * key so builds already in the field keep working.
511
+ */
512
+ deviceInfo: DeviceInfo;
365
513
  app: AppInfo;
514
+ /**
515
+ * Which of the host's projects this report is about. The agent resolves
516
+ * a feedback→fix task's working directory from this; without it the task
517
+ * falls back to whatever directory the agent happens to be sitting in.
518
+ * Populated automatically by `resolveReportIdentity()`.
519
+ */
520
+ project?: FeedbackProjectRef;
366
521
  userNote?: string;
522
+ reportKind?: 'feedback' | 'auto-report' | 'crash';
523
+ crash?: {
524
+ message: string;
525
+ isFatal: boolean;
526
+ source: 'manual' | 'global-handler';
527
+ autoFixRequested?: boolean;
528
+ };
529
+ twin?: {
530
+ sessionId?: string;
531
+ surface?: string;
532
+ artifactDir?: string;
533
+ };
367
534
  }
368
535
 
369
536
  export interface DeviceInfo {
@@ -372,6 +539,8 @@ export interface DeviceInfo {
372
539
  model: string;
373
540
  screenWidth: number;
374
541
  screenHeight: number;
542
+ /** Host app name. First key the agent's fix router checks. */
543
+ appName?: string;
375
544
  }
376
545
 
377
546
  export interface AppInfo {
@@ -380,6 +549,43 @@ export interface AppInfo {
380
549
  buildNumber?: string;
381
550
  }
382
551
 
552
+ /**
553
+ * Identifies the host project a report belongs to. Mirrors the web SDK's
554
+ * `FeedbackProjectRef` and the agent's `FeedbackProject`.
555
+ */
556
+ export interface FeedbackProjectRef {
557
+ appName?: string;
558
+ projectName?: string;
559
+ /**
560
+ * Bundle identifier / applicationId. The only unambiguous key: an app's
561
+ * display name ("Talos") does not match the agent's registry name for it
562
+ * ("talos / mobile"), and one repo can hold several mobile projects that
563
+ * all share a name prefix. The agent matches this against the project's
564
+ * pbxproj, build.gradle, and app.json.
565
+ */
566
+ bundleId?: string;
567
+ /**
568
+ * Deliberately never set by this SDK. The agent ignores client-supplied
569
+ * paths for feedback reports (an untrusted guest could otherwise point the
570
+ * fix task's CWD at ~/.ssh) and resolves the path server-side. Present only
571
+ * so the type matches the wire format the agent parses.
572
+ */
573
+ projectPath?: string;
574
+ surface?: YaverSurface;
575
+ surfaces?: YaverSurface[];
576
+ stack?: string;
577
+ stacks?: string[];
578
+ testSurfaces?: string[];
579
+ feedbackSdk?: string;
580
+ feedbackTransport?: string;
581
+ voiceCapabilities?: string[];
582
+ sttProvider?: string;
583
+ ttsProvider?: string;
584
+ releaseChannel?: 'production' | 'candidate' | 'development';
585
+ }
586
+
587
+ export type YaverSurface = 'web' | 'mobile' | 'backend' | 'watch' | 'tv' | 'car' | 'vision' | 'desktop' | 'cli';
588
+
383
589
  export interface TimelineEvent {
384
590
  type: 'screenshot' | 'audio' | 'video';
385
591
  path: string;
@@ -451,12 +657,20 @@ export interface TestSession {
451
657
  export interface VoiceCapability {
452
658
  /** Always true — mobile can always record and send audio. */
453
659
  voiceInputEnabled: boolean;
454
- /** Speech-to-speech provider (e.g. "personaplex", "openai"), or null. */
660
+ /** Speech-to-speech provider (legacy), or null. */
455
661
  s2sProvider?: string;
456
662
  /** Whether the S2S provider is ready for real-time sessions. */
457
663
  s2sReady?: boolean;
458
- /** Speech-to-text provider for transcription (e.g. "whisper", "openai"). */
664
+ /** Speech-to-text provider for transcription, e.g. "deepgram" for Deepgram Flux. */
459
665
  sttProvider?: string;
460
666
  /** Whether STT is ready (auto-transcription of voice input). */
461
667
  sttReady?: boolean;
668
+ /** Text-to-speech provider for readback, e.g. "cartesia". */
669
+ ttsProvider?: string;
670
+ /** Whether TTS readback is ready. */
671
+ ttsReady?: boolean;
672
+ /** Whether the agent-side hands-free task loop is enabled. */
673
+ enabled?: boolean;
674
+ /** Default project slug used by the agent voice loop. */
675
+ defaultProject?: string;
462
676
  }
package/src/voice.ts ADDED
@@ -0,0 +1,270 @@
1
+ // Voice vibe-coding for the feedback SDK — speak a change, the agent
2
+ // acts (full MCP), and reads back a spoken headline. Ported from the
3
+ // Yaver mobile app's AgentVoiceSession (mobile/src/lib/agentVoice.ts) but
4
+ // decoupled from the app: connection details (WS URL + auth headers) come
5
+ // from the SDK's P2PClient, so it works both inside the Yaver container
6
+ // (inherited auth) and standalone in a third-party app.
7
+ //
8
+ // Local vs remote STT/TTS is decided entirely agent-side (free local
9
+ // whisper.cpp by default, Deepgram/OpenAI/etc when keys are configured),
10
+ // so nothing model-related is bundled here — the SDK just streams mic
11
+ // audio and renders the transcript + TTS the agent sends back.
12
+ //
13
+ // expo-file-system + buffer are loaded lazily so a bare-RN app that
14
+ // hasn't installed them can still use the rest of the SDK; the voice
15
+ // button hides itself via isVoiceStreamSupported() when they're absent.
16
+
17
+ export interface SDKVoiceStartOpts {
18
+ /** WS URL for the agent voice stream — P2PClient.voiceStreamUrl(). */
19
+ wsUrl: string;
20
+ /** Auth headers — P2PClient.voiceAuthHeaders(). */
21
+ headers: Record<string, string>;
22
+ project?: string;
23
+ model?: string;
24
+ runner?: string;
25
+ /** Surface hint for the agent's prompt wrapper. */
26
+ surface?: string;
27
+ /** Max chars for the spoken readback (Cartesia default ~280). */
28
+ ttsBudget?: number;
29
+ /** Per-session STT engine. "" = agent default. "local" = free
30
+ * whisper.cpp on the host; "deepgram" = Flux nova-3 streaming. */
31
+ sttProvider?: string;
32
+ /** Per-session TTS engine. "" = agent default. "local"/"device" =
33
+ * client synthesizes from the result text; cloud engines stream PCM. */
34
+ ttsProvider?: string;
35
+ }
36
+
37
+ export interface SDKVoiceCallbacks {
38
+ /** Active engines, echoed by the agent right after start — lets the UI
39
+ * show "Local" vs "Flux". */
40
+ onProviders?: (stt: string, tts: string) => void;
41
+ onTranscriptPartial?: (text: string) => void;
42
+ onTranscriptFinal?: (text: string) => void;
43
+ onTaskCreated?: (taskId: string) => void;
44
+ onTaskResult?: (taskId: string, text: string, status: string) => void;
45
+ onTTSReady?: (pcm: Uint8Array, sampleRate: number) => void;
46
+ onError?: (msg: string) => void;
47
+ onDone?: () => void;
48
+ }
49
+
50
+ interface WireMsg {
51
+ type: string;
52
+ text?: string;
53
+ taskId?: string;
54
+ status?: string;
55
+ pcm?: string;
56
+ sampleRate?: number;
57
+ error?: string;
58
+ stt?: string;
59
+ tts?: string;
60
+ }
61
+
62
+ function loadBuffer(): any {
63
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
64
+ return require('buffer').Buffer;
65
+ }
66
+
67
+ function loadFS(): any {
68
+ // expo-file-system v16+ moved the classic API under /legacy; fall back
69
+ // to the root export for older installs.
70
+ try {
71
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
72
+ return require('expo-file-system/legacy');
73
+ } catch {
74
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
75
+ return require('expo-file-system');
76
+ }
77
+ }
78
+
79
+ /** True when the deps the voice stream needs (expo-file-system + buffer)
80
+ * are installed. The feedback UI hides the mic button otherwise. */
81
+ export function isVoiceStreamSupported(): boolean {
82
+ try {
83
+ loadBuffer();
84
+ const fs = loadFS();
85
+ return typeof fs?.readAsStringAsync === 'function';
86
+ } catch {
87
+ return false;
88
+ }
89
+ }
90
+
91
+ export class SDKVoiceSession {
92
+ private ws: WebSocket | null = null;
93
+ private callbacks: SDKVoiceCallbacks;
94
+ private ttsChunks: Uint8Array[] = [];
95
+ private ttsTotalBytes = 0;
96
+ private ttsSampleRate = 22050;
97
+ private closed = false;
98
+
99
+ constructor(callbacks: SDKVoiceCallbacks) {
100
+ this.callbacks = callbacks;
101
+ }
102
+
103
+ /** Open the WS and send the start frame. Resolves once open. */
104
+ async start(opts: SDKVoiceStartOpts): Promise<void> {
105
+ return new Promise((resolve, reject) => {
106
+ let opened = false;
107
+ let ws: WebSocket;
108
+ try {
109
+ // RN-specific 3rd arg carries request headers.
110
+ ws = new (WebSocket as any)(opts.wsUrl, undefined, { headers: opts.headers });
111
+ } catch (e) {
112
+ reject(e);
113
+ return;
114
+ }
115
+ this.ws = ws;
116
+ ws.onopen = () => {
117
+ opened = true;
118
+ try {
119
+ ws.send(
120
+ JSON.stringify({
121
+ type: 'start',
122
+ project: opts.project ?? '',
123
+ model: opts.model ?? '',
124
+ runner: opts.runner ?? '',
125
+ surface: opts.surface ?? '',
126
+ ttsBudget: opts.ttsBudget ?? 0,
127
+ sttProvider: opts.sttProvider ?? '',
128
+ ttsProvider: opts.ttsProvider ?? '',
129
+ }),
130
+ );
131
+ resolve();
132
+ } catch (e) {
133
+ reject(e);
134
+ }
135
+ };
136
+ ws.onmessage = (e: any) => this.handleMessage(e);
137
+ ws.onerror = () => {
138
+ if (!opened) reject(new Error('voice WS connect failed'));
139
+ else this.callbacks.onError?.('voice WS error');
140
+ };
141
+ ws.onclose = () => {
142
+ this.closed = true;
143
+ if (!opened) reject(new Error('voice WS closed before open'));
144
+ };
145
+ });
146
+ }
147
+
148
+ /** Stream a recorded WAV/PCM file as binary frames. Records produced by
149
+ * recordPcmWav() are LPCM 16-bit/16kHz mono with a 44-byte RIFF header
150
+ * we strip here — the exact shape the backend → STT expects. */
151
+ async streamAudioFile(uri: string, opts?: { skipWavHeader?: boolean; chunkBytes?: number }): Promise<void> {
152
+ if (!this.ws || this.closed) throw new Error('voice WS not open');
153
+ const Buffer = loadBuffer();
154
+ const FileSystem = loadFS();
155
+ const skipWavHeader = opts?.skipWavHeader ?? true;
156
+ const chunkBytes = opts?.chunkBytes ?? 16384;
157
+
158
+ const b64 = await FileSystem.readAsStringAsync(uri, { encoding: 'base64' });
159
+ let buf = Buffer.from(b64, 'base64');
160
+ if (skipWavHeader && buf.length > 44 && buf.slice(0, 4).toString() === 'RIFF') {
161
+ buf = buf.slice(44);
162
+ }
163
+ for (let i = 0; i < buf.length; i += chunkBytes) {
164
+ if (this.closed) return;
165
+ const slice = buf.slice(i, Math.min(i + chunkBytes, buf.length));
166
+ this.ws.send(slice.buffer.slice(slice.byteOffset, slice.byteOffset + slice.byteLength));
167
+ await new Promise((r) => setTimeout(r, 0));
168
+ }
169
+ }
170
+
171
+ /** Done speaking — flush STT and create the agent task. */
172
+ finalize(): void {
173
+ if (this.ws && !this.closed) {
174
+ this.ws.send(JSON.stringify({ type: 'stop' }));
175
+ }
176
+ }
177
+
178
+ close(): void {
179
+ this.closed = true;
180
+ try { this.ws?.close(); } catch { /* ignore */ }
181
+ this.ws = null;
182
+ }
183
+
184
+ private handleMessage(e: { data: any }): void {
185
+ let msg: WireMsg;
186
+ try {
187
+ msg = JSON.parse(typeof e.data === 'string' ? e.data : '');
188
+ } catch {
189
+ return;
190
+ }
191
+ switch (msg.type) {
192
+ case 'providers':
193
+ this.callbacks.onProviders?.(msg.stt ?? '', msg.tts ?? '');
194
+ break;
195
+ case 'transcript-partial':
196
+ this.callbacks.onTranscriptPartial?.(msg.text ?? '');
197
+ break;
198
+ case 'transcript-final':
199
+ this.callbacks.onTranscriptFinal?.(msg.text ?? '');
200
+ break;
201
+ case 'task-created':
202
+ this.callbacks.onTaskCreated?.(msg.taskId ?? '');
203
+ break;
204
+ case 'task-result':
205
+ this.callbacks.onTaskResult?.(msg.taskId ?? '', msg.text ?? '', msg.status ?? '');
206
+ break;
207
+ case 'tts-frame': {
208
+ if (!msg.pcm) break;
209
+ const Buffer = loadBuffer();
210
+ const arr = new Uint8Array(Buffer.from(msg.pcm, 'base64'));
211
+ this.ttsChunks.push(arr);
212
+ this.ttsTotalBytes += arr.length;
213
+ if (msg.sampleRate) this.ttsSampleRate = msg.sampleRate;
214
+ break;
215
+ }
216
+ case 'done': {
217
+ if (this.ttsTotalBytes > 0) {
218
+ const pcm = new Uint8Array(this.ttsTotalBytes);
219
+ let off = 0;
220
+ for (const c of this.ttsChunks) { pcm.set(c, off); off += c.length; }
221
+ this.callbacks.onTTSReady?.(pcm, this.ttsSampleRate);
222
+ }
223
+ this.callbacks.onDone?.();
224
+ this.close();
225
+ break;
226
+ }
227
+ case 'error':
228
+ this.callbacks.onError?.(msg.error ?? 'voice error');
229
+ break;
230
+ }
231
+ }
232
+ }
233
+
234
+ /** Wrap raw PCM (signed 16-bit LE) in a minimal WAV container for
235
+ * expo-av playback. 44-byte header + samples. */
236
+ export function wrapPCMAsWAV(pcm: Uint8Array, sampleRate: number, channels = 1): Uint8Array {
237
+ const bitsPerSample = 16;
238
+ const byteRate = (sampleRate * channels * bitsPerSample) / 8;
239
+ const blockAlign = (channels * bitsPerSample) / 8;
240
+ const dataSize = pcm.length;
241
+ const buf = new Uint8Array(44 + dataSize);
242
+ const dv = new DataView(buf.buffer);
243
+ buf[0] = 0x52; buf[1] = 0x49; buf[2] = 0x46; buf[3] = 0x46; // RIFF
244
+ dv.setUint32(4, 36 + dataSize, true);
245
+ buf[8] = 0x57; buf[9] = 0x41; buf[10] = 0x56; buf[11] = 0x45; // WAVE
246
+ buf[12] = 0x66; buf[13] = 0x6d; buf[14] = 0x74; buf[15] = 0x20; // "fmt "
247
+ dv.setUint32(16, 16, true);
248
+ dv.setUint16(20, 1, true);
249
+ dv.setUint16(22, channels, true);
250
+ dv.setUint32(24, sampleRate, true);
251
+ dv.setUint32(28, byteRate, true);
252
+ dv.setUint16(32, blockAlign, true);
253
+ dv.setUint16(34, bitsPerSample, true);
254
+ buf[36] = 0x64; buf[37] = 0x61; buf[38] = 0x74; buf[39] = 0x61; // data
255
+ dv.setUint32(40, dataSize, true);
256
+ buf.set(pcm, 44);
257
+ return buf;
258
+ }
259
+
260
+ /** Write a PCM buffer to a temp WAV file; returns its file:// URI. */
261
+ export async function pcmToTempWavURI(pcm: Uint8Array, sampleRate: number): Promise<string> {
262
+ const Buffer = loadBuffer();
263
+ const FileSystem = loadFS();
264
+ const wav = wrapPCMAsWAV(pcm, sampleRate);
265
+ const b64 = Buffer.from(wav).toString('base64');
266
+ const dir = FileSystem.cacheDirectory ?? FileSystem.documentDirectory ?? '';
267
+ const path = `${dir}yaver-voice-tts-${Date.now()}.wav`;
268
+ await FileSystem.writeAsStringAsync(path, b64, { encoding: 'base64' });
269
+ return path;
270
+ }