@gemies/sdk 0.0.0-stage → 1.0.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.
Files changed (242) hide show
  1. package/CHANGELOG.md +1662 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +15 -0
  4. package/README.md +516 -2
  5. package/package.json +102 -4
  6. package/src/animations.ts +5 -0
  7. package/src/ask-eager.ts +8 -0
  8. package/src/ask-text.ts +11 -0
  9. package/src/ask.ts +12 -0
  10. package/src/avatar.ts +13 -0
  11. package/src/character.ts +1 -0
  12. package/src/components/AmbientField.tsx +580 -0
  13. package/src/components/ComposerDropZone.tsx +235 -0
  14. package/src/components/ComposerSuggestions.tsx +45 -0
  15. package/src/components/GemieAskCore.tsx +184 -0
  16. package/src/components/GemieAskProvider.tsx +18 -0
  17. package/src/components/GemieAskProviderLazy.tsx +27 -0
  18. package/src/components/GemieAskProviderText.tsx +25 -0
  19. package/src/components/GemieAskSheet.tsx +51 -0
  20. package/src/components/GemieAskSheetWithVoice.tsx +10 -0
  21. package/src/components/GemieAvatar.tsx +57 -0
  22. package/src/components/GemieAvatarIcon.tsx +35 -0
  23. package/src/components/GemieChatContent.tsx +900 -0
  24. package/src/components/GemieChatHeader.tsx +123 -0
  25. package/src/components/GemieChatScreen.tsx +170 -0
  26. package/src/components/GemieChatSheet.tsx +368 -0
  27. package/src/components/GemieChatWithVoice.tsx +13 -0
  28. package/src/components/GemieComposer.tsx +388 -0
  29. package/src/components/GemieGroupWelcome.tsx +37 -0
  30. package/src/components/GemieParticipants.tsx +133 -0
  31. package/src/components/GemieParticipantsHeader.tsx +27 -0
  32. package/src/components/GemieRecentConversations.tsx +65 -0
  33. package/src/components/GemieSharedConversation.tsx +87 -0
  34. package/src/components/GemieWelcomeMessage.tsx +58 -0
  35. package/src/components/IdentityMark.tsx +225 -0
  36. package/src/components/Image.tsx +12 -0
  37. package/src/components/InertWhen.tsx +48 -0
  38. package/src/components/PlanPreviewCard.tsx +53 -0
  39. package/src/components/QuestionCard.tsx +64 -0
  40. package/src/components/ReplyMarkdown.tsx +373 -0
  41. package/src/components/RichBlocks.tsx +195 -0
  42. package/src/components/VoiceModeIcon.tsx +18 -0
  43. package/src/components/canvas/CanvasComponent.tsx +65 -0
  44. package/src/components/canvas/ChartRenderer.tsx +73 -0
  45. package/src/components/canvas/CodeRenderer.tsx +20 -0
  46. package/src/components/canvas/DashboardRenderer.tsx +70 -0
  47. package/src/components/canvas/DeckRenderer.tsx +43 -0
  48. package/src/components/canvas/FormRenderer.tsx +101 -0
  49. package/src/components/canvas/MarkdownRenderer.tsx +14 -0
  50. package/src/components/canvas/TableRenderer.tsx +47 -0
  51. package/src/components/icons/RiEmojiPicker.tsx +39 -0
  52. package/src/components/icons/RiMoreDots.tsx +32 -0
  53. package/src/components/icons/RiReplyLine.tsx +25 -0
  54. package/src/components/thought/FilesAndSources.tsx +120 -0
  55. package/src/components/thought/ThoughtPanel.tsx +426 -0
  56. package/src/components/thought/ToolStep.tsx +134 -0
  57. package/src/components/thread/AgentExchangeView.tsx +112 -0
  58. package/src/components/thread/AgentResultCard.tsx +125 -0
  59. package/src/components/thread/AgentTaskCard.tsx +127 -0
  60. package/src/components/thread/ChatBubble.tsx +256 -0
  61. package/src/components/thread/GemieThread.tsx +455 -0
  62. package/src/components/thread/MessageBlockBoundary.tsx +78 -0
  63. package/src/components/thread/NewConversationOffer.tsx +54 -0
  64. package/src/components/thread/ThreadRow.tsx +598 -0
  65. package/src/components/thread/ThreadSearch.tsx +130 -0
  66. package/src/components/thread/ThreadSkeleton.tsx +30 -0
  67. package/src/components/thread/ToolResultCard.tsx +254 -0
  68. package/src/components/thread/TurnMenu.tsx +54 -0
  69. package/src/components/thread/TurnStatusLine.tsx +34 -0
  70. package/src/components/voice/GemieVoiceCall.tsx +21 -0
  71. package/src/components/voice/GemieVoiceCall.web.tsx +17 -0
  72. package/src/components/voice/VoiceCallContext.ts +13 -0
  73. package/src/components/voice/VoiceControls.tsx +106 -0
  74. package/src/components/voice/VoiceSession.tsx +120 -0
  75. package/src/components/voice/withVoiceCall.tsx +25 -0
  76. package/src/csp.ts +50 -0
  77. package/src/dictation.ts +40 -0
  78. package/src/hooks/useAmbientWave.ts +184 -0
  79. package/src/hooks/useAtBottom.ts +51 -0
  80. package/src/hooks/useAttachMenu.ts +93 -0
  81. package/src/hooks/useAttachmentIntake.ts +401 -0
  82. package/src/hooks/useAudioLevelMonitor.ts +46 -0
  83. package/src/hooks/useAudioLevels.ts +51 -0
  84. package/src/hooks/useChatComposer.ts +309 -0
  85. package/src/hooks/useChatVoice.ts +129 -0
  86. package/src/hooks/useComposerSuggestions.ts +84 -0
  87. package/src/hooks/useDictation.ts +292 -0
  88. package/src/hooks/useDocumentPicker.ts +11 -0
  89. package/src/hooks/useFailedTurnToast.ts +43 -0
  90. package/src/hooks/useFocusWhenPresented.ts +41 -0
  91. package/src/hooks/useGemieActivity.ts +31 -0
  92. package/src/hooks/useImagePicker.ts +38 -0
  93. package/src/hooks/useMessageReactions.ts +119 -0
  94. package/src/hooks/useMessageVote.ts +50 -0
  95. package/src/hooks/useOpenThought.ts +79 -0
  96. package/src/hooks/usePendingQuestions.ts +19 -0
  97. package/src/hooks/useReadAloud.ts +92 -0
  98. package/src/hooks/useShareHandler.ts +24 -0
  99. package/src/hooks/useSoundEffects.ts +137 -0
  100. package/src/hooks/useTTS.ts +303 -0
  101. package/src/hooks/useThoughtScope.ts +59 -0
  102. package/src/hooks/useThreadRows.ts +157 -0
  103. package/src/hooks/useThreadView.ts +67 -0
  104. package/src/hooks/useTimelineWindow.ts +256 -0
  105. package/src/hooks/useVoiceLauncher.ts +180 -0
  106. package/src/hooks/useVoiceRoom.ts +212 -0
  107. package/src/index.ts +140 -0
  108. package/src/lib/activity-socket.ts +102 -0
  109. package/src/lib/activity-store.ts +53 -0
  110. package/src/lib/add-menu.ts +7 -0
  111. package/src/lib/agent-character.ts +28 -0
  112. package/src/lib/alia-character.ts +14 -0
  113. package/src/lib/attachment-intake.ts +154 -0
  114. package/src/lib/attachment-tiles.ts +74 -0
  115. package/src/lib/audio-level.ts +130 -0
  116. package/src/lib/audio-request-auth.ts +4 -0
  117. package/src/lib/audio-session-binding.ts +27 -0
  118. package/src/lib/bubbles.tsx +16 -0
  119. package/src/lib/call-thread.ts +33 -0
  120. package/src/lib/canvas-result.ts +21 -0
  121. package/src/lib/catalogue-tool.ts +22 -0
  122. package/src/lib/citations.ts +192 -0
  123. package/src/lib/clipboard.ts +23 -0
  124. package/src/lib/content-utils.ts +46 -0
  125. package/src/lib/copy-en.ts +291 -0
  126. package/src/lib/copy-es.ts +287 -0
  127. package/src/lib/copy.ts +38 -0
  128. package/src/lib/deferred/document-picker.ts +2 -0
  129. package/src/lib/deferred/document-picker.web.ts +12 -0
  130. package/src/lib/deferred/expo-audio.ts +2 -0
  131. package/src/lib/deferred/expo-audio.web.ts +12 -0
  132. package/src/lib/deferred/image-data-url.ts +5 -0
  133. package/src/lib/deferred/image-data-url.web.ts +12 -0
  134. package/src/lib/dictation-protocol.ts +142 -0
  135. package/src/lib/dictation-recorder-types.ts +37 -0
  136. package/src/lib/dictation-recorder.native.ts +90 -0
  137. package/src/lib/dictation-recorder.ts +131 -0
  138. package/src/lib/dictation-stream.ts +238 -0
  139. package/src/lib/dictation.ts +216 -0
  140. package/src/lib/document-picker.ts +31 -0
  141. package/src/lib/domain.ts +12 -0
  142. package/src/lib/flights.ts +33 -0
  143. package/src/lib/focus-return.ts +66 -0
  144. package/src/lib/greeting.ts +15 -0
  145. package/src/lib/image-data-url.ts +35 -0
  146. package/src/lib/keyboard.native.tsx +25 -0
  147. package/src/lib/keyboard.tsx +55 -0
  148. package/src/lib/labels-es.ts +113 -0
  149. package/src/lib/labels.tsx +207 -0
  150. package/src/lib/origins.ts +28 -0
  151. package/src/lib/participants.ts +97 -0
  152. package/src/lib/pcm.ts +57 -0
  153. package/src/lib/power-level-options.ts +66 -0
  154. package/src/lib/questions.ts +92 -0
  155. package/src/lib/speech-language.ts +20 -0
  156. package/src/lib/speech-messages.ts +54 -0
  157. package/src/lib/speech-synthesis.ts +156 -0
  158. package/src/lib/suggestions.ts +53 -0
  159. package/src/lib/task-labels.ts +35 -0
  160. package/src/lib/text-input.ts +10 -0
  161. package/src/lib/tool-call-status.ts +28 -0
  162. package/src/lib/tool-icons.ts +36 -0
  163. package/src/lib/tool-registry.ts +71 -0
  164. package/src/lib/tool-renderers.tsx +32 -0
  165. package/src/lib/turn-state.ts +15 -0
  166. package/src/lib/utils.ts +35 -0
  167. package/src/lib/voice-audio-engine-types.ts +59 -0
  168. package/src/lib/voice-audio-engine.native.ts +232 -0
  169. package/src/lib/voice-audio-engine.ts +206 -0
  170. package/src/lib/voice-call-request.ts +49 -0
  171. package/src/lib/voice-call.ts +627 -0
  172. package/src/lib/voice-controls-labels.ts +31 -0
  173. package/src/lib/voice-levels.ts +64 -0
  174. package/src/lib/voice-protocol.ts +328 -0
  175. package/src/lib/voice-worklets.ts +19 -0
  176. package/src/lib/work-log.ts +370 -0
  177. package/src/metro/chart-importers.json +18 -0
  178. package/src/metro/granular-charts.js +3 -0
  179. package/src/metro/index.cjs +227 -0
  180. package/src/metro/index.d.cts +5 -0
  181. package/src/runtime/agents.ts +151 -0
  182. package/src/runtime/api.ts +144 -0
  183. package/src/runtime/app-assertion.ts +51 -0
  184. package/src/runtime/attachment-utils.ts +97 -0
  185. package/src/runtime/chat-turn-control.ts +74 -0
  186. package/src/runtime/composer-draft-store.ts +270 -0
  187. package/src/runtime/config.tsx +222 -0
  188. package/src/runtime/conversation-dates.ts +31 -0
  189. package/src/runtime/conversation-store.ts +49 -0
  190. package/src/runtime/conversations.ts +633 -0
  191. package/src/runtime/error-utils.ts +144 -0
  192. package/src/runtime/host-tools.ts +290 -0
  193. package/src/runtime/index.ts +137 -0
  194. package/src/runtime/message-history.ts +124 -0
  195. package/src/runtime/message-reactions.ts +214 -0
  196. package/src/runtime/model.ts +39 -0
  197. package/src/runtime/oxy-files.ts +37 -0
  198. package/src/runtime/power-levels.ts +66 -0
  199. package/src/runtime/query-keys.ts +49 -0
  200. package/src/runtime/random-uuid.ts +25 -0
  201. package/src/runtime/reaction-cache.ts +45 -0
  202. package/src/runtime/room-events.ts +333 -0
  203. package/src/runtime/routes.ts +81 -0
  204. package/src/runtime/sharing.ts +217 -0
  205. package/src/runtime/sse-frame-reader.ts +88 -0
  206. package/src/runtime/stream-events.ts +154 -0
  207. package/src/runtime/stream-outcome.ts +21 -0
  208. package/src/runtime/thought-store.ts +103 -0
  209. package/src/runtime/thread/agent-activity.ts +261 -0
  210. package/src/runtime/thread/agent-exchange.ts +94 -0
  211. package/src/runtime/thread/automation-labels.ts +79 -0
  212. package/src/runtime/thread/conversation-export.ts +135 -0
  213. package/src/runtime/thread/message-days.ts +120 -0
  214. package/src/runtime/thread/message-processor.ts +93 -0
  215. package/src/runtime/thread/speaker-changes.ts +66 -0
  216. package/src/runtime/thread/task-utils.ts +11 -0
  217. package/src/runtime/thread/thought-utils.ts +750 -0
  218. package/src/runtime/thread/thread-history.ts +139 -0
  219. package/src/runtime/thread/timeline.ts +202 -0
  220. package/src/runtime/thread/title-tags.ts +8 -0
  221. package/src/runtime/thread/tool-cards.ts +387 -0
  222. package/src/runtime/turn-failure.ts +108 -0
  223. package/src/runtime/turn-preparation.ts +21 -0
  224. package/src/runtime/types.ts +172 -0
  225. package/src/runtime/usage-limit-error.ts +44 -0
  226. package/src/runtime/use-agent-activity.ts +80 -0
  227. package/src/runtime/use-conversation-stream.ts +1669 -0
  228. package/src/runtime/use-conversation-thread.ts +590 -0
  229. package/src/runtime/use-gemie-thread.ts +54 -0
  230. package/src/runtime/use-room-events.ts +75 -0
  231. package/src/runtime/use-start-conversation.ts +107 -0
  232. package/src/runtime/use-thread-history.ts +73 -0
  233. package/src/runtime/use-thread-search.ts +100 -0
  234. package/src/runtime/use-turn-edit.ts +99 -0
  235. package/src/text.ts +19 -0
  236. package/src/theme.ts +16 -0
  237. package/src/tools.ts +27 -0
  238. package/src/types.ts +161 -0
  239. package/src/voice-messages.ts +2 -0
  240. package/src/voice.ts +67 -0
  241. package/tsconfig.json +17 -0
  242. package/worklets/voice-processors.js +152 -0
