@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,131 @@
1
+ /**
2
+ * Dictation's web recorder: `MediaRecorder` over `getUserMedia`, with an
3
+ * `AnalyserNode` on the same stream for the level meter. See
4
+ * `dictation-recorder-types.ts`.
5
+ */
6
+
7
+ import { useMemo } from 'react';
8
+ import { levelFromFrames } from './audio-level';
9
+ import { normalizeAudioMediaType, type DictationClip } from './dictation';
10
+ import { DictationRecorderError, type DictationRecorder } from './dictation-recorder-types';
11
+
12
+ export * from './dictation-recorder-types';
13
+
14
+ const LEVEL_POLL_MS = 100;
15
+
16
+ /** Opus in WebM where the browser records it (Chromium, Firefox), MP4/AAC on Safari. */
17
+ function recordingMimeType(): string | null {
18
+ const Recorder = globalThis.MediaRecorder;
19
+ if (!Recorder) return null;
20
+ for (const type of ['audio/webm;codecs=opus', 'audio/webm', 'audio/mp4']) {
21
+ if (Recorder.isTypeSupported?.(type)) return type;
22
+ }
23
+ return null;
24
+ }
25
+
26
+ export function createWebDictationRecorder(): DictationRecorder {
27
+ let stream: MediaStream | null = null;
28
+ let recorder: MediaRecorder | null = null;
29
+ let context: AudioContext | null = null;
30
+ let levelTimer: ReturnType<typeof setInterval> | null = null;
31
+ let chunks: Blob[] = [];
32
+ let startedAt = 0;
33
+
34
+ const release = (): void => {
35
+ if (levelTimer !== null) clearInterval(levelTimer);
36
+ levelTimer = null;
37
+ for (const track of stream?.getTracks() ?? []) track.stop();
38
+ void context?.close().catch(() => undefined);
39
+ stream = null;
40
+ context = null;
41
+ };
42
+
43
+ return {
44
+ async start(onLevel) {
45
+ const mimeType = recordingMimeType();
46
+ const media = globalThis.navigator?.mediaDevices;
47
+ if (mimeType === null || !media?.getUserMedia)
48
+ throw new DictationRecorderError('mic-unavailable');
49
+ try {
50
+ stream = await media.getUserMedia({
51
+ audio: { noiseSuppression: true, echoCancellation: true, autoGainControl: true },
52
+ });
53
+ } catch (caught: unknown) {
54
+ const name = (caught as { name?: unknown } | null)?.name;
55
+ throw new DictationRecorderError(
56
+ name === 'NotAllowedError' || name === 'SecurityError' ? 'mic-denied' : 'mic-unavailable',
57
+ );
58
+ }
59
+
60
+ const AudioContextCtor = globalThis.AudioContext;
61
+ if (AudioContextCtor) {
62
+ context = new AudioContextCtor();
63
+ const analyser = context.createAnalyser();
64
+ analyser.fftSize = 1024;
65
+ context.createMediaStreamSource(stream).connect(analyser);
66
+ const frames = new Float32Array(analyser.fftSize);
67
+ levelTimer = setInterval(() => {
68
+ analyser.getFloatTimeDomainData(frames);
69
+ onLevel(levelFromFrames(Array.from(frames)));
70
+ }, LEVEL_POLL_MS);
71
+ }
72
+
73
+ chunks = [];
74
+ const active = new MediaRecorder(stream, { mimeType });
75
+ recorder = active;
76
+ active.ondataavailable = (event) => {
77
+ if (event.data.size > 0) chunks.push(event.data);
78
+ };
79
+ await new Promise<void>((resolve, reject) => {
80
+ active.onstart = () => {
81
+ startedAt = Date.now();
82
+ resolve();
83
+ };
84
+ active.onerror = () => reject(new DictationRecorderError('mic-unavailable'));
85
+ try {
86
+ active.start();
87
+ } catch {
88
+ reject(new DictationRecorderError('mic-unavailable'));
89
+ }
90
+ }).catch((error: unknown) => {
91
+ release();
92
+ throw error;
93
+ });
94
+ },
95
+
96
+ stop(): Promise<DictationClip | null> {
97
+ const active = recorder;
98
+ recorder = null;
99
+ if (active === null || active.state === 'inactive') {
100
+ release();
101
+ return Promise.resolve(null);
102
+ }
103
+ return new Promise((resolve) => {
104
+ active.onstop = () => {
105
+ const durationMs = Date.now() - startedAt;
106
+ const mediaType = normalizeAudioMediaType(active.mimeType || 'audio/webm');
107
+ const blob = new Blob(chunks, { type: mediaType });
108
+ chunks = [];
109
+ release();
110
+ resolve(blob.size === 0 ? null : { file: blob, mediaType, durationMs });
111
+ };
112
+ active.stop();
113
+ });
114
+ },
115
+
116
+ cancel(): void {
117
+ const active = recorder;
118
+ recorder = null;
119
+ chunks = [];
120
+ if (active !== null && active.state !== 'inactive') {
121
+ active.onstop = null;
122
+ active.stop();
123
+ }
124
+ release();
125
+ },
126
+ };
127
+ }
128
+
129
+ export function useDictationRecorder(): DictationRecorder {
130
+ return useMemo(() => createWebDictationRecorder(), []);
131
+ }
@@ -0,0 +1,238 @@
1
+ /**
2
+ * Streaming dictation's network half (ADR 0024): the caller's microphone PCM to
3
+ * `GET /v1/audio/transcriptions/stream`, and Alia's segments back while the
4
+ * person speaks.
5
+ *
6
+ * It records nothing and draws nothing: the caller brings PCM16 LE mono at
7
+ * 24 kHz from its own recorder (an AudioWorklet, a native module) and shows
8
+ * the segments its own way. A segment's `transcript.final` is the only text to
9
+ * keep; `transcript.interim` and `transcript.delta` are display state the
10
+ * final supersedes. When the stream cannot open (`TRANSCRIPTION_UNAVAILABLE`),
11
+ * batch `requestTranscription` is the fallback.
12
+ */
13
+
14
+ import {
15
+ type DictationClientEvent,
16
+ type DictationCloseReason,
17
+ type DictationServerEvent,
18
+ DICTATION_PROTOCOL_VERSION,
19
+ DICTATION_SAMPLE_RATE,
20
+ dictationStreamUrl,
21
+ parseDictationServerEvent,
22
+ } from './dictation-protocol';
23
+
24
+ /** The WebSocket the stream drives: a browser's, React Native's or a test's. */
25
+ export interface DictationSocket {
26
+ binaryType: string;
27
+ readonly readyState: number;
28
+ onopen: ((event: unknown) => void) | null;
29
+ onmessage: ((event: { data: unknown }) => void) | null;
30
+ onclose: ((event: unknown) => void) | null;
31
+ onerror: ((event: unknown) => void) | null;
32
+ send(data: string | ArrayBufferLike | ArrayBufferView): void;
33
+ close(code?: number, reason?: string): void;
34
+ }
35
+
36
+ /** How the stream proves the person: their Oxy session token, read once at open. */
37
+ export type DictationStreamAuthentication =
38
+ | {
39
+ readonly getToken: (
40
+ target: string,
41
+ options?: { signal?: AbortSignal },
42
+ ) => string | null | Promise<string | null>;
43
+ readonly token?: never;
44
+ }
45
+ | { readonly token: string; readonly getToken?: never };
46
+
47
+ export type DictationStreamOptions = DictationStreamAuthentication & {
48
+ /** The Gemies API origin, `https://api.gemies.ai`. */
49
+ readonly apiUrl: string;
50
+ /** BCP 47; omitted lets the model detect the language. */
51
+ readonly language?: string;
52
+ /**
53
+ * Every event, in order. It always ends with one `dictation.closed`; a failure
54
+ * comes as `error` just before it. A connection Alia never answered on is
55
+ * reported as `TRANSCRIPTION_FAILED`, retryable.
56
+ */
57
+ readonly onEvent: (event: DictationServerEvent) => void;
58
+ /** Aborting it is `close()`. */
59
+ readonly signal?: AbortSignal;
60
+ /** The socket factory; the platform's `WebSocket` by default. */
61
+ readonly openSocket?: (url: string) => DictationSocket;
62
+ /** How long `end()` waits for Alia's `dictation.closed` before closing the socket. */
63
+ readonly endTimeoutMs?: number;
64
+ };
65
+
66
+ export interface DictationStream {
67
+ /** One microphone frame: PCM16 LE, mono, {@link DICTATION_SAMPLE_RATE} Hz. */
68
+ append(pcm16: Uint8Array): void;
69
+ /** End the current segment now (push-to-talk). */
70
+ commit(): void;
71
+ /** No more audio: resolves with how the dictation closed, once the finals have arrived. */
72
+ end(): Promise<DictationCloseReason>;
73
+ /** Drop the dictation now; nothing more is reported. */
74
+ close(): void;
75
+ /** Settles with how the dictation closed, whatever closed it. */
76
+ readonly closed: Promise<DictationCloseReason>;
77
+ }
78
+
79
+ const OPEN = 1;
80
+ const DEFAULT_END_TIMEOUT_MS = 8_000;
81
+ /** Audio held until the socket is open and the start sent: ten seconds. */
82
+ const MAX_HELD_BYTES = 10 * DICTATION_SAMPLE_RATE * 2;
83
+
84
+ function defaultSocket(url: string): DictationSocket {
85
+ const WebSocketClass = (globalThis as { WebSocket?: new (url: string) => DictationSocket })
86
+ .WebSocket;
87
+ if (!WebSocketClass) throw new Error('This platform has no WebSocket');
88
+ return new WebSocketClass(url);
89
+ }
90
+
91
+ /** Open one streaming dictation. */
92
+ export function openDictationStream(options: DictationStreamOptions): DictationStream {
93
+ const url = dictationStreamUrl(options.apiUrl);
94
+ const credentialAbort = new AbortController();
95
+ let socket: DictationSocket | null = null;
96
+ let started = false;
97
+ let finished = false;
98
+ let held: Uint8Array[] = [];
99
+ let heldBytes = 0;
100
+ let endRequested = false;
101
+ let endTimer: ReturnType<typeof setTimeout> | null = null;
102
+ let resolveClosed!: (reason: DictationCloseReason) => void;
103
+ const closed = new Promise<DictationCloseReason>((resolve) => {
104
+ resolveClosed = resolve;
105
+ });
106
+
107
+ const sendEvent = (event: DictationClientEvent) => {
108
+ if (socket?.readyState === OPEN) socket.send(JSON.stringify(event));
109
+ };
110
+
111
+ const finish = (reason: DictationCloseReason, report: boolean) => {
112
+ if (finished) return;
113
+ finished = true;
114
+ if (endTimer !== null) clearTimeout(endTimer);
115
+ credentialAbort.abort();
116
+ held = [];
117
+ const current = socket;
118
+ socket = null;
119
+ if (current) {
120
+ current.onmessage = null;
121
+ current.onclose = null;
122
+ current.onerror = null;
123
+ if (current.readyState === OPEN || current.readyState === 0) current.close(1000);
124
+ }
125
+ if (report) options.onEvent({ type: 'dictation.closed', reason });
126
+ resolveClosed(reason);
127
+ };
128
+
129
+ const fail = () => {
130
+ if (finished) return;
131
+ options.onEvent({
132
+ type: 'error',
133
+ code: 'TRANSCRIPTION_FAILED',
134
+ message: 'The dictation lost its connection to Alia.',
135
+ retryable: true,
136
+ });
137
+ finish('error', true);
138
+ };
139
+
140
+ const readToken = async (): Promise<string | null> => {
141
+ if (options.token !== undefined) return options.token || null;
142
+ try {
143
+ const token = await options.getToken(url, { signal: credentialAbort.signal });
144
+ return token || null;
145
+ } catch {
146
+ return null;
147
+ }
148
+ };
149
+
150
+ const begin = async (opened: DictationSocket) => {
151
+ const token = await readToken();
152
+ if (finished || socket !== opened) return;
153
+ if (!token) {
154
+ options.onEvent({
155
+ type: 'error',
156
+ code: 'NOT_AUTHENTICATED',
157
+ message: 'Sign in to Alia to dictate.',
158
+ retryable: false,
159
+ });
160
+ finish('error', true);
161
+ return;
162
+ }
163
+ sendEvent({ type: 'auth', token });
164
+ sendEvent({
165
+ type: 'dictation.start',
166
+ protocol: DICTATION_PROTOCOL_VERSION,
167
+ sampleRate: DICTATION_SAMPLE_RATE,
168
+ ...(options.language === undefined ? {} : { language: options.language }),
169
+ });
170
+ started = true;
171
+ for (const frame of held) opened.send(frame);
172
+ held = [];
173
+ heldBytes = 0;
174
+ if (endRequested) sendEvent({ type: 'dictation.end' });
175
+ };
176
+
177
+ try {
178
+ socket = (options.openSocket ?? defaultSocket)(url);
179
+ } catch {
180
+ queueMicrotask(fail);
181
+ }
182
+ if (socket) {
183
+ const opened = socket;
184
+ opened.binaryType = 'arraybuffer';
185
+ opened.onopen = () => {
186
+ void begin(opened);
187
+ };
188
+ opened.onmessage = (message) => {
189
+ if (typeof message.data !== 'string') return;
190
+ const event = parseDictationServerEvent(message.data);
191
+ if (event === null || finished) return;
192
+ if (event.type === 'dictation.closed') {
193
+ options.onEvent(event);
194
+ finish(event.reason, false);
195
+ return;
196
+ }
197
+ options.onEvent(event);
198
+ };
199
+ opened.onclose = () => fail();
200
+ opened.onerror = () => undefined;
201
+ }
202
+
203
+ const close = () => finish('ended', false);
204
+ if (options.signal) {
205
+ if (options.signal.aborted) queueMicrotask(close);
206
+ else options.signal.addEventListener('abort', close, { once: true });
207
+ }
208
+
209
+ return {
210
+ append(pcm16) {
211
+ if (finished || endRequested || pcm16.byteLength === 0) return;
212
+ if (started && socket?.readyState === OPEN) {
213
+ socket.send(pcm16);
214
+ return;
215
+ }
216
+ if (heldBytes + pcm16.byteLength > MAX_HELD_BYTES) return;
217
+ held.push(pcm16.slice());
218
+ heldBytes += pcm16.byteLength;
219
+ },
220
+ commit() {
221
+ if (!finished && started) sendEvent({ type: 'dictation.commit' });
222
+ },
223
+ end() {
224
+ if (finished) return closed;
225
+ if (!endRequested) {
226
+ endRequested = true;
227
+ if (started) sendEvent({ type: 'dictation.end' });
228
+ endTimer = setTimeout(
229
+ () => finish('ended', true),
230
+ options.endTimeoutMs ?? DEFAULT_END_TIMEOUT_MS,
231
+ );
232
+ }
233
+ return closed;
234
+ },
235
+ close,
236
+ closed,
237
+ };
238
+ }
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Dictation's network half: a recorded clip to `POST /v1/audio/transcriptions`
3
+ * (ADR 0017 §7), which Alia answers with a Kaana transcription model computed
4
+ * from the catalogue. Free on every plan; at most five minutes per clip.
5
+ *
6
+ * Batch, not streaming: the text arrives once the person stops. Nothing is
7
+ * recognized on the device.
8
+ */
9
+
10
+ import type { AudioRequestAuthentication } from './audio-request-auth';
11
+ import type { VoiceErrorCode } from './speech-messages';
12
+
13
+ /** The longest clip one dictation may be. */
14
+ export const MAX_DICTATION_MS = 5 * 60_000;
15
+
16
+ /** A clip as a recorder hands it over: a web `Blob`, or a React Native file. */
17
+ export interface DictationClip {
18
+ readonly file: Blob | { readonly uri: string; readonly name: string; readonly type: string };
19
+ /** Without parameters: `audio/webm`, `audio/mp4`, … */
20
+ readonly mediaType: string;
21
+ /** Measured by the recorder. */
22
+ readonly durationMs: number;
23
+ }
24
+
25
+ export interface TranscriptionResult {
26
+ readonly text: string;
27
+ readonly language?: string;
28
+ readonly durationMs?: number;
29
+ /** The model that transcribed it (its name may be shown). */
30
+ readonly model?: string;
31
+ }
32
+
33
+ /** What the route answers a failure with, plus the two this side knows on its own. */
34
+ export type DictationErrorCode =
35
+ | 'TRANSCRIPTION_UNAVAILABLE'
36
+ | 'TRANSCRIPTION_LIMITED'
37
+ | 'TRANSCRIPTION_REJECTED'
38
+ | 'TRANSCRIPTION_FAILED'
39
+ | 'CLIP_TOO_LONG'
40
+ | 'INVALID_REQUEST'
41
+ | 'NOT_AUTHENTICATED'
42
+ | 'CREDENTIAL_NOT_SUPPORTED';
43
+
44
+ const SERVER_CODES: ReadonlySet<string> = new Set<DictationErrorCode>([
45
+ 'TRANSCRIPTION_UNAVAILABLE',
46
+ 'TRANSCRIPTION_LIMITED',
47
+ 'TRANSCRIPTION_REJECTED',
48
+ 'TRANSCRIPTION_FAILED',
49
+ 'CLIP_TOO_LONG',
50
+ 'INVALID_REQUEST',
51
+ 'NOT_AUTHENTICATED',
52
+ 'CREDENTIAL_NOT_SUPPORTED',
53
+ ]);
54
+
55
+ export class DictationError extends Error {
56
+ /** `null` when no request was answered (network) or the code is unknown. */
57
+ readonly code: DictationErrorCode | null;
58
+ readonly status: number | null;
59
+ readonly retryable: boolean;
60
+
61
+ constructor(
62
+ message: string,
63
+ details: { code: DictationErrorCode | null; status: number | null; retryable?: boolean },
64
+ ) {
65
+ super(message);
66
+ this.name = 'DictationError';
67
+ this.code = details.code;
68
+ this.status = details.status;
69
+ this.retryable = details.retryable ?? false;
70
+ }
71
+ }
72
+
73
+ /** The `VoiceErrorCode` an app says a failed transcription with. */
74
+ export function dictationFailureCode(error: unknown): VoiceErrorCode {
75
+ if (!(error instanceof DictationError)) return 'transcription-failed';
76
+ switch (error.code) {
77
+ case 'TRANSCRIPTION_UNAVAILABLE':
78
+ return 'transcription-unavailable';
79
+ case 'TRANSCRIPTION_LIMITED':
80
+ return 'transcription-limited';
81
+ case 'TRANSCRIPTION_REJECTED':
82
+ case 'INVALID_REQUEST':
83
+ return 'transcription-rejected';
84
+ case 'CLIP_TOO_LONG':
85
+ return 'too-long';
86
+ case 'NOT_AUTHENTICATED':
87
+ return 'not-authenticated';
88
+ case 'CREDENTIAL_NOT_SUPPORTED':
89
+ return 'credential-not-supported';
90
+ case 'TRANSCRIPTION_FAILED':
91
+ case null:
92
+ return 'transcription-failed';
93
+ }
94
+ }
95
+
96
+ /** `audio/webm;codecs=opus` → `audio/webm`; iOS's m4a names → `audio/mp4`. */
97
+ export function normalizeAudioMediaType(type: string): string {
98
+ const bare = type.split(';')[0]!.trim().toLowerCase();
99
+ if (bare === 'audio/x-m4a' || bare === 'audio/m4a' || bare === 'audio/aac-mp4')
100
+ return 'audio/mp4';
101
+ return bare;
102
+ }
103
+
104
+ function fileNameFor(mediaType: string): string {
105
+ switch (mediaType) {
106
+ case 'audio/webm':
107
+ return 'dictation.webm';
108
+ case 'audio/ogg':
109
+ return 'dictation.ogg';
110
+ case 'audio/mpeg':
111
+ return 'dictation.mp3';
112
+ case 'audio/wav':
113
+ return 'dictation.wav';
114
+ default:
115
+ return 'dictation.m4a';
116
+ }
117
+ }
118
+
119
+ export type TranscriptionRequest = AudioRequestAuthentication & {
120
+ readonly apiUrl: string;
121
+ readonly clip: DictationClip;
122
+ /** BCP-47. */
123
+ readonly language: string;
124
+ readonly signal?: AbortSignal;
125
+ };
126
+
127
+ /**
128
+ * Transcribe one clip.
129
+ *
130
+ * @throws {DictationError} for every refusal; an abort is thrown as `fetch` threw it.
131
+ */
132
+ export async function requestTranscription(
133
+ request: TranscriptionRequest,
134
+ ): Promise<TranscriptionResult> {
135
+ if (request.token === '')
136
+ throw new DictationError('Not authenticated', { code: 'NOT_AUTHENTICATED', status: null });
137
+ const mediaType = normalizeAudioMediaType(request.clip.mediaType);
138
+ const form = new FormData();
139
+ const { file } = request.clip;
140
+ if (typeof Blob !== 'undefined' && file instanceof Blob) {
141
+ form.append('file', file, fileNameFor(mediaType));
142
+ } else {
143
+ // React Native's FormData takes a file by `{ uri, name, type }`.
144
+ form.append('file', file as unknown as Blob);
145
+ }
146
+ form.append('language', request.language);
147
+ form.append('durationMs', String(Math.max(0, Math.round(request.clip.durationMs))));
148
+
149
+ let response: Response;
150
+ try {
151
+ response = await (request.transport?.fetch ?? fetch)(
152
+ `${request.apiUrl}/v1/audio/transcriptions`,
153
+ {
154
+ method: 'POST',
155
+ headers: request.transport ? undefined : { Authorization: `Bearer ${request.token}` },
156
+ redirect: 'error',
157
+ credentials: 'omit',
158
+ body: form,
159
+ ...(request.signal ? { signal: request.signal } : {}),
160
+ },
161
+ );
162
+ } catch (caught: unknown) {
163
+ if ((caught as { name?: unknown } | null)?.name === 'AbortError') throw caught;
164
+ const code = (caught as { code?: unknown } | null)?.code;
165
+ if (code === 'AUTH_REQUIRED' || code === 'AUTH_SESSION_CHANGED')
166
+ throw new DictationError('Not authenticated', { code: 'NOT_AUTHENTICATED', status: null });
167
+ throw new DictationError('The transcription request did not reach Alia', {
168
+ code: null,
169
+ status: null,
170
+ retryable: true,
171
+ });
172
+ }
173
+
174
+ const body: unknown = await response.json().catch(() => null);
175
+ if (!response.ok) {
176
+ const envelope =
177
+ body !== null && typeof body === 'object' ? (body as { error?: unknown }).error : undefined;
178
+ const error =
179
+ envelope !== null && typeof envelope === 'object'
180
+ ? (envelope as { code?: unknown; message?: unknown; retryable?: unknown })
181
+ : {};
182
+ const named =
183
+ typeof error.code === 'string' && SERVER_CODES.has(error.code)
184
+ ? (error.code as DictationErrorCode)
185
+ : null;
186
+ throw new DictationError(
187
+ typeof error.message === 'string' && error.message !== ''
188
+ ? error.message
189
+ : 'Transcription failed',
190
+ {
191
+ code:
192
+ named ??
193
+ (response.status === 401
194
+ ? 'NOT_AUTHENTICATED'
195
+ : response.status === 413
196
+ ? 'CLIP_TOO_LONG'
197
+ : null),
198
+ status: response.status,
199
+ retryable: error.retryable === true,
200
+ },
201
+ );
202
+ }
203
+ const result = body !== null && typeof body === 'object' ? (body as Record<string, unknown>) : {};
204
+ if (typeof result.text !== 'string') {
205
+ throw new DictationError('Alia answered no transcription', {
206
+ code: 'TRANSCRIPTION_FAILED',
207
+ status: response.status,
208
+ });
209
+ }
210
+ return {
211
+ text: result.text,
212
+ ...(typeof result.language === 'string' ? { language: result.language } : {}),
213
+ ...(typeof result.durationMs === 'number' ? { durationMs: result.durationMs } : {}),
214
+ ...(typeof result.model === 'string' ? { model: result.model } : {}),
215
+ };
216
+ }
@@ -0,0 +1,31 @@
1
+ import * as DocumentPicker from 'expo-document-picker';
2
+
3
+ export type DocumentPickerResult = {
4
+ uri: string;
5
+ name: string;
6
+ size: number;
7
+ mimeType: string;
8
+ };
9
+
10
+ /** The platform's document picker, several at once; nothing when the person cancels or it fails. */
11
+ export async function pickDocuments(): Promise<DocumentPickerResult[] | undefined> {
12
+ try {
13
+ const result = await DocumentPicker.getDocumentAsync({
14
+ type: '*/*',
15
+ multiple: true,
16
+ copyToCacheDirectory: true,
17
+ });
18
+
19
+ if (result.canceled === false && result.assets && result.assets.length > 0) {
20
+ return result.assets.map((asset) => ({
21
+ uri: asset.uri,
22
+ name: asset.name,
23
+ size: asset.size || 0,
24
+ mimeType: asset.mimeType || 'application/octet-stream',
25
+ }));
26
+ }
27
+ } catch (error) {
28
+ console.warn('Failed to pick document:', error);
29
+ }
30
+ return undefined;
31
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The host of a URL, or the string itself when it is not one. Citations drop a leading `www.`
3
+ * (the number in `[3]` names a site); a source row in the work log keeps the host as served.
4
+ */
5
+ export function domainOf(url: string, { stripWww = false }: { stripWww?: boolean } = {}): string {
6
+ try {
7
+ const host = new URL(url).hostname;
8
+ return stripWww ? host.replace(/^www\./, '') : host;
9
+ } catch {
10
+ return url;
11
+ }
12
+ }
@@ -0,0 +1,33 @@
1
+ import { createContext, useContext } from 'react';
2
+ import type { AvatarFlights, AvatarFlightSpec } from '@oxy.so/bloom/avatar-flight';
3
+
4
+ import type { GemieParticipant } from './participants';
5
+
6
+ /**
7
+ * Where the conversation's avatars are: the lead's, large in the greeting; everybody's, small in
8
+ * the header's participants; and a consulted agent's, beside the reply it is writing.
9
+ */
10
+ export const ANCHORS = {
11
+ welcome: 'lead:welcome',
12
+ profile: 'participants',
13
+ reply: (agentId: string) => `reply:${agentId}`,
14
+ } as const;
15
+
16
+ /** The greeting's avatar flies up into the header's participants as the conversation begins. */
17
+ export function leadToProfile(lead: GemieParticipant): AvatarFlightSpec {
18
+ return {
19
+ key: 'lead',
20
+ character: lead.character,
21
+ from: ANCHORS.welcome,
22
+ to: ANCHORS.profile,
23
+ duration: 800,
24
+ };
25
+ }
26
+
27
+ const FlightsContext = createContext<AvatarFlights | null>(null);
28
+
29
+ /** The chat's avatar flights, for the greeting, the thread and the header that share them. */
30
+ export const GemieFlightsProvider = FlightsContext.Provider;
31
+
32
+ /** `null` outside a chat: the greeting, the replies and the header then draw their avatars without flying. */
33
+ export const useGemieFlights = () => useContext(FlightsContext);