@gemies/sdk 0.0.0-stage → 1.1.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 (246) hide show
  1. package/CHANGELOG.md +1678 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +15 -0
  4. package/README.md +516 -2
  5. package/package.json +105 -4
  6. package/src/accounts.ts +29 -0
  7. package/src/animations.ts +5 -0
  8. package/src/ask-eager.ts +8 -0
  9. package/src/ask-text.ts +11 -0
  10. package/src/ask.ts +12 -0
  11. package/src/avatar.ts +13 -0
  12. package/src/character.ts +1 -0
  13. package/src/components/AmbientField.tsx +580 -0
  14. package/src/components/ComposerDropZone.tsx +235 -0
  15. package/src/components/ComposerSuggestions.tsx +45 -0
  16. package/src/components/GemieAccounts.tsx +433 -0
  17. package/src/components/GemieAskCore.tsx +184 -0
  18. package/src/components/GemieAskProvider.tsx +18 -0
  19. package/src/components/GemieAskProviderLazy.tsx +27 -0
  20. package/src/components/GemieAskProviderText.tsx +25 -0
  21. package/src/components/GemieAskSheet.tsx +51 -0
  22. package/src/components/GemieAskSheetWithVoice.tsx +10 -0
  23. package/src/components/GemieAvatar.tsx +57 -0
  24. package/src/components/GemieAvatarIcon.tsx +35 -0
  25. package/src/components/GemieChatContent.tsx +900 -0
  26. package/src/components/GemieChatHeader.tsx +123 -0
  27. package/src/components/GemieChatScreen.tsx +170 -0
  28. package/src/components/GemieChatSheet.tsx +368 -0
  29. package/src/components/GemieChatWithVoice.tsx +13 -0
  30. package/src/components/GemieComposer.tsx +388 -0
  31. package/src/components/GemieGroupWelcome.tsx +37 -0
  32. package/src/components/GemieParticipants.tsx +133 -0
  33. package/src/components/GemieParticipantsHeader.tsx +27 -0
  34. package/src/components/GemieRecentConversations.tsx +65 -0
  35. package/src/components/GemieSharedConversation.tsx +87 -0
  36. package/src/components/GemieWelcomeMessage.tsx +58 -0
  37. package/src/components/IdentityMark.tsx +225 -0
  38. package/src/components/Image.tsx +12 -0
  39. package/src/components/InertWhen.tsx +48 -0
  40. package/src/components/PlanPreviewCard.tsx +53 -0
  41. package/src/components/QuestionCard.tsx +64 -0
  42. package/src/components/ReplyMarkdown.tsx +373 -0
  43. package/src/components/RichBlocks.tsx +195 -0
  44. package/src/components/VoiceModeIcon.tsx +18 -0
  45. package/src/components/canvas/CanvasComponent.tsx +65 -0
  46. package/src/components/canvas/ChartRenderer.tsx +73 -0
  47. package/src/components/canvas/CodeRenderer.tsx +20 -0
  48. package/src/components/canvas/DashboardRenderer.tsx +70 -0
  49. package/src/components/canvas/DeckRenderer.tsx +43 -0
  50. package/src/components/canvas/FormRenderer.tsx +101 -0
  51. package/src/components/canvas/MarkdownRenderer.tsx +14 -0
  52. package/src/components/canvas/TableRenderer.tsx +47 -0
  53. package/src/components/icons/RiEmojiPicker.tsx +39 -0
  54. package/src/components/icons/RiMoreDots.tsx +32 -0
  55. package/src/components/icons/RiReplyLine.tsx +25 -0
  56. package/src/components/thought/FilesAndSources.tsx +120 -0
  57. package/src/components/thought/ThoughtPanel.tsx +426 -0
  58. package/src/components/thought/ToolStep.tsx +134 -0
  59. package/src/components/thread/AgentExchangeView.tsx +112 -0
  60. package/src/components/thread/AgentResultCard.tsx +125 -0
  61. package/src/components/thread/AgentTaskCard.tsx +127 -0
  62. package/src/components/thread/ChatBubble.tsx +256 -0
  63. package/src/components/thread/GemieThread.tsx +455 -0
  64. package/src/components/thread/MessageBlockBoundary.tsx +78 -0
  65. package/src/components/thread/NewConversationOffer.tsx +54 -0
  66. package/src/components/thread/ThreadRow.tsx +598 -0
  67. package/src/components/thread/ThreadSearch.tsx +130 -0
  68. package/src/components/thread/ThreadSkeleton.tsx +30 -0
  69. package/src/components/thread/ToolResultCard.tsx +254 -0
  70. package/src/components/thread/TurnMenu.tsx +54 -0
  71. package/src/components/thread/TurnStatusLine.tsx +34 -0
  72. package/src/components/voice/GemieVoiceCall.tsx +21 -0
  73. package/src/components/voice/GemieVoiceCall.web.tsx +17 -0
  74. package/src/components/voice/VoiceCallContext.ts +13 -0
  75. package/src/components/voice/VoiceControls.tsx +106 -0
  76. package/src/components/voice/VoiceSession.tsx +120 -0
  77. package/src/components/voice/withVoiceCall.tsx +25 -0
  78. package/src/csp.ts +50 -0
  79. package/src/dictation.ts +40 -0
  80. package/src/hooks/useAmbientWave.ts +184 -0
  81. package/src/hooks/useAtBottom.ts +51 -0
  82. package/src/hooks/useAttachMenu.ts +93 -0
  83. package/src/hooks/useAttachmentIntake.ts +401 -0
  84. package/src/hooks/useAudioLevelMonitor.ts +46 -0
  85. package/src/hooks/useAudioLevels.ts +51 -0
  86. package/src/hooks/useChatComposer.ts +309 -0
  87. package/src/hooks/useChatVoice.ts +129 -0
  88. package/src/hooks/useComposerSuggestions.ts +84 -0
  89. package/src/hooks/useDictation.ts +292 -0
  90. package/src/hooks/useDocumentPicker.ts +11 -0
  91. package/src/hooks/useFailedTurnToast.ts +43 -0
  92. package/src/hooks/useFocusWhenPresented.ts +41 -0
  93. package/src/hooks/useGemieActivity.ts +31 -0
  94. package/src/hooks/useImagePicker.ts +38 -0
  95. package/src/hooks/useMessageReactions.ts +119 -0
  96. package/src/hooks/useMessageVote.ts +50 -0
  97. package/src/hooks/useOpenThought.ts +79 -0
  98. package/src/hooks/usePendingQuestions.ts +19 -0
  99. package/src/hooks/useReadAloud.ts +92 -0
  100. package/src/hooks/useShareHandler.ts +24 -0
  101. package/src/hooks/useSoundEffects.ts +137 -0
  102. package/src/hooks/useTTS.ts +303 -0
  103. package/src/hooks/useThoughtScope.ts +59 -0
  104. package/src/hooks/useThreadRows.ts +157 -0
  105. package/src/hooks/useThreadView.ts +67 -0
  106. package/src/hooks/useTimelineWindow.ts +256 -0
  107. package/src/hooks/useVoiceLauncher.ts +180 -0
  108. package/src/hooks/useVoiceRoom.ts +212 -0
  109. package/src/index.ts +141 -0
  110. package/src/lib/activity-socket.ts +102 -0
  111. package/src/lib/activity-store.ts +53 -0
  112. package/src/lib/add-menu.ts +7 -0
  113. package/src/lib/agent-character.ts +28 -0
  114. package/src/lib/alia-character.ts +14 -0
  115. package/src/lib/alia-gemie.ts +6 -0
  116. package/src/lib/attachment-intake.ts +154 -0
  117. package/src/lib/attachment-tiles.ts +74 -0
  118. package/src/lib/audio-level.ts +130 -0
  119. package/src/lib/audio-request-auth.ts +4 -0
  120. package/src/lib/audio-session-binding.ts +27 -0
  121. package/src/lib/bubbles.tsx +16 -0
  122. package/src/lib/call-thread.ts +33 -0
  123. package/src/lib/canvas-result.ts +21 -0
  124. package/src/lib/catalogue-tool.ts +22 -0
  125. package/src/lib/citations.ts +192 -0
  126. package/src/lib/clipboard.ts +23 -0
  127. package/src/lib/content-utils.ts +46 -0
  128. package/src/lib/copy-en.ts +333 -0
  129. package/src/lib/copy-es.ts +330 -0
  130. package/src/lib/copy.ts +38 -0
  131. package/src/lib/deferred/document-picker.ts +2 -0
  132. package/src/lib/deferred/document-picker.web.ts +12 -0
  133. package/src/lib/deferred/expo-audio.ts +2 -0
  134. package/src/lib/deferred/expo-audio.web.ts +12 -0
  135. package/src/lib/deferred/image-data-url.ts +5 -0
  136. package/src/lib/deferred/image-data-url.web.ts +12 -0
  137. package/src/lib/dictation-protocol.ts +142 -0
  138. package/src/lib/dictation-recorder-types.ts +37 -0
  139. package/src/lib/dictation-recorder.native.ts +90 -0
  140. package/src/lib/dictation-recorder.ts +131 -0
  141. package/src/lib/dictation-stream.ts +238 -0
  142. package/src/lib/dictation.ts +216 -0
  143. package/src/lib/document-picker.ts +31 -0
  144. package/src/lib/domain.ts +12 -0
  145. package/src/lib/flights.ts +33 -0
  146. package/src/lib/focus-return.ts +66 -0
  147. package/src/lib/greeting.ts +15 -0
  148. package/src/lib/image-data-url.ts +35 -0
  149. package/src/lib/keyboard.native.tsx +25 -0
  150. package/src/lib/keyboard.tsx +55 -0
  151. package/src/lib/labels-es.ts +113 -0
  152. package/src/lib/labels.tsx +207 -0
  153. package/src/lib/origins.ts +28 -0
  154. package/src/lib/participants.ts +97 -0
  155. package/src/lib/pcm.ts +57 -0
  156. package/src/lib/power-level-options.ts +66 -0
  157. package/src/lib/questions.ts +92 -0
  158. package/src/lib/speech-language.ts +20 -0
  159. package/src/lib/speech-messages.ts +54 -0
  160. package/src/lib/speech-synthesis.ts +156 -0
  161. package/src/lib/suggestions.ts +53 -0
  162. package/src/lib/task-labels.ts +35 -0
  163. package/src/lib/text-input.ts +10 -0
  164. package/src/lib/tool-call-status.ts +28 -0
  165. package/src/lib/tool-icons.ts +36 -0
  166. package/src/lib/tool-registry.ts +71 -0
  167. package/src/lib/tool-renderers.tsx +32 -0
  168. package/src/lib/turn-state.ts +15 -0
  169. package/src/lib/utils.ts +35 -0
  170. package/src/lib/voice-audio-engine-types.ts +59 -0
  171. package/src/lib/voice-audio-engine.native.ts +232 -0
  172. package/src/lib/voice-audio-engine.ts +206 -0
  173. package/src/lib/voice-call-request.ts +49 -0
  174. package/src/lib/voice-call.ts +627 -0
  175. package/src/lib/voice-controls-labels.ts +31 -0
  176. package/src/lib/voice-levels.ts +64 -0
  177. package/src/lib/voice-protocol.ts +328 -0
  178. package/src/lib/voice-worklets.ts +19 -0
  179. package/src/lib/work-log.ts +370 -0
  180. package/src/metro/chart-importers.json +18 -0
  181. package/src/metro/granular-charts.js +3 -0
  182. package/src/metro/index.cjs +227 -0
  183. package/src/metro/index.d.cts +5 -0
  184. package/src/runtime/agents.ts +151 -0
  185. package/src/runtime/api.ts +144 -0
  186. package/src/runtime/app-assertion.ts +51 -0
  187. package/src/runtime/attachment-utils.ts +97 -0
  188. package/src/runtime/chat-turn-control.ts +74 -0
  189. package/src/runtime/composer-draft-store.ts +270 -0
  190. package/src/runtime/config.tsx +222 -0
  191. package/src/runtime/conversation-dates.ts +31 -0
  192. package/src/runtime/conversation-store.ts +49 -0
  193. package/src/runtime/conversations.ts +633 -0
  194. package/src/runtime/error-utils.ts +144 -0
  195. package/src/runtime/gemie-accounts.ts +182 -0
  196. package/src/runtime/host-tools.ts +290 -0
  197. package/src/runtime/index.ts +137 -0
  198. package/src/runtime/message-history.ts +124 -0
  199. package/src/runtime/message-reactions.ts +214 -0
  200. package/src/runtime/model.ts +39 -0
  201. package/src/runtime/oxy-files.ts +37 -0
  202. package/src/runtime/power-levels.ts +66 -0
  203. package/src/runtime/query-keys.ts +60 -0
  204. package/src/runtime/random-uuid.ts +25 -0
  205. package/src/runtime/reaction-cache.ts +45 -0
  206. package/src/runtime/room-events.ts +333 -0
  207. package/src/runtime/routes.ts +85 -0
  208. package/src/runtime/sharing.ts +217 -0
  209. package/src/runtime/sse-frame-reader.ts +88 -0
  210. package/src/runtime/stream-events.ts +154 -0
  211. package/src/runtime/stream-outcome.ts +21 -0
  212. package/src/runtime/thought-store.ts +103 -0
  213. package/src/runtime/thread/agent-activity.ts +261 -0
  214. package/src/runtime/thread/agent-exchange.ts +94 -0
  215. package/src/runtime/thread/automation-labels.ts +79 -0
  216. package/src/runtime/thread/conversation-export.ts +135 -0
  217. package/src/runtime/thread/message-days.ts +120 -0
  218. package/src/runtime/thread/message-processor.ts +93 -0
  219. package/src/runtime/thread/speaker-changes.ts +66 -0
  220. package/src/runtime/thread/task-utils.ts +11 -0
  221. package/src/runtime/thread/thought-utils.ts +750 -0
  222. package/src/runtime/thread/thread-history.ts +139 -0
  223. package/src/runtime/thread/timeline.ts +202 -0
  224. package/src/runtime/thread/title-tags.ts +8 -0
  225. package/src/runtime/thread/tool-cards.ts +387 -0
  226. package/src/runtime/turn-failure.ts +108 -0
  227. package/src/runtime/turn-preparation.ts +21 -0
  228. package/src/runtime/types.ts +172 -0
  229. package/src/runtime/usage-limit-error.ts +44 -0
  230. package/src/runtime/use-agent-activity.ts +80 -0
  231. package/src/runtime/use-conversation-stream.ts +1669 -0
  232. package/src/runtime/use-conversation-thread.ts +590 -0
  233. package/src/runtime/use-gemie-thread.ts +54 -0
  234. package/src/runtime/use-room-events.ts +75 -0
  235. package/src/runtime/use-start-conversation.ts +107 -0
  236. package/src/runtime/use-thread-history.ts +73 -0
  237. package/src/runtime/use-thread-search.ts +100 -0
  238. package/src/runtime/use-turn-edit.ts +99 -0
  239. package/src/text.ts +19 -0
  240. package/src/theme.ts +16 -0
  241. package/src/tools.ts +27 -0
  242. package/src/types.ts +161 -0
  243. package/src/voice-messages.ts +2 -0
  244. package/src/voice.ts +67 -0
  245. package/tsconfig.json +17 -0
  246. package/worklets/voice-processors.js +152 -0
