@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,287 @@
1
+ /** The SDK chat catalogue, matching the Spanish Alia app copy. */
2
+ import type { CopyEntry } from './copy-en';
3
+
4
+ export const COPY_ES: Readonly<Record<string, CopyEntry>> = {
5
+ 'automations.cron.dailyAt': 'Todos los días a las {{time}}',
6
+ 'automations.cron.dayPlural.0': 'domingos',
7
+ 'automations.cron.dayPlural.1': 'lunes',
8
+ 'automations.cron.dayPlural.2': 'martes',
9
+ 'automations.cron.dayPlural.3': 'miércoles',
10
+ 'automations.cron.dayPlural.4': 'jueves',
11
+ 'automations.cron.dayPlural.5': 'viernes',
12
+ 'automations.cron.dayPlural.6': 'sábados',
13
+ 'automations.cron.daysAt': 'Los {{days}} a las {{time}}',
14
+ 'automations.cron.everyHour': 'Cada hora',
15
+ 'automations.cron.everyHours': 'Cada {{count}} horas',
16
+ 'automations.cron.everyMinutes': { one: 'Cada minuto', other: 'Cada {{count}} minutos' },
17
+ 'automations.cron.weekdaysAt': 'De lunes a viernes a las {{time}}',
18
+ 'automations.cron.weekendsAt': 'Los fines de semana a las {{time}}',
19
+ 'automations.trigger.anyApp': 'Cualquier app',
20
+ 'automations.trigger.anyEvent': 'Cualquier evento',
21
+ 'automations.trigger.manual': 'A petición',
22
+ 'automations.trigger.unscheduled': 'Sin programar',
23
+ 'chat.agentRun.by': 'por %{name}',
24
+ 'chat.agentRun.complete': 'Tarea completada',
25
+ 'chat.agentRun.completed': 'Completada',
26
+ 'chat.agentRun.credits': '%{count} créditos',
27
+ 'chat.agentRun.error': 'Error',
28
+ 'chat.agentRun.failed': 'Fallida',
29
+ 'chat.agentRun.planItems': '%{done}/%{total} pasos del plan',
30
+ 'chat.agentRun.planSummary': 'Resumen del plan',
31
+ 'chat.agentRun.steps': '%{count} pasos',
32
+ 'chat.agentRun.taskComplete': 'Tarea completada',
33
+ 'chat.agentRun.taskFailed': 'La tarea falló',
34
+ 'chat.agentRun.unknown': 'Desconocido',
35
+ 'chat.agentRun.working': 'Gemie trabajando',
36
+ 'chat.backToLatest': 'Volver a lo último',
37
+ 'chat.blockFailed': 'Esta parte de la respuesta no se ha podido mostrar.',
38
+ 'chat.bloom.context.freeSpace': 'Espacio libre',
39
+ 'chat.bloom.context.mcp': 'Herramientas MCP',
40
+ 'chat.bloom.context.memory': 'Memoria',
41
+ 'chat.bloom.context.messages': 'Mensajes',
42
+ 'chat.bloom.context.skills': 'Skills',
43
+ 'chat.bloom.context.system': 'Prompt del sistema',
44
+ 'chat.bloom.context.title': 'Ventana de contexto',
45
+ 'chat.bloom.context.tools': 'Herramientas',
46
+ 'chat.bloom.createdFile': 'Creó',
47
+ 'chat.bloom.limits.close': 'Cerrar panel de créditos',
48
+ 'chat.bloom.limits.dailyFree': 'Créditos gratis diarios',
49
+ 'chat.bloom.limits.planUsage': 'Límites de uso del plan',
50
+ 'chat.bloom.limits.resetsDaily': 'Se renueva cada 24 horas',
51
+ 'chat.bloom.limits.resetsInHours': 'Se renueva en {{hours}} h {{minutes}} min',
52
+ 'chat.bloom.limits.resetsInMinutes': 'Se renueva en {{minutes}} min',
53
+ 'chat.bloom.limits.resetsSoon': 'Se renueva pronto',
54
+ 'chat.bloom.limits.window': 'Límite de {{hours}} horas',
55
+ 'chat.bloom.limits.windowFresh': 'Se renueva {{hours}} horas después de tu próximo mensaje',
56
+ 'chat.bloom.noResults': 'Sin resultados',
57
+ 'chat.bloom.researched': 'Investigó',
58
+ 'chat.bloom.researching': 'Investigando',
59
+ 'chat.bloom.resultCount': { one: '1 resultado', other: '{{count}} resultados' },
60
+ 'chat.bloom.scrollToLatest': 'Ir a los últimos mensajes',
61
+ 'chat.bloom.searchCount': { one: '1 búsqueda', other: '{{count}} búsquedas' },
62
+ 'chat.bloom.searchFailed': 'La búsqueda falló',
63
+ 'chat.bloom.searchedWeb': 'Buscó en la web',
64
+ 'chat.bloom.sourceCount': { one: '1 fuente', other: '{{count}} fuentes' },
65
+ 'chat.bloom.taskFailed': 'Devolvió un error',
66
+ 'chat.bloom.taskInput': 'Con',
67
+ 'chat.bloom.taskStopped': 'No terminó',
68
+ 'chat.bloom.visited': 'Visitó',
69
+ 'chat.bloom.writingFile': 'Escribiendo',
70
+ 'chat.copied': '¡Copiado!',
71
+ 'chat.copiedToClipboard': 'Copiado al portapapeles',
72
+ 'chat.copy': 'Copiar',
73
+ 'chat.copyFailed': 'No se pudo copiar al portapapeles',
74
+ 'chat.dislike': 'No me gusta',
75
+ 'chat.edit': 'Editar',
76
+ 'chat.feedbackFailed': 'No se ha podido guardar tu opinión.',
77
+ 'chat.like': 'Me gusta',
78
+ 'chat.newConversationAccept': 'Empezar una nueva',
79
+ 'chat.newConversationDismiss': 'Ahora no',
80
+ 'chat.newConversationOffer': '¿Empezar una conversación nueva?',
81
+ 'chat.newStretch': 'Conversación nueva',
82
+ 'chat.chattedWith': 'Habló con %{name}',
83
+ 'chat.agentChatNotice': 'Conversación entre Gemies. Solo lectura.',
84
+ 'chat.groupWelcome': 'Varias mentes, una conversación',
85
+ 'chat.groupPlaceholder': 'Escribe al grupo',
86
+ 'chat.reaction': 'Has reaccionado con {{emoji}}',
87
+ 'chat.reactionFailed': 'No se ha podido guardar tu reacción.',
88
+ 'chat.reactToMessage': 'Reaccionar al mensaje',
89
+ 'chat.replyToMessage': 'Responder al mensaje',
90
+ 'chat.moreActions': 'Más acciones del mensaje',
91
+ 'chat.readAloud': 'Leer en voz alta',
92
+ 'chat.readAloudFailed': 'No se pudo leer en voz alta',
93
+ 'chat.regenerate': 'Volver a generar',
94
+ 'chat.retry': 'Reintentar',
95
+ 'chat.richBlocks.source': 'Fuente: {{source}}',
96
+ 'chat.searchThreadAgent': 'Gemie',
97
+ 'chat.searchThreadEmpty': 'No hay coincidencias.',
98
+ 'chat.searchThreadFailed': 'No se pudo buscar.',
99
+ 'chat.searchThreadHint':
100
+ 'Busca todo lo que le has dicho a este Gemie, en todas las conversaciones.',
101
+ 'chat.searchThreadPlaceholder': 'Buscar en este hilo',
102
+ 'chat.searchThreadSearching': 'Buscando…',
103
+ 'chat.searchThreadYou': 'Tú',
104
+ 'chat.sources': 'Fuentes',
105
+ 'chat.stopReading': 'Dejar de leer',
106
+ 'chat.thanksFeedback': '¡Gracias por tu opinión!',
107
+ 'chat.thinking': 'Pensando',
108
+ 'chat.today': 'Hoy',
109
+ 'chat.toolCard.openTask': 'Abrir la tarea programada %{objective}',
110
+ 'chat.toolCard.paused': 'En pausa',
111
+ 'chat.toolCard.scheduled': 'Programada',
112
+ 'chat.turnActions': 'Acciones del mensaje',
113
+ 'chat.consultFailed': '%{name} no pudo responder.',
114
+ 'chat.shareFailed': 'No se pudo crear el enlace para compartir.',
115
+ 'chat.sharedFailed': 'No se pudo cargar esta conversación.',
116
+ 'chat.sharedGone': 'Esta conversación compartida ya no está disponible.',
117
+ 'chat.turnFailed': 'Alia no ha podido responder ahora mismo.',
118
+ 'chat.turnFailedRetryHint': 'Inténtalo de nuevo.',
119
+ 'chat.turnInterrupted': 'Alia se interrumpió antes de terminar.',
120
+ 'chat.working': 'Trabajando',
121
+ 'chat.yesterday': 'Ayer',
122
+ 'common.close': 'Cerrar',
123
+ 'composer.cancelEdit': 'Cancelar',
124
+ 'composer.editPlaceholder': 'Edita tu mensaje',
125
+ 'composer.editingMessage': 'Editando mensaje',
126
+ 'faircoin.indexed':
127
+ 'Precio indexado del pool WFAIR/USDC en Base — FairCoin no cotiza en ningún exchange',
128
+ 'faircoin.liquidity': 'Liquidez',
129
+ 'faircoin.marketCap': 'Capitalización',
130
+ 'faircoin.name': 'FairCoin',
131
+ 'faircoin.noChart': 'Sólo hay una muestra — no bastan para trazar una línea.',
132
+ 'faircoin.noPrice': 'Sin cotización',
133
+ 'faircoin.noPriceHint': 'El pool WFAIR/USDC no tenía precio indexado cuando se preguntó.',
134
+ 'faircoin.noSamples': 'Todavía no hay muestras de este periodo.',
135
+ 'faircoin.range.1y': '1 A',
136
+ 'faircoin.range.24h': '24 h',
137
+ 'faircoin.range.30d': '30 D',
138
+ 'faircoin.range.7d': '7 D',
139
+ 'faircoin.range.all': 'Todo',
140
+ 'faircoin.scale.billion': ' mil M',
141
+ 'faircoin.scale.million': ' M',
142
+ 'faircoin.scale.thousand': ' mil',
143
+ 'faircoin.scale.trillion': ' B',
144
+ 'faircoin.source': 'De %{source}',
145
+ 'faircoin.symbol': 'FAIR',
146
+ 'faircoin.unavailable': 'Sin histórico para %{ranges}',
147
+ 'faircoin.updated': 'Actualizado %{time}',
148
+ 'faircoin.volume': 'Volumen 24 h',
149
+ 'market.dayHigh': 'Máximo del día',
150
+ 'market.dayLow': 'Mínimo del día',
151
+ 'market.marketCap': 'Capitalización',
152
+ 'market.noChart': 'No hay histórico suficiente para dibujar este rango',
153
+ 'market.noPrice': 'Sin cotización disponible',
154
+ 'market.open': 'Apertura',
155
+ 'market.range.1D': '1D',
156
+ 'market.range.1M': '1M',
157
+ 'market.range.1Y': '1A',
158
+ 'market.range.5D': '5D',
159
+ 'market.range.5Y': '5A',
160
+ 'market.range.6M': '6M',
161
+ 'market.range.MAX': 'MAX',
162
+ 'market.range.YTD': 'YTD',
163
+ 'market.volume': 'Volumen (24 h)',
164
+ 'panels.canvas.image': 'Imagen',
165
+ 'panels.canvas.unsupported': 'Tipo de componente no compatible: {{type}}',
166
+ 'panels.chart.share': 'Porcentaje',
167
+ 'panels.chart.value': 'Valor',
168
+ 'panels.code.copied': 'Código copiado',
169
+ 'panels.code.copy': 'Copiar código',
170
+ 'panels.form.enter': 'Escribe {{field}}',
171
+ 'panels.form.select': 'Selecciona…',
172
+ 'panels.form.submit': 'Enviar',
173
+ 'powerLevels.auto.description': 'Elige el nivel adecuado para cada mensaje',
174
+ 'powerLevels.auto.label': 'Auto',
175
+ 'powerLevels.high.description': 'Piensa más en las preguntas difíciles',
176
+ 'powerLevels.high.label': 'Alto',
177
+ 'powerLevels.instant.description': 'Lo más rápido y barato, para respuestas rápidas',
178
+ 'powerLevels.instant.label': 'Instantáneo',
179
+ 'powerLevels.medium.description': 'Rápido y capaz, para el día a día',
180
+ 'powerLevels.medium.label': 'Medio',
181
+ 'powerLevels.onDevice': 'En %{device}',
182
+ 'powerLevels.pro.description': 'Modelos punteros; más lento y más caro',
183
+ 'powerLevels.pro.label': 'Pro',
184
+ 'powerLevels.ultra.description': 'El más capaz; el más lento y el más caro',
185
+ 'powerLevels.ultra.label': 'Ultra',
186
+ 'powerLevels.xhigh.description': 'Piensa aún más; algo más lento',
187
+ 'powerLevels.xhigh.label': 'Muy alto',
188
+ 'tasks.tool.done.agentSearch': 'Buscó Gemies',
189
+ 'tasks.tool.done.browse': 'Navegó',
190
+ 'tasks.tool.done.codeInterpreter': 'Ejecutó código',
191
+ 'tasks.tool.done.consultAgent': 'Consultó a un Gemie',
192
+ 'tasks.tool.done.fileEdit': 'Editó un archivo',
193
+ 'tasks.tool.done.generateFile': 'Generó un archivo',
194
+ 'tasks.tool.done.shellExec': 'Ejecutó un comando',
195
+ 'tasks.tool.done.loadTools': 'Cargó herramientas',
196
+ 'tasks.tool.done.userMemory': 'Recordó',
197
+ 'tasks.tool.done.webScraper': 'Leyó la página',
198
+ 'tasks.tool.pill.agentSearch': 'Buscando Gemies',
199
+ 'tasks.tool.pill.browse': 'Navegando',
200
+ 'tasks.tool.pill.codeInterpreter': 'Ejecutando código',
201
+ 'tasks.tool.pill.consultAgent': 'Consultando a un Gemie',
202
+ 'tasks.tool.pill.fileEdit': 'Editando archivo',
203
+ 'tasks.tool.pill.generateFile': 'Generando archivo',
204
+ 'tasks.tool.pill.sendDiscord': 'Discord',
205
+ 'tasks.tool.pill.sendEmail': 'Correo',
206
+ 'tasks.tool.pill.sendSignal': 'Signal',
207
+ 'tasks.tool.pill.sendSlack': 'Slack',
208
+ 'tasks.tool.pill.sendTelegramMessage': 'Telegram',
209
+ 'tasks.tool.pill.shellExec': 'Ejecutando comando',
210
+ 'tasks.tool.pill.loadTools': 'Cargando herramientas',
211
+ 'tasks.tool.pill.userMemory': 'Recordando',
212
+ 'tasks.tool.pill.webScraper': 'Leyendo la página',
213
+ 'tasks.tool.pill.webSearch': 'Búsqueda web',
214
+ 'thought.activity': 'Actividad',
215
+ 'thought.audit.agent': 'Gemie: {{name}}',
216
+ 'thought.audit.fileGenerated': 'Archivo generado',
217
+ 'thought.audit.plan': 'Plan',
218
+ 'thought.audit.planSteps': { one: '1 paso', other: '{{count}} pasos' },
219
+ 'thought.audit.researchComplete': 'Investigación completada',
220
+ 'thought.audit.researchIncomplete': 'Investigación incompleta',
221
+ 'thought.audit.researchPhase.decomposing': 'Investigación: desglosando la pregunta',
222
+ 'thought.audit.researchPhase.finalizing': 'Investigación: terminando',
223
+ 'thought.audit.researchPhase.follow_up': 'Investigación: profundizando',
224
+ 'thought.audit.researchPhase.reading': 'Investigación: leyendo artículos',
225
+ 'thought.audit.researchPhase.searching': 'Investigación: buscando fuentes',
226
+ 'thought.audit.researchPhase.synthesizing': 'Investigación: sintetizando hallazgos',
227
+ 'thought.audit.researching': 'Investigando',
228
+ 'thought.cancelled': 'Detenido',
229
+ 'thought.done': 'Listo',
230
+ 'thought.failed': 'Falló',
231
+ 'thought.failedAfter': 'Falló tras {{elapsed}}',
232
+ 'thought.filesAndSources': 'Archivos y fuentes',
233
+ 'thought.input': 'Entrada',
234
+ 'thought.loadFailed': 'No se pudo cargar esta conversación',
235
+ 'thought.messageGone': 'Este mensaje ya no está en la conversación',
236
+ 'thought.noActivity': 'Aún no hay acciones registradas',
237
+ 'thought.noOutputs': 'No se generaron archivos',
238
+ 'thought.noSources': 'No se usaron fuentes',
239
+ 'thought.noSteps': 'No hay pasos para mostrar',
240
+ 'thought.openOutput': 'Abrir {{name}} en el lienzo',
241
+ 'thought.output': 'Salida',
242
+ 'thought.outputs': 'Resultados',
243
+ 'thought.reasoning': 'Razonamiento',
244
+ 'thought.references': 'Referencias',
245
+ 'thought.sourceLabel': 'Fuente {{n}}: {{title}}',
246
+ 'thought.sources': 'Fuentes',
247
+ 'thought.steps': 'Pasos',
248
+ 'thought.stoppedAfter': 'Detenido tras {{elapsed}}',
249
+ 'thought.thinking': 'Pensando',
250
+ 'thought.thinkingFor': 'Pensando por {{seconds}}s...',
251
+ 'thought.thoughtFor': 'Pensó por {{seconds}} segundos',
252
+ 'thought.title': 'Pensamiento',
253
+ 'thought.tool.browse': 'Navegando por la web',
254
+ 'thought.tool.generateFile': 'Generando archivo',
255
+ 'thought.tool.getCurrentDate': 'Consultando la fecha actual',
256
+ 'thought.tool.getTimeline': 'Obteniendo la cronología',
257
+ 'thought.tool.getWhatsAppChats': 'Cargando chats de WhatsApp',
258
+ 'thought.tool.getWhatsAppMessages': 'Leyendo mensajes de WhatsApp',
259
+ 'thought.tool.saveUserMemory': 'Guardando en la memoria',
260
+ 'thought.tool.scrapeURL': 'Leyendo URL',
261
+ 'thought.tool.searchKnowledgeBase': 'Buscando en la base de conocimiento',
262
+ 'thought.tool.sendTelegramMessage': 'Enviando mensaje de Telegram',
263
+ 'thought.tool.sendWhatsAppMessage': 'Enviando mensaje de WhatsApp',
264
+ 'thought.tool.updateUserContext': 'Actualizando contexto',
265
+ 'thought.tool.updateUserPreferences': 'Actualizando preferencias',
266
+ 'thought.tool.webScraper': 'Leyendo página web',
267
+ 'thought.tool.webSearch': 'Buscando en la web',
268
+ 'thought.viewDetails': 'Ver detalles',
269
+ 'thought.websites': 'Sitios web',
270
+ 'thought.worked': 'Trabajó',
271
+ 'thought.workedFor': 'Trabajó durante {{elapsed}}',
272
+ 'thought.working': 'Trabajando…',
273
+ 'thought.workingFor': 'Trabajando desde hace {{elapsed}}…',
274
+ 'thought.writing': 'Escribiendo',
275
+ 'usageLimit.inputDisabledPlaceholder': 'Límite de uso alcanzado',
276
+ 'weather.condition.clear': 'Despejado',
277
+ 'weather.condition.cloudy': 'Nublado',
278
+ 'weather.condition.drizzle': 'Llovizna',
279
+ 'weather.condition.fog': 'Niebla',
280
+ 'weather.condition.partly-cloudy': 'Parcialmente nublado',
281
+ 'weather.condition.rain': 'Lluvia',
282
+ 'weather.condition.showers': 'Chubascos',
283
+ 'weather.condition.snow': 'Nieve',
284
+ 'weather.condition.snow-showers': 'Chubascos de nieve',
285
+ 'weather.condition.thunderstorm': 'Tormenta',
286
+ 'weather.toggleUnit': 'Cambiar unidad de temperatura',
287
+ };
@@ -0,0 +1,38 @@
1
+ import { COPY_EN, type CopyEntry } from './copy-en';
2
+ import { COPY_ES } from './copy-es';
3
+
4
+ /**
5
+ * A translator keyed the way the Alia app's own catalogue keys its strings, so the app hands its
6
+ * `t` straight in (`labels.t`). The words the chat draws that are not one fixed `labels` field —
7
+ * the thread, its cards, the thought panel, the work log — are asked for by key.
8
+ */
9
+ export type Translate = (key: string, params?: Record<string, unknown>) => string;
10
+
11
+ function entryFor(entry: CopyEntry, count: number | undefined): string {
12
+ if (typeof entry === 'string') return entry;
13
+ if (count === 0 && entry.zero !== undefined) return entry.zero;
14
+ if (count === 1 && entry.one !== undefined) return entry.one;
15
+ return entry.other;
16
+ }
17
+
18
+ /** `{{name}}` and `%{name}` both name a parameter, as in the app's catalogue. */
19
+ const PLACEHOLDER = /\{\{\s*(\w+)\s*\}\}|%\{(\w+)\}/g;
20
+
21
+ /**
22
+ * The default translator: the English in `copy-en.ts`, with `{{count}}` plurals and parameters.
23
+ * A key it does not know answers itself, so a missing string is visible rather than blank.
24
+ */
25
+ function createCopy(catalogue: Readonly<Record<string, CopyEntry>>): Translate {
26
+ return (key, params) => {
27
+ const entry = catalogue[key];
28
+ if (entry === undefined) return key;
29
+ const count = typeof params?.count === 'number' ? params.count : undefined;
30
+ return entryFor(entry, count).replace(PLACEHOLDER, (placeholder, a?: string, b?: string) => {
31
+ const value = params?.[(a ?? b) as string];
32
+ return value === undefined ? placeholder : String(value);
33
+ });
34
+ };
35
+ }
36
+
37
+ export const englishCopy = createCopy(COPY_EN);
38
+ export const spanishCopy = createCopy(COPY_ES);
@@ -0,0 +1,2 @@
1
+ /** The document picker, loaded when the person picks a file: native evaluates nothing of it before. */
2
+ export const loadDocumentPicker = () => import('../document-picker');
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The document picker on web, imported with the composer.
3
+ *
4
+ * On web this is a static import: a lazy `import()` would be an async chunk boundary inside the SDK,
5
+ * and Metro hoists every module two async chunks share into `__common.js`, loaded at first paint —
6
+ * an app that lazy-loads its Alia sheet would get the chat in its first paint. Native keeps the
7
+ * lazy load (`./document-picker.ts`); `scripts/check-entry-isolation.mjs` holds that web has no boundary.
8
+ */
9
+
10
+ import * as DocumentPicker from '../document-picker';
11
+
12
+ export const loadDocumentPicker = async () => DocumentPicker;
@@ -0,0 +1,2 @@
1
+ /** `expo-audio`, loaded on first use: native evaluates nothing of it until the chat plays a sound. */
2
+ export const loadExpoAudio = () => import('expo-audio');
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `expo-audio` on web, imported with the chat.
3
+ *
4
+ * On web this is a static import: a lazy `import()` would be an async chunk boundary inside the SDK,
5
+ * and Metro hoists every module two async chunks share into `__common.js`, loaded at first paint —
6
+ * an app that lazy-loads its Alia sheet would get the chat in its first paint. Native keeps the
7
+ * lazy load (`./expo-audio.ts`); `scripts/check-entry-isolation.mjs` holds that web has no boundary.
8
+ */
9
+
10
+ import * as ExpoAudio from 'expo-audio';
11
+
12
+ export const loadExpoAudio = async () => ExpoAudio;
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The attachment reader, loaded on the first attachment: on native a turn of plain text (and the
3
+ * runtime entry that sends it) never evaluates `expo-file-system`.
4
+ */
5
+ export const loadImageDataUrl = () => import('../image-data-url');
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The attachment reader on web, imported with the runtime.
3
+ *
4
+ * On web this is a static import: a lazy `import()` would be an async chunk boundary inside the SDK,
5
+ * and Metro hoists every module two async chunks share into `__common.js`, loaded at first paint —
6
+ * an app that lazy-loads its Alia sheet would get the chat in its first paint. Native keeps the
7
+ * lazy load (`./image-data-url.ts`); `scripts/check-entry-isolation.mjs` holds that web has no boundary.
8
+ */
9
+
10
+ import * as ImageDataUrl from '../image-data-url';
11
+
12
+ export const loadImageDataUrl = async () => ImageDataUrl;
@@ -0,0 +1,142 @@
1
+ /**
2
+ * The client half of Alia's streaming dictation protocol,
3
+ * `GET /v1/audio/transcriptions/stream` (ADR 0024).
4
+ *
5
+ * The server's copy is `packages/api/src/lib/dictation/protocol.ts`; the SDK
6
+ * does not depend on the API package, so the shapes are restated here and
7
+ * `DICTATION_PROTOCOL_VERSION` is what turns a mismatch into a refusal instead
8
+ * of a misunderstanding. The API's tests hold the two copies equal.
9
+ *
10
+ * - Binary, client → Alia: microphone PCM16 LE, 24 kHz, mono.
11
+ * - Text: one JSON event per frame, both ways.
12
+ *
13
+ * Segments are Alia's numbers, from 0, in the order the person spoke them. A
14
+ * segment's `transcript.final` is the only text a client keeps:
15
+ * `transcript.interim` (the segment's provisional text, whole, replacing the
16
+ * last) and `transcript.delta` (locked text appended) are display state the
17
+ * final supersedes.
18
+ */
19
+
20
+ export const DICTATION_PROTOCOL_VERSION = 1;
21
+
22
+ export const DICTATION_STREAM_PATH = '/v1/audio/transcriptions/stream';
23
+
24
+ /** PCM16 mono at this rate: the one encoding the stream takes. */
25
+ export const DICTATION_SAMPLE_RATE = 24_000;
26
+
27
+ /** What a dictation ends with that is not a failure. */
28
+ export type DictationCloseReason =
29
+ | 'ended'
30
+ | 'max-duration'
31
+ | 'idle-timeout'
32
+ | 'error'
33
+ | 'server-shutdown';
34
+
35
+ /** Why a dictation failed, as Alia names it. */
36
+ export type DictationStreamErrorCode =
37
+ | 'TRANSCRIPTION_UNAVAILABLE'
38
+ | 'TRANSCRIPTION_LIMITED'
39
+ | 'TRANSCRIPTION_REJECTED'
40
+ | 'TRANSCRIPTION_FAILED'
41
+ | 'CLIP_TOO_LONG'
42
+ | 'INVALID_REQUEST'
43
+ | 'NOT_AUTHENTICATED'
44
+ | 'CREDENTIAL_NOT_SUPPORTED';
45
+
46
+ export type DictationServerEvent =
47
+ | { readonly type: 'dictation.ready'; readonly maxDurationMs: number }
48
+ | { readonly type: 'transcript.interim'; readonly segment: number; readonly text: string }
49
+ | { readonly type: 'transcript.delta'; readonly segment: number; readonly text: string }
50
+ | { readonly type: 'transcript.final'; readonly segment: number; readonly text: string }
51
+ | {
52
+ readonly type: 'error';
53
+ readonly code: DictationStreamErrorCode;
54
+ readonly message: string;
55
+ readonly retryable: boolean;
56
+ }
57
+ | { readonly type: 'dictation.closed'; readonly reason: DictationCloseReason };
58
+
59
+ export type DictationClientEvent =
60
+ | { readonly type: 'auth'; readonly token: string }
61
+ | {
62
+ readonly type: 'dictation.start';
63
+ readonly protocol: number;
64
+ readonly language?: string;
65
+ readonly sampleRate: number;
66
+ }
67
+ | { readonly type: 'dictation.commit' }
68
+ | { readonly type: 'dictation.end' };
69
+
70
+ const CLOSE_REASONS: ReadonlySet<string> = new Set<DictationCloseReason>([
71
+ 'ended',
72
+ 'max-duration',
73
+ 'idle-timeout',
74
+ 'error',
75
+ 'server-shutdown',
76
+ ]);
77
+
78
+ const ERROR_CODES: ReadonlySet<string> = new Set<DictationStreamErrorCode>([
79
+ 'TRANSCRIPTION_UNAVAILABLE',
80
+ 'TRANSCRIPTION_LIMITED',
81
+ 'TRANSCRIPTION_REJECTED',
82
+ 'TRANSCRIPTION_FAILED',
83
+ 'CLIP_TOO_LONG',
84
+ 'INVALID_REQUEST',
85
+ 'NOT_AUTHENTICATED',
86
+ 'CREDENTIAL_NOT_SUPPORTED',
87
+ ]);
88
+
89
+ const isSegment = (value: unknown): value is number =>
90
+ typeof value === 'number' && Number.isInteger(value) && value >= 0;
91
+
92
+ /** One server text frame, or `null` when it is not one of protocol 1's events. */
93
+ export function parseDictationServerEvent(text: string): DictationServerEvent | null {
94
+ let value: unknown;
95
+ try {
96
+ value = JSON.parse(text);
97
+ } catch {
98
+ return null;
99
+ }
100
+ if (value === null || typeof value !== 'object') return null;
101
+ const event = value as Record<string, unknown>;
102
+ switch (event.type) {
103
+ case 'dictation.ready':
104
+ return typeof event.maxDurationMs === 'number' && event.maxDurationMs > 0
105
+ ? { type: 'dictation.ready', maxDurationMs: event.maxDurationMs }
106
+ : null;
107
+ case 'transcript.interim':
108
+ case 'transcript.delta':
109
+ case 'transcript.final':
110
+ return isSegment(event.segment) && typeof event.text === 'string'
111
+ ? { type: event.type, segment: event.segment, text: event.text }
112
+ : null;
113
+ case 'error':
114
+ return typeof event.code === 'string' &&
115
+ ERROR_CODES.has(event.code) &&
116
+ typeof event.message === 'string'
117
+ ? {
118
+ type: 'error',
119
+ code: event.code as DictationStreamErrorCode,
120
+ message: event.message,
121
+ retryable: event.retryable === true,
122
+ }
123
+ : null;
124
+ case 'dictation.closed':
125
+ return typeof event.reason === 'string' && CLOSE_REASONS.has(event.reason)
126
+ ? { type: 'dictation.closed', reason: event.reason as DictationCloseReason }
127
+ : null;
128
+ default:
129
+ return null;
130
+ }
131
+ }
132
+
133
+ /** `wss://…/v1/audio/transcriptions/stream` for an Gemies API origin. */
134
+ export function dictationStreamUrl(apiUrl: string): string {
135
+ const base = apiUrl.replace(/\/+$/, '');
136
+ const ws = base.startsWith('https://')
137
+ ? `wss://${base.slice('https://'.length)}`
138
+ : base.startsWith('http://')
139
+ ? `ws://${base.slice('http://'.length)}`
140
+ : base;
141
+ return `${ws}${DICTATION_STREAM_PATH}`;
142
+ }
@@ -0,0 +1,37 @@
1
+ import type { DictationClip } from './dictation';
2
+
3
+ /** Why the microphone could not record. */
4
+ export type DictationRecorderErrorCode = 'mic-denied' | 'mic-unavailable';
5
+
6
+ export class DictationRecorderError extends Error {
7
+ readonly code: DictationRecorderErrorCode;
8
+
9
+ constructor(code: DictationRecorderErrorCode, message?: string) {
10
+ super(message ?? code);
11
+ this.name = 'DictationRecorderError';
12
+ this.code = code;
13
+ }
14
+ }
15
+
16
+ /**
17
+ * A clip recorder for the composer's microphone:
18
+ *
19
+ * - web (`dictation-recorder.ts`): `MediaRecorder`, `audio/webm;codecs=opus`
20
+ * or `audio/mp4` (Safari), level from an `AnalyserNode` on the same stream;
21
+ * - iOS / Android (`dictation-recorder.native.ts`): the `expo-audio`
22
+ * recorder, `RecordingPresets.HIGH_QUALITY` (m4a/AAC → `audio/mp4`) with
23
+ * metering on.
24
+ *
25
+ * Levels are the real recorder's, 0..1 on the dictation meter's dBFS scale.
26
+ */
27
+ export interface DictationRecorder {
28
+ /**
29
+ * Ask for the microphone and start recording; resolves once the recorder
30
+ * says it started. Rejects with a {@link DictationRecorderError}.
31
+ */
32
+ start(onLevel: (level: number) => void): Promise<void>;
33
+ /** Stop and hand over the clip, or `null` when nothing was recorded. */
34
+ stop(): Promise<DictationClip | null>;
35
+ /** Stop and throw the clip away. */
36
+ cancel(): void;
37
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Dictation's iOS / Android recorder: the `expo-audio` recorder (already a
3
+ * peer of this SDK), `RecordingPresets.HIGH_QUALITY` in mono with metering on.
4
+ * The clip is m4a/AAC, sent as `audio/mp4`. No new native module: the call's
5
+ * engine (`react-native-audio-api`) is not needed to record a clip.
6
+ */
7
+
8
+ import { useMemo } from 'react';
9
+ import {
10
+ RecordingPresets,
11
+ requestRecordingPermissionsAsync,
12
+ setAudioModeAsync,
13
+ useAudioRecorder,
14
+ } from 'expo-audio';
15
+ import { levelFromDbfs } from './audio-level';
16
+ import type { DictationClip } from './dictation';
17
+ import { DictationRecorderError, type DictationRecorder } from './dictation-recorder-types';
18
+
19
+ export * from './dictation-recorder-types';
20
+
21
+ const LEVEL_POLL_MS = 100;
22
+
23
+ const OPTIONS = { ...RecordingPresets.HIGH_QUALITY, numberOfChannels: 1, isMeteringEnabled: true };
24
+
25
+ export function useDictationRecorder(): DictationRecorder {
26
+ const recorder = useAudioRecorder(OPTIONS);
27
+
28
+ return useMemo(() => {
29
+ let levelTimer: ReturnType<typeof setInterval> | null = null;
30
+ let lastDurationMs = 0;
31
+ let recording = false;
32
+
33
+ const stopLevels = (): void => {
34
+ if (levelTimer !== null) clearInterval(levelTimer);
35
+ levelTimer = null;
36
+ };
37
+ const releaseSession = (): void => {
38
+ void setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
39
+ };
40
+
41
+ return {
42
+ async start(onLevel) {
43
+ const permission = await requestRecordingPermissionsAsync().catch(() => null);
44
+ if (!permission?.granted) throw new DictationRecorderError('mic-denied');
45
+ try {
46
+ await setAudioModeAsync({ allowsRecording: true, playsInSilentMode: true });
47
+ await recorder.prepareToRecordAsync();
48
+ recorder.record();
49
+ } catch {
50
+ releaseSession();
51
+ throw new DictationRecorderError('mic-unavailable');
52
+ }
53
+ recording = true;
54
+ lastDurationMs = 0;
55
+ levelTimer = setInterval(() => {
56
+ const status = recorder.getStatus();
57
+ lastDurationMs = status.durationMillis;
58
+ onLevel(typeof status.metering === 'number' ? levelFromDbfs(status.metering) : 0);
59
+ }, LEVEL_POLL_MS);
60
+ },
61
+
62
+ async stop(): Promise<DictationClip | null> {
63
+ if (!recording) return null;
64
+ recording = false;
65
+ stopLevels();
66
+ const durationMs = recorder.getStatus().durationMillis || lastDurationMs;
67
+ try {
68
+ await recorder.stop();
69
+ } finally {
70
+ releaseSession();
71
+ }
72
+ const uri = recorder.uri;
73
+ if (!uri) return null;
74
+ return {
75
+ file: { uri, name: 'dictation.m4a', type: 'audio/mp4' },
76
+ mediaType: 'audio/mp4',
77
+ durationMs,
78
+ };
79
+ },
80
+
81
+ cancel(): void {
82
+ if (!recording) return;
83
+ recording = false;
84
+ stopLevels();
85
+ void recorder.stop().catch(() => undefined);
86
+ releaseSession();
87
+ },
88
+ };
89
+ }, [recorder]);
90
+ }