@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,25 @@
1
+ /**
2
+ * A UUID v4 that does not rely on `crypto.randomUUID()`.
3
+ *
4
+ * Web Crypto exposes `getRandomValues()` in every browsing context, while
5
+ * `randomUUID()` is restricted to secure contexts (a LAN-hosted development
6
+ * build is not one), and React Native has neither until a polyfill installs
7
+ * them. The last resort is `Math.random`: these ids name messages in a thread,
8
+ * they are not secrets.
9
+ */
10
+ export function createRandomUuid(): string {
11
+ const bytes = new Uint8Array(16);
12
+ const webCrypto = (globalThis as { crypto?: Crypto }).crypto;
13
+ if (webCrypto?.getRandomValues) {
14
+ webCrypto.getRandomValues(bytes);
15
+ } else {
16
+ for (let i = 0; i < bytes.length; i += 1) bytes[i] = Math.floor(Math.random() * 256);
17
+ }
18
+
19
+ // RFC 4122 version 4 and variant 1 bits.
20
+ bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
21
+ bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
22
+
23
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
24
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
25
+ }
@@ -0,0 +1,45 @@
1
+ import type { InfiniteData, QueryClient } from '@tanstack/react-query';
2
+ import { applyMessageReaction, type MessageReactionSnapshot } from './message-reactions';
3
+ import { gemieQueryKeys } from './query-keys';
4
+ import type { ThreadPage } from './thread/thread-history';
5
+ import type { Conversation } from './types';
6
+
7
+ /** Keep already fetched live messages and historical pages consistent with a saved reaction. */
8
+ export function updateReactionCaches(client: QueryClient, update: MessageReactionSnapshot): void {
9
+ client.setQueryData<Conversation>(
10
+ gemieQueryKeys.conversations.detail(update.conversationId),
11
+ (previous) =>
12
+ previous
13
+ ? { ...previous, messages: applyMessageReaction(previous.messages ?? [], update) }
14
+ : previous,
15
+ );
16
+ client.setQueriesData<InfiniteData<ThreadPage>>(
17
+ {
18
+ predicate: ({ queryKey }) =>
19
+ queryKey[0] === 'agent-thread-messages' || queryKey[0] === 'agent-thread-window',
20
+ },
21
+ (previous) =>
22
+ previous
23
+ ? {
24
+ ...previous,
25
+ pages: previous.pages.map((page) => ({
26
+ ...page,
27
+ messages: page.messages.map((message) =>
28
+ message.conversationId === update.conversationId &&
29
+ (message.id ?? message.cursor) === update.messageId &&
30
+ (update.revision === undefined ||
31
+ (message.reactionRevision ?? 0) <= update.revision)
32
+ ? {
33
+ ...message,
34
+ reactions: update.reactions,
35
+ ...(update.revision === undefined
36
+ ? {}
37
+ : { reactionRevision: update.revision }),
38
+ }
39
+ : message,
40
+ ),
41
+ })),
42
+ }
43
+ : previous,
44
+ );
45
+ }
@@ -0,0 +1,333 @@
1
+ /**
2
+ * A group conversation is a room (ADR 0025): its members keep talking after the request that
3
+ * started the round has ended, and the server pushes what they do over the socket as `group:event`.
4
+ *
5
+ * This file folds those events into the thread's messages. A member's reply is the SAME message the
6
+ * thread already draws for the request's `alia.agent_*` frames (`agentInfo`, `isStreaming`,
7
+ * `toolInvocations`), so nothing new is drawn. Pure: `use-room-events.ts` wires it to the host's
8
+ * socket and `use-conversation-stream.ts` shares the {@link RoomLedger} so a reply is never drawn
9
+ * twice, once for the request and once for the socket.
10
+ */
11
+
12
+ import type { Message, ToolInvocation } from './types';
13
+
14
+ /** `group:event` as the server pushes it: the frame body carries no `eventVersion`. */
15
+ export interface RoomEvent {
16
+ conversationId: string;
17
+ chainId?: string;
18
+ event: string;
19
+ data: unknown;
20
+ }
21
+
22
+ export type RoomFailureReason = 'error' | 'rate_limited' | 'turn_cap' | 'reply_cap';
23
+
24
+ /** A room failure is distinct from deliberate silence, supersession and a lost connection. */
25
+ export function roomFailureReason(value: unknown): RoomFailureReason | null {
26
+ return value === 'error' ||
27
+ value === 'rate_limited' ||
28
+ value === 'turn_cap' ||
29
+ value === 'reply_cap'
30
+ ? value
31
+ : null;
32
+ }
33
+
34
+ /**
35
+ * Which consultation is drawn in which message, and what the request already owns.
36
+ *
37
+ * Mutable on purpose: one per open conversation, held by the thread.
38
+ */
39
+ export interface RoomLedger {
40
+ /** `consultId` to the id of the message that draws it. */
41
+ messages: Map<string, string>;
42
+ /** Socket-observed chain for a consult, including one initially drawn by SSE. */
43
+ chains: Map<string, string>;
44
+ /** Consultations the chat request's SSE frames drew: the socket must not draw them again. */
45
+ claimed: Set<string>;
46
+ /** Claimed consultations whose request ended with `room_continues`: the socket carries them now. */
47
+ released: Set<string>;
48
+ /** Consultations whose end was applied. */
49
+ ended: Set<string>;
50
+ /** Provisional replies explicitly discarded by the room, never restored by late frames. */
51
+ discarded: Set<string>;
52
+ }
53
+
54
+ export function createRoomLedger(): RoomLedger {
55
+ return {
56
+ messages: new Map(),
57
+ chains: new Map(),
58
+ claimed: new Set(),
59
+ released: new Set(),
60
+ ended: new Set(),
61
+ discarded: new Set(),
62
+ };
63
+ }
64
+
65
+ /** The id a consultation drawn from the socket gets until its stored reply names it. */
66
+ const roomDraftId = (consultId: string): string => `room-${consultId}`;
67
+
68
+ /**
69
+ * The request drew `consultId` in message `id`. When the socket had already drawn it, the request
70
+ * adopts that message and returns its id: the request's frames are complete from their start, so
71
+ * the caller empties that message and lets the request say it all (what the socket added before
72
+ * would otherwise be said twice).
73
+ */
74
+ export function claimConsult(ledger: RoomLedger, consultId: string, id: string): string | null {
75
+ const existing = ledger.messages.get(consultId);
76
+ ledger.claimed.add(consultId);
77
+ if (existing !== undefined) return existing;
78
+ ledger.messages.set(consultId, id);
79
+ return null;
80
+ }
81
+
82
+ /** The request closed `consultId` with `room_continues`: the room goes on, the socket takes over. */
83
+ export function releaseConsult(ledger: RoomLedger, consultId: string): void {
84
+ if (ledger.claimed.has(consultId)) ledger.released.add(consultId);
85
+ }
86
+
87
+ /** Whether the room, not the request, owns `messageId` (so the request's end must not settle it). */
88
+ export function isRoomOwned(ledger: RoomLedger, messageId: string): boolean {
89
+ for (const [consultId, id] of ledger.messages) {
90
+ if (id === messageId) return ledger.released.has(consultId) && !ledger.ended.has(consultId);
91
+ }
92
+ return false;
93
+ }
94
+
95
+ type Raw = Record<string, unknown>;
96
+ const isObject = (value: unknown): value is Raw =>
97
+ value !== null && typeof value === 'object' && !Array.isArray(value);
98
+ const text = (value: unknown): string | undefined =>
99
+ typeof value === 'string' && value !== '' ? value : undefined;
100
+
101
+ /** A consultation the socket drives is live; one the request drew is, once it let go. */
102
+ const isLive = (ledger: RoomLedger, consultId: string): boolean =>
103
+ !ledger.claimed.has(consultId) || ledger.released.has(consultId);
104
+
105
+ const replace = (messages: Message[], id: string, change: (m: Message) => Message): Message[] =>
106
+ messages.map((m) => (m.id === id ? change(m) : m));
107
+
108
+ /** The message as the server stored it: no longer a draft. */
109
+ function stored(m: Message, reply: Raw): Message {
110
+ const { unsaved: _unsaved, ...rest } = m;
111
+ const createdAt = text(reply.createdAt);
112
+ const info = reply.agentInfo;
113
+ return {
114
+ ...rest,
115
+ content: typeof reply.content === 'string' ? reply.content : m.content,
116
+ ...(createdAt === undefined ? {} : { createdAt }),
117
+ ...(isObject(info) && text(info.id) && text(info.name)
118
+ ? { agentInfo: info as unknown as NonNullable<Message['agentInfo']> }
119
+ : {}),
120
+ isStreaming: false,
121
+ turnOutcome: 'completed',
122
+ };
123
+ }
124
+
125
+ /** A completed end names the stored reply: the draft becomes it, or yields to it if it is already here. */
126
+ function settleCompleted(
127
+ messages: Message[],
128
+ draftId: string | undefined,
129
+ messageId: string,
130
+ content: string | undefined,
131
+ ledger: RoomLedger,
132
+ consultId: string,
133
+ ): Message[] {
134
+ ledger.messages.set(consultId, messageId);
135
+ const reply: Raw = content === undefined ? {} : { content };
136
+ const has = messages.some((m) => m.id === messageId);
137
+ if (draftId === undefined || draftId === messageId) {
138
+ return has ? replace(messages, messageId, (m) => stored(m, reply)) : messages;
139
+ }
140
+ if (has) {
141
+ // `group.message` came first: it is the record, the draft only drops out.
142
+ return messages.filter((m) => m.id !== draftId);
143
+ }
144
+ return messages.map((m) => (m.id === draftId ? { ...stored(m, reply), id: messageId } : m));
145
+ }
146
+
147
+ /**
148
+ * What one room event does to the thread's messages. Events of other conversations, malformed ones
149
+ * and ones already applied return `messages` itself, so a caller can tell nothing changed.
150
+ */
151
+ export function applyRoomEvent(
152
+ messages: Message[],
153
+ ledger: RoomLedger,
154
+ conversationId: string,
155
+ incoming: RoomEvent,
156
+ ): Message[] {
157
+ if (incoming.conversationId !== conversationId || !isObject(incoming.data)) return messages;
158
+ const data = incoming.data;
159
+ const consultId = text(data.consultId);
160
+ const chainId = text(incoming.chainId);
161
+ if (
162
+ consultId !== undefined &&
163
+ chainId !== undefined &&
164
+ (incoming.event === 'alia.agent_start' ||
165
+ incoming.event === 'alia.agent_delta' ||
166
+ incoming.event === 'alia.agent_tool' ||
167
+ incoming.event === 'alia.agent_end')
168
+ ) {
169
+ // SSE may already own this consult, but only the socket carries its chain.
170
+ // Record it before the duplicate/ownership guards can discard the frame.
171
+ const knownChain = ledger.chains.get(consultId);
172
+ if (knownChain !== undefined && knownChain !== chainId) return messages;
173
+ ledger.chains.set(consultId, chainId);
174
+ }
175
+
176
+ switch (incoming.event) {
177
+ case 'alia.agent_start': {
178
+ const agent = data.agent;
179
+ if (consultId === undefined || ledger.messages.has(consultId)) return messages;
180
+ if (!isObject(agent) || !text(agent.id) || !text(agent.name)) return messages;
181
+ const id = roomDraftId(consultId);
182
+ ledger.messages.set(consultId, id);
183
+ return [
184
+ ...messages,
185
+ {
186
+ id,
187
+ unsaved: true,
188
+ role: 'assistant',
189
+ content: '',
190
+ toolInvocations: [],
191
+ createdAt: new Date().toISOString(),
192
+ isStreaming: true,
193
+ agentInfo: {
194
+ id: agent.id as string,
195
+ name: agent.name as string,
196
+ ...(text(agent.handle) ? { handle: agent.handle as string } : {}),
197
+ ...(text(agent.color) ? { color: agent.color as string } : {}),
198
+ ...(agent.character === undefined || agent.character === null
199
+ ? {}
200
+ : { character: agent.character }),
201
+ },
202
+ },
203
+ ];
204
+ }
205
+ case 'alia.agent_delta': {
206
+ if (consultId === undefined || ledger.ended.has(consultId) || !isLive(ledger, consultId)) {
207
+ return messages;
208
+ }
209
+ const id = ledger.messages.get(consultId);
210
+ if (id === undefined || typeof data.content !== 'string' || data.content === '') {
211
+ return messages;
212
+ }
213
+ const words = data.content;
214
+ return replace(messages, id, (m) => ({
215
+ ...m,
216
+ content: (typeof m.content === 'string' ? m.content : '') + words,
217
+ }));
218
+ }
219
+ case 'alia.agent_tool': {
220
+ if (consultId === undefined || ledger.ended.has(consultId) || !isLive(ledger, consultId)) {
221
+ return messages;
222
+ }
223
+ const id = ledger.messages.get(consultId);
224
+ const { phase, toolCallId, name, input } = data;
225
+ if (id === undefined || (phase !== 'call' && phase !== 'result')) return messages;
226
+ if (!text(toolCallId) || !text(name)) return messages;
227
+ return replace(messages, id, (m) => {
228
+ const invocations = [...(m.toolInvocations ?? [])];
229
+ const at = invocations.findIndex((call) => call.toolCallId === toolCallId);
230
+ const invocation: ToolInvocation = {
231
+ toolCallId: toolCallId as string,
232
+ toolName: name as string,
233
+ state: phase,
234
+ args: isObject(input) ? input : invocations[at]?.args,
235
+ ...(phase === 'result' ? { result: data.output } : {}),
236
+ };
237
+ if (at < 0) invocations.push(invocation);
238
+ else invocations[at] = invocation;
239
+ return { ...m, toolInvocations: invocations };
240
+ });
241
+ }
242
+ case 'alia.agent_end': {
243
+ if (consultId === undefined || ledger.discarded.has(consultId)) return messages;
244
+ const draftId = ledger.messages.get(consultId);
245
+ const { status } = data;
246
+ const messageId = text(data.messageId);
247
+ if (status === 'completed' && messageId !== undefined) {
248
+ // A stored completion is authoritative, even after a prior failed attempt.
249
+ // Replaying it converges on the same row rather than reviving a failed draft.
250
+ ledger.ended.add(consultId);
251
+ return settleCompleted(
252
+ messages,
253
+ draftId,
254
+ messageId,
255
+ typeof data.content === 'string' ? data.content.trim() : undefined,
256
+ ledger,
257
+ consultId,
258
+ );
259
+ }
260
+ if (ledger.ended.has(consultId) || !isLive(ledger, consultId)) return messages;
261
+ // `room_continues` is the request letting go, never a failure.
262
+ if (isObject(data.error) && data.error.code === 'room_continues') return messages;
263
+ ledger.ended.add(consultId);
264
+ if (draftId === undefined) return messages;
265
+ if (status === 'declined') {
266
+ ledger.discarded.add(consultId);
267
+ return messages.filter((m) => m.id !== draftId);
268
+ }
269
+ return replace(messages, draftId, (m) => ({
270
+ ...m,
271
+ isStreaming: false,
272
+ turnOutcome: status === 'failed' ? 'failed' : 'completed',
273
+ }));
274
+ }
275
+ case 'group.message': {
276
+ const reply = data.message;
277
+ if (!isObject(reply)) return messages;
278
+ const id = text(reply.id);
279
+ if (id === undefined || (reply.role !== undefined && reply.role !== 'assistant')) {
280
+ return messages;
281
+ }
282
+ // v2 room turns use their canonical reply ID as consultId. The stored
283
+ // message can therefore repair a failed draft even if agent_end was lost.
284
+ if (ledger.discarded.has(id)) return messages;
285
+ const draftId = ledger.messages.get(id);
286
+ const reconciled =
287
+ draftId === undefined
288
+ ? messages
289
+ : settleCompleted(
290
+ messages,
291
+ draftId,
292
+ id,
293
+ typeof reply.content === 'string' ? reply.content : undefined,
294
+ ledger,
295
+ id,
296
+ );
297
+ if (draftId !== undefined) ledger.ended.add(id);
298
+ if (reconciled.some((m) => m.id === id)) {
299
+ return replace(reconciled, id, (m) => stored(m, reply));
300
+ }
301
+ return [...reconciled, stored({ id, role: 'assistant', content: '' }, reply)];
302
+ }
303
+ case 'group.idle': {
304
+ // The room has ended. A failure must not look like deliberate silence.
305
+ const failure = roomFailureReason(data.reason);
306
+ // An old chain can finish after a new one starts. Unknown ownership is left
307
+ // for the synthetic silence timeout, never guessed from a terminal event.
308
+ if (chainId === undefined && data.reason !== 'silent') return messages;
309
+ const open = [...ledger.messages].filter(
310
+ ([cid]) =>
311
+ !ledger.ended.has(cid) &&
312
+ isLive(ledger, cid) &&
313
+ (chainId === undefined || ledger.chains.get(cid) === chainId),
314
+ );
315
+ if (open.length === 0) return messages;
316
+ const ids = new Set(open.map(([, id]) => id));
317
+ for (const [cid] of open) ledger.ended.add(cid);
318
+ return messages.flatMap((m) => {
319
+ if (!ids.has(m.id)) return [m];
320
+ if (m.content === '' && (m.toolInvocations?.length ?? 0) === 0) return [];
321
+ return [
322
+ {
323
+ ...m,
324
+ isStreaming: false,
325
+ ...(failure === null ? {} : { turnOutcome: 'failed' as const }),
326
+ },
327
+ ];
328
+ });
329
+ }
330
+ default:
331
+ return messages;
332
+ }
333
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The routes the SDK calls — all of them on the Gemies product API, `/v1`.
3
+ *
4
+ * The SDK is embedded by every Oxy app on its own web origin, so it may only call a surface that
5
+ * answers a browser from any origin with a bearer and no cookies: `/v1` (public CORS). The
6
+ * cookie-era routes (`/conversations`, `/alia/chat`) answer Alia's own origins alone and are not
7
+ * for the SDK. `tests/runtime/v1-only.test.ts` fails if the transport builds a URL outside `/v1`.
8
+ *
9
+ * `/v1/chat/completions` is the product's turn route: the same handler `/alia/chat` mounts, with
10
+ * every `alia.*` event, `conversationId` and the stored history.
11
+ */
12
+ export const API_ROUTES = {
13
+ chat: '/v1/chat/completions',
14
+ /** The answer to an awaited host action, read by the turn that is waiting for it. */
15
+ hostResults: (turnId: string) => `/v1/chat/turns/${encodeURIComponent(turnId)}/host-results`,
16
+ conversations: {
17
+ list: '/v1/conversations',
18
+ save: '/v1/conversations',
19
+ create: '/v1/conversations/new',
20
+ get: (id: string) => `/v1/conversations/${id}`,
21
+ remove: (id: string) => `/v1/conversations/${id}`,
22
+ /**
23
+ * Empty a thread without removing it: every message goes, the row and its
24
+ * title stay. A sub-resource DELETE rather than a `/clear` verb, because
25
+ * what is being deleted is the message collection and nothing else.
26
+ */
27
+ clearMessages: (id: string) => `/v1/conversations/${id}/messages`,
28
+ vote: (id: string, messageId: string) => `/v1/conversations/${id}/messages/${messageId}/vote`,
29
+ react: (id: string, messageId: string) =>
30
+ `/v1/conversations/${id}/messages/${messageId}/reactions`,
31
+ /** Mint (`POST { ttlHours }`) or revoke (`DELETE`) the conversation's read-only share link. */
32
+ share: (id: string) => `/v1/conversations/${id}/share`,
33
+ },
34
+ /** An agent any app can open: who it is, and which of Alia's features it gates. */
35
+ agents: {
36
+ profile: (id: string) => `/v1/agents/${encodeURIComponent(id)}/profile`,
37
+ features: (id: string) => `/v1/agents/${encodeURIComponent(id)}/features`,
38
+ },
39
+ /** A shared conversation, read without a session. */
40
+ shared: (token: string) => `/v1/shared/${encodeURIComponent(token)}`,
41
+ } as const;
42
+
43
+ /**
44
+ * Which thread a person holds with a gemie: by the gemie's Oxy handle, or by its id — Alia's, whose
45
+ * Oxy account has no handle yet (ADR 0034). The two address the SAME thread and the same routes.
46
+ */
47
+ export type GemieThreadAddress = { readonly handle: string } | { readonly gemieId: string };
48
+
49
+ /** The thread's own path; its messages and its search hang off it. */
50
+ function threadPath(thread: GemieThreadAddress): string {
51
+ return 'handle' in thread
52
+ ? `/agents/thread/${encodeURIComponent(thread.handle)}`
53
+ : `/agents/${encodeURIComponent(thread.gemieId)}/thread`;
54
+ }
55
+
56
+ /**
57
+ * The thread's cache key: the handle, as it always was (a host's own thread query lives under
58
+ * `gemieQueryKeys.threads.all(handle)`), or `id:<gemieId>`, which no handle can be.
59
+ */
60
+ export function threadKey(thread: GemieThreadAddress): string {
61
+ return 'handle' in thread ? thread.handle : `id:${thread.gemieId}`;
62
+ }
63
+
64
+ /**
65
+ * An agent's thread and its runs. These belong to Alia's own clients (the app), which are the only
66
+ * ones with agents of their own: `agentId`, `threadHandle` and the agent panel are not for an
67
+ * embedding Oxy app, and these routes answer Alia's origins alone, like `/conversations` does.
68
+ */
69
+ export const AGENT_ROUTES = {
70
+ /**
71
+ * Open the thread: `{ agent, conversationId, threadId }`, the active stretch (created the first
72
+ * time the two speak) and, for a gemie whose chats are loose (Alia), the thread row.
73
+ */
74
+ thread: (thread: GemieThreadAddress) => threadPath(thread),
75
+ /** A page of the thread, oldest-first, crossing the seams between its conversations. */
76
+ threadMessages: (thread: GemieThreadAddress) => `${threadPath(thread)}/messages`,
77
+ /** Everything said in the thread that matches, across every conversation in it. */
78
+ threadSearch: (thread: GemieThreadAddress) => `${threadPath(thread)}/search`,
79
+ /** What a run of an agent has done so far, to hydrate the live feed. */
80
+ sessionStatus: (sessionId: string) => `/agents/sessions/${sessionId}/status`,
81
+ /** The caller's WhatsApp and Telegram accounts linked to a gemie (ADR 0035), and one of them. */
82
+ accounts: (gemieId: string) => `/agents/${encodeURIComponent(gemieId)}/accounts`,
83
+ account: (gemieId: string, accountId: string) =>
84
+ `/agents/${encodeURIComponent(gemieId)}/accounts/${encodeURIComponent(accountId)}`,
85
+ } as const;