@@ -0,0 +1,137 @@
1
+ /**
2
+ * The conversation runtime: the data layer under the sheet, the screen and the Alia app.
3
+ *
4
+ * Layers, each depending only on the ones above it in this list:
5
+ *
6
+ * 1. transport — `api` (REST over the signed-in Oxy client), the turn's SSE stream
7
+ * 2. model and state — `types`, `query-keys`, the zustand stores, the cached conversation lists
8
+ * 3. hooks — `useConversations`…, `useConversationThread`
9
+ *
10
+ * Nothing here draws anything. It is also a leaf entry, `@gemies/sdk/runtime`, for a host that
11
+ * needs the data layer without the chat UI (a sidebar, a test).
12
+ */
13
+
14
+ export { GemieRuntimeProvider, useGemieRuntime } from './config';
15
+ export type {
16
+ GemieArtifact,
17
+ GemieRuntimeConfig,
18
+ GemieRuntimeHost,
19
+ GemieRuntimeProviderProps,
20
+ GemieTurnRequest,
21
+ GemieUsageFrame,
22
+ OfflineConversationStore,
23
+ SpeechPreferences,
24
+ ThoughtOpening,
25
+ } from './config';
26
+ export type { RoomEvent } from './room-events';
27
+ export type { MessageReactionUpdate } from './message-reactions';
28
+ export { GemieApiError, useGemieApi } from './api';
29
+ export {
30
+ GEMIE_FEATURES,
31
+ featureOffer,
32
+ readAgentFeatures,
33
+ readAgentProfile,
34
+ useAgentFeatures,
35
+ useAgentProfile,
36
+ } from './agents';
37
+ export type {
38
+ GemieAgentFeature,
39
+ GemieAgentProfile,
40
+ GemieAgentStarter,
41
+ FeatureOffer,
42
+ } from './agents';
43
+ export {
44
+ HOST_IMAGE_MEDIA_TYPES,
45
+ HOST_IMAGE_TEXT_MAX_CHARS,
46
+ HOST_OUTCOMES,
47
+ HOST_RESULT_MAX_CHARS,
48
+ HostOutcomeQueue,
49
+ hostImageResultProblem,
50
+ hostRequest,
51
+ } from './host-tools';
52
+ export type {
53
+ GemieHostAction,
54
+ GemieHostImageMediaType,
55
+ GemieHostImageResult,
56
+ GemieHostOutcome,
57
+ GemieHostOutcomeKind,
58
+ GemieHostToolDefinition,
59
+ GemieHostTools,
60
+ HostResultRecord as GemieHostResultRecord,
61
+ } from './host-tools';
62
+ export { FEATURE_ENTITLEMENT_REQUIRED, parseConsultEvent, parseHostAction } from './stream-events';
63
+ export type { ConsultAgent, ConsultEvent } from './stream-events';
64
+ export {
65
+ DEFAULT_SHARE_TTL_HOURS,
66
+ readSharedConversation,
67
+ SharedConversationGoneError,
68
+ sharedMessages,
69
+ useShareConversation,
70
+ useSharedConversation,
71
+ } from './sharing';
72
+ export { gemiesSharedConversationUrl } from '../lib/origins';
73
+ export type {
74
+ GemieConversationShare,
75
+ GemieSharedAgent,
76
+ GemieSharedConversationData,
77
+ GemieSharedMessage,
78
+ } from './sharing';
79
+ export { uploadToOxyFiles, useDocumentUpload } from './oxy-files';
80
+ export type { OxyFilesClient } from './oxy-files';
81
+ export type { GemieApi, GemieApiRequest, GemieApiResult } from './api';
82
+ export { gemieQueryKeys, type ConversationsFilter } from './query-keys';
83
+ export {
84
+ ConversationNotFoundError,
85
+ useClearConversation,
86
+ useConversation,
87
+ useConversations,
88
+ useCreateConversation,
89
+ useDeleteConversation,
90
+ usePrefetchConversation,
91
+ useRenameConversation,
92
+ useSaveConversation,
93
+ } from './conversations';
94
+ export { useConversationThread, mergeEditedContent } from './use-conversation-thread';
95
+ export type {
96
+ ConversationThread,
97
+ EditedContent,
98
+ UseConversationThreadOptions,
99
+ } from './use-conversation-thread';
100
+ export type { SendOutcome } from './use-conversation-stream';
101
+ export { useConversationStore } from './conversation-store';
102
+ export type { PendingInitialMessage } from './conversation-store';
103
+ export {
104
+ releaseAttachments,
105
+ useComposerDraft,
106
+ useComposerDraftStore,
107
+ useDraftAddress,
108
+ } from './composer-draft-store';
109
+ export type {
110
+ ComposerDraft,
111
+ DraftAddress,
112
+ DraftTarget,
113
+ } from './composer-draft-store';
114
+ export { useAgentActivity } from './use-agent-activity';
115
+ export type { UseAgentActivityResult } from './use-agent-activity';
116
+ export { useThoughtStore } from './thought-store';
117
+ export type {
118
+ ThoughtScope,
119
+ ThoughtScopeStatus,
120
+ ThoughtSelection,
121
+ ThoughtTab,
122
+ } from './thought-store';
123
+ export { useThreadHistory } from './use-thread-history';
124
+ export { useThreadSearch, useThreadWindow } from './use-thread-search';
125
+ export { useGemieThread } from './use-gemie-thread';
126
+ export type { GemieThreadInfo } from './use-gemie-thread';
127
+ export type { GemieThreadAddress } from './routes';
128
+ export { useStartConversation } from './use-start-conversation';
129
+ export type { StartConversationOptions } from './use-start-conversation';
130
+ export { useTurnEdit } from './use-turn-edit';
131
+ export { buildMessageContent } from './attachment-utils';
132
+ export type { BuiltMessageContent, DroppedAttachment, UploadDocument } from './attachment-utils';
133
+
134
+ // The conversation as data (also the leaf entry `@gemies/sdk/model`).
135
+ export * from './model';
136
+
137
+ export { createChatTurnControl, type GemieChatTurnControl } from './chat-turn-control';
@@ -0,0 +1,124 @@
1
+ import type { Message, ToolInvocation } from './types';
2
+
3
+ /** Message shape accepted by the chat-completions endpoint. */
4
+ export interface OutboundMessage {
5
+ /**
6
+ * The id this screen draws the message under. The server stores the turn
7
+ * with the ids it was sent (`packages/api/src/lib/conversation-saver.ts`), so
8
+ * a vote or a read-aloud addressed by `Message.id` finds the row without a
9
+ * reload in between.
10
+ */
11
+ id: string;
12
+ role: string;
13
+ content: Message['content'];
14
+ toolInvocations?: Array<{
15
+ toolCallId: string;
16
+ toolName: string;
17
+ state: ToolInvocation['state'];
18
+ args?: Record<string, unknown>;
19
+ result?: unknown;
20
+ }>;
21
+ }
22
+
23
+ function formatOutboundMessage(message: Message): OutboundMessage {
24
+ const outbound: OutboundMessage = {
25
+ id: message.id,
26
+ role: message.role,
27
+ content: message.content,
28
+ };
29
+
30
+ if (message.role === 'assistant' && message.toolInvocations?.length) {
31
+ outbound.toolInvocations = message.toolInvocations.map((invocation) => ({
32
+ toolCallId: invocation.toolCallId,
33
+ toolName: invocation.toolName,
34
+ state: invocation.state,
35
+ args: invocation.args,
36
+ result: invocation.result,
37
+ }));
38
+ }
39
+
40
+ return outbound;
41
+ }
42
+
43
+ /**
44
+ * The id of the `index`-th consulted agent's answer (`alia.agent_start`, in the
45
+ * order the consultations started) in the turn whose reply is `assistantMessageId`.
46
+ *
47
+ * Derived, not received: the frames name a consultation (`consultId`), not a
48
+ * message. The server stores the same answer under the same derivation
49
+ * (`conversation-saver.ts` `agentMessageId`).
50
+ */
51
+ export function agentMessageId(assistantMessageId: string, index: number): string {
52
+ return `${agentMessagePrefix(assistantMessageId)}${index}`;
53
+ }
54
+
55
+ /** Whether `id` is one of the agent answers {@link agentMessageId} names for this reply. */
56
+ export function isAgentMessageOf(id: string, assistantMessageId: string): boolean {
57
+ return id.startsWith(agentMessagePrefix(assistantMessageId));
58
+ }
59
+
60
+ function agentMessagePrefix(assistantMessageId: string): string {
61
+ return `${assistantMessageId}-agent-`;
62
+ }
63
+
64
+ /** Build a turn from the history captured before optimistic UI updates. */
65
+ export function buildOutboundMessages(
66
+ historySnapshot: readonly Message[],
67
+ userMessage: Message,
68
+ ): OutboundMessage[] {
69
+ return [...historySnapshot, userMessage].map(formatOutboundMessage);
70
+ }
71
+
72
+ function sameContent(a: Message['content'], b: Message['content']): boolean {
73
+ if (a === b) return true;
74
+ try {
75
+ return JSON.stringify(a) === JSON.stringify(b);
76
+ } catch {
77
+ return false;
78
+ }
79
+ }
80
+
81
+ function isEmptyAssistantPlaceholder(message: Message | undefined): boolean {
82
+ return (
83
+ message?.role === 'assistant' &&
84
+ message.content === '' &&
85
+ !message.thinking &&
86
+ !message.toolInvocations?.length &&
87
+ !message.agentInfo
88
+ );
89
+ }
90
+
91
+ /**
92
+ * Hide histories written by the former optimistic-send race.
93
+ *
94
+ * That race persisted one exact sequence: user, empty assistant placeholder,
95
+ * the same user again. Only that signature is collapsed; intentional repeated
96
+ * prompts separated by a real assistant response remain untouched. The next
97
+ * successful turn rewrites divergent server history from this clean view.
98
+ */
99
+ export function normalizeConversationMessages(messages: readonly Message[]): Message[] {
100
+ const normalized: Message[] = [];
101
+ // A host's client context travels as a system message and is never part of the thread.
102
+ messages = messages.filter((message) => message.role !== 'system');
103
+
104
+ for (let index = 0; index < messages.length; index += 1) {
105
+ const current = messages[index] as Message;
106
+ const placeholder = messages[index + 1];
107
+ const duplicate = messages[index + 2];
108
+
109
+ if (
110
+ current.role === 'user' &&
111
+ isEmptyAssistantPlaceholder(placeholder) &&
112
+ duplicate?.role === 'user' &&
113
+ sameContent(current.content, duplicate.content)
114
+ ) {
115
+ normalized.push(current);
116
+ index += 2;
117
+ continue;
118
+ }
119
+
120
+ normalized.push(current);
121
+ }
122
+
123
+ return normalized;
124
+ }
@@ -0,0 +1,214 @@
1
+ import type { Message } from './types';
2
+ import { createRandomUuid } from './random-uuid';
3
+
4
+ /** Saved reaction state; older HTTP responses do not carry a revision. */
5
+ export interface MessageReactionSnapshot {
6
+ conversationId: string;
7
+ messageId: string;
8
+ reactions: string[];
9
+ revision?: number;
10
+ mutationId?: string | null;
11
+ }
12
+
13
+ /** Versioned state published by current servers over `conversation:reaction`. */
14
+ export interface MessageReactionUpdate extends MessageReactionSnapshot {
15
+ revision: number;
16
+ }
17
+
18
+ export interface MessageReactionMutation {
19
+ conversationId: string;
20
+ messageId: string;
21
+ emoji: string;
22
+ active: boolean;
23
+ mutationId: string;
24
+ }
25
+
26
+ export function readMessageReactionUpdate(value: unknown): MessageReactionUpdate | null {
27
+ if (!value || typeof value !== 'object') return null;
28
+ const v = value as Record<string, unknown>;
29
+ if (
30
+ typeof v.conversationId !== 'string' ||
31
+ !v.conversationId ||
32
+ typeof v.messageId !== 'string' ||
33
+ !v.messageId ||
34
+ !Array.isArray(v.reactions) ||
35
+ !v.reactions.every((emoji) => typeof emoji === 'string' && emoji !== '') ||
36
+ !Number.isSafeInteger(v.revision) ||
37
+ (v.revision as number) < 0 ||
38
+ (v.mutationId != null && (typeof v.mutationId !== 'string' || !v.mutationId))
39
+ )
40
+ return null;
41
+ return v as unknown as MessageReactionUpdate;
42
+ }
43
+
44
+ /** Read current and legacy HTTP acknowledgements without treating optional metadata as failure. */
45
+ export function readMessageReactionAcknowledgement(
46
+ value: unknown,
47
+ conversationId: string,
48
+ messageId: string,
49
+ mutationId: string,
50
+ ): MessageReactionSnapshot | null {
51
+ if (!value || typeof value !== 'object') return null;
52
+ const data = value as Record<string, unknown>;
53
+ const update = readMessageReactionUpdate({ ...data, conversationId });
54
+ if (
55
+ update &&
56
+ update.messageId === messageId &&
57
+ (update.mutationId == null || update.mutationId === mutationId)
58
+ )
59
+ return update;
60
+ if (
61
+ Object.keys(data).length === 1 &&
62
+ Array.isArray(data.reactions) &&
63
+ data.reactions.every((emoji) => typeof emoji === 'string' && emoji !== '')
64
+ ) {
65
+ return { conversationId, messageId, reactions: data.reactions };
66
+ }
67
+ return null;
68
+ }
69
+
70
+ /** Update only the existing target row; a reaction never invents a chat message. */
71
+ export function applyMessageReaction<
72
+ T extends Pick<Message, 'id' | 'reactions' | 'reactionRevision'>,
73
+ >(messages: readonly T[], update: MessageReactionSnapshot): T[] {
74
+ return messages.map((message) =>
75
+ message.id !== update.messageId ||
76
+ (update.revision !== undefined && (message.reactionRevision ?? 0) > update.revision)
77
+ ? message
78
+ : {
79
+ ...message,
80
+ reactions: update.reactions,
81
+ ...(update.revision === undefined ? {} : { reactionRevision: update.revision }),
82
+ },
83
+ );
84
+ }
85
+
86
+ type Intent = { active: boolean; sequence: number };
87
+ type Entry = {
88
+ confirmed: { reactions: readonly string[]; revision: number };
89
+ desired: Map<string, Intent>;
90
+ running?: { mutation: MessageReactionMutation; acknowledged: boolean };
91
+ };
92
+ const keyOf = (conversationId: string, messageId: string) =>
93
+ JSON.stringify([conversationId, messageId]);
94
+
95
+ /** Per-message ordered intent, with authoritative revisions shared by HTTP and socket arrivals. */
96
+ export class MessageReactionController {
97
+ private entries = new Map<string, Entry>();
98
+ private sequence = 0;
99
+ private disposed = false;
100
+
101
+ private readonly options: {
102
+ send: (mutation: MessageReactionMutation) => Promise<MessageReactionSnapshot>;
103
+ changed: () => void;
104
+ confirmed: (update: MessageReactionSnapshot) => void;
105
+ failed: () => void;
106
+ };
107
+
108
+ constructor(options: MessageReactionController['options']) {
109
+ this.options = options;
110
+ }
111
+
112
+ activate(): void {
113
+ this.disposed = false;
114
+ }
115
+ dispose(): void {
116
+ this.disposed = true;
117
+ }
118
+
119
+ reactionsOf(
120
+ conversationId: string,
121
+ messageId: string,
122
+ stored: readonly string[],
123
+ revision = 0,
124
+ ): readonly string[] {
125
+ const entry = this.entries.get(keyOf(conversationId, messageId));
126
+ if (!entry) return stored;
127
+ let reactions = [...(revision > entry.confirmed.revision ? stored : entry.confirmed.reactions)];
128
+ for (const [emoji, intent] of entry.desired) {
129
+ reactions = reactions.filter((held) => held !== emoji);
130
+ if (intent.active) reactions.push(emoji);
131
+ }
132
+ return reactions;
133
+ }
134
+
135
+ receive(update: MessageReactionSnapshot): void {
136
+ if (this.disposed) return;
137
+ const key = keyOf(update.conversationId, update.messageId);
138
+ const entry: Entry = this.entries.get(key) ?? {
139
+ confirmed: { reactions: [], revision: -1 },
140
+ desired: new Map(),
141
+ };
142
+ if (entry.running && entry.running.mutation.mutationId === update.mutationId)
143
+ entry.running.acknowledged = true;
144
+ if (update.revision !== undefined && update.revision < entry.confirmed.revision) return;
145
+ entry.confirmed = {
146
+ reactions: update.reactions,
147
+ revision: update.revision ?? entry.confirmed.revision,
148
+ };
149
+ this.entries.set(key, entry);
150
+ this.options.confirmed(update);
151
+ this.options.changed();
152
+ }
153
+
154
+ toggle(
155
+ conversationId: string,
156
+ messageId: string,
157
+ emoji: string,
158
+ stored: readonly string[],
159
+ revision = 0,
160
+ ): void {
161
+ if (this.disposed) return;
162
+ const key = keyOf(conversationId, messageId);
163
+ const entry: Entry = this.entries.get(key) ?? {
164
+ confirmed: { reactions: stored, revision },
165
+ desired: new Map(),
166
+ };
167
+ if (revision > entry.confirmed.revision) entry.confirmed = { reactions: stored, revision };
168
+ this.entries.set(key, entry);
169
+ const active = !this.reactionsOf(conversationId, messageId, stored, revision).includes(emoji);
170
+ entry.desired.set(emoji, { active, sequence: ++this.sequence });
171
+ this.options.changed();
172
+ if (!entry.running) void this.drain(entry, conversationId, messageId);
173
+ }
174
+
175
+ private async drain(entry: Entry, conversationId: string, messageId: string): Promise<void> {
176
+ while (!this.disposed && entry.desired.size > 0) {
177
+ const next = [...entry.desired].sort((a, b) => a[1].sequence - b[1].sequence)[0];
178
+ if (!next) return;
179
+ const [emoji, intent] = next;
180
+ const mutation = {
181
+ conversationId,
182
+ messageId,
183
+ emoji,
184
+ active: intent.active,
185
+ mutationId: createRandomUuid(),
186
+ };
187
+ const running = { mutation, acknowledged: false };
188
+ entry.running = running;
189
+ let failure = false;
190
+ const revisionBeforeSend = entry.confirmed.revision;
191
+ try {
192
+ const update = await this.options.send(mutation);
193
+ if (this.disposed) return;
194
+ // A legacy acknowledgement has no ordering metadata. A newer socket
195
+ // revision received meanwhile takes precedence over that answer.
196
+ if (update.revision !== undefined || entry.confirmed.revision === revisionBeforeSend) {
197
+ this.receive(update);
198
+ }
199
+ } catch {
200
+ if (this.disposed) return;
201
+ // Socket delivery proves commitment even if its HTTP answer was lost.
202
+ // Never replay an ambiguous POST: a rolling release may still have
203
+ // legacy toggle-only workers, even after another worker sent a revision.
204
+ failure = !running.acknowledged;
205
+ }
206
+ if (entry.desired.get(emoji)?.sequence === intent.sequence) {
207
+ entry.desired.delete(emoji);
208
+ if (failure) this.options.failed();
209
+ }
210
+ entry.running = undefined;
211
+ this.options.changed();
212
+ }
213
+ }
214
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The conversation as data: the records, and what a list of messages becomes before anything
3
+ * draws it (the timeline, the thought panel's steps and sources, tool cards, day lines,
4
+ * the agent thread's windows, the markdown export), plus the typed ways a turn fails.
5
+ *
6
+ * Pure: no React, no React Native, no Oxy client. It is a leaf entry (`@gemies/sdk/model`) for
7
+ * code that only reads conversations, and the runtime re-exports all of it.
8
+ */
9
+
10
+ export { API_ROUTES as GEMIES_API_ROUTES } from './routes';
11
+ export * from './power-levels';
12
+ export { englishCopy } from '../lib/copy';
13
+ export type { Translate } from '../lib/copy';
14
+ export * from './thread/agent-activity';
15
+ export * from './thread/automation-labels';
16
+ export * from './thread/conversation-export';
17
+ export * from './thread/message-days';
18
+ export * from './thread/message-processor';
19
+ export * from './thread/task-utils';
20
+ export * from './thread/thought-utils';
21
+ export * from './thread/thread-history';
22
+ export * from './thread/timeline';
23
+ export * from './thread/tool-cards';
24
+ export { failureDetail } from './turn-failure';
25
+ export type { FailedTurn } from './turn-failure';
26
+ export type {
27
+ AgentRun,
28
+ AutomationResource,
29
+ AutomationTrigger,
30
+ Conversation,
31
+ ConversationsInfiniteData,
32
+ ConversationsPage,
33
+ Message,
34
+ MessageContent,
35
+ SendOptions,
36
+ ToolInvocation,
37
+ } from './types';
38
+ export { UsageLimitError } from './usage-limit-error';
39
+ export type { UsageLimitDetails, UsageLimitType } from './usage-limit-error';
@@ -0,0 +1,37 @@
1
+ import { useOxy } from '@oxy.so/services/ui/client';
2
+ import { useMemo } from 'react';
3
+ import type { GemieAttachment } from '../types';
4
+ import type { UploadDocument } from './attachment-utils';
5
+
6
+ /** The slice of `OxyServices` an upload needs: Oxy Files' own `assets.upload` (`POST /assets/upload`). */
7
+ export interface OxyFilesClient {
8
+ assets: {
9
+ upload(
10
+ file: { uri: string; type?: string; name?: string; size?: number },
11
+ options?: { visibility?: 'private' | 'public' | 'unlisted' },
12
+ ): Promise<{ file: { id: string } }>;
13
+ };
14
+ }
15
+
16
+ /** Put `attachment` in the person's Oxy Files, private, and answer its id. */
17
+ export function uploadToOxyFiles(oxy: OxyFilesClient): UploadDocument {
18
+ return async (attachment: GemieAttachment) => {
19
+ const { file } = await oxy.assets.upload(
20
+ {
21
+ uri: attachment.uri,
22
+ type: attachment.mimeType,
23
+ name: attachment.name,
24
+ size: attachment.size,
25
+ },
26
+ { visibility: 'private' },
27
+ );
28
+ if (typeof file?.id !== 'string' || file.id === '') throw new Error('Oxy Files gave no id');
29
+ return file.id;
30
+ };
31
+ }
32
+
33
+ /** The signed-in person's document upload, for a turn's `file` parts. */
34
+ export function useDocumentUpload(): UploadDocument {
35
+ const { oxyServices } = useOxy();
36
+ return useMemo(() => uploadToOxyFiles(oxyServices as unknown as OxyFilesClient), [oxyServices]);
37
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Power levels — what a person chooses in Alia instead of a model.
3
+ *
4
+ * A level is one of Oxy's routing profiles (a slug with no `/`). The chat sends
5
+ * it as the request's `model`; Oxy picks an available model of that level for
6
+ * each request, cheapest first, and fails over inside the level. The chat never
7
+ * names a hosted model. The one exception is a model running on one of the
8
+ * person's OWN devices (`local/<runtime>/<model>`): that is their machine, not
9
+ * a model Alia offers, and it stays selectable while the device is connected.
10
+ *
11
+ * The seven slugs are Oxy's fixed vocabulary, so the chat can put words to
12
+ * each one in every language it speaks.
13
+ */
14
+
15
+ export const POWER_LEVELS = ['auto', 'instant', 'medium', 'high', 'xhigh', 'pro', 'ultra'] as const;
16
+ export type PowerLevel = (typeof POWER_LEVELS)[number];
17
+
18
+ /** Where everyone starts, and what any choice no longer offered becomes. */
19
+ export const DEFAULT_POWER_LEVEL: PowerLevel = 'auto';
20
+
21
+ export function isPowerLevel(value: unknown): value is PowerLevel {
22
+ return typeof value === 'string' && (POWER_LEVELS as readonly string[]).includes(value);
23
+ }
24
+
25
+ /** A model served by one of the person's own devices. */
26
+ export function isDeviceModelId(value: unknown): value is string {
27
+ return typeof value === 'string' && value.startsWith('local/') && value.length > 'local/'.length;
28
+ }
29
+
30
+ export interface ModeSelection {
31
+ /** What the selector shows as chosen: a level, or a connected device model. */
32
+ readonly shown: string;
33
+ /** What a request carries as `model`. Always present: the chat always says. */
34
+ readonly send: string;
35
+ /**
36
+ * `requested`: the stored choice is sent. `replaced`: it is not offered right
37
+ * now (a device that is not connected, or a value from an older build), so
38
+ * `auto` answers and the selector says so.
39
+ */
40
+ readonly source: 'requested' | 'replaced';
41
+ }
42
+
43
+ /**
44
+ * Resolve a stored choice against what can be sent now.
45
+ *
46
+ * `deviceModelIds` is `undefined` while the person's devices are still being
47
+ * listed: a device model is then kept rather than replaced, so a slow cold
48
+ * start never moves the person off their own machine.
49
+ */
50
+ export function resolveModeSelection(
51
+ stored: string | null | undefined,
52
+ deviceModelIds: readonly string[] | undefined,
53
+ ): ModeSelection {
54
+ if (isPowerLevel(stored)) return { shown: stored, send: stored, source: 'requested' };
55
+ if (
56
+ isDeviceModelId(stored) &&
57
+ (deviceModelIds === undefined || deviceModelIds.includes(stored))
58
+ ) {
59
+ return { shown: stored, send: stored, source: 'requested' };
60
+ }
61
+ return {
62
+ shown: DEFAULT_POWER_LEVEL,
63
+ send: DEFAULT_POWER_LEVEL,
64
+ source: stored === null || stored === undefined || stored === '' ? 'requested' : 'replaced',
65
+ };
66
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The React Query keys of the conversation runtime. The host's persister and its sidebar read
3
+ * the same keys the hooks write, so a list shown anywhere is the list the chat updates.
4
+ */
5
+ /** What a conversation list may be narrowed to (`GET /v1/conversations?agentId=&app=`). */
6
+ export interface ConversationsFilter {
7
+ /** Only the conversations with this agent. */
8
+ agentId?: string;
9
+ /** Only the conversations started in this app, by its slug (`docs/agent-embedding.md` §6). */
10
+ app?: string;
11
+ }
12
+
13
+ export const gemieQueryKeys = {
14
+ conversations: {
15
+ all: ['conversations'] as const,
16
+ detail: (id: string) => ['conversation', id] as const,
17
+ /**
18
+ * The person's conversations narrowed to one agent, one app or both: under `all`, so every
19
+ * write to the list reaches it.
20
+ */
21
+ filtered: (filter: ConversationsFilter) =>
22
+ ['conversations', { agentId: filter.agentId, app: filter.app }] as const,
23
+ },
24
+ /**
25
+ * A gemie's connected accounts (ADR 0035): the caller's accounts on it, the code of one being
26
+ * linked and an account's chats. Their own roots, never persisted: phone numbers and a live code
27
+ * stay in memory.
28
+ */
29
+ accounts: {
30
+ all: (gemieId: string) => ['gemie-accounts', gemieId] as const,
31
+ qr: (gemieId: string, accountId: string) => ['gemie-account-qr', gemieId, accountId] as const,
32
+ chats: (gemieId: string, accountId: string) =>
33
+ ['gemie-account-chats', gemieId, accountId] as const,
34
+ },
35
+ /** An agent the chat is opened on: its profile and the state of its feature gates. */
36
+ agents: {
37
+ profile: (id: string) => ['alia-agent-profile', id] as const,
38
+ features: (id: string) => ['alia-agent-features', id] as const,
39
+ },
40
+ /** A conversation somebody shared, by its token. */
41
+ shared: (token: string) => ['alia-shared-conversation', token] as const,
42
+ /**
43
+ * An agent's permanent thread: the stretches behind the open conversation, and finding in them.
44
+ * Keyed by `threadKey(address)`: the handle, or `id:<gemieId>`.
45
+ */
46
+ threads: {
47
+ /** The thread itself (which conversation is active): the host's own query lives under it. */
48
+ all: (thread: string) => ['agent-thread', thread] as const,
49
+ /**
50
+ * The history, kept apart from the thread itself: re-reading which conversation is active is
51
+ * cheap and happens whenever a new stretch starts, while the pages behind it are immutable and
52
+ * expensive to refetch.
53
+ */
54
+ messages: (thread: string) => ['agent-thread-messages', thread] as const,
55
+ /** Keyed by the query as typed, so each one is cached and none is re-asked. */
56
+ search: (thread: string, query: string) => ['agent-thread-search', thread, query] as const,
57
+ /** One window of the thread, addressed by the cursor a search hit carries. */
58
+ window: (thread: string, cursor: string) => ['agent-thread-window', thread, cursor] as const,
59
+ },
60
+ };