@@ -0,0 +1,71 @@
1
+ interface ToolDefinition {
2
+ label: string;
3
+ category: 'search' | 'communication' | 'utility' | 'memory';
4
+ }
5
+
6
+ const TOOL_REGISTRY: Record<string, ToolDefinition> = {
7
+ // Search
8
+ webSearch: { label: 'Searching the web', category: 'search' },
9
+ scrapeURL: { label: 'Reading URL', category: 'search' },
10
+ getTimeline: { label: 'Getting timeline', category: 'search' },
11
+ searchKnowledgeBase: { label: 'Searching knowledge base', category: 'search' },
12
+ webScraper: { label: 'Reading web page', category: 'search' },
13
+ browse: { label: 'Browsing the web', category: 'search' },
14
+
15
+ // Communication
16
+ sendWhatsAppMessage: { label: 'Sending WhatsApp message', category: 'communication' },
17
+ getWhatsAppChats: { label: 'Loading WhatsApp chats', category: 'communication' },
18
+ getWhatsAppMessages: { label: 'Reading WhatsApp messages', category: 'communication' },
19
+ sendTelegramMessage: { label: 'Sending Telegram message', category: 'communication' },
20
+
21
+ // Utility
22
+ getCurrentDate: { label: 'Getting current date', category: 'utility' },
23
+ generateFile: { label: 'Generating file', category: 'utility' },
24
+
25
+ // Memory
26
+ saveUserMemory: { label: 'Saving to memory', category: 'memory' },
27
+ updateUserPreferences: { label: 'Updating preferences', category: 'memory' },
28
+ updateUserContext: { label: 'Updating context', category: 'memory' },
29
+ };
30
+
31
+ /**
32
+ * `Object.hasOwn`, not a bare index, in all three lookups below.
33
+ *
34
+ * Every key here comes off the wire — a tool name the server chose, a research
35
+ * phase the server chose — and these are plain object literals, so
36
+ * `REGISTRY['constructor']` is `Object.prototype`'s and not a miss.
37
+ * `getResearchActiveLabel('constructor')` returned that FUNCTION, which reaches
38
+ * a caption as `[object Function]`; the two tool lookups happened to survive
39
+ * only because `?.label` on a function is `undefined`, which is luck rather
40
+ * than a guard. The API states the same rule for its own lookups
41
+ * (`prototype-keyed-lookups.test.ts`).
42
+ */
43
+ function lookup<T>(table: Record<string, T>, key: string): T | undefined {
44
+ return Object.hasOwn(table, key) ? table[key] : undefined;
45
+ }
46
+
47
+ export function getToolLabel(toolName: string): string {
48
+ return lookup(TOOL_REGISTRY, toolName)?.label || toolName;
49
+ }
50
+
51
+ export function getToolActiveLabel(toolName: string): string | undefined {
52
+ const label = lookup(TOOL_REGISTRY, toolName)?.label;
53
+ if (!label) return undefined;
54
+ return label + '...';
55
+ }
56
+
57
+ /** Status strings for the ThinkingIndicator during research phases. */
58
+ const RESEARCH_ACTIVE_LABELS: Record<string, string> = {
59
+ decomposing: 'Decomposing query...',
60
+ searching: 'Searching sources...',
61
+ reading: 'Reading articles...',
62
+ synthesizing: 'Synthesizing findings...',
63
+ follow_up: 'Following up...',
64
+ finalizing: 'Finalizing research...',
65
+ };
66
+
67
+ export function getResearchActiveLabel(phase: string): string | undefined {
68
+ return lookup(RESEARCH_ACTIVE_LABELS, phase);
69
+ }
70
+
71
+ export { TOOL_REGISTRY };
@@ -0,0 +1,32 @@
1
+ import { createContext, type ReactNode, useContext } from 'react';
2
+
3
+ /**
4
+ * A tool's result as a host's renderer receives it (`docs/agent-embedding.md` §3): the app and the
5
+ * tool its canonical name names, what it was called with and what it returned.
6
+ */
7
+ export interface GemieToolResult {
8
+ /** The app of `oxy_<app>__<tool>` / `self_<app>__<tool>`. */
9
+ app: string;
10
+ tool: string;
11
+ toolCallId: string;
12
+ input?: Record<string, unknown>;
13
+ output: unknown;
14
+ /** The consulted agent that called it; absent for the lead's own calls. */
15
+ agentId?: string;
16
+ }
17
+
18
+ /**
19
+ * The host's own drawings of catalogue tools' results, keyed `<app>:<tool>` — `homiio:searchListings`
20
+ * for `oxy_homiio__searchListings`. Drawn before the generic tool card, for the lead's calls and a
21
+ * consulted agent's alike.
22
+ */
23
+ export type GemieToolRenderers = Readonly<Record<string, (result: GemieToolResult) => ReactNode>>;
24
+
25
+ export { parseCatalogueTool, toolRendererKey } from './catalogue-tool';
26
+
27
+ const RenderersContext = createContext<GemieToolRenderers>({});
28
+
29
+ export const GemieToolRenderersProvider = RenderersContext.Provider;
30
+
31
+ /** The host's renderers, `{}` when it brought none. */
32
+ export const useToolRenderers = () => useContext(RenderersContext);
@@ -0,0 +1,15 @@
1
+ import type { Message } from '../runtime/types';
2
+ import type { GemieAvatarState } from '../components/GemieAvatar';
3
+
4
+ /** What a chat turn is doing, from its messages: the one reading the header mark and every button share. */
5
+ export function turnActivityState(
6
+ messages: ReadonlyArray<Message>,
7
+ isStreaming: boolean,
8
+ ): GemieAvatarState {
9
+ if (!isStreaming) return 'idle';
10
+ const last = messages[messages.length - 1];
11
+ if (last?.role === 'assistant' && last.toolInvocations?.some((t) => t.state === 'call'))
12
+ return 'working';
13
+ if (last?.thinking) return 'thinking';
14
+ return 'writing';
15
+ }
@@ -0,0 +1,35 @@
1
+ import { clsx, type ClassValue } from 'clsx';
2
+ import { twMerge } from 'tailwind-merge';
3
+
4
+ export function cn(...inputs: ClassValue[]) {
5
+ return twMerge(clsx(inputs));
6
+ }
7
+
8
+ /** Extract a human-readable message from an unknown caught error. */
9
+ export function errorMessage(err: unknown, fallback = 'Something went wrong'): string {
10
+ if (err instanceof Error) return err.message;
11
+ if (typeof err === 'object' && err !== null) {
12
+ const maybe = err as { message?: string };
13
+ if (maybe.message) return maybe.message;
14
+ }
15
+ if (typeof err === 'string') return err;
16
+ return fallback;
17
+ }
18
+
19
+ export function formatFileSize(bytes: number): string {
20
+ if (!Number.isFinite(bytes) || bytes <= 0) return '0 B';
21
+ const k = 1024;
22
+ const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
23
+ /**
24
+ * Clamped to the unit table.
25
+ *
26
+ * `Math.floor(Math.log(bytes) / Math.log(k))` is unbounded at both ends, and
27
+ * `sizes[i]` is `undefined` outside it — so a file of a terabyte or more read
28
+ * "1 undefined", and any size below one byte (a fractional value, which
29
+ * `attachment.size` can be) took `log` of a number below 1, giving `i = -1`
30
+ * and the same undefined unit. Negative and non-finite inputs went further:
31
+ * `Math.log` of them is `NaN`, and `sizes[NaN]` is undefined too.
32
+ */
33
+ const i = Math.min(sizes.length - 1, Math.max(0, Math.floor(Math.log(bytes) / Math.log(k))));
34
+ return `${String(Math.round((bytes / Math.pow(k, i)) * 100) / 100)} ${sizes[i]}`;
35
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The seam between a voice call and the device's audio (ADR 0017 §4).
3
+ *
4
+ * One engine captures the microphone and plays the answer, because echo
5
+ * cancellation only cancels what the SAME audio stack plays:
6
+ *
7
+ * - web (`voice-audio-engine.ts`): `getUserMedia` with echo cancellation, noise
8
+ * suppression and gain control, and two `AudioWorklet`s in one `AudioContext`;
9
+ * - iOS / Android (`voice-audio-engine.native.ts`): `react-native-audio-api`.
10
+ *
11
+ * Audio crosses the seam as PCM16 little-endian, 24 kHz, mono — the format the
12
+ * call carries in both directions — so the call never resamples or converts.
13
+ * Tests drive a call through a fake engine that implements this interface.
14
+ */
15
+
16
+ /** Why an engine could not start, or stopped working mid-call. */
17
+ export type VoiceAudioEngineErrorCode = 'mic-denied' | 'mic-unavailable' | 'voice-unavailable';
18
+
19
+ export class VoiceAudioEngineError extends Error {
20
+ readonly code: VoiceAudioEngineErrorCode;
21
+
22
+ constructor(code: VoiceAudioEngineErrorCode, message?: string) {
23
+ super(message ?? code);
24
+ this.name = 'VoiceAudioEngineError';
25
+ this.code = code;
26
+ }
27
+ }
28
+
29
+ export interface VoiceAudioEngineHandlers {
30
+ /** One captured frame (~40 ms), PCM16 24 kHz mono. */
31
+ onCaptureFrame(pcm16: Uint8Array): void;
32
+ /** The microphone's level, 0..1, from the real captured buffers. */
33
+ onCaptureLevel(level: number): void;
34
+ /** The first sample of `itemId` is audible now — not received, PLAYING. */
35
+ onPlaybackStarted(itemId: string): void;
36
+ /** The level of what is playing, 0..1, from the real played buffers. */
37
+ onPlaybackLevel(level: number): void;
38
+ /** Everything queued has been played. */
39
+ onPlaybackIdle(): void;
40
+ /** The device failed during the call (the microphone went away). */
41
+ onError(error: VoiceAudioEngineError): void;
42
+ }
43
+
44
+ export interface VoiceAudioEngine {
45
+ /**
46
+ * Ask for the microphone and start capturing and the player. Rejects with a
47
+ * {@link VoiceAudioEngineError}.
48
+ */
49
+ start(handlers: VoiceAudioEngineHandlers): Promise<void>;
50
+ /** Queue a chunk of `itemId`'s audio behind what is already queued. */
51
+ enqueue(itemId: string, pcm16: Uint8Array): void;
52
+ /**
53
+ * Drop everything queued and stop playing at once. Resolves with how much of
54
+ * the item that was playing was actually heard, or `null` when nothing was.
55
+ */
56
+ flush(): Promise<{ itemId: string; playedMs: number } | null>;
57
+ /** Release the microphone and the player. Safe to call more than once. */
58
+ stop(): void;
59
+ }
@@ -0,0 +1,232 @@
1
+ /**
2
+ * The iOS / Android voice-call engine, on `react-native-audio-api` (Software
3
+ * Mansion) — capture and playback in ONE native audio stack, because the
4
+ * platform echo canceller only removes what that same stack plays (ADR 0017
5
+ * §4). `expo-audio` cannot do this: its stream captures without echo
6
+ * cancellation and it cannot play a PCM stream.
7
+ *
8
+ * - **iOS:** the audio session is `playAndRecord` in mode `voiceChat`, which is
9
+ * Apple's voice-processing path (echo cancellation, noise suppression, gain
10
+ * control), with the loudspeaker as default output and Bluetooth headsets
11
+ * allowed.
12
+ * - **Android:** `react-native-audio-api` 0.13.6 opens its recorder through
13
+ * Oboe with the default input preset and exposes no `voiceCommunication`
14
+ * preset, so the platform echo canceller is NOT engaged by this engine. That
15
+ * is the Android AEC gate of ADR 0017 §4, to be measured on the Pixel 8a; if
16
+ * it fails, the ADR's fallback is a small Expo module of Alia's own around
17
+ * `AudioRecord(VOICE_COMMUNICATION)` behind this same interface.
18
+ *
19
+ * A new native build is required: the library's config plugin is in
20
+ * `packages/app/app.json`.
21
+ */
22
+
23
+ import {
24
+ type AudioBufferQueueSourceNode,
25
+ AudioContext,
26
+ AudioManager,
27
+ AudioRecorder,
28
+ } from 'react-native-audio-api';
29
+ import { floatToPcm16, levelOfPcm16, pcm16ToFloat } from './pcm';
30
+ import { pcmBytesToMs, VOICE_FRAME_SAMPLES, VOICE_SAMPLE_RATE } from './voice-protocol';
31
+ import {
32
+ VoiceAudioEngineError,
33
+ type VoiceAudioEngine,
34
+ type VoiceAudioEngineHandlers,
35
+ } from './voice-audio-engine-types';
36
+
37
+ export * from './voice-audio-engine-types';
38
+
39
+ /** Held before the first buffer of a burst, so network jitter does not stutter it. */
40
+ const PREBUFFER_MS = 80;
41
+ /** A burst shorter than that still plays once nothing more arrives for this long. */
42
+ const PREBUFFER_IDLE_MS = 100;
43
+
44
+ interface Queued {
45
+ readonly id: string;
46
+ readonly itemId: string;
47
+ readonly ms: number;
48
+ readonly level: number;
49
+ }
50
+
51
+ export function createVoiceAudioEngine(): VoiceAudioEngine {
52
+ let context: AudioContext | null = null;
53
+ let recorder: AudioRecorder | null = null;
54
+ let player: AudioBufferQueueSourceNode | null = null;
55
+ let handlers: VoiceAudioEngineHandlers | null = null;
56
+ let stopped = false;
57
+
58
+ /** Buffers handed to the player, oldest (playing) first. */
59
+ let queued: Queued[] = [];
60
+ /** Chunks held back until the prebuffer is full. */
61
+ let pending: Array<{ itemId: string; pcm: Uint8Array }> = [];
62
+ let pendingMs = 0;
63
+ let prebufferTimer: ReturnType<typeof setTimeout> | null = null;
64
+ /** The item playing now, how much of it has finished, and when its current buffer began. */
65
+ let current: { itemId: string; playedMs: number; bufferStartedAt: number } | null = null;
66
+
67
+ const beginBuffer = (entry: Queued): void => {
68
+ if (context === null || handlers === null) return;
69
+ if (current === null || current.itemId !== entry.itemId) {
70
+ current = { itemId: entry.itemId, playedMs: 0, bufferStartedAt: context.currentTime };
71
+ handlers.onPlaybackStarted(entry.itemId);
72
+ } else {
73
+ current.bufferStartedAt = context.currentTime;
74
+ }
75
+ handlers.onPlaybackLevel(entry.level);
76
+ };
77
+
78
+ const releasePlayer = (): void => {
79
+ if (player === null) return;
80
+ const old = player;
81
+ player = null;
82
+ old.onBufferEnded = null;
83
+ try {
84
+ old.clearBuffers();
85
+ old.stop();
86
+ } catch {
87
+ // Already stopped.
88
+ }
89
+ old.disconnect();
90
+ };
91
+
92
+ /** A fresh player per burst: a queue source that ran dry is not relied on to resume. */
93
+ const ensurePlayer = (): AudioBufferQueueSourceNode | null => {
94
+ if (player !== null || context === null) return player;
95
+ const node = context.createBufferQueueSource();
96
+ node.connect(context.destination);
97
+ node.onBufferEnded = ({ bufferId }) => {
98
+ if (stopped || node !== player) return;
99
+ const index = queued.findIndex((entry) => entry.id === bufferId);
100
+ if (index === -1) return;
101
+ const [ended] = queued.splice(index, 1);
102
+ if (ended && current?.itemId === ended.itemId) current.playedMs += ended.ms;
103
+ const next = queued[0];
104
+ if (next !== undefined) {
105
+ beginBuffer(next);
106
+ return;
107
+ }
108
+ releasePlayer();
109
+ handlers?.onPlaybackLevel(0);
110
+ handlers?.onPlaybackIdle();
111
+ };
112
+ node.start();
113
+ player = node;
114
+ return node;
115
+ };
116
+
117
+ const push = (itemId: string, pcm: Uint8Array): void => {
118
+ const node = ensurePlayer();
119
+ if (node === null || context === null) return;
120
+ const samples = pcm16ToFloat(pcm);
121
+ if (samples.length === 0) return;
122
+ const buffer = context.createBuffer(1, samples.length, VOICE_SAMPLE_RATE);
123
+ buffer.copyToChannel(samples as Float32Array<ArrayBuffer>, 0);
124
+ const id = node.enqueueBuffer(buffer);
125
+ const entry: Queued = {
126
+ id,
127
+ itemId,
128
+ ms: pcmBytesToMs(pcm.byteLength),
129
+ level: levelOfPcm16(pcm),
130
+ };
131
+ queued.push(entry);
132
+ if (queued.length === 1) beginBuffer(entry);
133
+ };
134
+
135
+ const releasePending = (): void => {
136
+ if (prebufferTimer !== null) clearTimeout(prebufferTimer);
137
+ prebufferTimer = null;
138
+ const chunks = pending;
139
+ pending = [];
140
+ pendingMs = 0;
141
+ for (const chunk of chunks) push(chunk.itemId, chunk.pcm);
142
+ };
143
+
144
+ return {
145
+ async start(nextHandlers: VoiceAudioEngineHandlers): Promise<void> {
146
+ handlers = nextHandlers;
147
+ AudioManager.setAudioSessionOptions({
148
+ iosCategory: 'playAndRecord',
149
+ iosMode: 'voiceChat',
150
+ iosOptions: ['defaultToSpeaker', 'allowBluetoothHFP'],
151
+ });
152
+ const permission = await AudioManager.requestRecordingPermissions().catch(() => 'Denied');
153
+ if (permission !== 'Granted') throw new VoiceAudioEngineError('mic-denied');
154
+ try {
155
+ await AudioManager.setAudioSessionActivity(true);
156
+ } catch {
157
+ throw new VoiceAudioEngineError('mic-unavailable');
158
+ }
159
+ if (stopped) return;
160
+
161
+ context = new AudioContext({ sampleRate: VOICE_SAMPLE_RATE });
162
+ recorder = new AudioRecorder();
163
+ const ready = recorder.onAudioReady(
164
+ { sampleRate: VOICE_SAMPLE_RATE, bufferLength: VOICE_FRAME_SAMPLES, channelCount: 1 },
165
+ ({ buffer }) => {
166
+ if (stopped) return;
167
+ const pcm = floatToPcm16(buffer.getChannelData(0));
168
+ handlers?.onCaptureLevel(levelOfPcm16(pcm));
169
+ handlers?.onCaptureFrame(pcm);
170
+ },
171
+ );
172
+ if (ready.status === 'error')
173
+ throw new VoiceAudioEngineError('mic-unavailable', ready.message);
174
+ const started = await recorder.start();
175
+ if (started.status === 'error')
176
+ throw new VoiceAudioEngineError('mic-unavailable', started.message);
177
+ },
178
+
179
+ enqueue(itemId: string, pcm16: Uint8Array): void {
180
+ if (stopped || context === null) return;
181
+ if (player !== null) {
182
+ push(itemId, pcm16);
183
+ return;
184
+ }
185
+ pending.push({ itemId, pcm: pcm16 });
186
+ pendingMs += pcmBytesToMs(pcm16.byteLength);
187
+ if (prebufferTimer !== null) clearTimeout(prebufferTimer);
188
+ if (pendingMs >= PREBUFFER_MS) releasePending();
189
+ else prebufferTimer = setTimeout(releasePending, PREBUFFER_IDLE_MS);
190
+ },
191
+
192
+ async flush(): Promise<{ itemId: string; playedMs: number } | null> {
193
+ if (prebufferTimer !== null) clearTimeout(prebufferTimer);
194
+ prebufferTimer = null;
195
+ pending = [];
196
+ pendingMs = 0;
197
+ const playing = current;
198
+ const head = queued[0];
199
+ let heard: { itemId: string; playedMs: number } | null = null;
200
+ if (playing !== null && context !== null) {
201
+ const intoBuffer =
202
+ head !== undefined && head.itemId === playing.itemId
203
+ ? Math.min(head.ms, Math.max(0, (context.currentTime - playing.bufferStartedAt) * 1000))
204
+ : 0;
205
+ heard = { itemId: playing.itemId, playedMs: Math.round(playing.playedMs + intoBuffer) };
206
+ }
207
+ queued = [];
208
+ current = null;
209
+ releasePlayer();
210
+ handlers?.onPlaybackLevel(0);
211
+ return heard;
212
+ },
213
+
214
+ stop(): void {
215
+ if (stopped) return;
216
+ stopped = true;
217
+ if (prebufferTimer !== null) clearTimeout(prebufferTimer);
218
+ releasePlayer();
219
+ if (recorder !== null) {
220
+ recorder.clearOnAudioReady();
221
+ void recorder.stop().catch(() => undefined);
222
+ }
223
+ void context?.close().catch(() => undefined);
224
+ void AudioManager.setAudioSessionActivity(false).catch(() => undefined);
225
+ recorder = null;
226
+ context = null;
227
+ handlers = null;
228
+ queued = [];
229
+ pending = [];
230
+ },
231
+ };
232
+ }
@@ -0,0 +1,206 @@
1
+ /**
2
+ * The web voice-call engine: one `AudioContext`, the microphone through
3
+ * `getUserMedia` (echo cancellation, noise suppression, automatic gain), an
4
+ * `AudioWorklet` that turns it into 24 kHz PCM16 frames, and a second
5
+ * `AudioWorklet` that plays the answer from a jitter-buffered queue.
6
+ *
7
+ * Both worklets run in the same context, so the page's audio graph is one
8
+ * stack. Whether Chrome's echo canceller removes Web Audio playback (it is
9
+ * proven for audio played through an `RTCPeerConnection`) is a release gate of
10
+ * ADR 0017 §4, measured on real hardware; the fallback it names (routing
11
+ * playback through a local `RTCPeerConnection` loopback) is not built until the
12
+ * measurement says it is needed.
13
+ *
14
+ * The worklets are one module served by the Gemies web app (`./voice-worklets.ts`),
15
+ * never a `blob:` URL a host's CSP would have to allow as script. Their numbers
16
+ * (stream rate, frame size, prebuffer) are passed as `processorOptions`.
17
+ */
18
+
19
+ import { levelOfPcm16, pcm16ToFloat } from './pcm';
20
+ import { VOICE_FRAME_SAMPLES, VOICE_SAMPLE_RATE } from './voice-protocol';
21
+ import { VOICE_WORKLETS_URL } from './voice-worklets';
22
+ import {
23
+ VoiceAudioEngineError,
24
+ type VoiceAudioEngine,
25
+ type VoiceAudioEngineHandlers,
26
+ } from './voice-audio-engine-types';
27
+
28
+ export * from './voice-audio-engine-types';
29
+
30
+ /** Played before the first sample of a burst, so network jitter does not stutter it. */
31
+ const PREBUFFER_MS = 80;
32
+ /** A burst shorter than the prebuffer still plays once nothing more arrives for this long. */
33
+ const PREBUFFER_IDLE_MS = 100;
34
+
35
+ function deviceError(caught: unknown): VoiceAudioEngineError {
36
+ const name = (caught as { name?: unknown } | null)?.name;
37
+ if (name === 'NotAllowedError' || name === 'SecurityError' || name === 'PermissionDeniedError')
38
+ return new VoiceAudioEngineError('mic-denied');
39
+ return new VoiceAudioEngineError(
40
+ 'mic-unavailable',
41
+ typeof name === 'string' ? name : 'The microphone could not be opened',
42
+ );
43
+ }
44
+
45
+ /** Level of the RMS a worklet reported, on the dictation meter's dBFS scale. */
46
+ function levelOfRms(rms: number): number {
47
+ if (rms <= 0) return 0;
48
+ return Math.min(1, Math.max(0, (20 * Math.log10(rms) + 60) / 60));
49
+ }
50
+
51
+ export function createVoiceAudioEngine(): VoiceAudioEngine {
52
+ let context: AudioContext | null = null;
53
+ let stream: MediaStream | null = null;
54
+ let capture: AudioWorkletNode | null = null;
55
+ let playback: AudioWorkletNode | null = null;
56
+ let stopped = false;
57
+ let pendingFlush: ((value: { itemId: string; playedMs: number } | null) => void) | null = null;
58
+ let lastProgress: { itemId: string; playedMs: number } | null = null;
59
+
60
+ return {
61
+ async start(handlers: VoiceAudioEngineHandlers): Promise<void> {
62
+ const media = globalThis.navigator?.mediaDevices;
63
+ const AudioContextCtor = globalThis.AudioContext;
64
+ if (!media?.getUserMedia || !AudioContextCtor || !('AudioWorkletNode' in globalThis)) {
65
+ throw new VoiceAudioEngineError('voice-unavailable');
66
+ }
67
+ try {
68
+ stream = await media.getUserMedia({
69
+ audio: {
70
+ echoCancellation: true,
71
+ noiseSuppression: true,
72
+ autoGainControl: true,
73
+ channelCount: 1,
74
+ },
75
+ });
76
+ } catch (caught: unknown) {
77
+ throw deviceError(caught);
78
+ }
79
+ if (stopped) {
80
+ for (const track of stream.getTracks()) track.stop();
81
+ return;
82
+ }
83
+
84
+ context = new AudioContextCtor({ latencyHint: 'interactive' });
85
+ try {
86
+ await context.audioWorklet.addModule(VOICE_WORKLETS_URL);
87
+ } catch {
88
+ throw new VoiceAudioEngineError('voice-unavailable');
89
+ }
90
+ await context.resume().catch(() => undefined);
91
+
92
+ const source = context.createMediaStreamSource(stream);
93
+ capture = new AudioWorkletNode(context, 'alia-voice-capture', {
94
+ numberOfInputs: 1,
95
+ numberOfOutputs: 0,
96
+ channelCount: 1,
97
+ processorOptions: {
98
+ streamSampleRate: VOICE_SAMPLE_RATE,
99
+ frameSamples: VOICE_FRAME_SAMPLES,
100
+ },
101
+ });
102
+ capture.port.onmessage = (event: MessageEvent<ArrayBuffer>) => {
103
+ if (stopped) return;
104
+ const pcm = new Uint8Array(event.data);
105
+ handlers.onCaptureLevel(levelOfPcm16(pcm));
106
+ handlers.onCaptureFrame(pcm);
107
+ };
108
+ source.connect(capture);
109
+
110
+ playback = new AudioWorkletNode(context, 'alia-voice-playback', {
111
+ numberOfInputs: 0,
112
+ numberOfOutputs: 1,
113
+ outputChannelCount: [context.destination.channelCount || 2],
114
+ processorOptions: {
115
+ streamSampleRate: VOICE_SAMPLE_RATE,
116
+ prebufferMs: PREBUFFER_MS,
117
+ prebufferIdleMs: PREBUFFER_IDLE_MS,
118
+ },
119
+ });
120
+ playback.port.onmessage = (event: MessageEvent) => {
121
+ const message = event.data as
122
+ | { type: 'started'; itemId: string }
123
+ | { type: 'progress'; itemId: string | null; playedMs: number; rms: number }
124
+ | { type: 'idle' }
125
+ | { type: 'flushed'; itemId: string | null; playedMs: number | null };
126
+ if (stopped) return;
127
+ switch (message.type) {
128
+ case 'started':
129
+ handlers.onPlaybackStarted(message.itemId);
130
+ return;
131
+ case 'progress':
132
+ lastProgress =
133
+ message.itemId === null
134
+ ? null
135
+ : { itemId: message.itemId, playedMs: message.playedMs };
136
+ handlers.onPlaybackLevel(levelOfRms(message.rms));
137
+ return;
138
+ case 'idle':
139
+ handlers.onPlaybackLevel(0);
140
+ handlers.onPlaybackIdle();
141
+ return;
142
+ case 'flushed': {
143
+ const resolve = pendingFlush;
144
+ pendingFlush = null;
145
+ handlers.onPlaybackLevel(0);
146
+ resolve?.(
147
+ message.itemId === null || message.playedMs === null
148
+ ? null
149
+ : { itemId: message.itemId, playedMs: Math.round(message.playedMs) },
150
+ );
151
+ }
152
+ }
153
+ };
154
+ playback.connect(context.destination);
155
+
156
+ for (const track of stream.getAudioTracks()) {
157
+ track.addEventListener('ended', () => {
158
+ if (!stopped) handlers.onError(new VoiceAudioEngineError('mic-unavailable'));
159
+ });
160
+ }
161
+ },
162
+
163
+ enqueue(itemId: string, pcm16: Uint8Array): void {
164
+ if (stopped || playback === null) return;
165
+ const samples = pcm16ToFloat(pcm16);
166
+ playback.port.postMessage({ type: 'chunk', itemId, samples }, [samples.buffer]);
167
+ },
168
+
169
+ flush(): Promise<{ itemId: string; playedMs: number } | null> {
170
+ if (stopped || playback === null) return Promise.resolve(null);
171
+ const fallback = lastProgress;
172
+ return new Promise((resolve) => {
173
+ // The worklet answers within a render quantum; if the context is
174
+ // suspended it never will, and the last progress report is the answer.
175
+ const timer = setTimeout(() => {
176
+ pendingFlush = null;
177
+ resolve(
178
+ fallback === null ? null : { ...fallback, playedMs: Math.round(fallback.playedMs) },
179
+ );
180
+ }, 250);
181
+ pendingFlush = (value) => {
182
+ clearTimeout(timer);
183
+ resolve(value);
184
+ };
185
+ playback?.port.postMessage({ type: 'flush' });
186
+ });
187
+ },
188
+
189
+ stop(): void {
190
+ if (stopped) return;
191
+ stopped = true;
192
+ pendingFlush?.(null);
193
+ pendingFlush = null;
194
+ capture?.port.close();
195
+ playback?.port.close();
196
+ capture?.disconnect();
197
+ playback?.disconnect();
198
+ for (const track of stream?.getTracks() ?? []) track.stop();
199
+ void context?.close().catch(() => undefined);
200
+ capture = null;
201
+ playback = null;
202
+ stream = null;
203
+ context = null;
204
+ },
205
+ };
206
+ }