@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,370 @@
1
+ import { RiBookOpenLine } from '@oxy.so/bloom/icons/RiBookOpenLine';
2
+ import { RiFileTextLine } from '@oxy.so/bloom/icons/RiFileTextLine';
3
+ import { RiGlobalLine } from '@oxy.so/bloom/icons/RiGlobalLine';
4
+ import { RiSearchLine } from '@oxy.so/bloom/icons/RiSearchLine';
5
+ import { RiTerminalBoxLine } from '@oxy.so/bloom/icons/RiTerminalBoxLine';
6
+ import { RiToolsLine } from '@oxy.so/bloom/icons/RiToolsLine';
7
+ import type { TaskListChip, TaskListStep, TaskListTask } from '@oxy.so/bloom/task-list';
8
+ import type { WebSearchBrand, WebSearchSource, WebSearchStep } from '@oxy.so/bloom/web-search';
9
+ import type { ToolInvocation } from '../runtime/types';
10
+ import { extractCitationSources } from './citations';
11
+ import { domainOf } from './domain';
12
+ import { getToolDoneLabel, getToolPillLabel } from './task-labels';
13
+ import { toolCallStatus } from './tool-call-status';
14
+ import { englishCopy, type Translate } from './copy';
15
+
16
+ /**
17
+ * A turn's tool calls, as the two Bloom logs draw them.
18
+ *
19
+ * Where the turn WENT (searches, page visits, research) is a `WebSearch`
20
+ * trail; what it DID with every other tool is a `TaskList`. Calls that return
21
+ * a card (weather, market…) are neither — the caller filters them out first.
22
+ *
23
+ * Both logs count UNITS and are driven by `revealed`, never by their own
24
+ * ticker: a unit counts as revealed only when the event that produced it has
25
+ * arrived. A call whose arguments are still streaming (`partial-call`) is a
26
+ * step that is known but not yet revealed, so the log shimmers on it and shows
27
+ * its Working tail; a step's sources are a unit that exists only once the
28
+ * result carried them.
29
+ */
30
+
31
+ /** What a host can swap: the words, and where a site's icon is served from. */
32
+ export interface WorkLogOptions {
33
+ /** Translator for the log's words (see `copy.ts`). Default: English. */
34
+ t?: Translate;
35
+ /** The URL of a site's cached icon, or nothing for Bloom's quiet dot. */
36
+ faviconUrl?: (url: string) => string | null | undefined;
37
+ }
38
+
39
+ /** The result of a call, when it is an object (the tools return objects). */
40
+ function resultOf(inv: Pick<ToolInvocation, 'result'>): Record<string, unknown> | undefined {
41
+ const result = inv.result;
42
+ return result !== null && typeof result === 'object' && !Array.isArray(result)
43
+ ? (result as Record<string, unknown>)
44
+ : undefined;
45
+ }
46
+
47
+ /** The research the live stream reports before the answer is persisted. */
48
+ export interface LiveResearch {
49
+ isComplete?: boolean;
50
+ currentQuery?: string;
51
+ sourcesFound?: number;
52
+ sources?: Array<{ id?: unknown; url?: unknown; title?: unknown }> | null;
53
+ }
54
+
55
+ /** Tools whose calls are a place the turn went, not a task it did. */
56
+ const WEB_TOOLS = new Set(['webSearch', 'browse', 'webScraper', 'deepResearch']);
57
+
58
+ export function isWebInvocation(inv: Pick<ToolInvocation, 'toolName'>): boolean {
59
+ return WEB_TOOLS.has(inv.toolName);
60
+ }
61
+
62
+ function str(value: unknown): string | undefined {
63
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
64
+ }
65
+
66
+ /** The site marks Bloom draws, by registrable domain. Anything else is a quiet dot. */
67
+ const BRANDS: Array<[string, WebSearchBrand]> = [
68
+ ['github.com', 'github'],
69
+ ['gitlab.com', 'gitlab'],
70
+ ['bitbucket.org', 'bitbucket'],
71
+ ['x.com', 'x'],
72
+ ['twitter.com', 'x'],
73
+ ['reddit.com', 'reddit'],
74
+ ['facebook.com', 'facebook'],
75
+ ['instagram.com', 'instagram'],
76
+ ['linkedin.com', 'linkedin'],
77
+ ['tiktok.com', 'tiktok'],
78
+ ['spotify.com', 'spotify'],
79
+ ['twitch.tv', 'twitch'],
80
+ ['notion.so', 'notion'],
81
+ ['notion.site', 'notion'],
82
+ ['figma.com', 'figma'],
83
+ ['apple.com', 'apple'],
84
+ ['microsoft.com', 'microsoft'],
85
+ ['google.com', 'google'],
86
+ ['discord.com', 'discord'],
87
+ ['slack.com', 'slack'],
88
+ ['dropbox.com', 'dropbox'],
89
+ ['telegram.org', 'telegram'],
90
+ ['t.me', 'telegram'],
91
+ ['whatsapp.com', 'whatsapp'],
92
+ ['amazon.com', 'amazon'],
93
+ ];
94
+
95
+ function brandOf(domain: string): WebSearchBrand | undefined {
96
+ const host = domain.toLowerCase();
97
+ return BRANDS.find(([site]) => host === site || host.endsWith(`.${site}`))?.[1];
98
+ }
99
+
100
+ /**
101
+ * One source row. Its favicon is Clarity's copy of the site's icon: the one a
102
+ * search result carries, or the URL Clarity serves it at for anything else
103
+ * (a page Alia read). Bloom draws a brand mark over it, and the dot when
104
+ * Clarity has not fetched that site yet.
105
+ */
106
+ function source(
107
+ url: string,
108
+ options: WorkLogOptions,
109
+ title?: string,
110
+ faviconUrl?: string,
111
+ ): WebSearchSource {
112
+ const domain = domainOf(url);
113
+ const brand = brandOf(domain);
114
+ const favicon = faviconUrl ?? options.faviconUrl?.(url);
115
+ return {
116
+ title: title ?? domain,
117
+ domain,
118
+ href: url,
119
+ ...(brand ? { brand } : {}),
120
+ ...(favicon ? { faviconUrl: favicon } : {}),
121
+ };
122
+ }
123
+
124
+ function uniqueSources(list: WebSearchSource[]): WebSearchSource[] {
125
+ const seen = new Set<string>();
126
+ return list.filter((s) => {
127
+ const key = s.href ?? s.title;
128
+ if (seen.has(key)) return false;
129
+ seen.add(key);
130
+ return true;
131
+ });
132
+ }
133
+
134
+ function succeeded(inv: ToolInvocation): boolean {
135
+ return toolCallStatus(inv, true) === 'done';
136
+ }
137
+
138
+ function isSearch(inv: ToolInvocation): boolean {
139
+ if (inv.toolName === 'webSearch') return true;
140
+ const action = str(resultOf(inv)?.action) ?? str(inv.args?.action);
141
+ return inv.toolName === 'browse' && action === 'search';
142
+ }
143
+
144
+ /** One step, and whether the event that produced it has arrived. */
145
+ interface MappedStep {
146
+ step: WebSearchStep;
147
+ arrived: boolean;
148
+ }
149
+
150
+ function webStep(
151
+ inv: ToolInvocation,
152
+ live: LiveResearch | undefined,
153
+ options: WorkLogOptions,
154
+ ): MappedStep {
155
+ const t = options.t ?? englishCopy;
156
+ const arrived = inv.state !== 'partial-call';
157
+ const ok = succeeded(inv);
158
+ const res = resultOf(inv);
159
+
160
+ if (inv.toolName === 'deepResearch') {
161
+ const cited = extractCitationSources([inv], live?.sources);
162
+ const searches = typeof res?.totalSearches === 'number' ? res.totalSearches : 0;
163
+ return {
164
+ arrived,
165
+ step: {
166
+ label: t('chat.bloom.researched'),
167
+ query: str(inv.args?.query),
168
+ icon: RiBookOpenLine,
169
+ ...(searches > 0 ? { meta: t('chat.bloom.searchCount', { count: searches }) } : {}),
170
+ ...(cited.length > 0 ? { sources: cited.map((c) => source(c.url, options, c.title)) } : {}),
171
+ },
172
+ };
173
+ }
174
+
175
+ if (isSearch(inv)) {
176
+ const results: unknown[] = ok && Array.isArray(res?.results) ? res.results : [];
177
+ const sources = uniqueSources(
178
+ results.flatMap((r) => {
179
+ const url = str((r as { url?: unknown })?.url);
180
+ return url
181
+ ? [
182
+ source(
183
+ url,
184
+ options,
185
+ str((r as { title?: unknown }).title),
186
+ str((r as { faviconUrl?: unknown }).faviconUrl),
187
+ ),
188
+ ]
189
+ : [];
190
+ }),
191
+ );
192
+ const count = typeof res?.count === 'number' ? res.count : results.length;
193
+ return {
194
+ arrived,
195
+ step: {
196
+ label: t('chat.bloom.searchedWeb'),
197
+ query: str(inv.args?.query),
198
+ icon: RiSearchLine,
199
+ // Say what came back, including nothing: a search that found nothing or
200
+ // failed must not look like one whose sources are missing.
201
+ ...(inv.state !== 'result'
202
+ ? {}
203
+ : !ok
204
+ ? { meta: t('chat.bloom.searchFailed') }
205
+ : count === 0
206
+ ? { meta: t('chat.bloom.noResults') }
207
+ : { meta: t('chat.bloom.resultCount', { count }) }),
208
+ ...(sources.length > 0 ? { sources } : {}),
209
+ },
210
+ };
211
+ }
212
+
213
+ // A page visit: `webScraper`, or `browse` reading a URL.
214
+ const url = str(res?.url) ?? str(inv.args?.url);
215
+ return {
216
+ arrived,
217
+ step: {
218
+ label: t('chat.bloom.visited'),
219
+ query: url ? domainOf(url) : undefined,
220
+ icon: RiGlobalLine,
221
+ ...(ok && url && inv.state === 'result'
222
+ ? { sources: [source(url, options, str(res?.title))] }
223
+ : {}),
224
+ },
225
+ };
226
+ }
227
+
228
+ /** How many leading units have arrived. Units are revealed in order, so the first missing one stops the count. */
229
+ function arrivedUnits(mapped: MappedStep[]): number {
230
+ let revealed = 0;
231
+ for (const { step, arrived } of mapped) {
232
+ if (!arrived) break;
233
+ revealed += step.sources?.length ? 2 : 1;
234
+ }
235
+ return revealed;
236
+ }
237
+
238
+ export interface WebSearchLog {
239
+ steps: WebSearchStep[];
240
+ revealed: number;
241
+ }
242
+
243
+ /**
244
+ * The `WebSearch` trail of a turn: one step per search, page visit or
245
+ * research run, with the sources each surfaced.
246
+ *
247
+ * `research` is the live `researchProgress` of a research answer. Before the
248
+ * answer is saved there is no `deepResearch` invocation yet, so the progress
249
+ * is the step; once it is saved the invocation is, and the live sources only
250
+ * fill in what the persisted ones lack.
251
+ */
252
+ export function webSearchLog(
253
+ invocations: readonly ToolInvocation[] | undefined,
254
+ research: LiveResearch | undefined,
255
+ options: WorkLogOptions = {},
256
+ ): WebSearchLog {
257
+ const t = options.t ?? englishCopy;
258
+ const web = (invocations ?? []).filter(isWebInvocation);
259
+ const mapped = web.map((inv) => webStep(inv, research, options));
260
+
261
+ const hasResearchCall = web.some((inv) => inv.toolName === 'deepResearch');
262
+ if (research && !hasResearchCall) {
263
+ const cited = extractCitationSources(undefined, research.sources);
264
+ const found = typeof research.sourcesFound === 'number' ? research.sourcesFound : cited.length;
265
+ mapped.push({
266
+ arrived: true,
267
+ step: {
268
+ label: t(research.isComplete ? 'chat.bloom.researched' : 'chat.bloom.researching'),
269
+ query: str(research.currentQuery),
270
+ icon: RiBookOpenLine,
271
+ ...(found > 0 ? { meta: t('chat.bloom.sourceCount', { count: found }) } : {}),
272
+ ...(cited.length > 0 ? { sources: cited.map((c) => source(c.url, options, c.title)) } : {}),
273
+ },
274
+ });
275
+ }
276
+
277
+ return { steps: mapped.map((m) => m.step), revealed: arrivedUnits(mapped) };
278
+ }
279
+
280
+ /** Argument keys worth a chip, in the order they are shown. */
281
+ const CHIP_KEYS = [
282
+ 'filename',
283
+ 'path',
284
+ 'file',
285
+ 'command',
286
+ 'url',
287
+ 'query',
288
+ 'name',
289
+ 'title',
290
+ 'subject',
291
+ 'to',
292
+ 'handle',
293
+ ];
294
+ const CHIP_MAX = 60;
295
+
296
+ function argChips(args: Record<string, unknown> | undefined): TaskListChip[] {
297
+ if (!args) return [];
298
+ const chips: TaskListChip[] = [];
299
+ for (const key of CHIP_KEYS) {
300
+ const value = str(args[key]);
301
+ if (value && value.length <= CHIP_MAX) chips.push({ label: value });
302
+ if (chips.length === 3) break;
303
+ }
304
+ return chips;
305
+ }
306
+
307
+ const TASK_ICONS: Record<string, NonNullable<TaskListTask['icon']>> = {
308
+ generateFile: RiFileTextLine,
309
+ fileEdit: RiFileTextLine,
310
+ shellExec: RiTerminalBoxLine,
311
+ codeInterpreter: RiTerminalBoxLine,
312
+ };
313
+
314
+ export interface TaskListLog {
315
+ tasks: TaskListTask[];
316
+ revealed: number;
317
+ }
318
+
319
+ /**
320
+ * The `TaskList` of a turn: one task per call that is neither a web step nor
321
+ * a card, titled from `task-utils.ts`.
322
+ *
323
+ * Steps come from what the call really carried: its arguments as chips once
324
+ * the call is made (the file name for `generateFile`), and how it ended once
325
+ * the result is in — an error, or a call the turn left behind (`live` false
326
+ * with no result). A successful call adds no "Done" row: the swap from the
327
+ * running title to the finished one already says it.
328
+ */
329
+ export function taskListLog(
330
+ invocations: readonly ToolInvocation[] | undefined,
331
+ live: boolean,
332
+ options: WorkLogOptions = {},
333
+ ): TaskListLog {
334
+ const t = options.t ?? englishCopy;
335
+ let revealed = 0;
336
+ let open = true;
337
+ const tasks = (invocations ?? [])
338
+ .filter((inv) => !isWebInvocation(inv))
339
+ .map((inv): TaskListTask => {
340
+ const status = toolCallStatus(inv, live);
341
+ const steps: TaskListStep[] = [];
342
+
343
+ if (inv.toolName === 'generateFile') {
344
+ const name = str(resultOf(inv)?.filename) ?? str(inv.args?.filename);
345
+ if (name)
346
+ steps.push({
347
+ label: t(status === 'done' ? 'chat.bloom.createdFile' : 'chat.bloom.writingFile'),
348
+ chips: [{ label: name }],
349
+ });
350
+ } else {
351
+ const chips = argChips(inv.args);
352
+ if (chips.length > 0) steps.push({ label: t('chat.bloom.taskInput'), chips });
353
+ }
354
+ if (status === 'error') steps.push({ label: t('chat.bloom.taskFailed') });
355
+ if (status === 'interrupted') steps.push({ label: t('chat.bloom.taskStopped') });
356
+
357
+ // Header and argument steps land with the call; the outcome with the result.
358
+ const arrived = inv.state !== 'partial-call';
359
+ if (open && arrived) revealed += 1 + steps.length;
360
+ else open = false;
361
+
362
+ return {
363
+ title: getToolDoneLabel(inv.toolName, t),
364
+ runningTitle: getToolPillLabel(inv.toolName, t),
365
+ icon: TASK_ICONS[inv.toolName] ?? RiToolsLine,
366
+ steps,
367
+ };
368
+ });
369
+ return { tasks, revealed };
370
+ }
@@ -0,0 +1,18 @@
1
+ {
2
+ "format": 1,
3
+ "sdkVersion": "1.0.0",
4
+ "adapter": {
5
+ "path": "src/metro/granular-charts.js",
6
+ "sha256": "252add5b6642f8637f9b044a76fd05aff52fc9751bcff3e3587a95444f9ec1c1"
7
+ },
8
+ "importers": [
9
+ {
10
+ "path": "src/components/thread/ToolResultCard.tsx",
11
+ "sha256": "887ee8e6e586248a172ab0234450498463f660a707c0a402c8ceba7b0cfc8932"
12
+ },
13
+ {
14
+ "path": "src/components/canvas/ChartRenderer.tsx",
15
+ "sha256": "14a6c3a6531a706f3b5c7b135034dfaaf6abe236acc53f98524bfcbb52d3d755"
16
+ }
17
+ ]
18
+ }
@@ -0,0 +1,3 @@
1
+ // Imported only by the opt-in Metro resolver. The default SDK entries remain unchanged.
2
+ export { BarListCard } from '@oxy.so/bloom/chart-cards/bar-list';
3
+ export { LineChartCard } from '@oxy.so/bloom/chart-cards/line';
@@ -0,0 +1,227 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Optional Metro-only resolver for Alia's chart imports. The regular SDK entries
5
+ * and their Bloom peer remain unchanged. Each opted-in SDK copy carries the
6
+ * exact importers and adapter it supports; an unknown copy fails explicitly.
7
+ */
8
+ const fs = require('node:fs');
9
+ const path = require('node:path');
10
+ const crypto = require('node:crypto');
11
+
12
+ const SDK_ROOT = path.resolve(__dirname, '../..');
13
+ const LEGACY = '@oxy.so/bloom/chart-cards';
14
+ const GRANULAR = [`${LEGACY}/bar-list`, `${LEGACY}/line`];
15
+ const PREFIX = '[Gemies granular charts]';
16
+ const WRAPPED = Symbol.for('@gemies/sdk/metro/granular-charts-resolver/v1');
17
+
18
+ function checkedFile(root, entry) {
19
+ if (!entry || typeof entry.path !== 'string' || !/^[a-f0-9]{64}$/.test(entry.sha256 ?? '')) {
20
+ throw new Error(`${PREFIX} invalid SDK manifest entry`);
21
+ }
22
+ let actual;
23
+ try {
24
+ actual = fs.realpathSync(path.resolve(root, entry.path));
25
+ } catch (error) {
26
+ throw new Error(`${PREFIX} missing SDK file ${entry.path}`, { cause: error });
27
+ }
28
+ if (!actual.startsWith(`${root}${path.sep}`))
29
+ throw new Error(`${PREFIX} SDK file escapes its package`);
30
+ const digest = crypto.createHash('sha256').update(fs.readFileSync(actual)).digest('hex');
31
+ if (digest !== entry.sha256) throw new Error(`${PREFIX} changed SDK file ${entry.path}`);
32
+ return actual;
33
+ }
34
+
35
+ function collectTargets(roots) {
36
+ const targets = new Map();
37
+ for (const input of roots) {
38
+ let root, pkg, metadata;
39
+ try {
40
+ root = fs.realpathSync(input);
41
+ pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
42
+ metadata = JSON.parse(
43
+ fs.readFileSync(path.join(root, 'src/metro/chart-importers.json'), 'utf8'),
44
+ );
45
+ } catch (error) {
46
+ throw new Error(`${PREFIX} SDK copy lacks opt-in metadata`, { cause: error });
47
+ }
48
+ if (
49
+ pkg.name !== '@gemies/sdk' ||
50
+ metadata.format !== 1 ||
51
+ metadata.sdkVersion !== pkg.version ||
52
+ !Array.isArray(metadata.importers) ||
53
+ metadata.importers.length !== 2
54
+ ) {
55
+ throw new Error(`${PREFIX} unsupported SDK copy or version`);
56
+ }
57
+ const adapter = checkedFile(root, metadata.adapter);
58
+ for (const importer of metadata.importers) {
59
+ const target = { root, adapter };
60
+ targets.set(checkedFile(root, importer), target);
61
+ targets.set(path.resolve(root, importer.path), target);
62
+ targets.set(path.resolve(input, importer.path), target);
63
+ }
64
+ }
65
+ return targets;
66
+ }
67
+
68
+ function sourceFile(resolution, name) {
69
+ if (resolution?.type !== 'sourceFile' || typeof resolution.filePath !== 'string') {
70
+ throw new Error(`${PREFIX} ${name} did not resolve to a source file`);
71
+ }
72
+ try {
73
+ return fs.realpathSync(resolution.filePath);
74
+ } catch (error) {
75
+ throw new Error(`${PREFIX} ${name} resolved to a missing file`, { cause: error });
76
+ }
77
+ }
78
+
79
+ function bloomRoot(file) {
80
+ let dir = path.dirname(file);
81
+ for (;;) {
82
+ const manifest = path.join(dir, 'package.json');
83
+ if (fs.existsSync(manifest)) {
84
+ let pkg;
85
+ try {
86
+ pkg = JSON.parse(fs.readFileSync(manifest, 'utf8'));
87
+ } catch (error) {
88
+ throw new Error(`${PREFIX} invalid package manifest`, { cause: error });
89
+ }
90
+ if (pkg.name === '@oxy.so/bloom') return fs.realpathSync(dir);
91
+ }
92
+ const parent = path.dirname(dir);
93
+ if (parent === dir) throw new Error(`${PREFIX} resolved file is not inside Bloom`);
94
+ dir = parent;
95
+ }
96
+ }
97
+
98
+ /** Resolve only explicit, file-valued exports with Metro's active conditions. */
99
+ function exportedFile(root, entry, context, platform, subpath) {
100
+ const names = new Set([
101
+ 'default',
102
+ context.isESMImport === true ? 'import' : 'require',
103
+ ...(context.unstable_conditionNames ?? []),
104
+ ...(context.unstable_conditionsByPlatform?.[platform] ?? []),
105
+ ]);
106
+ let target = entry;
107
+ while (target && typeof target === 'object' && !Array.isArray(target)) {
108
+ const key = Object.keys(target).find((condition) => names.has(condition));
109
+ target = key === undefined ? null : target[key];
110
+ }
111
+ if (
112
+ typeof target !== 'string' ||
113
+ !target.startsWith('./') ||
114
+ target.includes('\\') ||
115
+ target.includes('*') ||
116
+ target.split('/').some((segment) => segment === '..' || segment === 'node_modules')
117
+ ) {
118
+ throw new Error(`${PREFIX} ${subpath} has no supported export for ${platform}`);
119
+ }
120
+ try {
121
+ const file = fs.realpathSync(path.resolve(root, target));
122
+ if (!file.startsWith(`${root}${path.sep}`) || !fs.statSync(file).isFile())
123
+ throw new Error('invalid target');
124
+ return file;
125
+ } catch (error) {
126
+ throw new Error(`${PREFIX} ${subpath} export target is unavailable for ${platform}`, {
127
+ cause: error,
128
+ });
129
+ }
130
+ }
131
+
132
+ /**
133
+ * Wrap a finished Metro config. Only the two verified importers in each
134
+ * explicitly opted-in SDK copy are redirected. Register other installed copies
135
+ * through `additionalSdkRoots`; unregistered copies use their original path.
136
+ * The app must install Bloom with both granular chart subpaths.
137
+ *
138
+ * @param {object} config Metro config, after the app's other resolver wrappers.
139
+ * @param {{additionalSdkRoots?: string[]}} [options]
140
+ * @returns {object} The same config, with its previous resolver preserved.
141
+ */
142
+ function withGemieGranularCharts(config, options = {}) {
143
+ if (!Array.isArray(options.additionalSdkRoots ?? []))
144
+ throw new Error(`${PREFIX} additionalSdkRoots must be an array`);
145
+ const previous = config.resolver?.resolveRequest;
146
+ if (config[WRAPPED] || previous?.[WRAPPED]) {
147
+ throw new Error(
148
+ `${PREFIX} already configured; register all SDK copies with additionalSdkRoots in one call`,
149
+ );
150
+ }
151
+ const targets = collectTargets([SDK_ROOT, ...(options.additionalSdkRoots ?? [])]);
152
+ config.resolver ??= {};
153
+ const delegate = (context, name, platform) =>
154
+ previous ? previous(context, name, platform) : context.resolveRequest(context, name, platform);
155
+ const wrapped = (context, name, platform) => {
156
+ if (name !== LEGACY) return delegate(context, name, platform);
157
+ const lexicalOrigin = path.resolve(context.originModulePath);
158
+ const lexicalTarget = targets.get(lexicalOrigin);
159
+ let origin;
160
+ try {
161
+ origin = fs.realpathSync(lexicalOrigin);
162
+ } catch (error) {
163
+ if (lexicalTarget) throw new Error(`${PREFIX} SDK importer is missing`, { cause: error });
164
+ return delegate(context, name, platform);
165
+ }
166
+ const registered = lexicalTarget ?? targets.get(origin);
167
+ if (!registered) return delegate(context, name, platform);
168
+ const refreshed = collectTargets([registered.root]).get(origin);
169
+ if (!refreshed || refreshed.adapter !== registered.adapter) {
170
+ throw new Error(`${PREFIX} SDK targets changed; restart Metro`);
171
+ }
172
+ const adapter = refreshed.adapter;
173
+
174
+ let legacy;
175
+ try {
176
+ legacy = sourceFile(delegate(context, LEGACY, platform), LEGACY);
177
+ } catch (error) {
178
+ throw new Error(`${PREFIX} the original Bloom chart barrel is unavailable for ${platform}`, {
179
+ cause: error,
180
+ });
181
+ }
182
+ const expectedBloom = bloomRoot(legacy);
183
+ const bloom = JSON.parse(fs.readFileSync(path.join(expectedBloom, 'package.json'), 'utf8'));
184
+ const adapterContext = { ...context, originModulePath: adapter };
185
+ for (const subpath of GRANULAR) {
186
+ const exported = `.${subpath.slice('@oxy.so/bloom'.length)}`;
187
+ if (!bloom.exports || !Object.hasOwn(bloom.exports, exported)) {
188
+ throw new Error(
189
+ `${PREFIX} ${subpath} is not exported by this Bloom; install a compatible Bloom`,
190
+ );
191
+ }
192
+ const publicTarget = exportedFile(
193
+ expectedBloom,
194
+ bloom.exports[exported],
195
+ context,
196
+ platform,
197
+ subpath,
198
+ );
199
+ let originalTarget, adapterTarget;
200
+ try {
201
+ originalTarget = sourceFile(delegate(context, subpath, platform), subpath);
202
+ adapterTarget = sourceFile(delegate(adapterContext, subpath, platform), subpath);
203
+ } catch (error) {
204
+ throw new Error(
205
+ `${PREFIX} ${subpath} is unavailable for ${platform}; install a compatible Bloom`,
206
+ { cause: error },
207
+ );
208
+ }
209
+ if (originalTarget !== adapterTarget || bloomRoot(originalTarget) !== expectedBloom) {
210
+ throw new Error(`${PREFIX} ${subpath} selects a different Bloom copy for ${platform}`);
211
+ }
212
+ if (originalTarget !== publicTarget) {
213
+ throw new Error(
214
+ `${PREFIX} ${subpath} did not resolve to its declared public export for ${platform}`,
215
+ );
216
+ }
217
+ }
218
+ const resolvedAdapter = sourceFile(delegate(context, adapter, platform), 'SDK chart adapter');
219
+ if (resolvedAdapter !== adapter) throw new Error(`${PREFIX} SDK chart adapter was redirected`);
220
+ return { type: 'sourceFile', filePath: adapter };
221
+ };
222
+ Object.defineProperty(wrapped, WRAPPED, { value: true });
223
+ Object.defineProperty(config, WRAPPED, { value: true, enumerable: true });
224
+ config.resolver.resolveRequest = wrapped;
225
+ return config;
226
+ }
227
+ module.exports = { withGemieGranularCharts };
@@ -0,0 +1,5 @@
1
+ /** Wrap an existing Metro config without replacing its previous resolver. */
2
+ export function withGemieGranularCharts<T extends { resolver?: object }>(
3
+ config: T,
4
+ options?: { additionalSdkRoots?: string[] },
5
+ ): T;