@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,75 @@
1
+ import { useEffect, useRef } from 'react';
2
+ import { useGemieRuntime } from './config';
3
+ import {
4
+ applyRoomEvent,
5
+ roomFailureReason,
6
+ type RoomFailureReason,
7
+ type RoomLedger,
8
+ } from './room-events';
9
+ import type { Message } from './types';
10
+
11
+ /**
12
+ * While a conversation is open, fold its room's events (`group:event`, ADR 0025) into the thread.
13
+ * Group turns and reaction-triggered agent replies share this lifecycle. A host without
14
+ * `subscribeRoomEvents` sees background replies on reload.
15
+ */
16
+ /**
17
+ * How long a room may say nothing while a member still shows as typing before the thread stops
18
+ * waiting. Events reach the socket at most once, so a dropped connection can lose the `group.idle`
19
+ * that would have ended it; a member's turn is bounded well inside this, and streaming deltas keep
20
+ * resetting it while anyone is actually speaking.
21
+ */
22
+ export const ROOM_SILENCE_MS = 120_000;
23
+ const SILENCE_CHECK_MS = 15_000;
24
+
25
+ export function useRoomEvents(
26
+ conversationId: string | undefined,
27
+ ledger: RoomLedger,
28
+ setMessages: (update: (prev: Message[]) => Message[]) => void,
29
+ onFailure?: (failure: { chainId: string; reason: RoomFailureReason }) => void,
30
+ ): void {
31
+ const { host } = useGemieRuntime();
32
+ const subscribe = host.subscribeRoomEvents;
33
+ const failureRef = useRef(onFailure);
34
+ failureRef.current = onFailure;
35
+ useEffect(() => {
36
+ if (!conversationId || !subscribe) return;
37
+ let lastEventAt = Date.now();
38
+ const failedChains = new Set<string>();
39
+ const unsubscribe = subscribe(conversationId, (event) => {
40
+ lastEventAt = Date.now();
41
+ setMessages((prev) => applyRoomEvent(prev, ledger, conversationId, event));
42
+ const reason =
43
+ event.event === 'group.idle' && event.data !== null && typeof event.data === 'object'
44
+ ? roomFailureReason((event.data as { reason?: unknown }).reason)
45
+ : null;
46
+ if (
47
+ event.conversationId === conversationId &&
48
+ reason !== null &&
49
+ typeof event.chainId === 'string' &&
50
+ event.chainId !== '' &&
51
+ !failedChains.has(event.chainId)
52
+ ) {
53
+ failedChains.add(event.chainId);
54
+ failureRef.current?.({ chainId: event.chainId, reason });
55
+ }
56
+ });
57
+ // A quiet room whose `group.idle` was lost: end it the way that event would have. Nothing open
58
+ // means `applyRoomEvent` hands back the same array and nothing re-renders.
59
+ const timer = setInterval(() => {
60
+ if (Date.now() - lastEventAt < ROOM_SILENCE_MS) return;
61
+ lastEventAt = Date.now();
62
+ setMessages((prev) =>
63
+ applyRoomEvent(prev, ledger, conversationId, {
64
+ conversationId,
65
+ event: 'group.idle',
66
+ data: { reason: 'silent' },
67
+ }),
68
+ );
69
+ }, SILENCE_CHECK_MS);
70
+ return () => {
71
+ clearInterval(timer);
72
+ unsubscribe();
73
+ };
74
+ }, [conversationId, ledger, subscribe, setMessages]);
75
+ }
@@ -0,0 +1,107 @@
1
+ import { toast } from '@oxy.so/bloom/toast';
2
+ import { useCallback } from 'react';
3
+ import { type GemieChatLabels, useLabels } from '../lib/labels';
4
+ import type { GemieAttachment } from '../types';
5
+ import { buildMessageContent, type DroppedAttachment } from './attachment-utils';
6
+ import { useDocumentUpload } from './oxy-files';
7
+ import { useComposerDraftStore, type DraftTarget } from './composer-draft-store';
8
+ import { useGemieRuntime } from './config';
9
+ import { useConversationStore } from './conversation-store';
10
+ import { useCreateConversation } from './conversations';
11
+ import type { SendOptions } from './types';
12
+
13
+ /**
14
+ * Say which attachments the turn went without.
15
+ *
16
+ * `buildMessageContent` used to drop them in silence: a document was filtered
17
+ * out by `a.type === 'image'`, and an image whose bytes would not read was a
18
+ * bare `continue`. The composer had already shown both as attached, so the
19
+ * turn left with the person believing the file went with it — the visible
20
+ * state and the real capability disagreeing, which is the failure #608 §1.6
21
+ * names.
22
+ *
23
+ * A toast rather than a blocked send: the message itself is fine and worth
24
+ * sending, and refusing the whole turn over a file the format cannot carry
25
+ * would be a worse trade. What matters is that nobody finds out by noticing
26
+ * the answer ignored their PDF.
27
+ */
28
+ export function reportDroppedAttachments(
29
+ dropped: DroppedAttachment[] | undefined,
30
+ labels: Pick<GemieChatLabels, 'attachmentNotSent' | 'attachmentUnreadable'>,
31
+ ): void {
32
+ if (dropped === undefined || dropped.length === 0) return;
33
+
34
+ for (const attachment of dropped) {
35
+ toast.error(
36
+ attachment.reason === 'unsupported'
37
+ ? labels.attachmentNotSent(attachment.name)
38
+ : labels.attachmentUnreadable(attachment.name),
39
+ );
40
+ }
41
+ }
42
+
43
+ export interface StartConversationOptions {
44
+ attachments?: GemieAttachment[];
45
+ options?: SendOptions;
46
+ /**
47
+ * The composer whose draft the message came from, to hand it back if the conversation cannot
48
+ * be made. A new-chat screen is `null` (the default); a screen that asks outside a chat names
49
+ * its own (`surface:automations`).
50
+ */
51
+ draft?: DraftTarget;
52
+ }
53
+
54
+ /**
55
+ * Start a conversation with a first message.
56
+ *
57
+ * The conversation is created, the message is queued for THAT conversation, and the host is told
58
+ * to show it (`openConversation`): the thread that opens sends the message, so the person lands
59
+ * on the conversation being answered. If the conversation cannot be made the composer gets its
60
+ * draft back. This is the one path for a new-chat screen, the sheet's first turn and a screen
61
+ * that starts a chat from elsewhere (a scheduled task described in words).
62
+ */
63
+ export function useStartConversation({ agentId }: { agentId?: string } = {}) {
64
+ const labels = useLabels();
65
+ const { host } = useGemieRuntime();
66
+ const { mutateAsync: createConversation } = useCreateConversation();
67
+ const upload = useDocumentUpload();
68
+
69
+ return useCallback(
70
+ async (
71
+ text: string,
72
+ { attachments = [], options, draft: target = null }: StartConversationOptions = {},
73
+ ): Promise<boolean> => {
74
+ if (!text.trim() && attachments.length === 0) return false;
75
+ const draft = useComposerDraftStore.getState().address(target);
76
+
77
+ // Attachments become multi-part content. The raw text and attachments ride along so a
78
+ // failed send can restore them.
79
+ const built =
80
+ attachments.length > 0 ? await buildMessageContent(text, attachments, upload) : null;
81
+ reportDroppedAttachments(built?.dropped, labels);
82
+ try {
83
+ const conversation = await createConversation({ agentId });
84
+ useConversationStore.getState().setPendingInitialMessage({
85
+ conversationId: conversation.id,
86
+ content: built ? built.content : text,
87
+ text,
88
+ attachments,
89
+ mcpServerId: options?.mcpServerId ?? null,
90
+ skillNames: options?.skillNames ?? [],
91
+ });
92
+ host.openConversation?.(conversation.id);
93
+ return true;
94
+ } catch {
95
+ // useCreateConversation.onError already shows the toast.
96
+ useComposerDraftStore.getState().restore(draft, {
97
+ text,
98
+ attachments,
99
+ mcpServerId: options?.mcpServerId ?? null,
100
+ skillNames: options?.skillNames ?? [],
101
+ });
102
+ return false;
103
+ }
104
+ },
105
+ [labels, host, createConversation, agentId, upload],
106
+ );
107
+ }
@@ -0,0 +1,73 @@
1
+ import { useInfiniteQuery } from '@tanstack/react-query';
2
+ import { useMemo } from 'react';
3
+ import { useGemieApi } from './api';
4
+ import { errorStatus } from './error-utils';
5
+ import { gemieQueryKeys } from './query-keys';
6
+ import { AGENT_ROUTES, type GemieThreadAddress, threadKey } from './routes';
7
+ import { type ThreadPage, threadHistory } from './thread/thread-history';
8
+
9
+ /**
10
+ * Everything said in this thread before the conversation on screen, a page at a time, going back.
11
+ *
12
+ * The screen streams into the most recent conversation of the thread and knows nothing older;
13
+ * the thread's messages route is what crosses the seams into the stretches before it. Pages are
14
+ * pulled as the reader approaches the top, never eagerly — a thread has no end going backwards,
15
+ * and the first page is already everything a reader who does not scroll will see.
16
+ *
17
+ * `nextCursor` is what says whether anything older remains, and it is the server's answer rather
18
+ * than a count: a page that comes back empty after its live messages are dropped is ordinary, and
19
+ * treating that as the end would stop the history dead on any thread whose current conversation
20
+ * is long.
21
+ */
22
+
23
+ /** How many messages a page carries. The server clamps its own maximum. */
24
+ const PAGE_SIZE = 50;
25
+
26
+ /** Whether there is a thread to ask about: an address with a non-empty handle or gemie id. */
27
+ export function isThreadAddress(
28
+ thread: GemieThreadAddress | undefined,
29
+ ): thread is GemieThreadAddress {
30
+ if (thread === undefined) return false;
31
+ return ('handle' in thread ? thread.handle : thread.gemieId).length > 0;
32
+ }
33
+
34
+ /** A 404 is the answer — the agent does not exist or is not the person's, and asking again does not change it. */
35
+ export function retryThreadRead(failureCount: number, error: unknown): boolean {
36
+ return errorStatus(error) !== 404 && failureCount < 2;
37
+ }
38
+
39
+ export function useThreadHistory(
40
+ thread: GemieThreadAddress | undefined,
41
+ activeConversationId: string | undefined,
42
+ ) {
43
+ const api = useGemieApi();
44
+ const query = useInfiniteQuery({
45
+ queryKey: gemieQueryKeys.threads.messages(thread === undefined ? '' : threadKey(thread)),
46
+ queryFn: async ({ pageParam }): Promise<ThreadPage> => {
47
+ if (thread === undefined) throw new Error('No thread to read');
48
+ const { data } = await api.get<ThreadPage>(AGENT_ROUTES.threadMessages(thread), {
49
+ params: { limit: PAGE_SIZE, before: pageParam },
50
+ });
51
+ return data;
52
+ },
53
+ initialPageParam: undefined as string | undefined,
54
+ getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
55
+ // Nothing to page through until the thread has answered which conversation is the live one:
56
+ // without it every message would be history, including the ones already on screen.
57
+ enabled: isThreadAddress(thread) && activeConversationId !== undefined,
58
+ retry: retryThreadRead,
59
+ });
60
+
61
+ const messages = useMemo(
62
+ () => threadHistory(query.data?.pages ?? [], activeConversationId ?? ''),
63
+ [query.data?.pages, activeConversationId],
64
+ );
65
+
66
+ return {
67
+ messages,
68
+ /** Whether a page older than the ones held remains to be asked for. */
69
+ hasMore: query.hasNextPage,
70
+ isLoadingMore: query.isFetchingNextPage,
71
+ loadMore: query.fetchNextPage,
72
+ };
73
+ }
@@ -0,0 +1,100 @@
1
+ import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
2
+ import { useMemo } from 'react';
3
+ import { useGemieApi } from './api';
4
+ import { gemieQueryKeys } from './query-keys';
5
+ import { AGENT_ROUTES, type GemieThreadAddress, threadKey } from './routes';
6
+ import {
7
+ type ThreadMessage,
8
+ type ThreadPage,
9
+ type ThreadSearchHit,
10
+ threadHistory,
11
+ } from './thread/thread-history';
12
+ import { isThreadAddress, retryThreadRead } from './use-thread-history';
13
+
14
+ /**
15
+ * Finding something said earlier in a thread, and getting back to it.
16
+ *
17
+ * Two halves, and the second is why the first is worth anything: a hit tells you the message
18
+ * exists, and its CURSOR is what opens the stretch of thread around it — however many
19
+ * conversations back it lives. Without that, a result list is a wall you can read and not reach.
20
+ */
21
+
22
+ /** How many hits to ask for. The server clamps its own maximum. */
23
+ const HIT_LIMIT = 30;
24
+
25
+ export function useThreadSearch(thread: GemieThreadAddress | undefined, query: string) {
26
+ const api = useGemieApi();
27
+ const trimmed = query.trim();
28
+
29
+ return useQuery({
30
+ queryKey: gemieQueryKeys.threads.search(thread === undefined ? '' : threadKey(thread), trimmed),
31
+ queryFn: async (): Promise<ThreadSearchHit[]> => {
32
+ if (thread === undefined) throw new Error('No thread to search');
33
+ const { data } = await api.get<{ hits: ThreadSearchHit[] }>(
34
+ AGENT_ROUTES.threadSearch(thread),
35
+ { params: { q: trimmed, limit: HIT_LIMIT } },
36
+ );
37
+ return data.hits;
38
+ },
39
+ // An empty query is not a search, and asking for one would return the thread's most recent
40
+ // everything under the guise of a result.
41
+ enabled: isThreadAddress(thread) && trimmed.length > 0,
42
+ // What was said cannot change, so a query already asked is answered from the cache.
43
+ staleTime: 1000 * 60 * 5,
44
+ retry: retryThreadRead,
45
+ });
46
+ }
47
+
48
+ /** How many messages a window carries, half of them before the hit. */
49
+ const WINDOW_SIZE = 40;
50
+
51
+ /**
52
+ * The stretch of thread around one message, opened from a search hit.
53
+ *
54
+ * `at=` rather than `before=`: `before` is exclusive, so the one message the window exists to
55
+ * reveal would be the one missing from it.
56
+ *
57
+ * Reading further back from here is the same paging as anywhere else — the window's own oldest
58
+ * cursor continues it — so this is an infinite query too, and only its first page is addressed
59
+ * differently. There is no paging FORWARD: the way back to the present is leaving the window, not
60
+ * walking to it.
61
+ */
62
+ export function useThreadWindow(thread: GemieThreadAddress | undefined, cursor: string | null) {
63
+ const api = useGemieApi();
64
+ const query = useInfiniteQuery({
65
+ queryKey: gemieQueryKeys.threads.window(
66
+ thread === undefined ? '' : threadKey(thread),
67
+ cursor ?? '',
68
+ ),
69
+ queryFn: async ({ pageParam }): Promise<ThreadPage> => {
70
+ if (thread === undefined) throw new Error('No thread to read');
71
+ const { data } = await api.get<ThreadPage>(AGENT_ROUTES.threadMessages(thread), {
72
+ params:
73
+ pageParam === undefined
74
+ ? { limit: WINDOW_SIZE, at: cursor ?? undefined }
75
+ : { limit: WINDOW_SIZE, before: pageParam },
76
+ });
77
+ return data;
78
+ },
79
+ initialPageParam: undefined as string | undefined,
80
+ getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
81
+ enabled: isThreadAddress(thread) && cursor !== null,
82
+ retry: retryThreadRead,
83
+ });
84
+
85
+ // Nothing is dropped here, unlike the tail: a window is a view of the PAST, and the live
86
+ // conversation is not on screen underneath it to be duplicated. The empty string is a
87
+ // conversation id no message has.
88
+ const messages: ThreadMessage[] = useMemo(
89
+ () => threadHistory(query.data?.pages ?? [], ''),
90
+ [query.data?.pages],
91
+ );
92
+
93
+ return {
94
+ messages,
95
+ hasMore: query.hasNextPage,
96
+ isLoadingMore: query.isFetchingNextPage,
97
+ loadMore: query.fetchNextPage,
98
+ isLoading: query.isPending && cursor !== null,
99
+ };
100
+ }
@@ -0,0 +1,99 @@
1
+ import { useCallback, useRef } from 'react';
2
+ import { getTextFromContent } from '../lib/content-utils';
3
+ import type { Message, SendOptions } from './types';
4
+ import type { GemieAttachment } from '../types';
5
+ import { useComposerDraft, useComposerDraftStore, type DraftTarget } from './composer-draft-store';
6
+
7
+ export interface TurnEditOptions {
8
+ /** The composer the edit happens in: this chat's draft. */
9
+ target: DraftTarget;
10
+ messages: readonly Message[];
11
+ /** The options a question was sent with, when this screen sent it. */
12
+ turnOptionsOf?: (userMessageId: string) => SendOptions | undefined;
13
+ /** Send the rewrite in place of the question (`useChatConversation.editMessage`). */
14
+ onEditMessage?: (
15
+ messageId: string,
16
+ text: string,
17
+ options?: SendOptions,
18
+ attachments?: GemieAttachment[],
19
+ ) => Promise<boolean>;
20
+ }
21
+
22
+ /**
23
+ * Rewriting a question already sent, in the composer (#608 §7).
24
+ *
25
+ * Before the template this was an "Editing message" strip over the input, with
26
+ * the id in the screen's own `useState` — so leaving the chat and coming back
27
+ * forgot the edit and the next send became a new turn. The edit lives in the
28
+ * chat's draft now (`composer-draft-store.ts`), like the text it is made of:
29
+ * per account and per conversation, and gone when the draft is.
30
+ *
31
+ * - `start` loads the question's words and the connector and skills it was sent
32
+ * with into the composer, keeping aside what the composer held. A question
33
+ * this screen did not send has no record of its options, so the composer's
34
+ * own choice stays.
35
+ * - `cancel` gives the composer back what it held.
36
+ * - `submit` sends the rewrite; a failure leaves the composer still editing,
37
+ * with the words back in it (the send path restores those).
38
+ *
39
+ * `editing` is the edit only while its question is still in the thread: a
40
+ * conversation cleared, or cut back by another edit, takes it away, and the
41
+ * composer goes back to writing a new turn.
42
+ */
43
+ export function useTurnEdit({ target, messages, turnOptionsOf, onEditMessage }: TurnEditOptions) {
44
+ const draftEdit = useComposerDraft(target).editing;
45
+ const editing =
46
+ draftEdit !== undefined && messages.some((m) => m.id === draftEdit.messageId)
47
+ ? draftEdit
48
+ : undefined;
49
+
50
+ // Read through a ref: `start` is a prop of every row in the thread, and an
51
+ // identity that changed per streamed token would re-render all of them.
52
+ const latestMessages = useRef(messages);
53
+ latestMessages.current = messages;
54
+
55
+ const start = useCallback(
56
+ (messageId: string) => {
57
+ const message = latestMessages.current.find((m) => m.id === messageId);
58
+ if (message === undefined) return;
59
+ const store = useComposerDraftStore.getState();
60
+ const current = store.drafts[target ?? ''];
61
+ const sentWith = turnOptionsOf?.(messageId);
62
+ store.startEdit(store.address(target), {
63
+ messageId,
64
+ text: getTextFromContent(message.content),
65
+ mcpServerId: sentWith?.mcpServerId ?? current?.mcpServerId ?? null,
66
+ skillNames: sentWith?.skillNames ?? current?.skillNames ?? [],
67
+ });
68
+ },
69
+ [target, turnOptionsOf],
70
+ );
71
+
72
+ const cancel = useCallback(() => {
73
+ const store = useComposerDraftStore.getState();
74
+ store.cancelEdit(store.address(target));
75
+ }, [target]);
76
+
77
+ /** Send `text` in place of the question being edited. The caller has cleared the draft. */
78
+ const submit = useCallback(
79
+ async (
80
+ text: string,
81
+ options?: SendOptions,
82
+ attachments?: GemieAttachment[],
83
+ ): Promise<boolean> => {
84
+ if (editing === undefined || onEditMessage === undefined) return false;
85
+ const address = useComposerDraftStore.getState().address(target);
86
+ const sent = await onEditMessage(editing.messageId, text, options, attachments);
87
+ if (!sent) useComposerDraftStore.getState().restore(address, { editing });
88
+ return sent;
89
+ },
90
+ [editing, onEditMessage, target],
91
+ );
92
+
93
+ return {
94
+ editing: onEditMessage === undefined ? undefined : editing,
95
+ start: onEditMessage === undefined ? undefined : start,
96
+ cancel,
97
+ submit,
98
+ };
99
+ }
package/src/text.ts ADDED
@@ -0,0 +1,19 @@
1
+ /// <reference types="nativewind/types" />
2
+ // @gemies/sdk/text — the chat without the voice call, and without bundling it
3
+ // The same `GemieChatSheet`, `GemieChatScreen` and `GemieChatContent` as the root entry, but none of
4
+ // them reaches the call's modules (its socket, protocol and audio engine): a text-only app takes
5
+ // its chat from here. Read-aloud and dictation stay — they are the composer's and the thread's.
6
+ // Types can be imported from the root entry (they are erased); values from the root would bring
7
+ // the call along.
8
+
9
+ export { GemieChatContent } from './components/GemieChatContent';
10
+ export type {
11
+ GemieChatAgentRef,
12
+ GemieChatChrome,
13
+ GemieChatContentProps,
14
+ GemieChatState,
15
+ } from './components/GemieChatContent';
16
+ export { GemieChatSheet } from './components/GemieChatSheet';
17
+ export type { GemieChatSheetProps, GemieChatSheetRef } from './components/GemieChatSheet';
18
+ export { GemieChatScreen } from './components/GemieChatScreen';
19
+ export type { GemieChatScreenProps } from './components/GemieChatScreen';
package/src/theme.ts ADDED
@@ -0,0 +1,16 @@
1
+ /** Color interface used by SDK components that need resolved color values (e.g., Markdown renderer). */
2
+ export interface GemieColors {
3
+ text: string;
4
+ background: string;
5
+ card: string;
6
+ inputBackground: string;
7
+ border: string;
8
+ secondaryText: string;
9
+ icon: string;
10
+ tint: string;
11
+ muted: string;
12
+ mutedForeground: string;
13
+ primary: string;
14
+ primary10: string;
15
+ isDark: boolean;
16
+ }
package/src/tools.ts ADDED
@@ -0,0 +1,27 @@
1
+ // @gemies/sdk/tools — what a turn's tool calls mean, without the UI.
2
+ // Pure functions: the status of a call, the numbered sources of a research answer, the
3
+ // words for a tool. They load no React Native, so a host's models and tests can use them.
4
+
5
+ export {
6
+ citationLabel,
7
+ extractCitationSources,
8
+ linkifyCitations,
9
+ normalizeCitationMarkers,
10
+ } from './lib/citations';
11
+ export { domainOf } from './lib/domain';
12
+ export { parseCatalogueTool, toolRendererKey } from './lib/catalogue-tool';
13
+ export type { CitationSource } from './lib/citations';
14
+ export { getToolDoneLabel, getToolPillLabel } from './lib/task-labels';
15
+ export {
16
+ ASK_USER_QUESTION_TOOL,
17
+ askedQuestions,
18
+ formatAnswers,
19
+ isQuestionInvocation,
20
+ pendingQuestions,
21
+ } from './lib/questions';
22
+ export type { AskedOption, AskedQuestion, QuestionAnswer } from './lib/questions';
23
+ export { classifyIntake, MAX_ATTACHMENT_BYTES } from './lib/attachment-intake';
24
+ export { toolCallStatus } from './lib/tool-call-status';
25
+ export type { ToolCallStatus } from './lib/tool-call-status';
26
+ export { englishCopy } from './lib/copy';
27
+ export type { Translate } from './lib/copy';
package/src/types.ts ADDED
@@ -0,0 +1,161 @@
1
+ import type { SharedValue } from 'react-native-reanimated';
2
+ import type { VoiceErrorCode } from './lib/speech-messages';
3
+ import type { VoiceCloseReason } from './lib/voice-protocol';
4
+
5
+ // ── Suggestion Types ──
6
+
7
+ /** A line the person can pick: `text` is what is shown and what is sent. */
8
+ export interface GemieSuggestion {
9
+ id: string;
10
+ text: string;
11
+ /** It has blanks to fill: picking it puts it in the composer for the person to finish, instead of sending it. */
12
+ template?: boolean;
13
+ }
14
+
15
+ // ── Composer Types ──
16
+
17
+ /** A file in the composer's draft, on its way into a turn. */
18
+ export interface GemieAttachment {
19
+ id: string;
20
+ /** A `data:` URL once read; a picker's `blob:`/`file:` URI for a photo not yet read. */
21
+ uri: string;
22
+ type: 'image' | 'document';
23
+ name: string;
24
+ size: number;
25
+ mimeType: string;
26
+ isLoading?: boolean;
27
+ }
28
+
29
+ // ── Chat Message Types ──
30
+
31
+ export interface ResearchSource {
32
+ id: number;
33
+ url: string;
34
+ title: string;
35
+ }
36
+
37
+ export interface ResearchProgress {
38
+ phase?: string;
39
+ message?: string;
40
+ subQuestions?: string[];
41
+ sourcesFound?: number;
42
+ currentQuery?: string;
43
+ iteration?: number;
44
+ isComplete?: boolean;
45
+ sources?: ResearchSource[];
46
+ totalSearches?: number;
47
+ }
48
+
49
+ export interface PlanStep {
50
+ action: string;
51
+ description: string;
52
+ toolName?: string;
53
+ }
54
+
55
+ /** A plan the agent shows before it works (`alia.plan_preview`). Shown only: nothing waits on it. */
56
+ export interface MessagePlan {
57
+ planId: string;
58
+ steps: PlanStep[];
59
+ }
60
+
61
+ // ── Voice Types ──
62
+
63
+ /**
64
+ * The call's connection, coarse: what a bar or a wave needs. `reconnecting`
65
+ * while a dropped socket resumes or Alia re-opens the session upstream.
66
+ */
67
+ export type RoomState = 'disconnected' | 'connecting' | 'connected' | 'reconnecting' | 'error';
68
+ /** Who has the turn, coarse: the palette of the ambient field and the bar's word. */
69
+ export type AgentState = 'idle' | 'listening' | 'thinking' | 'speaking';
70
+
71
+ /**
72
+ * The call's honest state (ADR 0017 §4). Every state is entered on an event
73
+ * that proves it, never on a timer:
74
+ *
75
+ * - `connecting` — socket open → authenticated → `session.start` accepted →
76
+ * the realtime session created upstream (`session.ready`).
77
+ * - `listening` — ONLY once the session is ready, the microphone delivered its
78
+ * first buffer and Alia acknowledged the first appended audio.
79
+ * - `user-speaking` — the server heard speech start.
80
+ * - `thinking` — from the end of the person's speech to the first answer
81
+ * audio or a tool.
82
+ * - `using-tool` — a tool runs in Alia; `tool` is its name, for a label only.
83
+ * - `speaking` — the first answer frame is PLAYING, not merely received.
84
+ * - `reconnecting` — a resume, or Alia re-opening the session upstream.
85
+ * - `ended` — the call is over; `call-moved-elsewhere` is a reason, not an error.
86
+ * - `error` — a typed failure ended it.
87
+ */
88
+ export type VoiceCallState =
89
+ | { kind: 'idle' }
90
+ | { kind: 'connecting' }
91
+ | { kind: 'listening' }
92
+ | { kind: 'user-speaking' }
93
+ | { kind: 'thinking' }
94
+ | { kind: 'using-tool'; tool: string }
95
+ | { kind: 'speaking' }
96
+ | { kind: 'reconnecting' }
97
+ | { kind: 'ended'; reason: VoiceCloseReason }
98
+ | { kind: 'error'; code: VoiceErrorCode };
99
+
100
+ export interface VoiceToolInvocation {
101
+ toolCallId: string;
102
+ toolName: string;
103
+ state: 'call' | 'result';
104
+ args?: Record<string, unknown>;
105
+ }
106
+
107
+ export interface VoiceMessage {
108
+ id: string;
109
+ role: 'user' | 'assistant';
110
+ speaker?: 'primary';
111
+ content: string;
112
+ timestamp: number;
113
+ isStreaming: boolean;
114
+ toolInvocations?: VoiceToolInvocation[];
115
+ }
116
+
117
+ // ── Voice Session (injected capability) ──
118
+
119
+ /** Everything a live call reports back to the chat shell. */
120
+ export interface VoiceSessionState {
121
+ /** The room is up and the agent is live. */
122
+ isConnected: boolean;
123
+ agentState: AgentState;
124
+ /** Audio amplitude channel that drives the ambient wave overlay. */
125
+ waveAmplitude: SharedValue<number>;
126
+ /** Transcript so far; the shell adapts it into the chat message list. */
127
+ messages: VoiceMessage[];
128
+ }
129
+
130
+ export interface VoiceSessionProps {
131
+ /** Gemies API base URL. */
132
+ apiUrl?: string;
133
+ /**
134
+ * The conversation the call's transcript is stored in. Omitted, each call
135
+ * starts a conversation of its own in the person's Alia history.
136
+ */
137
+ conversationId?: string;
138
+ /** The agent the call talks to; omitted, Alia. */
139
+ agentId?: string;
140
+ /** Language spoken (BCP-47); omitted, the platform's. */
141
+ locale?: string;
142
+ /** Which of the product's two voices answers. */
143
+ voice?: 'male' | 'female';
144
+ /** Alia stored messages of the call in the conversation: refresh the thread. */
145
+ onMessagesSaved?: (conversationId: string, messageIds: readonly string[]) => void;
146
+ /**
147
+ * What the call tells the person, in the chat's language (`labels`): a failure, a call moved
148
+ * to another device, the time limit near. Omitted, Bloom's toast.
149
+ */
150
+ onNotice?: (notice: VoiceNotice) => void;
151
+ /** Called on every room, agent, or transcript change. */
152
+ onStateChange: (state: VoiceSessionState) => void;
153
+ /** The call is over: hung up, failed, ended by the server or dropped. The person was told why. */
154
+ onEnd: () => void;
155
+ }
156
+
157
+ /** Something the call tells the person: a failure, how it ended, or that it is about to end. */
158
+ export interface VoiceNotice {
159
+ kind: 'error' | 'info' | 'warning';
160
+ text: string;
161
+ }