@gemies/sdk 1.0.0 → 2.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # @gemies/sdk
2
2
 
3
+ ## 2.0.0
4
+
5
+ - **Lighter chat on web: the chart cards come from their own Bloom entries.** `ChartRenderer` and
6
+ `ToolResultCard` import `@oxy.so/bloom/chart-cards/bar-list` and `/line` instead of the
7
+ `chart-cards` root, which is every chart Bloom draws. Measured in the Gemies web export, the
8
+ first paint of `/` carries 50,210 B of chart code instead of 188,724 B. Both entries exist in
9
+ every Bloom the peer range admits (`>=17.41.0`), so nothing changes for a consumer.
10
+ - **Breaking: `@gemies/sdk/metro` is gone.** `withGemieGranularCharts` redirected those same two
11
+ imports at resolution time, for apps whose Bloom did not yet ship the chart entries; now the
12
+ SDK imports them itself, so a consumer that wrapped its Metro config with it removes the
13
+ wrapper and changes nothing else. No app used it.
14
+
15
+ ## 1.1.0
16
+
17
+ - **New entry `@gemies/sdk/accounts`** (Gemies ADR 0035): `GemieAccounts`, the panel that links a
18
+ person's WhatsApp or Telegram account to a gemie (QR code, live status, last message, who the
19
+ gemie answers and in groups, the chats it answers, removal), and its hooks
20
+ (`useGemieAccounts`, `useGemieAccountQr`, `useGemieAccountChats`, `useGemieAccountMutations`)
21
+ with their types. It draws no frame of its own: the host puts it in its card or settings page and
22
+ hands its translator (`t`, keys `gemie.accounts.*`; English and Spanish in the SDK). It needs
23
+ `react-native-qrcode-svg` (a new peer dependency, which `@oxy.so/services` already requires).
24
+ - **`ALIA_GEMIE_ID`** (root and `/accounts`): the fixed id of Alia's gemie, for a client that
25
+ addresses her by id (her thread, her connected accounts).
26
+ - **The connected-account tools are one set for every platform:** `listAccountChats`,
27
+ `readAccountMessages` and `sendAccountMessage` replace `getWhatsAppChats`,
28
+ `getWhatsAppMessages` and `sendWhatsAppMessage` in the tool labels, icons and the thought panel
29
+ (`thought.tool.*`, en/es). The unused `tasks.tool.pill.sendSignal` copy is gone (Signal is retired).
30
+
3
31
  ## 1.0.0
4
32
 
5
33
  **`@alia.onl/sdk` becomes `@gemies/sdk`** (Gemies ADR 0034 §6), with no bridge package. The code is
