@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,49 @@
1
+ import { create } from 'zustand';
2
+
3
+ /** A call somebody asked for, waiting for the screen that shows its conversation. */
4
+ export interface VoiceCallRequest {
5
+ readonly conversationId: string;
6
+ readonly accountId: string | null;
7
+ readonly at: number;
8
+ }
9
+
10
+ /** How long a request waits for its screen. A navigation that never arrives must not open a call later. */
11
+ export const CALL_REQUEST_TTL_MS = 15_000;
12
+
13
+ interface VoiceCallRequestStore {
14
+ request: VoiceCallRequest | null;
15
+ ask: (conversationId: string, accountId: string | null) => void;
16
+ clear: () => void;
17
+ }
18
+
19
+ /**
20
+ * Where a call is asked for, apart from where it opens.
21
+ *
22
+ * Starting a call and showing it are the same thing when the conversation is already on screen,
23
+ * and two screens apart when it is not: a new-chat route makes the conversation and the host
24
+ * navigates to it. Both go the same way. The launcher AND the screen of the conversation meet
25
+ * here — it asks, and whichever launcher is mounted for that conversation (that account, in time)
26
+ * takes the request and opens the call. The sheet, the screen and the app share this one path.
27
+ */
28
+ export const useVoiceCallRequests = create<VoiceCallRequestStore>((set) => ({
29
+ request: null,
30
+ ask: (conversationId, accountId) =>
31
+ set({ request: { conversationId, accountId, at: Date.now() } }),
32
+ clear: () => set({ request: null }),
33
+ }));
34
+
35
+ /** Whether `request` is for this conversation and account, and still worth opening. */
36
+ export function isRequestFor(
37
+ request: VoiceCallRequest | null,
38
+ conversationId: string | undefined,
39
+ accountId: string | null,
40
+ now = Date.now(),
41
+ ): boolean {
42
+ return (
43
+ request !== null &&
44
+ conversationId !== undefined &&
45
+ request.conversationId === conversationId &&
46
+ request.accountId === accountId &&
47
+ now - request.at <= CALL_REQUEST_TTL_MS
48
+ );
49
+ }
@@ -0,0 +1,627 @@
1
+ /**
2
+ * One voice call over Alia's `/v1/voice/session` socket (ADR 0017 §3–§4),
3
+ * without React: the hook (`useVoiceRoom`) owns one and renders its snapshots.
4
+ *
5
+ * Alia holds the realtime session with Kaana; turn detection and barge-in are
6
+ * the model's, on the server. The device only:
7
+ *
8
+ * - captures the microphone and sends it as PCM16 frames (nothing while muted);
9
+ * - plays the answer's PCM16 frames from a jitter-buffered queue;
10
+ * - when the server says the person started speaking, drops what it has not
11
+ * played and tells Alia how much of the answer was HEARD
12
+ * (`playback.interrupted`), so the model remembers what was said, not what it
13
+ * generated;
14
+ * - shows a state it can prove (`VoiceCallState`). "Listening" needs the
15
+ * session ready upstream, a first captured buffer and Alia's acknowledgement
16
+ * of the first appended audio; "speaking" needs the first answer frame
17
+ * actually playing.
18
+ *
19
+ * A socket that drops without `session.closed` is resumed within the session's
20
+ * resume window (`session.resume { afterSeq }`), and the call reads
21
+ * `reconnecting` meanwhile — never `listening`.
22
+ */
23
+
24
+ import type { VoiceCallState, VoiceMessage } from '../types';
25
+ import type { VoiceErrorCode } from './speech-messages';
26
+ import type { VoiceLevelChannel } from './voice-levels';
27
+ import {
28
+ VoiceAudioEngineError,
29
+ type VoiceAudioEngine,
30
+ type VoiceAudioEngineHandlers,
31
+ } from './voice-audio-engine-types';
32
+ import {
33
+ decodeAssistantAudioFrame,
34
+ parseVoiceServerEvent,
35
+ VOICE_PROTOCOL_VERSION,
36
+ voiceSessionUrl,
37
+ type ProductVoice,
38
+ type ReceivedVoiceEvent,
39
+ type VoiceClientEvent,
40
+ type VoiceCloseReason,
41
+ } from './voice-protocol';
42
+
43
+ /** The part of a WebSocket a call uses: the browser's and React Native's both fit. */
44
+ export interface VoiceSocket {
45
+ binaryType: string;
46
+ readonly readyState: number;
47
+ onopen: ((event: unknown) => void) | null;
48
+ onmessage: ((event: { data: unknown }) => void) | null;
49
+ onclose: ((event: unknown) => void) | null;
50
+ onerror: ((event: unknown) => void) | null;
51
+ send(data: string | ArrayBufferLike | ArrayBufferView): void;
52
+ close(code?: number, reason?: string): void;
53
+ }
54
+
55
+ export type VoiceSocketFactory = (url: string) => VoiceSocket;
56
+
57
+ const OPEN = 1;
58
+
59
+ /** How often the Oxy token is re-read, and re-sent when it changed. */
60
+ const TOKEN_REFRESH_MS = 4 * 60_000;
61
+ /** Between two attempts to resume a dropped socket. */
62
+ const RESUME_RETRY_MS = 1_000;
63
+ /** Until the server says otherwise in `session.ready`. */
64
+ const DEFAULT_RESUME_WINDOW_MS = 30_000;
65
+
66
+ export interface VoiceCallSnapshot {
67
+ readonly state: VoiceCallState;
68
+ readonly messages: readonly VoiceMessage[];
69
+ readonly isMuted: boolean;
70
+ /** Milliseconds left when the server warned that the call is about to end. */
71
+ readonly endingSoonMs: number | null;
72
+ /** The model serving the call, once the session is ready. */
73
+ readonly model: { id: string; displayName: string; publisher: string } | null;
74
+ }
75
+
76
+ export interface VoiceCallOptions {
77
+ readonly apiUrl: string;
78
+ /** The person's Oxy session token, read at connect and every few minutes. */
79
+ readonly getToken: (
80
+ target: string,
81
+ options?: { signal?: AbortSignal },
82
+ ) => string | null | Promise<string | null>;
83
+ /**
84
+ * The host's Oxy app assertion, sent with the first `auth` of each socket so
85
+ * an agent Oxy confines to an app opens only there (ADR 0021). Absent: none.
86
+ */
87
+ readonly getAppAssertion?: () => Promise<string | null>;
88
+ readonly conversationId: string;
89
+ readonly agentId?: string;
90
+ readonly voice: ProductVoice;
91
+ /** BCP-47. */
92
+ readonly locale: string;
93
+ readonly createEngine: () => VoiceAudioEngine;
94
+ readonly openSocket: VoiceSocketFactory;
95
+ readonly levels: VoiceLevelChannel;
96
+ readonly onChange: (snapshot: VoiceCallSnapshot) => void;
97
+ /** Alia stored messages of the call in the conversation. */
98
+ readonly onMessagesSaved?: (conversationId: string, messageIds: readonly string[]) => void;
99
+ readonly tokenRefreshMs?: number;
100
+ readonly resumeRetryMs?: number;
101
+ }
102
+
103
+ const LIVE: ReadonlySet<VoiceCallState['kind']> = new Set([
104
+ 'listening',
105
+ 'user-speaking',
106
+ 'thinking',
107
+ 'using-tool',
108
+ 'speaking',
109
+ ]);
110
+
111
+ function asBytes(data: unknown): Uint8Array | null {
112
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
113
+ if (ArrayBuffer.isView(data))
114
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
115
+ return null;
116
+ }
117
+
118
+ export class VoiceCall {
119
+ private readonly options: VoiceCallOptions;
120
+ private state: VoiceCallState = { kind: 'idle' };
121
+ private messages: VoiceMessage[] = [];
122
+ /**
123
+ * Each message's text by the item it was spoken in, in the order the items
124
+ * began: an assistant turn that called a tool is one message of two items.
125
+ */
126
+ private readonly itemTexts = new Map<string, Map<string, string>>();
127
+ /** The message each item belongs to. */
128
+ private readonly messageOfItem = new Map<string, string>();
129
+ private muted = false;
130
+ private endingSoonMs: number | null = null;
131
+ private model: VoiceCallSnapshot['model'] = null;
132
+
133
+ private engine: VoiceAudioEngine | null = null;
134
+ private socket: VoiceSocket | null = null;
135
+ private authenticated = false;
136
+ private lastToken: string | null = null;
137
+ private voiceSessionId: string | null = null;
138
+ private lastSeq = -1;
139
+ private resumeWindowMs = DEFAULT_RESUME_WINDOW_MS;
140
+ private droppedAt: number | null = null;
141
+ private resumeTimer: ReturnType<typeof setTimeout> | null = null;
142
+ private tokenTimer: ReturnType<typeof setInterval> | null = null;
143
+ private finished = false;
144
+ private readonly credentialAbort = new AbortController();
145
+ private refreshingToken = false;
146
+
147
+ /** The three facts "listening" needs. */
148
+ private ready = false;
149
+ private captured = false;
150
+ private inputReady = false;
151
+
152
+ /** Assistant items the person talked over: late frames of them are dropped. */
153
+ private readonly interrupted = new Set<string>();
154
+ private lastReceivedItem: string | null = null;
155
+ private playingItem: string | null = null;
156
+ private readonly activeTools = new Map<string, string>();
157
+ /** A tool ran since the last response ended: another response follows it. */
158
+ private toolRan = false;
159
+ /** The error Alia sent before closing, which the close then ends the call with. */
160
+ private serverError: VoiceErrorCode | null = null;
161
+
162
+ constructor(options: VoiceCallOptions) {
163
+ this.options = options;
164
+ }
165
+
166
+ snapshot(): VoiceCallSnapshot {
167
+ return {
168
+ state: this.state,
169
+ messages: this.messages,
170
+ isMuted: this.muted,
171
+ endingSoonMs: this.endingSoonMs,
172
+ model: this.model,
173
+ };
174
+ }
175
+
176
+ /** Ask for the microphone, then open the socket and the session. */
177
+ async start(): Promise<void> {
178
+ if (this.state.kind !== 'idle') return;
179
+ this.setState({ kind: 'connecting' });
180
+ if (!(await this.readToken()) || this.finished) return;
181
+ const engine = this.options.createEngine();
182
+ this.engine = engine;
183
+ try {
184
+ await engine.start(this.engineHandlers());
185
+ } catch (caught: unknown) {
186
+ if (this.finished) return;
187
+ this.fail(caught instanceof VoiceAudioEngineError ? caught.code : 'voice-unavailable');
188
+ return;
189
+ }
190
+ if (this.finished) return;
191
+ await this.openSocket(false);
192
+ if (this.finished) return;
193
+ this.tokenTimer = setInterval(
194
+ () => void this.refreshToken(),
195
+ this.options.tokenRefreshMs ?? TOKEN_REFRESH_MS,
196
+ );
197
+ }
198
+
199
+ /** The person hung up, or the screen holding the call went away. */
200
+ hangUp(): void {
201
+ if (this.finished) return;
202
+ this.send({ type: 'session.end' });
203
+ this.finish({ kind: 'ended', reason: 'hangup' });
204
+ }
205
+
206
+ setMuted(muted: boolean): void {
207
+ if (this.muted === muted) return;
208
+ this.muted = muted;
209
+ if (muted) this.options.levels.setCapture(0);
210
+ this.emit();
211
+ }
212
+
213
+ /* ------------------------------------------------------------------------ */
214
+
215
+ private engineHandlers(): VoiceAudioEngineHandlers {
216
+ return {
217
+ onCaptureFrame: (pcm) => {
218
+ if (this.finished) return;
219
+ if (!this.captured) {
220
+ this.captured = true;
221
+ this.maybeListening();
222
+ }
223
+ if (this.muted || !this.ready || !this.authenticated) return;
224
+ if (this.socket?.readyState !== OPEN) return;
225
+ this.socket.send(pcm);
226
+ },
227
+ onCaptureLevel: (level) => this.options.levels.setCapture(this.muted ? 0 : level),
228
+ onPlaybackStarted: (itemId) => {
229
+ if (this.finished || this.interrupted.has(itemId)) return;
230
+ this.playingItem = itemId;
231
+ if (LIVE.has(this.state.kind)) this.setState({ kind: 'speaking' });
232
+ },
233
+ onPlaybackLevel: (level) => this.options.levels.setPlayback(level),
234
+ onPlaybackIdle: () => {
235
+ this.playingItem = null;
236
+ if (this.state.kind === 'speaking') this.afterSpeech();
237
+ },
238
+ onError: (error) => this.fail(error.code),
239
+ };
240
+ }
241
+
242
+ private async openSocket(resuming: boolean): Promise<void> {
243
+ if (!(await this.readToken()) || this.finished) return;
244
+ this.authenticated = false;
245
+ let socket: VoiceSocket;
246
+ try {
247
+ socket = this.options.openSocket(voiceSessionUrl(this.options.apiUrl));
248
+ } catch {
249
+ if (resuming) this.scheduleResume();
250
+ else this.fail('connection-lost');
251
+ return;
252
+ }
253
+ socket.binaryType = 'arraybuffer';
254
+ this.socket = socket;
255
+ socket.onopen = () => {
256
+ void this.authenticateSocket(socket);
257
+ };
258
+ socket.onmessage = (event) => {
259
+ if (this.socket !== socket || this.finished) return;
260
+ if (typeof event.data === 'string') {
261
+ const parsed = parseVoiceServerEvent(event.data);
262
+ if (parsed !== null) this.handle(parsed, resuming);
263
+ return;
264
+ }
265
+ const bytes = asBytes(event.data);
266
+ if (bytes !== null) this.handleAudio(bytes);
267
+ };
268
+ socket.onerror = () => undefined;
269
+ socket.onclose = () => {
270
+ if (this.socket !== socket || this.finished) return;
271
+ this.socket = null;
272
+ this.authenticated = false;
273
+ if (this.serverError !== null) {
274
+ this.fail(this.serverError);
275
+ return;
276
+ }
277
+ if (this.voiceSessionId === null) {
278
+ this.fail('connection-lost');
279
+ return;
280
+ }
281
+ this.droppedAt ??= Date.now();
282
+ this.setState({ kind: 'reconnecting' });
283
+ this.scheduleResume();
284
+ };
285
+ }
286
+
287
+ private scheduleResume(): void {
288
+ if (this.finished) return;
289
+ const droppedAt = this.droppedAt ?? Date.now();
290
+ this.droppedAt = droppedAt;
291
+ if (Date.now() - droppedAt >= this.resumeWindowMs) {
292
+ this.fail('connection-lost');
293
+ return;
294
+ }
295
+ if (this.resumeTimer !== null) clearTimeout(this.resumeTimer);
296
+ this.resumeTimer = setTimeout(() => {
297
+ this.resumeTimer = null;
298
+ if (!this.finished) void this.openSocket(true);
299
+ }, this.options.resumeRetryMs ?? RESUME_RETRY_MS);
300
+ }
301
+
302
+ /** The shared session owns refresh and validates the actual socket destination. */
303
+ private async readToken(): Promise<string | null> {
304
+ try {
305
+ const token = await this.options.getToken(voiceSessionUrl(this.options.apiUrl), {
306
+ signal: this.credentialAbort.signal,
307
+ });
308
+ if (this.finished) return null;
309
+ if (!token) this.fail('not-authenticated');
310
+ return token || null;
311
+ } catch {
312
+ if (!this.finished) this.fail('not-authenticated');
313
+ return null;
314
+ }
315
+ }
316
+
317
+ private async authenticateSocket(socket: VoiceSocket): Promise<void> {
318
+ const assertion = await this.options.getAppAssertion?.().catch(() => null);
319
+ const token = await this.readToken();
320
+ if (!token || this.finished || this.socket !== socket || socket.readyState !== OPEN) return;
321
+ this.lastToken = token;
322
+ socket.send(
323
+ JSON.stringify({
324
+ type: 'auth',
325
+ token,
326
+ ...(assertion ? { appAssertion: assertion } : {}),
327
+ } satisfies VoiceClientEvent),
328
+ );
329
+ }
330
+
331
+ private async refreshToken(): Promise<void> {
332
+ if (this.refreshingToken || !this.authenticated || this.socket?.readyState !== OPEN) return;
333
+ const socket = this.socket;
334
+ this.refreshingToken = true;
335
+ try {
336
+ const token = await this.readToken();
337
+ if (
338
+ !token ||
339
+ this.finished ||
340
+ this.socket !== socket ||
341
+ !this.authenticated ||
342
+ socket.readyState !== OPEN
343
+ )
344
+ return;
345
+ if (token === this.lastToken) return;
346
+ this.lastToken = token;
347
+ this.send({ type: 'auth', token });
348
+ } finally {
349
+ this.refreshingToken = false;
350
+ }
351
+ }
352
+
353
+ private send(event: VoiceClientEvent): void {
354
+ if (this.socket?.readyState === OPEN) this.socket.send(JSON.stringify(event));
355
+ }
356
+
357
+ private handle(event: ReceivedVoiceEvent, resuming: boolean): void {
358
+ if (event.seq !== undefined) {
359
+ if (event.seq <= this.lastSeq) return;
360
+ this.lastSeq = event.seq;
361
+ }
362
+ switch (event.type) {
363
+ case 'auth.ok':
364
+ if (this.authenticated) return;
365
+ this.authenticated = true;
366
+ if (resuming && this.voiceSessionId !== null) {
367
+ this.send({
368
+ type: 'session.resume',
369
+ protocol: VOICE_PROTOCOL_VERSION,
370
+ voiceSessionId: this.voiceSessionId,
371
+ afterSeq: this.lastSeq,
372
+ });
373
+ } else {
374
+ this.send({
375
+ type: 'session.start',
376
+ protocol: VOICE_PROTOCOL_VERSION,
377
+ conversationId: this.options.conversationId,
378
+ ...(this.options.agentId === undefined ? {} : { agentId: this.options.agentId }),
379
+ voice: this.options.voice,
380
+ locale: this.options.locale,
381
+ });
382
+ }
383
+ return;
384
+ case 'session.accepted':
385
+ this.voiceSessionId = event.voiceSessionId;
386
+ return;
387
+ case 'session.ready':
388
+ this.ready = true;
389
+ this.model = event.model;
390
+ this.resumeWindowMs = event.resumeWindowMs;
391
+ if (this.state.kind === 'reconnecting') this.setState({ kind: 'listening' });
392
+ else this.maybeListening();
393
+ this.emit();
394
+ return;
395
+ case 'input.ready':
396
+ this.inputReady = true;
397
+ this.maybeListening();
398
+ return;
399
+ case 'session.resumed':
400
+ this.droppedAt = null;
401
+ if (this.state.kind === 'reconnecting') this.setState({ kind: 'listening' });
402
+ return;
403
+ case 'session.reconnecting':
404
+ this.setState({ kind: 'reconnecting' });
405
+ return;
406
+ case 'user.speech_started':
407
+ this.bargeIn();
408
+ if (LIVE.has(this.state.kind)) this.setState({ kind: 'user-speaking' });
409
+ return;
410
+ case 'user.speech_stopped':
411
+ if (this.state.kind === 'user-speaking' || this.state.kind === 'listening')
412
+ this.setState({ kind: 'thinking' });
413
+ return;
414
+ case 'transcript.delta':
415
+ this.upsertMessage(event, (previous) => previous + event.text, true);
416
+ return;
417
+ case 'transcript.done':
418
+ this.upsertMessage(event, () => event.text, false);
419
+ return;
420
+ case 'assistant.audio_done':
421
+ return;
422
+ case 'assistant.done':
423
+ this.settleStreaming(event.itemId);
424
+ if (this.toolRan) {
425
+ // A response that called tools is followed by the one that answers.
426
+ this.toolRan = false;
427
+ return;
428
+ }
429
+ if (this.state.kind === 'thinking' && this.playingItem === null) this.afterSpeech();
430
+ return;
431
+ case 'tool.started':
432
+ this.recordTool(event, 'call');
433
+ this.activeTools.set(event.callId, event.name);
434
+ this.toolRan = true;
435
+ if (LIVE.has(this.state.kind)) this.setState({ kind: 'using-tool', tool: event.name });
436
+ return;
437
+ case 'tool.finished': {
438
+ this.recordTool(event, 'result');
439
+ this.activeTools.delete(event.callId);
440
+ if (this.state.kind !== 'using-tool') return;
441
+ const still = [...this.activeTools.values()].at(-1);
442
+ this.setState(
443
+ still === undefined ? { kind: 'thinking' } : { kind: 'using-tool', tool: still },
444
+ );
445
+ return;
446
+ }
447
+ case 'messages.saved':
448
+ this.options.onMessagesSaved?.(event.conversationId, event.messageIds);
449
+ return;
450
+ case 'session.warning':
451
+ this.endingSoonMs = event.remainingMs;
452
+ this.emit();
453
+ return;
454
+ case 'error':
455
+ this.serverError = event.code;
456
+ return;
457
+ case 'session.closed':
458
+ this.closedByServer(event.reason);
459
+ return;
460
+ }
461
+ }
462
+
463
+ private handleAudio(frame: Uint8Array): void {
464
+ const decoded = decodeAssistantAudioFrame(frame);
465
+ if (decoded === null || this.interrupted.has(decoded.itemId)) return;
466
+ this.lastReceivedItem = decoded.itemId;
467
+ // Copied: the socket's buffer is not the engine's to keep.
468
+ this.engine?.enqueue(decoded.itemId, decoded.pcm.slice());
469
+ }
470
+
471
+ /** The person spoke: stop the answer now and report what of it was heard. */
472
+ private bargeIn(): void {
473
+ const received = this.lastReceivedItem;
474
+ if (received !== null) this.interrupted.add(received);
475
+ const engine = this.engine;
476
+ if (engine === null) return;
477
+ this.playingItem = null;
478
+ void engine.flush().then((heard) => {
479
+ if (heard === null || this.finished) return;
480
+ this.interrupted.add(heard.itemId);
481
+ this.send({ type: 'playback.interrupted', itemId: heard.itemId, playedMs: heard.playedMs });
482
+ });
483
+ }
484
+
485
+ /** Back to listening once the answer has been said, or nothing more is coming. */
486
+ private afterSpeech(): void {
487
+ if (this.activeTools.size > 0) {
488
+ this.setState({ kind: 'using-tool', tool: [...this.activeTools.values()].at(-1)! });
489
+ return;
490
+ }
491
+ this.setState({ kind: 'listening' });
492
+ }
493
+
494
+ private maybeListening(): void {
495
+ if (this.state.kind !== 'connecting') return;
496
+ if (this.ready && this.captured && this.inputReady) this.setState({ kind: 'listening' });
497
+ }
498
+
499
+ private closedByServer(reason: VoiceCloseReason): void {
500
+ if (reason === 'error') {
501
+ this.fail(this.serverError ?? 'realtime-failed');
502
+ return;
503
+ }
504
+ this.finish({ kind: 'ended', reason });
505
+ }
506
+
507
+ /**
508
+ * One message per `messageId`, the id the server stores and announces it
509
+ * under, so the stored copy that reaches the thread is this message, not a
510
+ * second one. Its text is its items' texts in order.
511
+ */
512
+ private upsertMessage(
513
+ event: { role: 'user' | 'assistant'; messageId: string; itemId: string },
514
+ text: (previous: string) => string,
515
+ isStreaming: boolean,
516
+ ): void {
517
+ const { messageId, itemId } = event;
518
+ const items = this.itemTexts.get(messageId) ?? new Map<string, string>();
519
+ this.itemTexts.set(messageId, items);
520
+ this.messageOfItem.set(itemId, messageId);
521
+ items.set(itemId, text(items.get(itemId) ?? ''));
522
+ const content = [...items.values()].filter((part) => part !== '').join(' ');
523
+ this.writeMessage(messageId, event.role, (message) => ({ ...message, content, isStreaming }));
524
+ }
525
+
526
+ /**
527
+ * A tool the answer ran, inside the answer's message, by name and state: the
528
+ * device never receives its arguments or result, and the stored message that
529
+ * carries them replaces this one once it is saved.
530
+ */
531
+ private recordTool(
532
+ event: { messageId: string; callId: string; name: string },
533
+ state: 'call' | 'result',
534
+ ): void {
535
+ this.writeMessage(event.messageId, 'assistant', (message) => {
536
+ const invocation = { toolCallId: event.callId, toolName: event.name, state };
537
+ const tools = message.toolInvocations ?? [];
538
+ const index = tools.findIndex((tool) => tool.toolCallId === event.callId);
539
+ return {
540
+ ...message,
541
+ toolInvocations:
542
+ index === -1
543
+ ? [...tools, invocation]
544
+ : tools.map((tool, at) => (at === index ? invocation : tool)),
545
+ };
546
+ });
547
+ }
548
+
549
+ private writeMessage(
550
+ messageId: string,
551
+ role: 'user' | 'assistant',
552
+ change: (message: VoiceMessage) => VoiceMessage,
553
+ ): void {
554
+ const index = this.messages.findIndex((message) => message.id === messageId);
555
+ const current: VoiceMessage =
556
+ index === -1
557
+ ? {
558
+ id: messageId,
559
+ role,
560
+ ...(role === 'assistant' ? { speaker: 'primary' as const } : {}),
561
+ content: '',
562
+ timestamp: Date.now(),
563
+ isStreaming: false,
564
+ }
565
+ : this.messages[index]!;
566
+ const next = change(current);
567
+ this.messages =
568
+ index === -1
569
+ ? [...this.messages, next]
570
+ : this.messages.map((message, at) => (at === index ? next : message));
571
+ this.emit();
572
+ }
573
+
574
+ private settleStreaming(itemId: string | null): void {
575
+ const messageId = itemId === null ? undefined : this.messageOfItem.get(itemId);
576
+ if (messageId === undefined) return;
577
+ if (!this.messages.some((message) => message.id === messageId && message.isStreaming)) return;
578
+ this.messages = this.messages.map((message) =>
579
+ message.id === messageId ? { ...message, isStreaming: false } : message,
580
+ );
581
+ this.emit();
582
+ }
583
+
584
+ private fail(code: VoiceErrorCode): void {
585
+ this.finish({ kind: 'error', code });
586
+ }
587
+
588
+ private finish(state: VoiceCallState): void {
589
+ if (this.finished) return;
590
+ this.finished = true;
591
+ this.credentialAbort.abort();
592
+ if (this.resumeTimer !== null) clearTimeout(this.resumeTimer);
593
+ if (this.tokenTimer !== null) clearInterval(this.tokenTimer);
594
+ this.resumeTimer = null;
595
+ this.tokenTimer = null;
596
+ this.engine?.stop();
597
+ this.engine = null;
598
+ const socket = this.socket;
599
+ this.socket = null;
600
+ if (socket !== null) {
601
+ socket.onopen = null;
602
+ socket.onmessage = null;
603
+ socket.onclose = null;
604
+ socket.onerror = null;
605
+ try {
606
+ socket.close(1000, 'call ended');
607
+ } catch {
608
+ // Already closed.
609
+ }
610
+ }
611
+ this.options.levels.reset();
612
+ this.messages = this.messages.map((message) =>
613
+ message.isStreaming ? { ...message, isStreaming: false } : message,
614
+ );
615
+ this.setState(state);
616
+ }
617
+
618
+ private setState(state: VoiceCallState): void {
619
+ if (this.finished && state.kind !== 'ended' && state.kind !== 'error') return;
620
+ this.state = state;
621
+ this.emit();
622
+ }
623
+
624
+ private emit(): void {
625
+ this.options.onChange(this.snapshot());
626
+ }
627
+ }
@@ -0,0 +1,31 @@
1
+ // The call bar's words, apart from the component so the chat's labels can hold them without
2
+ // reaching React Native.
3
+
4
+ /** Every word the bar shows or announces. An app in another language passes its own. */
5
+ export interface VoiceControlsLabels {
6
+ connecting: string;
7
+ reconnecting: string;
8
+ connected: string;
9
+ listening: string;
10
+ muted: string;
11
+ thinking: string;
12
+ usingTool: string;
13
+ speaking: string;
14
+ mute: string;
15
+ unmute: string;
16
+ end: string;
17
+ }
18
+
19
+ export const VOICE_CONTROLS_LABELS: VoiceControlsLabels = {
20
+ connecting: 'Connecting...',
21
+ reconnecting: 'Reconnecting...',
22
+ connected: 'Connected',
23
+ listening: 'Listening...',
24
+ muted: 'Muted',
25
+ thinking: 'Thinking...',
26
+ usingTool: 'Working on it...',
27
+ speaking: 'Speaking...',
28
+ mute: 'Mute',
29
+ unmute: 'Unmute',
30
+ end: 'End',
31
+ };