@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,387 @@
1
+ import type { AutomationTrigger, ToolInvocation } from '../types';
2
+
3
+ /**
4
+ * The cards a tool result draws inside the assistant turn, as data.
5
+ *
6
+ * Everything here is pure: the snapshot the tool stored with the message goes
7
+ * in, and what Bloom's `LineChartCard`, `Card` and `Item` are handed comes
8
+ * out. A thread reopened next month shows the numbers it was answered with,
9
+ * because nothing is fetched — every range the card offers is already in the
10
+ * snapshot. The producers are `packages/api/src/lib/tools/{weather,market,
11
+ * faircoin}.ts` and the scheduling tool.
12
+ */
13
+
14
+ type Translate = (key: string, params?: Record<string, string>) => string;
15
+
16
+ /** The tool results that are a card rather than a step of the turn's work. */
17
+ const CARD_TYPES = new Set(['weather', 'market', 'faircoin', 'scheduled-task']);
18
+
19
+ export type ToolCard =
20
+ | { type: 'weather'; data: WeatherCardData }
21
+ | { type: 'market'; data: MarketCardData }
22
+ | { type: 'faircoin'; data: FairCoinCardData }
23
+ | { type: 'scheduled-task'; data: ScheduledTaskCardData };
24
+
25
+ /**
26
+ * The card a finished call returned, if it is one this conversation draws.
27
+ *
28
+ * It checks the card's NAME, not the shape of its `data`, which is then cast
29
+ * unchecked — so each card renders inside its own error boundary, and the
30
+ * builders below guard every field they read.
31
+ */
32
+ export function cardOf(t: ToolInvocation): ToolCard | null {
33
+ if (t.state !== 'result') return null;
34
+ const card = (t.result as { card?: { type?: string; data?: unknown } } | undefined)?.card;
35
+ if (card?.type === undefined || !CARD_TYPES.has(card.type) || !card.data) return null;
36
+ return { type: card.type, data: card.data } as ToolCard;
37
+ }
38
+
39
+ // ---------------------------------------------------------------------------
40
+ // Shared formatting
41
+ // ---------------------------------------------------------------------------
42
+
43
+ /** `[msSinceEpoch, price]`, exactly as the tool stored it. */
44
+ export type PricePoint = [number, number];
45
+
46
+ /** A coin worth 0.000023 is not "0.00", and one worth 60000 is not "60000.000000". */
47
+ const priceDigits = (value: number) => (Math.abs(value) < 1 ? 6 : 2);
48
+
49
+ /**
50
+ * ISO 4217 is three letters and `Intl` throws a `RangeError` on anything that
51
+ * is not. The currency arrives from whatever the reader typed, so a typo must
52
+ * not take the whole card down.
53
+ */
54
+ const isCurrencyCode = (code: string) => /^[A-Za-z]{3}$/.test(code);
55
+
56
+ export function formatPrice(value: number, currency: string, locale: string): string {
57
+ const options: Intl.NumberFormatOptions = {
58
+ minimumFractionDigits: 2,
59
+ maximumFractionDigits: priceDigits(value),
60
+ };
61
+ if (!isCurrencyCode(currency)) {
62
+ return `${value.toLocaleString(locale, options)} ${currency.toUpperCase()}`;
63
+ }
64
+ return value.toLocaleString(locale, {
65
+ ...options,
66
+ style: 'currency',
67
+ currency: currency.toUpperCase(),
68
+ });
69
+ }
70
+
71
+ /**
72
+ * The axis labels a price scale, not a currency: no symbol, compact, and three
73
+ * significant digits — the chart's axis is 44px wide, and "60,000" does not fit
74
+ * in it where "60K" does.
75
+ */
76
+ const formatAxis = (value: number, locale: string) =>
77
+ value.toLocaleString(locale, { notation: 'compact', maximumSignificantDigits: 3 });
78
+
79
+ /**
80
+ * The scale names go through a translation whole — Spanish "billón" is 10¹²,
81
+ * not 10⁹ — so a suffix is never appended in one language and reused in the
82
+ * next.
83
+ */
84
+ const SCALES = [
85
+ { at: 1e12, key: 'trillion' },
86
+ { at: 1e9, key: 'billion' },
87
+ { at: 1e6, key: 'million' },
88
+ { at: 1e3, key: 'thousand' },
89
+ ] as const;
90
+
91
+ function formatCompact(
92
+ value: number,
93
+ namespace: string,
94
+ locale: string,
95
+ t: Translate,
96
+ fallback: string,
97
+ ): string {
98
+ const scale = SCALES.find((s) => Math.abs(value) >= s.at);
99
+ if (!scale) return fallback;
100
+ return t(`${namespace}.scale.${scale.key}`, {
101
+ value: (value / scale.at).toLocaleString(locale, { maximumFractionDigits: 2 }),
102
+ });
103
+ }
104
+
105
+ /**
106
+ * A field the row did not carry reads the same as one that could not be
107
+ * priced: `null` from the tool, `undefined` from an older row and a `NaN` that
108
+ * survived a parse are all "no number".
109
+ */
110
+ const quoted = (value: number | null | undefined): value is number =>
111
+ typeof value === 'number' && Number.isFinite(value);
112
+
113
+ /** A series point as the chart reads it, labelled with its moment. */
114
+ function toPoints(series: readonly PricePoint[], intraday: boolean, locale: string) {
115
+ return series.map(([at, value]) => ({
116
+ label: new Date(at).toLocaleString(
117
+ locale,
118
+ intraday
119
+ ? { hour: 'numeric', minute: '2-digit' }
120
+ : { day: 'numeric', month: 'short', year: 'numeric' },
121
+ ),
122
+ value,
123
+ }));
124
+ }
125
+
126
+ /** First-to-last change as a ratio, or none for a run that started at nothing. */
127
+ function runDelta(series: readonly PricePoint[]): number | undefined {
128
+ const first = (series[0] as PricePoint)[1];
129
+ const last = (series[series.length - 1] as PricePoint)[1];
130
+ return first === 0 ? undefined : (last - first) / first;
131
+ }
132
+
133
+ export interface PriceChartRange {
134
+ id: string;
135
+ label: string;
136
+ data: { label: string; value: number }[];
137
+ headline: number;
138
+ delta?: number;
139
+ }
140
+
141
+ /** What `LineChartCard` is handed, plus the lines the card cannot draw itself. */
142
+ export interface PriceChart {
143
+ title: string;
144
+ ranges: PriceChartRange[];
145
+ defaultRange: string;
146
+ format: (value: number) => string;
147
+ formatAxisValue: (value: number) => string;
148
+ /** Secondary lines under the chart, in reading order. */
149
+ notes: string[];
150
+ }
151
+
152
+ // ---------------------------------------------------------------------------
153
+ // Market
154
+ // ---------------------------------------------------------------------------
155
+
156
+ export interface MarketCardData {
157
+ id: string;
158
+ name: string;
159
+ symbol: string;
160
+ currency: string;
161
+ price?: number;
162
+ changePct?: number;
163
+ changeAbs?: number;
164
+ marketCap?: number;
165
+ volume24h?: number;
166
+ /** Optional per key: a row stored by an older version of the tool is not a crash. */
167
+ series: Record<string, PricePoint[] | undefined>;
168
+ }
169
+
170
+ /** The order the switcher offers, not the order the tool happens to store. */
171
+ const MARKET_RANGES = ['1D', '5D', '1M', '6M', 'YTD', '1Y', '5Y', 'MAX'] as const;
172
+
173
+ /**
174
+ * A quote as a line chart, or `null` when no range has two points to draw —
175
+ * the card then says the price in words.
176
+ *
177
+ * A range with one point cannot be drawn and a range with none was never
178
+ * stored, so neither is offered (YTD in the first days of January is the real
179
+ * case). 1D reports the tool's own change rather than the ends of the series,
180
+ * which starts whenever the window opened.
181
+ */
182
+ export function marketChart(data: MarketCardData, t: Translate, locale: string): PriceChart | null {
183
+ const series = data.series ?? {};
184
+ const ranges: PriceChartRange[] = [];
185
+ for (const id of MARKET_RANGES) {
186
+ const run = series[id];
187
+ if (!run || run.length < 2) continue;
188
+ ranges.push({
189
+ id,
190
+ label: t(`market.range.${id}`),
191
+ data: toPoints(run, id === '1D', locale),
192
+ headline: quoted(data.price) ? data.price : (run[run.length - 1] as PricePoint)[1],
193
+ delta: id === '1D' && quoted(data.changePct) ? data.changePct / 100 : runDelta(run),
194
+ });
195
+ }
196
+ if (ranges.length === 0) return null;
197
+
198
+ const format = (value: number) => formatPrice(value, data.currency, locale);
199
+ const compact = (value: number) => {
200
+ const scaled = formatCompact(value, 'market', locale, t, '');
201
+ return scaled === '' ? format(value) : `${scaled} ${data.currency.toUpperCase()}`;
202
+ };
203
+ const notes: string[] = [];
204
+ const intraday = (series['1D'] ?? []).map(([, price]) => price);
205
+ if (intraday.length >= 2) {
206
+ notes.push(
207
+ [
208
+ `${t('market.open')} ${format(intraday[0] as number)}`,
209
+ `${t('market.dayHigh')} ${format(Math.max(...intraday))}`,
210
+ `${t('market.dayLow')} ${format(Math.min(...intraday))}`,
211
+ ].join(' · '),
212
+ );
213
+ }
214
+ const totals = [
215
+ quoted(data.volume24h) ? `${t('market.volume')} ${compact(data.volume24h)}` : null,
216
+ quoted(data.marketCap) ? `${t('market.marketCap')} ${compact(data.marketCap)}` : null,
217
+ ].filter((part): part is string => part !== null);
218
+ if (totals.length > 0) notes.push(totals.join(' · '));
219
+
220
+ return {
221
+ title: `${data.name} · ${data.symbol}`,
222
+ ranges,
223
+ defaultRange: ranges.some((r) => r.id === '1D')
224
+ ? '1D'
225
+ : (ranges[0] as (typeof ranges)[number]).id,
226
+ format,
227
+ formatAxisValue: (value) => formatAxis(value, locale),
228
+ notes,
229
+ };
230
+ }
231
+
232
+ // ---------------------------------------------------------------------------
233
+ // FairCoin
234
+ // ---------------------------------------------------------------------------
235
+
236
+ export interface FairCoinCardData {
237
+ /** `null` is a real answer: the pool had no indexed price when asked. */
238
+ price: number | null;
239
+ changePct: number | null;
240
+ volume24h: number | null;
241
+ liquidityUsd: number | null;
242
+ marketCapUsd: number | null;
243
+ /** Where the number came from, which is the one thing this card cannot drop. */
244
+ source: string;
245
+ updatedAt: string;
246
+ /**
247
+ * Absent key and empty array mean different things: the tool omits a period
248
+ * whose fetch failed, and stores `[]` for one with no samples yet.
249
+ */
250
+ series: Record<string, PricePoint[] | undefined>;
251
+ }
252
+
253
+ /** Exactly what the explorer retains, in the order the switcher offers them. */
254
+ const FAIRCOIN_RANGES = ['24h', '7d', '30d', '1y', 'all'] as const;
255
+
256
+ /**
257
+ * FairCoin's price as a line chart, with its provenance ALWAYS in the notes.
258
+ *
259
+ * FairCoin has no exchange listing: the price is GeckoTerminal's indexed price
260
+ * for a thin pool, so where it came from and when is printed in the reading
261
+ * order — a number off a thin pool that looks exactly like an exchange quote
262
+ * is the one thing this card must not ship. `chart` is `null` when no period
263
+ * has two samples; the notes still say why.
264
+ */
265
+ export function faircoinChart(
266
+ data: FairCoinCardData,
267
+ t: Translate,
268
+ locale: string,
269
+ ): { chart: PriceChart | null; notes: string[] } {
270
+ const series = data.series ?? {};
271
+ const format = (value: number) => formatPrice(value, 'USD', locale);
272
+ const ranges: PriceChartRange[] = [];
273
+ for (const id of FAIRCOIN_RANGES) {
274
+ const run = series[id];
275
+ if (!run || run.length < 2) continue;
276
+ ranges.push({
277
+ id,
278
+ label: t(`faircoin.range.${id}`),
279
+ data: toPoints(run, id === '24h', locale),
280
+ headline: quoted(data.price) ? data.price : (run[run.length - 1] as PricePoint)[1],
281
+ delta: id === '24h' && quoted(data.changePct) ? data.changePct / 100 : runDelta(run),
282
+ });
283
+ }
284
+
285
+ const notes: string[] = [t('faircoin.indexed')];
286
+ const at = Date.parse(data.updatedAt);
287
+ // An unparseable stamp is left out rather than printed raw: the source alone
288
+ // is still true.
289
+ notes.push(
290
+ [
291
+ t('faircoin.source', { source: data.source }),
292
+ Number.isNaN(at)
293
+ ? null
294
+ : t('faircoin.updated', {
295
+ time: new Date(at).toLocaleString(locale, { dateStyle: 'medium', timeStyle: 'short' }),
296
+ }),
297
+ ]
298
+ .filter((part): part is string => part !== null)
299
+ .join(' · '),
300
+ );
301
+ if (!quoted(data.price)) notes.push(t('faircoin.noPriceHint'));
302
+ // A period the explorer never answered for is named; one it answered with too
303
+ // few samples is said out loud, so neither reads as a period nobody asked about.
304
+ const missing = FAIRCOIN_RANGES.filter((id) => series[id] === undefined);
305
+ if (missing.length > 0) {
306
+ notes.push(
307
+ t('faircoin.unavailable', {
308
+ ranges: missing.map((id) => t(`faircoin.range.${id}`)).join(', '),
309
+ }),
310
+ );
311
+ }
312
+ if (ranges.length === 0 && missing.length < FAIRCOIN_RANGES.length) {
313
+ const anySample = FAIRCOIN_RANGES.some((id) => (series[id]?.length ?? 0) === 1);
314
+ notes.push(t(anySample ? 'faircoin.noChart' : 'faircoin.noSamples'));
315
+ }
316
+ // FairCoin's scale strings are SUFFIXES ("K", " mil"), unlike the market's
317
+ // templates, so the number is written here and the word appended.
318
+ const compact = (value: number) => {
319
+ const scale = SCALES.find((s) => Math.abs(value) >= s.at);
320
+ if (!scale) return format(value);
321
+ const short = (value / scale.at).toLocaleString(locale, { maximumFractionDigits: 2 });
322
+ return `$${short}${t(`faircoin.scale.${scale.key}`)}`;
323
+ };
324
+ const totals = [
325
+ quoted(data.volume24h) ? `${t('faircoin.volume')} ${compact(data.volume24h)}` : null,
326
+ quoted(data.liquidityUsd) ? `${t('faircoin.liquidity')} ${compact(data.liquidityUsd)}` : null,
327
+ quoted(data.marketCapUsd) ? `${t('faircoin.marketCap')} ${compact(data.marketCapUsd)}` : null,
328
+ ].filter((part): part is string => part !== null);
329
+ if (totals.length > 0) notes.push(totals.join(' · '));
330
+
331
+ if (ranges.length === 0) return { chart: null, notes };
332
+ return {
333
+ chart: {
334
+ title: `${t('faircoin.name')} · ${t('faircoin.symbol')}`,
335
+ ranges,
336
+ defaultRange: ranges.some((r) => r.id === '24h')
337
+ ? '24h'
338
+ : (ranges[0] as (typeof ranges)[number]).id,
339
+ format,
340
+ formatAxisValue: (value) => formatAxis(value, locale),
341
+ notes: [],
342
+ },
343
+ notes,
344
+ };
345
+ }
346
+
347
+ // ---------------------------------------------------------------------------
348
+ // Weather
349
+ // ---------------------------------------------------------------------------
350
+
351
+ export interface WeatherCardData {
352
+ place: string;
353
+ timezone: string;
354
+ current: { temperature: number; humidity: number; windSpeed: number; condition: string };
355
+ hourly: { time: string; temperature: number; precipitationChance: number }[];
356
+ daily: { date: string; condition: string; high: number; low: number }[];
357
+ }
358
+
359
+ /** Celsius on the wire; what the reader sees is their choice, not the answer's. */
360
+ export type TemperatureUnit = 'C' | 'F';
361
+
362
+ export const degrees = (celsius: number, unit: TemperatureUnit) =>
363
+ `${Math.round(unit === 'C' ? celsius : (celsius * 9) / 5 + 32)}°`;
364
+
365
+ /**
366
+ * The weekday a forecast date names, in the reader's language.
367
+ *
368
+ * `YYYY-MM-DD` parses as UTC midnight, which is the previous evening west of
369
+ * Greenwich — so the day is read at noon UTC, which is the same calendar day
370
+ * everywhere a person lives.
371
+ */
372
+ export function forecastWeekday(date: string, locale: string): string {
373
+ const at = Date.parse(`${date}T12:00:00Z`);
374
+ if (Number.isNaN(at)) return date;
375
+ return new Date(at).toLocaleDateString(locale, { weekday: 'short', timeZone: 'UTC' });
376
+ }
377
+
378
+ // ---------------------------------------------------------------------------
379
+ // Scheduled task
380
+ // ---------------------------------------------------------------------------
381
+
382
+ export interface ScheduledTaskCardData {
383
+ id: string;
384
+ objective: string;
385
+ enabled: boolean;
386
+ trigger: AutomationTrigger;
387
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * A turn that did not get its answer, and what the thread shows for it.
3
+ *
4
+ * ## Why this is a thing at all
5
+ *
6
+ * A hosted-inference failure reaches the client as a typed error, never as
7
+ * an answer: on the open stream, an `{"error": {code, retryable, reference}}`
8
+ * frame and no stop chunk; before the stream opened, an HTTP 503/500 with the
9
+ * same envelope (`packages/api/src/routes/v1/chat-completions.ts`,
10
+ * `failTurn`). Older servers answered a failure BEFORE any output with HTTP
11
+ * 200 and an ordinary content delta — "all models are busy, try again in a few
12
+ * seconds" — flagged only by `alia_meta: { synthetic: true, retryable: true }`
13
+ * on the chunk; that flag is still read, so a stand-in is never rendered.
14
+ * Rendered as prose a stand-in reads as Alia declining; rolled back either
15
+ * vanishes with a toast, and once the toast is gone there is nothing on screen
16
+ * that says what happened or offers to try again.
17
+ *
18
+ * So a failed send keeps the person's turn in the thread and hangs this on it:
19
+ * a persistent error the row is drawn with, and the material a retry needs.
20
+ *
21
+ * ## What the server persists when the reply is synthetic — measured, not assumed
22
+ *
23
+ * Nothing. `saveConversationResult` is called from `lib/chat/provider-loop.ts`
24
+ * only after a stream COMPLETES (`:331`); every other exit returns
25
+ * `{ status: 'exhausted' }` (`:458`) or throws, and both the route's synthetic
26
+ * branch and its outer `catch` write the stand-in chunk without ever reaching
27
+ * the saver. So the user message of a failed turn is not in the database, and
28
+ * a retry can simply re-send it through the same path — no second user row is
29
+ * created because no first one was. (Were a turn ever saved before its tail
30
+ * failed, `saveConversation` converges storage on the client's history anyway,
31
+ * by full rewrite on divergence.)
32
+ */
33
+ export interface FailedTurn {
34
+ /** The person's message the missing answer belonged to. */
35
+ userMessageId: string;
36
+ /**
37
+ * The row the error is drawn UNDER: the user message when nothing came
38
+ * back, or the assistant message when real output arrived before the tail
39
+ * failed — in which case the output is kept and the error sits after it.
40
+ */
41
+ anchorMessageId: string;
42
+ /** Whether trying again is offered. `false` when the server said so. */
43
+ retryable: boolean;
44
+ /** Real output arrived before the failure; the error is a tail, not the answer. */
45
+ partial: boolean;
46
+ /** The server's own words, when it sent any worth repeating. */
47
+ detail?: string;
48
+ }
49
+
50
+ /** What a chunk's `alia_meta` says about itself. */
51
+ export interface GemieMeta {
52
+ /** The content is a stand-in the server wrote, not something the model said. */
53
+ synthetic: boolean;
54
+ /** Sending the same turn again is worth a try. Defaults to `true`. */
55
+ retryable: boolean;
56
+ /** Stable product error code; never an upstream/provider message. */
57
+ code?: string;
58
+ /** Safe Alia run identifier support can use to trace the failed turn. */
59
+ reference?: string;
60
+ retryAfter?: number;
61
+ }
62
+
63
+ /**
64
+ * Read `alia_meta` off a parsed stream chunk.
65
+ *
66
+ * Tolerant of every shape a chunk can have — no meta, meta with only one of
67
+ * the flags, a non-object where an object was expected — because this runs
68
+ * on every content delta and a throw here would take the whole stream down.
69
+ */
70
+ export function readGemieMeta(chunk: unknown): GemieMeta {
71
+ const meta = (chunk as { alia_meta?: unknown } | null | undefined)?.alia_meta;
72
+ if (meta === null || typeof meta !== 'object') {
73
+ return { synthetic: false, retryable: true };
74
+ }
75
+ const { synthetic, retryable, error } = meta as {
76
+ synthetic?: unknown;
77
+ retryable?: unknown;
78
+ error?: unknown;
79
+ };
80
+ const failure =
81
+ error !== null && typeof error === 'object'
82
+ ? (error as { code?: unknown; reference?: unknown; retryAfter?: unknown })
83
+ : null;
84
+ return {
85
+ synthetic: synthetic === true,
86
+ retryable: retryable !== false,
87
+ ...(typeof failure?.code === 'string' ? { code: failure.code } : {}),
88
+ ...(typeof failure?.reference === 'string' ? { reference: failure.reference } : {}),
89
+ ...(typeof failure?.retryAfter === 'number' ? { retryAfter: failure.retryAfter } : {}),
90
+ };
91
+ }
92
+
93
+ /**
94
+ * The line under a failed turn's card: the stable code and the run reference.
95
+ *
96
+ * Never the server's prose. The card's own line is the app's, in the reader's
97
+ * language; this is what support needs, and both halves are language-free.
98
+ * Empty when the server sent neither.
99
+ */
100
+ export function failureDetail(failure: { code?: string; reference?: string }): string | undefined {
101
+ const detail = [
102
+ failure.code,
103
+ failure.reference === undefined ? undefined : `Ref ${failure.reference}`,
104
+ ]
105
+ .filter((value): value is string => typeof value === 'string' && value !== '')
106
+ .join(' · ');
107
+ return detail === '' ? undefined : detail;
108
+ }
@@ -0,0 +1,21 @@
1
+ /** Fence asynchronous host preparation without waiting for an uncooperative host. */
2
+ export function awaitTurnPreparation<T>(pending: Promise<T>, signal: AbortSignal): Promise<T> {
3
+ return new Promise<T>((resolve, reject) => {
4
+ const aborted = () => {
5
+ signal.removeEventListener('abort', aborted);
6
+ reject(signal.reason);
7
+ };
8
+ pending.then(
9
+ (value) => {
10
+ signal.removeEventListener('abort', aborted);
11
+ resolve(value);
12
+ },
13
+ (error) => {
14
+ signal.removeEventListener('abort', aborted);
15
+ reject(error);
16
+ },
17
+ );
18
+ if (signal.aborted) aborted();
19
+ else signal.addEventListener('abort', aborted, { once: true });
20
+ });
21
+ }
@@ -0,0 +1,172 @@
1
+ import type { MessagePlan, ResearchProgress } from '../types';
2
+
3
+ /**
4
+ * The canonical tool invocation: streaming, the conversation hooks and the
5
+ * thread UI all read this one shape.
6
+ */
7
+ export interface ToolInvocation {
8
+ toolCallId: string;
9
+ toolName: string;
10
+ state: 'partial-call' | 'call' | 'result';
11
+ args?: Record<string, unknown>;
12
+ // Tool output is dynamically shaped per tool and consumed structurally
13
+ // (e.g. `result.results`, `result.url`) by the thread UI; typing it more
14
+ // narrowly would require validating every tool's output shape.
15
+ // biome-ignore lint/suspicious/noExplicitAny: structural per-tool output, see above
16
+ result?: any;
17
+ }
18
+
19
+ /** What a message carries to the model: plain text, or multi-part once images are attached. */
20
+ export type MessageContent = string | Array<{ type: string; [key: string]: unknown }>;
21
+
22
+ export interface Message {
23
+ id: string;
24
+ role: 'user' | 'assistant' | 'system';
25
+ content: MessageContent;
26
+ /** The emoji the person left on this message, as the server holds them. */
27
+ reactions?: string[];
28
+ /** Server revision of the reaction snapshot; omitted by older servers. */
29
+ reactionRevision?: number;
30
+ /** Extended thinking content (when thinking mode is enabled). */
31
+ thinking?: string;
32
+ toolInvocations?: ToolInvocation[];
33
+ /** Voice fields (optional, only present for voice-originated messages). */
34
+ source?: 'text' | 'voice';
35
+ /** Speaker identity in voice mode. */
36
+ speaker?: 'primary';
37
+ /**
38
+ * The turn is being streamed into this message right now.
39
+ *
40
+ * Set by `useConversationStream` on the assistant placeholder it appends and
41
+ * cleared by it when the stream ends, whichever way it ends; voice sets it
42
+ * on its own rows. Absent on a message read back from the server.
43
+ */
44
+ isStreaming?: boolean;
45
+ /**
46
+ * How the turn that wrote this message ended, once it has: on its own
47
+ * (`completed`), on an error (`failed`), or because the person stopped it
48
+ * (`cancelled`). Stamped by `useConversationStream` alongside clearing
49
+ * `isStreaming`, and absent on a message the server sent.
50
+ */
51
+ turnOutcome?: 'completed' | 'failed' | 'cancelled';
52
+ /**
53
+ * The server does not hold this message yet, so nothing can be addressed to
54
+ * it by id — a vote, a read-aloud clip stored on it.
55
+ *
56
+ * Set on every message of a turn the stream sends (the question, the reply,
57
+ * a delegated agent's answer) and cleared when that turn completes, which is
58
+ * when the server has stored it under these same ids. A turn that failed or
59
+ * was stopped keeps it.
60
+ */
61
+ unsaved?: true;
62
+ /**
63
+ * The agent that wrote this message: a consultation (`consultAgent`, ADR 0020 §5), a group
64
+ * member, or the direct agent's proactive/scheduled reply. Identity alone does not mean
65
+ * delegation: the conversation's members speak directly to the person.
66
+ *
67
+ * `character` is the agent's look as the server stores it (JSON), parsed
68
+ * where it is drawn; absent, the default look.
69
+ */
70
+ agentInfo?: {
71
+ id: string;
72
+ name: string;
73
+ character?: unknown;
74
+ handle?: string;
75
+ color?: string;
76
+ };
77
+ /**
78
+ * When the message was written, ISO — what the date separators are derived
79
+ * from, in the reader's own timezone. Absent means the turn has not been
80
+ * persisted yet and carries no stamp of its own.
81
+ */
82
+ createdAt?: string;
83
+ // Streaming UI metadata (deep research, plan preview)
84
+ researchProgress?: ResearchProgress;
85
+ plan?: MessagePlan;
86
+ }
87
+
88
+ export interface Conversation {
89
+ id: string;
90
+ title: string;
91
+ lastMessage?: string;
92
+ source?: string;
93
+ /**
94
+ * The agent this conversation is a stretch of, or none.
95
+ *
96
+ * NULLABLE, not optional-absent: the column is `agent_id text` and the list
97
+ * route sends `c.agentId` straight through, so an ordinary conversation
98
+ * arrives carrying an explicit `null`.
99
+ */
100
+ agentId?: string | null;
101
+ /**
102
+ * The agents of a GROUP conversation, in the order they answer; absent on any other. A group has
103
+ * no lead: every message is answered by each member in turn (`agentId` is `null`).
104
+ */
105
+ memberAgentIds?: string[];
106
+ /**
107
+ * The space this conversation is the ROOM of (ADR 0028), or `null`. Set only on a space's room, a
108
+ * group conversation whose `memberAgentIds` are the space's agents; a client files it under its
109
+ * space instead of among Alia's chats or the group chats.
110
+ */
111
+ spaceId?: string | null;
112
+ /**
113
+ * The thread row this conversation is a stretch of, or `null`. Set on the stretches of Alia's
114
+ * thread (`useGemieThread`): a client files them under the thread, never among her loose chats,
115
+ * though both carry `agentId: null` (Alia).
116
+ */
117
+ threadId?: string | null;
118
+ /** The app the conversation started in, by its slug, or `null` for Alia's own surfaces. */
119
+ app?: string | null;
120
+ createdAt: Date;
121
+ updatedAt: Date;
122
+ messages: Message[];
123
+ }
124
+
125
+ /** The run a delegated agent started for a turn: its session is `turnId`, in the agent's own room. */
126
+ export interface AgentRun {
127
+ turnId: string;
128
+ agentId: string;
129
+ }
130
+
131
+ /** One page of the paginated conversation list. */
132
+ export interface ConversationsPage {
133
+ conversations: Conversation[];
134
+ nextCursor: string | null;
135
+ hasMore: boolean;
136
+ }
137
+
138
+ /** React Query infinite-query cache shape for the conversation list. */
139
+ export interface ConversationsInfiniteData {
140
+ pages: ConversationsPage[];
141
+ pageParams: unknown[];
142
+ }
143
+
144
+ /** What a chat turn is sent with. */
145
+ export interface SendOptions {
146
+ /** `null` explicitly withholds MCP tools; omission preserves legacy callers. */
147
+ mcpServerId?: string | null;
148
+ /**
149
+ * The skills chosen for THIS message, by name. Per turn rather than per
150
+ * session; omitted means the person chose none.
151
+ */
152
+ skillNames?: string[];
153
+ }
154
+
155
+ /** A resource an automation acts on or listens to. */
156
+ export interface AutomationResource {
157
+ appId: string;
158
+ effectiveAccountId: string;
159
+ resourceType: string;
160
+ resourceId: string;
161
+ }
162
+
163
+ /** What starts a scheduled task. */
164
+ export type AutomationTrigger =
165
+ | { type: 'manual' }
166
+ | {
167
+ type: 'event';
168
+ appId: string | null;
169
+ eventType: string | null;
170
+ resource?: AutomationResource | null;
171
+ }
172
+ | { type: 'schedule'; cron: string | null; timezone: string | null };