package/README.md CHANGED
@@ -17,43 +17,6 @@ hooks are named `Gemie*` (`GemieChatContent`, `GemieChatSheet`, `GemieAvatar`, `
17
17
  the default API is `https://api.gemies.ai` and the shared web origin is `https://gemies.ai`. The
18
18
  mapping is in [`CHANGELOG.md`](./CHANGELOG.md) under 1.0.0.
19
19
 
20
- ## Optional granular chart imports for Metro
21
-
22
- The standard SDK entries and Bloom peer range are unchanged. Apps that install a Bloom
23
- version exposing `chart-cards/bar-list` and `chart-cards/line` can opt into a narrower
24
- chart graph by wrapping their **finished** Metro configuration:
25
-
26
- ```js
27
- const { withGemieGranularCharts } = require('@gemies/sdk/metro');
28
-
29
- module.exports = withGemieGranularCharts(existingMetroConfig);
30
- ```
31
-
32
- This Node-only entry wraps the previous resolver and redirects two verified chart imports
33
- in this SDK copy. It delegates extra resolution probes to that resolver, so resolver
34
- implementations with side effects will observe those calls. It checks that the original
35
- barrel and both granular imports resolve to
36
- the same physical Bloom copy for the original importer and the adapter. Both subpaths
37
- must be explicit `exports` keys resolving under the active Metro conditions to files
38
- inside that copy; arrays, patterns and redirects to other files are not supported.
39
- The SDK importer hashes are rechecked on affected resolutions, including in watch mode.
40
- Detection uses the registered paths and their real paths; new aliases introduced later
41
- may be treated as unregistered, so restart Metro after changing SDK links.
42
- Missing exports,
43
- an altered SDK importer or incompatible metadata fail with an explicit build error; the
44
- normal SDK does not require those exports when this option is not used. File hashes detect
45
- changes requiring review; they do not authenticate packages.
46
-
47
- Apply the wrapper once, after other Metro wrappers. Reapplying it directly throws;
48
- register all copies together instead. Opaque wrappers or cloned configurations can
49
- hide the marker; do not apply this helper again after composing them.
50
- Multiple installed SDK copies are not discovered automatically. To opt in other copies,
51
- pass `{ additionalSdkRoots: ['/absolute/path/to/sdk'] }`; each must ship matching opt-in
52
- metadata. Unregistered copies retain their original imports and may still include the chart
53
- barrel. This does not deduplicate React, Bloom or SDK providers, nor prove a bundle-size
54
- reduction. Review importers, update the version and hashes in `chart-importers.json`, and
55
- run the Metro tests when updating the SDK package or those files.
56
-
57
20
  ## Install
58
21
 
59
22
  ```sh
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gemies/sdk",
3
- "version": "1.0.0",
3
+ "version": "2.0.0",
4
4
  "description": "The Gemies SDK: the conversation runtime, chat UI, voice calls and dictation for Oxy apps that talk to a gemie",
5
5
  "main": "src/index.ts",
6
6
  "react-native": "src/index.ts",
@@ -8,6 +8,7 @@
8
8
  "types": "src/index.ts",
9
9
  "exports": {
10
10
  ".": "./src/index.ts",
11
+ "./accounts": "./src/accounts.ts",
11
12
  "./ask": "./src/ask.ts",
12
13
  "./ask/eager": "./src/ask-eager.ts",
13
14
  "./ask/text": "./src/ask-text.ts",
@@ -17,10 +18,6 @@
17
18
  "./csp": "./src/csp.ts",
18
19
  "./dictation": "./src/dictation.ts",
19
20
  "./model": "./src/runtime/model.ts",
20
- "./metro": {
21
- "types": "./src/metro/index.d.cts",
22
- "default": "./src/metro/index.cjs"
23
- },
24
21
  "./runtime": "./src/runtime/index.ts",
25
22
  "./text": "./src/text.ts",
26
23
  "./tools": "./src/tools.ts",
@@ -48,7 +45,6 @@
48
45
  "scripts": {
49
46
  "typecheck": "tsc --noEmit",
50
47
  "test": "vitest run",
51
- "test:metro": "node --test scripts/metro/opt-in.node.cjs",
52
48
  "check:entries": "node scripts/check-entry-isolation.mjs",
53
49
  "check:entry-types": "node scripts/check-entry-types.mjs"
54
50
  },
@@ -83,7 +79,8 @@
83
79
  "expo-file-system": "^57.0.0 || ^58.0.0",
84
80
  "expo-web-browser": "^57.0.0 || ^58.0.0",
85
81
  "react-native-css": "^3.0.7",
86
- "react-native-audio-api": "^0.13.6"
82
+ "react-native-audio-api": "^0.13.6",
83
+ "react-native-qrcode-svg": "^6.3.21"
87
84
  },
88
85
  "peerDependenciesMeta": {
89
86
  "nativewind": {
@@ -95,10 +92,10 @@
95
92
  },
96
93
  "devDependencies": {
97
94
  "@types/react-test-renderer": "^19.1.0",
98
- "metro-resolver": "0.87.1",
95
+ "react-native-audio-api": "0.13.6",
96
+ "react-native-qrcode-svg": "^6.3.21",
99
97
  "react-test-renderer": "19.3.0",
100
98
  "typescript": "^5.9.3",
101
- "vitest": "^4.1.10",
102
- "react-native-audio-api": "0.13.6"
99
+ "vitest": "^4.1.10"
103
100
  }
104
101
  }
@@ -0,0 +1,29 @@
1
+ /// <reference types="nativewind/types" />
2
+ /**
3
+ * The connected-accounts leaf entry (ADR 0035): the WhatsApp and Telegram accounts a person links
4
+ * to a gemie, and the panel that manages them. Its own entry so an app that does not draw it never
5
+ * reaches its QR encoder.
6
+ */
7
+ export { GemieAccounts } from './components/GemieAccounts';
8
+ export { ALIA_GEMIE_ID } from './lib/alia-gemie';
9
+ export type { GemieAccountsProps } from './components/GemieAccounts';
10
+ export {
11
+ GEMIE_ACCOUNT_GROUP_REPLIES,
12
+ GEMIE_ACCOUNT_PLATFORMS,
13
+ GEMIE_ACCOUNT_REPLIES,
14
+ GEMIE_ACCOUNT_STATUSES,
15
+ useGemieAccountChats,
16
+ useGemieAccountMutations,
17
+ useGemieAccountQr,
18
+ useGemieAccounts,
19
+ } from './runtime/gemie-accounts';
20
+ export type {
21
+ GemieAccount,
22
+ GemieAccountChat,
23
+ GemieAccountGroupReplies,
24
+ GemieAccountLink,
25
+ GemieAccountPlatform,
26
+ GemieAccountReplies,
27
+ GemieAccountsAnswer,
28
+ GemieAccountStatus,
29
+ } from './runtime/gemie-accounts';
@@ -0,0 +1,433 @@
1
+ import { Button } from '@oxy.so/bloom/button';
2
+ import {
3
+ Select,
4
+ SelectContent,
5
+ SelectIcon,
6
+ SelectItem,
7
+ SelectItemText,
8
+ SelectTrigger,
9
+ SelectValue,
10
+ } from '@oxy.so/bloom/select';
11
+ import * as Skeleton from '@oxy.so/bloom/skeleton';
12
+ import { confirm } from '@oxy.so/bloom/surfaces';
13
+ import { Switch } from '@oxy.so/bloom/switch';
14
+ import { toast } from '@oxy.so/bloom/toast';
15
+ import { Text } from '@oxy.so/bloom/typography';
16
+ import { useCallback, useEffect, useState } from 'react';
17
+ import { View } from 'react-native';
18
+ import QRCode from 'react-native-qrcode-svg';
19
+ import { englishCopy, type Translate } from '../lib/copy';
20
+ import { errorMessage } from '../runtime/error-utils';
21
+ import {
22
+ GEMIE_ACCOUNT_STATUSES,
23
+ useGemieAccountChats,
24
+ useGemieAccountMutations,
25
+ useGemieAccountQr,
26
+ useGemieAccounts,
27
+ type GemieAccount,
28
+ type GemieAccountGroupReplies,
29
+ type GemieAccountLink,
30
+ type GemieAccountPlatform,
31
+ type GemieAccountReplies,
32
+ } from '../runtime/gemie-accounts';
33
+
34
+ /** This component's own strings. */
35
+ const K = 'gemie.accounts';
36
+
37
+ /** Product names, the same in every language. */
38
+ const PLATFORM_LABELS: Record<GemieAccountPlatform, string> = {
39
+ whatsapp: 'WhatsApp',
40
+ telegram: 'Telegram',
41
+ };
42
+
43
+ /** One row of the list: the same rhythm as a settings row, a divider above all but the first. */
44
+ function Row({ children, first }: { children: React.ReactNode; first?: boolean }) {
45
+ return (
46
+ <View className={`gap-3 py-2.5 pe-2.5 ${first ? '' : 'border-t border-border'}`}>
47
+ {children}
48
+ </View>
49
+ );
50
+ }
51
+
52
+ function Choice<T extends string>({
53
+ label,
54
+ value,
55
+ items,
56
+ disabled,
57
+ onChange,
58
+ }: {
59
+ label: string;
60
+ value: T;
61
+ items: readonly { value: T; label: string }[];
62
+ disabled: boolean;
63
+ onChange: (value: T) => void;
64
+ }) {
65
+ return (
66
+ <View className="gap-1">
67
+ <Text variant="body-2-regular" className="text-text-secondary">
68
+ {label}
69
+ </Text>
70
+ <Select
71
+ size="sm"
72
+ value={value}
73
+ onValueChange={(next) => onChange(next as T)}
74
+ disabled={disabled}
75
+ >
76
+ <SelectTrigger label={label}>
77
+ <SelectValue placeholder={label} />
78
+ <SelectIcon />
79
+ </SelectTrigger>
80
+ <SelectContent
81
+ label={label}
82
+ items={items.map((item) => ({ ...item, id: item.value }))}
83
+ width={280}
84
+ valueExtractor={(item) => item.id}
85
+ renderItem={(item) => (
86
+ <SelectItem value={item.id} label={item.label}>
87
+ <SelectItemText>{item.label}</SelectItemText>
88
+ </SelectItem>
89
+ )}
90
+ />
91
+ </Select>
92
+ </View>
93
+ );
94
+ }
95
+
96
+ /** The account being linked: its QR code until the person scans it with the platform's app. */
97
+ function LinkingAccount({
98
+ gemieId,
99
+ name,
100
+ platform,
101
+ link,
102
+ t,
103
+ onDone,
104
+ onCancel,
105
+ }: {
106
+ gemieId: string;
107
+ name: string;
108
+ platform: GemieAccountPlatform;
109
+ link: GemieAccountLink;
110
+ t: Translate;
111
+ onDone: () => void;
112
+ onCancel: () => void;
113
+ }) {
114
+ const { data } = useGemieAccountQr(gemieId, link);
115
+ const status = data?.status ?? 'qr-pending';
116
+ const label = PLATFORM_LABELS[platform];
117
+
118
+ useEffect(() => {
119
+ if (status === 'qr-pending') return;
120
+ if (status === 'connected') toast.success(t(`${K}.linked`, { platform: label, name }));
121
+ else toast.error(t(`${K}.linkExpired`, { platform: label }));
122
+ onDone();
123
+ }, [label, name, onDone, status, t]);
124
+
125
+ return (
126
+ <Row>
127
+ <Text variant="body-2-semibold">{t(`${K}.scanTitle`, { platform: label })}</Text>
128
+ <Text variant="body-2-regular" className="text-text-secondary">
129
+ {t(`${K}.scan.${platform}`)}
130
+ </Text>
131
+ {data?.qr ? (
132
+ // The code carries its own white quiet zone, so it scans on a dark theme too.
133
+ <QRCode value={data.qr} size={200} quietZone={12} backgroundColor="white" color="black" />
134
+ ) : (
135
+ // The code's own shape while the provider makes it: the same square, the quiet zone in.
136
+ <Skeleton.Region>
137
+ <Skeleton.Box width={224} height={224} />
138
+ </Skeleton.Region>
139
+ )}
140
+ <View className="flex-row">
141
+ <Button size="sm" appearance="outline" tone="neutral" onPress={onCancel}>
142
+ {t(`${K}.cancel`)}
143
+ </Button>
144
+ </View>
145
+ </Row>
146
+ );
147
+ }
148
+
149
+ /** The chats a `chosen` account answers, picked from its recent ones. */
150
+ function ChosenChats({
151
+ gemieId,
152
+ account,
153
+ t,
154
+ }: {
155
+ gemieId: string;
156
+ account: GemieAccount;
157
+ t: Translate;
158
+ }) {
159
+ const { data: chats, isPending } = useGemieAccountChats(gemieId, account._id);
160
+ const { setReplies } = useGemieAccountMutations(gemieId);
161
+
162
+ const toggle = async (chatId: string, on: boolean) => {
163
+ const replyChatIds = on
164
+ ? [...account.replyChatIds, chatId]
165
+ : account.replyChatIds.filter((id) => id !== chatId);
166
+ try {
167
+ await setReplies.mutateAsync({ accountId: account._id, replyChatIds });
168
+ } catch {
169
+ toast.error(t(`${K}.saveFailed`));
170
+ }
171
+ };
172
+
173
+ if (isPending) {
174
+ return (
175
+ <Skeleton.Region>
176
+ <View className="gap-2">
177
+ {[0, 1, 2].map((row) => (
178
+ <Skeleton.Box key={row} width={180} height={14} />
179
+ ))}
180
+ </View>
181
+ </Skeleton.Region>
182
+ );
183
+ }
184
+ if (!chats?.length) {
185
+ return (
186
+ <Text variant="body-2-regular" className="text-text-secondary">
187
+ {t(`${K}.noChats`)}
188
+ </Text>
189
+ );
190
+ }
191
+ return (
192
+ <View className="gap-1">
193
+ {chats.map((chat) => (
194
+ <View key={chat.chatId} className="flex-row items-center justify-between gap-3 py-1">
195
+ <Text variant="body-2-regular" numberOfLines={1} className="flex-1">
196
+ {chat.kind === 'group' ? t(`${K}.groupChat`, { name: chat.name }) : chat.name}
197
+ </Text>
198
+ <Switch
199
+ accessibilityLabel={t(`${K}.answerChat`, { name: chat.name })}
200
+ checked={account.replyChatIds.includes(chat.chatId)}
201
+ disabled={setReplies.isPending}
202
+ onCheckedChange={(on) => toggle(chat.chatId, on)}
203
+ />
204
+ </View>
205
+ ))}
206
+ </View>
207
+ );
208
+ }
209
+
210
+ /** One linked account: its live status, who it answers, and removing it. */
211
+ function AccountRow({
212
+ gemieId,
213
+ name,
214
+ account,
215
+ first,
216
+ t,
217
+ }: {
218
+ gemieId: string;
219
+ name: string;
220
+ account: GemieAccount;
221
+ first: boolean;
222
+ t: Translate;
223
+ }) {
224
+ const { setReplies, remove } = useGemieAccountMutations(gemieId);
225
+ const platform = PLATFORM_LABELS[account.platform] ?? account.platform;
226
+ const status = GEMIE_ACCOUNT_STATUSES.includes(account.status)
227
+ ? t(`${K}.status.${account.status}`)
228
+ : account.status;
229
+ const identifier = account.phoneNumber || account.displayName;
230
+ const live = account.status === 'connected' || account.status === 'disconnected';
231
+
232
+ const save = async (patch: {
233
+ replies?: GemieAccountReplies;
234
+ groupReplies?: GemieAccountGroupReplies;
235
+ }) => {
236
+ try {
237
+ await setReplies.mutateAsync({ accountId: account._id, ...patch });
238
+ } catch {
239
+ toast.error(t(`${K}.saveFailed`));
240
+ }
241
+ };
242
+
243
+ const handleRemove = async () => {
244
+ const ok = await confirm({
245
+ title: t(`${K}.removeTitle`, { platform }),
246
+ description: t(`${K}.removeDescription`, { platform, name }),
247
+ confirmLabel: t(`${K}.remove`),
248
+ cancelLabel: t(`${K}.cancel`),
249
+ destructive: true,
250
+ });
251
+ if (!ok) return;
252
+ try {
253
+ await remove.mutateAsync(account._id);
254
+ toast.success(t(`${K}.removed`, { platform }));
255
+ } catch {
256
+ toast.error(t(`${K}.removeFailed`));
257
+ }
258
+ };
259
+
260
+ return (
261
+ <Row first={first}>
262
+ <View className="flex-row flex-wrap items-center justify-between gap-3">
263
+ <View className="flex-1 gap-0.5">
264
+ <Text variant="body-2-semibold">{platform}</Text>
265
+ <Text variant="body-2-regular">{[identifier, status].filter(Boolean).join(' · ')}</Text>
266
+ <Text variant="body-2-regular" className="text-text-secondary">
267
+ {account.lastActiveAt
268
+ ? t(`${K}.lastMessage`, { when: new Date(account.lastActiveAt).toLocaleString() })
269
+ : t(`${K}.noMessagesYet`)}
270
+ </Text>
271
+ </View>
272
+ <Button
273
+ size="sm"
274
+ appearance="outline"
275
+ tone="danger"
276
+ accessibilityLabel={t(`${K}.removeNamed`, { platform })}
277
+ disabled={remove.isPending}
278
+ onPress={handleRemove}
279
+ >
280
+ {t(`${K}.remove`)}
281
+ </Button>
282
+ </View>
283
+ {live ? (
284
+ <>
285
+ <Choice
286
+ label={t(`${K}.repliesLabel`, { name })}
287
+ value={account.replies}
288
+ disabled={setReplies.isPending}
289
+ items={[
290
+ { value: 'everyone', label: t(`${K}.replies.everyone`) },
291
+ { value: 'chosen', label: t(`${K}.replies.chosen`) },
292
+ { value: 'nobody', label: t(`${K}.replies.nobody`, { name }) },
293
+ ]}
294
+ onChange={(replies) => save({ replies })}
295
+ />
296
+ {account.replies === 'chosen' ? (
297
+ <ChosenChats gemieId={gemieId} account={account} t={t} />
298
+ ) : null}
299
+ {account.replies !== 'nobody' ? (
300
+ <Choice
301
+ label={t(`${K}.groupRepliesLabel`)}
302
+ value={account.groupReplies}
303
+ disabled={setReplies.isPending}
304
+ items={[
305
+ { value: 'mentions', label: t(`${K}.groupReplies.mentions`) },
306
+ { value: 'never', label: t(`${K}.groupReplies.never`) },
307
+ ]}
308
+ onChange={(groupReplies) => save({ groupReplies })}
309
+ />
310
+ ) : null}
311
+ </>
312
+ ) : null}
313
+ </Row>
314
+ );
315
+ }
316
+
317
+ export interface GemieAccountsProps {
318
+ /** The gemie the accounts are linked to (Alia's id, in the Alia app). */
319
+ gemieId: string;
320
+ /** The gemie's name, as the copy says it. */
321
+ name: string;
322
+ /** The host's translator, keyed as `gemie.accounts.*`; English when absent. */
323
+ t?: Translate;
324
+ }
325
+
326
+ /**
327
+ * The WhatsApp and Telegram accounts the person linked to a gemie (ADR 0035), drawn without a
328
+ * frame of its own so each app puts it in its own: the Gemies app in a gemie's editor card, the
329
+ * Alia app in its settings. The gemie answers what arrives on them as the person chooses, and only
330
+ * its own turns can read or send through them. Only what this deployment can link is offered.
331
+ */
332
+ export function GemieAccounts({ gemieId, name, t = englishCopy }: GemieAccountsProps) {
333
+ const { data, isPending, isError } = useGemieAccounts(gemieId);
334
+ const { link, remove } = useGemieAccountMutations(gemieId);
335
+ const [linking, setLinking] = useState<{
336
+ platform: GemieAccountPlatform;
337
+ link: GemieAccountLink;
338
+ } | null>(null);
339
+ const linked = useCallback(() => setLinking(null), []);
340
+
341
+ if (isPending) {
342
+ return (
343
+ <Skeleton.Region>
344
+ <View className="gap-3 py-2.5">
345
+ <Skeleton.Box width={260} height={14} />
346
+ <Skeleton.Box width={160} height={14} />
347
+ </View>
348
+ </Skeleton.Region>
349
+ );
350
+ }
351
+
352
+ const handleLink = async (platform: GemieAccountPlatform) => {
353
+ try {
354
+ setLinking({ platform, link: await link.mutateAsync(platform) });
355
+ } catch (error) {
356
+ toast.error(
357
+ t(`${K}.linkFailed`, {
358
+ platform: PLATFORM_LABELS[platform],
359
+ reason: errorMessage(error, t(`${K}.tryAgain`)),
360
+ }),
361
+ );
362
+ }
363
+ };
364
+
365
+ const handleCancel = async () => {
366
+ const pending = linking;
367
+ setLinking(null);
368
+ if (pending) await remove.mutateAsync(pending.link.accountId).catch(() => {});
369
+ };
370
+
371
+ // The account being linked shows as its QR code, not as a row beside it.
372
+ const accounts = (data?.accounts ?? []).filter(
373
+ (account) => account._id !== linking?.link.accountId,
374
+ );
375
+ const platforms = data?.platforms ?? [];
376
+
377
+ return (
378
+ <View>
379
+ <Row first>
380
+ <Text variant="body-2-regular" className="text-text-secondary">
381
+ {isError ? t(`${K}.loadFailed`) : t(`${K}.description`, { name })}
382
+ </Text>
383
+ </Row>
384
+ {accounts.map((account) => (
385
+ <AccountRow
386
+ key={account._id}
387
+ gemieId={gemieId}
388
+ name={name}
389
+ account={account}
390
+ first={false}
391
+ t={t}
392
+ />
393
+ ))}
394
+ {linking ? (
395
+ <LinkingAccount
396
+ gemieId={gemieId}
397
+ name={name}
398
+ platform={linking.platform}
399
+ link={linking.link}
400
+ t={t}
401
+ onDone={linked}
402
+ onCancel={handleCancel}
403
+ />
404
+ ) : isError ? null : (
405
+ <Row>
406
+ <Text variant="body-2-semibold">{t(`${K}.link`)}</Text>
407
+ {platforms.length === 0 ? (
408
+ <Text variant="body-2-regular" className="text-text-secondary">
409
+ {t(`${K}.unavailable`)}
410
+ </Text>
411
+ ) : (
412
+ <View className="flex-row gap-2">
413
+ {platforms.map((platform) => (
414
+ <Button
415
+ key={platform}
416
+ size="sm"
417
+ appearance="outline"
418
+ tone="neutral"
419
+ accessibilityLabel={t(`${K}.linkNamed`, { platform: PLATFORM_LABELS[platform] })}
420
+ loading={link.isPending && link.variables === platform}
421
+ disabled={link.isPending}
422
+ onPress={() => handleLink(platform)}
423
+ >
424
+ {PLATFORM_LABELS[platform]}
425
+ </Button>
426
+ ))}
427
+ </View>
428
+ )}
429
+ </Row>
430
+ )}
431
+ </View>
432
+ );
433
+ }
@@ -1,5 +1,7 @@
1
1
  import { useLabels } from '../../lib/labels';
2
- import { BarListCard, LineChartCard } from '@oxy.so/bloom/chart-cards';
2
+ // The two cards by subpath: the `chart-cards` root is every chart Bloom draws (~190 KB on web).
3
+ import { BarListCard } from '@oxy.so/bloom/chart-cards/bar-list';
4
+ import { LineChartCard } from '@oxy.so/bloom/chart-cards/line';
3
5
  import { formatNumber } from '@oxy.so/bloom/locale';
4
6
 
5
7
  interface ChartData {
@@ -18,7 +18,7 @@ import { useGemieRuntime } from '../../runtime/config';
18
18
  import { AiChatMessageLine } from '@oxy.so/bloom/ai-chat';
19
19
  import { Badge } from '@oxy.so/bloom/badge';
20
20
  import { Card, CardBody, CardHeader } from '@oxy.so/bloom/card';
21
- import { LineChartCard } from '@oxy.so/bloom/chart-cards';
21
+ import { LineChartCard } from '@oxy.so/bloom/chart-cards/line';
22
22
  import { IconCircle } from '@oxy.so/bloom/icon-circle';
23
23
  import { RiArrowRightSLine } from '@oxy.so/bloom/icons/RiArrowRightSLine';
24
24
  import { RiCalendarScheduleLine } from '@oxy.so/bloom/icons/RiCalendarScheduleLine';
package/src/index.ts CHANGED
@@ -17,6 +17,7 @@ export type {
17
17
  } from './components/GemieParticipants';
18
18
  export { GemieParticipantsHeader } from './components/GemieParticipantsHeader';
19
19
  export type { GemieParticipantsHeaderProps } from './components/GemieParticipantsHeader';
20
+ export { ALIA_GEMIE_ID } from './lib/alia-gemie';
20
21
  export { ALIA_LEAD, leadOf } from './lib/participants';
21
22
  export type { GemieChatParticipants, GemieLead, GemieParticipant } from './lib/participants';
22
23
  export { ANCHORS, leadToProfile } from './lib/flights';
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Alia's gemie: the official, global `agents` row everybody uses (ADR 0034 §2), seeded with this
3
+ * fixed id. A client that addresses her by id — her thread, her connected accounts — uses it. A
4
+ * leaf: imports nothing.
5
+ */
6
+ export const ALIA_GEMIE_ID = '01a1cf00-cecf-7a24-868b-42b452105a6f';
@@ -150,6 +150,49 @@ export const COPY_EN: Readonly<Record<string, CopyEntry>> = {
150
150
  'faircoin.unavailable': 'No history for %{ranges}',
151
151
  'faircoin.updated': 'Updated %{time}',
152
152
  'faircoin.volume': '24h volume',
153
+ 'gemie.accounts.answerChat': 'Answer {{name}}',
154
+ 'gemie.accounts.cancel': 'Cancel',
155
+ 'gemie.accounts.description':
156
+ 'Link a WhatsApp or Telegram account and {{name}} answers the messages that arrive on it, as you choose below. Only {{name}} can read or send through it.',
157
+ 'gemie.accounts.groupChat': '{{name}} (group)',
158
+ 'gemie.accounts.groupReplies.mentions': 'Only when mentioned or replied to',
159
+ 'gemie.accounts.groupReplies.never': 'Never',
160
+ 'gemie.accounts.groupRepliesLabel': 'In groups',
161
+ 'gemie.accounts.lastMessage': 'Last message: {{when}}',
162
+ 'gemie.accounts.link': 'Link an account',
163
+ 'gemie.accounts.linkExpired':
164
+ 'The {{platform}} code expired before it was scanned. Link it again.',
165
+ 'gemie.accounts.linkFailed': 'Could not link {{platform}}: {{reason}}',
166
+ 'gemie.accounts.linkNamed': 'Link a {{platform}} account',
167
+ 'gemie.accounts.linked': '{{platform}} is linked. {{name}} answers there now.',
168
+ 'gemie.accounts.loadFailed': 'Could not load this. Try again.',
169
+ 'gemie.accounts.noChats': 'No chats yet. They appear here once messages arrive.',
170
+ 'gemie.accounts.noMessagesYet': 'No messages yet',
171
+ 'gemie.accounts.remove': 'Remove',
172
+ 'gemie.accounts.removeDescription':
173
+ '{{name}} stops answering on this {{platform}} account and its synced chats are deleted. You can link it again by scanning a new code.',
174
+ 'gemie.accounts.removeFailed': 'Could not remove it. Try again.',
175
+ 'gemie.accounts.removeNamed': 'Remove the {{platform}} account',
176
+ 'gemie.accounts.removeTitle': 'Remove {{platform}}',
177
+ 'gemie.accounts.removed': '{{platform}} removed',
178
+ 'gemie.accounts.replies.chosen': 'Only the chats I choose',
179
+ 'gemie.accounts.replies.everyone': 'Everyone who writes',
180
+ 'gemie.accounts.replies.nobody': 'Nobody: {{name}} only reads and sends when you ask',
181
+ 'gemie.accounts.repliesLabel': 'Who {{name}} answers',
182
+ 'gemie.accounts.saveFailed': 'Could not save. Try again.',
183
+ 'gemie.accounts.scan.telegram':
184
+ 'Open Telegram on your phone, go to Settings > Devices > Link Desktop Device, and scan this code.',
185
+ 'gemie.accounts.scan.whatsapp':
186
+ 'Open WhatsApp on your phone, go to Settings > Linked devices > Link a device, and scan this code.',
187
+ 'gemie.accounts.scanTitle': 'Scan with {{platform}}',
188
+ 'gemie.accounts.status.connected': 'Connected',
189
+ 'gemie.accounts.status.disconnected': 'Reconnecting',
190
+ 'gemie.accounts.status.failed': 'Could not reconnect. Remove it and link it again.',
191
+ 'gemie.accounts.status.logged-out': 'Unlinked from the phone. Remove it and link it again.',
192
+ 'gemie.accounts.status.qr-pending': 'Waiting for the scan',
193
+ 'gemie.accounts.title': 'Connected accounts',
194
+ 'gemie.accounts.tryAgain': 'try again in a moment.',
195
+ 'gemie.accounts.unavailable': 'Linking WhatsApp or Telegram is not available right now.',
153
196
  'market.dayHigh': 'Day high',
154
197
  'market.dayLow': 'Day low',
155
198
  'market.marketCap': 'Market cap',
@@ -207,7 +250,6 @@ export const COPY_EN: Readonly<Record<string, CopyEntry>> = {
207
250
  'tasks.tool.pill.generateFile': 'Generating file',
208
251
  'tasks.tool.pill.sendDiscord': 'Discord',
209
252
  'tasks.tool.pill.sendEmail': 'Email',
210
- 'tasks.tool.pill.sendSignal': 'Signal',
211
253
  'tasks.tool.pill.sendSlack': 'Slack',
212
254
  'tasks.tool.pill.sendTelegramMessage': 'Telegram',
213
255
  'tasks.tool.pill.shellExec': 'Running command',
@@ -258,13 +300,13 @@ export const COPY_EN: Readonly<Record<string, CopyEntry>> = {
258
300
  'thought.tool.generateFile': 'Generating file',
259
301
  'thought.tool.getCurrentDate': 'Getting current date',
260
302
  'thought.tool.getTimeline': 'Getting timeline',
261
- 'thought.tool.getWhatsAppChats': 'Loading WhatsApp chats',
262
- 'thought.tool.getWhatsAppMessages': 'Reading WhatsApp messages',
303
+ 'thought.tool.listAccountChats': 'Loading chats',
304
+ 'thought.tool.readAccountMessages': 'Reading messages',
263
305
  'thought.tool.saveUserMemory': 'Saving to memory',
264
306
  'thought.tool.scrapeURL': 'Reading URL',
265
307
  'thought.tool.searchKnowledgeBase': 'Searching knowledge base',
266
308
  'thought.tool.sendTelegramMessage': 'Sending Telegram message',
267
- 'thought.tool.sendWhatsAppMessage': 'Sending WhatsApp message',
309
+ 'thought.tool.sendAccountMessage': 'Sending a message',
268
310
  'thought.tool.updateUserContext': 'Updating context',
269
311
  'thought.tool.updateUserPreferences': 'Updating preferences',
270
312
  'thought.tool.webScraper': 'Reading web page',
@@ -146,6 +146,50 @@ export const COPY_ES: Readonly<Record<string, CopyEntry>> = {
146
146
  'faircoin.unavailable': 'Sin histórico para %{ranges}',
147
147
  'faircoin.updated': 'Actualizado %{time}',
148
148
  'faircoin.volume': 'Volumen 24 h',
149
+ 'gemie.accounts.answerChat': 'Responder a {{name}}',
150
+ 'gemie.accounts.cancel': 'Cancelar',
151
+ 'gemie.accounts.description':
152
+ 'Vincula una cuenta de WhatsApp o Telegram y {{name}} responderá los mensajes que lleguen a ella, como elijas abajo. Solo {{name}} puede leer o enviar por ella.',
153
+ 'gemie.accounts.groupChat': '{{name}} (grupo)',
154
+ 'gemie.accounts.groupReplies.mentions': 'Solo cuando le mencionan o le responden',
155
+ 'gemie.accounts.groupReplies.never': 'Nunca',
156
+ 'gemie.accounts.groupRepliesLabel': 'En grupos',
157
+ 'gemie.accounts.lastMessage': 'Último mensaje: {{when}}',
158
+ 'gemie.accounts.link': 'Vincular una cuenta',
159
+ 'gemie.accounts.linkExpired':
160
+ 'El código de {{platform}} caducó antes de escanearlo. Vuelve a vincularlo.',
161
+ 'gemie.accounts.linkFailed': 'No se ha podido vincular {{platform}}: {{reason}}',
162
+ 'gemie.accounts.linkNamed': 'Vincular una cuenta de {{platform}}',
163
+ 'gemie.accounts.linked': '{{platform}} está vinculado. {{name}} ya responde allí.',
164
+ 'gemie.accounts.loadFailed': 'No se ha podido cargar. Inténtalo de nuevo.',
165
+ 'gemie.accounts.noChats': 'Aún no hay chats. Aparecen aquí cuando llegan mensajes.',
166
+ 'gemie.accounts.noMessagesYet': 'Aún no hay mensajes',
167
+ 'gemie.accounts.remove': 'Quitar',
168
+ 'gemie.accounts.removeDescription':
169
+ '{{name}} dejará de responder en esta cuenta de {{platform}} y se borrarán sus chats sincronizados. Puedes volver a vincularla escaneando un código nuevo.',
170
+ 'gemie.accounts.removeFailed': 'No se ha podido quitar. Inténtalo de nuevo.',
171
+ 'gemie.accounts.removeNamed': 'Quitar la cuenta de {{platform}}',
172
+ 'gemie.accounts.removeTitle': 'Quitar {{platform}}',
173
+ 'gemie.accounts.removed': '{{platform}} quitado',
174
+ 'gemie.accounts.replies.chosen': 'Solo a los chats que elija',
175
+ 'gemie.accounts.replies.everyone': 'A todo el que escriba',
176
+ 'gemie.accounts.replies.nobody': 'A nadie: {{name}} solo lee y envía cuando se lo pides',
177
+ 'gemie.accounts.repliesLabel': 'A quién responde {{name}}',
178
+ 'gemie.accounts.saveFailed': 'No se ha podido guardar. Inténtalo de nuevo.',
179
+ 'gemie.accounts.scan.telegram':
180
+ 'Abre Telegram en tu teléfono, ve a Ajustes > Dispositivos > Vincular dispositivo de escritorio y escanea este código.',
181
+ 'gemie.accounts.scan.whatsapp':
182
+ 'Abre WhatsApp en tu teléfono, ve a Ajustes > Dispositivos vinculados > Vincular un dispositivo y escanea este código.',
183
+ 'gemie.accounts.scanTitle': 'Escanea con {{platform}}',
184
+ 'gemie.accounts.status.connected': 'Conectada',
185
+ 'gemie.accounts.status.disconnected': 'Reconectando',
186
+ 'gemie.accounts.status.failed': 'No se ha podido reconectar. Quítala y vuelve a vincularla.',
187
+ 'gemie.accounts.status.logged-out':
188
+ 'Desvinculada desde el teléfono. Quítala y vuelve a vincularla.',
189
+ 'gemie.accounts.status.qr-pending': 'Esperando el escaneo',
190
+ 'gemie.accounts.title': 'Cuentas conectadas',
191
+ 'gemie.accounts.tryAgain': 'inténtalo de nuevo en un momento.',
192
+ 'gemie.accounts.unavailable': 'Ahora mismo no se puede vincular WhatsApp ni Telegram.',
149
193
  'market.dayHigh': 'Máximo del día',
150
194
  'market.dayLow': 'Mínimo del día',
151
195
  'market.marketCap': 'Capitalización',
@@ -203,7 +247,6 @@ export const COPY_ES: Readonly<Record<string, CopyEntry>> = {
203
247
  'tasks.tool.pill.generateFile': 'Generando archivo',
204
248
  'tasks.tool.pill.sendDiscord': 'Discord',
205
249
  'tasks.tool.pill.sendEmail': 'Correo',
206
- 'tasks.tool.pill.sendSignal': 'Signal',
207
250
  'tasks.tool.pill.sendSlack': 'Slack',
208
251
  'tasks.tool.pill.sendTelegramMessage': 'Telegram',
209
252
  'tasks.tool.pill.shellExec': 'Ejecutando comando',
@@ -254,13 +297,13 @@ export const COPY_ES: Readonly<Record<string, CopyEntry>> = {
254
297
  'thought.tool.generateFile': 'Generando archivo',
255
298
  'thought.tool.getCurrentDate': 'Consultando la fecha actual',
256
299
  'thought.tool.getTimeline': 'Obteniendo la cronología',
257
- 'thought.tool.getWhatsAppChats': 'Cargando chats de WhatsApp',
258
- 'thought.tool.getWhatsAppMessages': 'Leyendo mensajes de WhatsApp',
300
+ 'thought.tool.listAccountChats': 'Cargando chats',
301
+ 'thought.tool.readAccountMessages': 'Leyendo mensajes',
259
302
  'thought.tool.saveUserMemory': 'Guardando en la memoria',
260
303
  'thought.tool.scrapeURL': 'Leyendo URL',
261
304
  'thought.tool.searchKnowledgeBase': 'Buscando en la base de conocimiento',
262
305
  'thought.tool.sendTelegramMessage': 'Enviando mensaje de Telegram',
263
- 'thought.tool.sendWhatsAppMessage': 'Enviando mensaje de WhatsApp',
306
+ 'thought.tool.sendAccountMessage': 'Enviando un mensaje',
264
307
  'thought.tool.updateUserContext': 'Actualizando contexto',
265
308
  'thought.tool.updateUserPreferences': 'Actualizando preferencias',
266
309
  'thought.tool.webScraper': 'Leyendo página web',
@@ -19,9 +19,9 @@ const TOOL_ICONS: ReadonlyMap<string, BloomIconComponent> = new Map([
19
19
  ['searchKnowledgeBase', RiDatabase2Line],
20
20
  ['webScraper', RiGlobalLine],
21
21
  ['browse', RiGlobalLine],
22
- ['sendWhatsAppMessage', RiChat3Line],
23
- ['getWhatsAppChats', RiChat3Line],
24
- ['getWhatsAppMessages', RiChat3Line],
22
+ ['sendAccountMessage', RiChat3Line],
23
+ ['listAccountChats', RiChat3Line],
24
+ ['readAccountMessages', RiChat3Line],
25
25
  ['sendTelegramMessage', RiSendPlaneLine],
26
26
  ['getCurrentDate', RiCalendarLine],
27
27
  ['generateFile', RiFileTextLine],
@@ -13,9 +13,9 @@ const TOOL_REGISTRY: Record<string, ToolDefinition> = {
13
13
  browse: { label: 'Browsing the web', category: 'search' },
14
14
 
15
15
  // Communication
16
- sendWhatsAppMessage: { label: 'Sending WhatsApp message', category: 'communication' },
17
- getWhatsAppChats: { label: 'Loading WhatsApp chats', category: 'communication' },
18
- getWhatsAppMessages: { label: 'Reading WhatsApp messages', category: 'communication' },
16
+ sendAccountMessage: { label: 'Sending a message', category: 'communication' },
17
+ listAccountChats: { label: 'Loading chats', category: 'communication' },
18
+ readAccountMessages: { label: 'Reading messages', category: 'communication' },
19
19
  sendTelegramMessage: { label: 'Sending Telegram message', category: 'communication' },
20
20
 
21
21
  // Utility
@@ -0,0 +1,182 @@
1
+ import { useOxy } from '@oxy.so/services/ui/client';
2
+ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
3
+ import { useGemieApi } from './api';
4
+ import { errorStatus } from './error-utils';
5
+ import { gemieQueryKeys } from './query-keys';
6
+ import { AGENT_ROUTES } from './routes';
7
+
8
+ /**
9
+ * A gemie's connected accounts (ADR 0035): the WhatsApp and Telegram accounts the person linked to
10
+ * a gemie, which answers what arrives on them as their replies say. Each is the caller's own; the
11
+ * API never lists another person's. The Gemies app (in a gemie's editor) and the Alia app (for
12
+ * Alia's gemie) both manage them through these hooks and `GemieAccounts` (`@gemies/sdk/accounts`).
13
+ */
14
+
15
+ export const GEMIE_ACCOUNT_PLATFORMS = ['whatsapp', 'telegram'] as const;
16
+ export type GemieAccountPlatform = (typeof GEMIE_ACCOUNT_PLATFORMS)[number];
17
+
18
+ /** Where an account's session is, as the API reports it (the gateway's own vocabulary). */
19
+ export const GEMIE_ACCOUNT_STATUSES = [
20
+ 'qr-pending',
21
+ 'connected',
22
+ 'disconnected',
23
+ 'logged-out',
24
+ 'failed',
25
+ ] as const;
26
+ export type GemieAccountStatus = (typeof GEMIE_ACCOUNT_STATUSES)[number];
27
+
28
+ /** Who the gemie answers: everybody who writes, only the chosen chats, or nobody. */
29
+ export const GEMIE_ACCOUNT_REPLIES = ['everyone', 'chosen', 'nobody'] as const;
30
+ export type GemieAccountReplies = (typeof GEMIE_ACCOUNT_REPLIES)[number];
31
+ /** In a group: only when the message mentions or replies to the account, or never. */
32
+ export const GEMIE_ACCOUNT_GROUP_REPLIES = ['mentions', 'never'] as const;
33
+ export type GemieAccountGroupReplies = (typeof GEMIE_ACCOUNT_GROUP_REPLIES)[number];
34
+
35
+ /** One account, as `GET /agents/:id/accounts` lists it. */
36
+ export interface GemieAccount {
37
+ _id: string;
38
+ platform: GemieAccountPlatform;
39
+ displayName: string | null;
40
+ phoneNumber: string | null;
41
+ status: GemieAccountStatus;
42
+ oxyTaskState: 'active' | 'reauth_required';
43
+ replies: GemieAccountReplies;
44
+ replyChatIds: string[];
45
+ groupReplies: GemieAccountGroupReplies;
46
+ lastActiveAt: string | null;
47
+ }
48
+
49
+ /** One chat of an account, to choose which ones it answers. */
50
+ export interface GemieAccountChat {
51
+ chatId: string;
52
+ name: string;
53
+ kind: 'direct' | 'group';
54
+ }
55
+
56
+ /** A link waiting for its scan. */
57
+ export interface GemieAccountLink {
58
+ accountId: string;
59
+ qr: string | null;
60
+ }
61
+
62
+ export interface GemieAccountsAnswer {
63
+ accounts: GemieAccount[];
64
+ /** The platforms this deployment can link now: only those are offered. */
65
+ platforms: GemieAccountPlatform[];
66
+ }
67
+
68
+ /**
69
+ * The caller's accounts on a gemie, each as its session is now, and what can be linked. An account
70
+ * whose Oxy task lapsed is renewed on the way (the provider link is kept; the person looking is the
71
+ * verified requester); a renewal that fails leaves it typed inactive for the next visit to retry.
72
+ */
73
+ export function useGemieAccounts(gemieId: string) {
74
+ const api = useGemieApi();
75
+ const { isAuthenticated } = useOxy();
76
+ return useQuery({
77
+ queryKey: gemieQueryKeys.accounts.all(gemieId),
78
+ queryFn: async (): Promise<GemieAccountsAnswer> => {
79
+ const { data } = await api.get<GemieAccountsAnswer>(AGENT_ROUTES.accounts(gemieId));
80
+ await Promise.all(
81
+ data.accounts
82
+ .filter((account) => account.oxyTaskState === 'reauth_required')
83
+ .map(async (account) => {
84
+ try {
85
+ await api.post(`${AGENT_ROUTES.account(gemieId, account._id)}/reauthorize`);
86
+ account.oxyTaskState = 'active';
87
+ } catch {
88
+ /* Remains typed inactive; the next verified visit may retry. */
89
+ }
90
+ }),
91
+ );
92
+ return data;
93
+ },
94
+ enabled: isAuthenticated && gemieId !== '',
95
+ });
96
+ }
97
+
98
+ /**
99
+ * The code of an account being linked, refreshed while it waits (WhatsApp rotates its code every
100
+ * few seconds). It stops once the session leaves `qr-pending`, and the list is re-read then, so the
101
+ * account shows as it is.
102
+ */
103
+ export function useGemieAccountQr(gemieId: string, link: GemieAccountLink | null) {
104
+ const api = useGemieApi();
105
+ const queryClient = useQueryClient();
106
+ const accountId = link?.accountId ?? '';
107
+ return useQuery({
108
+ queryKey: gemieQueryKeys.accounts.qr(gemieId, accountId),
109
+ queryFn: async (): Promise<{ status: GemieAccountStatus; qr: string | null }> => {
110
+ const { data } = await api.get<{ status: GemieAccountStatus; qr: string | null }>(
111
+ `${AGENT_ROUTES.account(gemieId, accountId)}/qr`,
112
+ );
113
+ if (data.status !== 'qr-pending') {
114
+ await queryClient.invalidateQueries({ queryKey: gemieQueryKeys.accounts.all(gemieId) });
115
+ }
116
+ return data;
117
+ },
118
+ enabled: link !== null,
119
+ initialData: link ? { status: 'qr-pending' as const, qr: link.qr } : undefined,
120
+ initialDataUpdatedAt: 0,
121
+ refetchInterval: (query) => (query.state.data?.status === 'qr-pending' ? 4000 : false),
122
+ });
123
+ }
124
+
125
+ /** An account's recent chats, read while the person chooses which ones it answers. */
126
+ export function useGemieAccountChats(gemieId: string, accountId: string) {
127
+ const api = useGemieApi();
128
+ return useQuery({
129
+ queryKey: gemieQueryKeys.accounts.chats(gemieId, accountId),
130
+ queryFn: async (): Promise<GemieAccountChat[]> => {
131
+ try {
132
+ const { data } = await api.get<{ chats: GemieAccountChat[] }>(
133
+ `${AGENT_ROUTES.account(gemieId, accountId)}/chats`,
134
+ );
135
+ return data.chats;
136
+ } catch (error) {
137
+ if (errorStatus(error) === 404) return [];
138
+ throw error;
139
+ }
140
+ },
141
+ });
142
+ }
143
+
144
+ /** Linking, who it answers, and removing (its session ends and its task is revoked). */
145
+ export function useGemieAccountMutations(gemieId: string) {
146
+ const api = useGemieApi();
147
+ const queryClient = useQueryClient();
148
+ const invalidate = () =>
149
+ queryClient.invalidateQueries({ queryKey: gemieQueryKeys.accounts.all(gemieId) });
150
+
151
+ const link = useMutation({
152
+ mutationFn: async (platform: GemieAccountPlatform): Promise<GemieAccountLink> => {
153
+ const { data } = await api.post<GemieAccountLink>(AGENT_ROUTES.accounts(gemieId), {
154
+ platform,
155
+ });
156
+ return data;
157
+ },
158
+ onSuccess: invalidate,
159
+ });
160
+
161
+ const setReplies = useMutation({
162
+ mutationFn: async (input: {
163
+ accountId: string;
164
+ replies?: GemieAccountReplies;
165
+ replyChatIds?: string[];
166
+ groupReplies?: GemieAccountGroupReplies;
167
+ }) => {
168
+ const { accountId, ...patch } = input;
169
+ await api.patch(AGENT_ROUTES.account(gemieId, accountId), patch);
170
+ },
171
+ onSuccess: invalidate,
172
+ });
173
+
174
+ const remove = useMutation({
175
+ mutationFn: async (accountId: string) => {
176
+ await api.delete(AGENT_ROUTES.account(gemieId, accountId));
177
+ },
178
+ onSuccess: invalidate,
179
+ });
180
+
181
+ return { link, setReplies, remove };
182
+ }
@@ -21,6 +21,17 @@ export const gemieQueryKeys = {
21
21
  filtered: (filter: ConversationsFilter) =>
22
22
  ['conversations', { agentId: filter.agentId, app: filter.app }] as const,
23
23
  },
24
+ /**
25
+ * A gemie's connected accounts (ADR 0035): the caller's accounts on it, the code of one being
26
+ * linked and an account's chats. Their own roots, never persisted: phone numbers and a live code
27
+ * stay in memory.
28
+ */
29
+ accounts: {
30
+ all: (gemieId: string) => ['gemie-accounts', gemieId] as const,
31
+ qr: (gemieId: string, accountId: string) => ['gemie-account-qr', gemieId, accountId] as const,
32
+ chats: (gemieId: string, accountId: string) =>
33
+ ['gemie-account-chats', gemieId, accountId] as const,
34
+ },
24
35
  /** An agent the chat is opened on: its profile and the state of its feature gates. */
25
36
  agents: {
26
37
  profile: (id: string) => ['alia-agent-profile', id] as const,
@@ -78,4 +78,8 @@ export const AGENT_ROUTES = {
78
78
  threadSearch: (thread: GemieThreadAddress) => `${threadPath(thread)}/search`,
79
79
  /** What a run of an agent has done so far, to hydrate the live feed. */
80
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)}`,
81
85
  } as const;
@@ -381,9 +381,9 @@ const TRANSLATED_TOOLS: ReadonlySet<string> = new Set([
381
381
  'searchKnowledgeBase',
382
382
  'webScraper',
383
383
  'browse',
384
- 'sendWhatsAppMessage',
385
- 'getWhatsAppChats',
386
- 'getWhatsAppMessages',
384
+ 'sendAccountMessage',
385
+ 'listAccountChats',
386
+ 'readAccountMessages',
387
387
  'sendTelegramMessage',
388
388
  'getCurrentDate',
389
389
  'generateFile',
@@ -1,18 +0,0 @@
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
- }
@@ -1,3 +0,0 @@
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';
@@ -1,227 +0,0 @@
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 };
@@ -1,5 +0,0 @@
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;