@gemies/sdk 3.3.1 → 4.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.
@@ -1,189 +0,0 @@
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 (Business, ADR 0037) accounts
10
- * the person linked to 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
- 'paused',
24
- 'logged-out',
25
- 'failed',
26
- ] as const;
27
- export type GemieAccountStatus = (typeof GEMIE_ACCOUNT_STATUSES)[number];
28
-
29
- /** Who the gemie answers: everybody who writes, only the chosen chats, or nobody. */
30
- export const GEMIE_ACCOUNT_REPLIES = ['everyone', 'chosen', 'nobody'] as const;
31
- export type GemieAccountReplies = (typeof GEMIE_ACCOUNT_REPLIES)[number];
32
- /** In a group: only when the message mentions or replies to the account, or never. */
33
- export const GEMIE_ACCOUNT_GROUP_REPLIES = ['mentions', 'never'] as const;
34
- export type GemieAccountGroupReplies = (typeof GEMIE_ACCOUNT_GROUP_REPLIES)[number];
35
-
36
- /** One account, as `GET /agents/:id/accounts` lists it. */
37
- export interface GemieAccount {
38
- _id: string;
39
- platform: GemieAccountPlatform;
40
- displayName: string | null;
41
- phoneNumber: string | null;
42
- status: GemieAccountStatus;
43
- /** Whether the platform lets the gemie write from it (Telegram Business); `null` elsewhere. */
44
- canReply: boolean | null;
45
- oxyTaskState: 'active' | 'reauth_required';
46
- replies: GemieAccountReplies;
47
- replyChatIds: string[];
48
- groupReplies: GemieAccountGroupReplies;
49
- lastActiveAt: string | null;
50
- }
51
-
52
- /** One chat of an account, to choose which ones it answers. */
53
- export interface GemieAccountChat {
54
- chatId: string;
55
- name: string;
56
- kind: 'direct' | 'group';
57
- }
58
-
59
- /**
60
- * A link waiting to be finished: WhatsApp's code to scan, or Telegram's t.me link to
61
- * open (or scan from another device).
62
- */
63
- export interface GemieAccountLink {
64
- accountId: string;
65
- qr: string | null;
66
- }
67
-
68
- export interface GemieAccountsAnswer {
69
- accounts: GemieAccount[];
70
- /** The platforms this deployment can link now: only those are offered. */
71
- platforms: GemieAccountPlatform[];
72
- }
73
-
74
- /**
75
- * The caller's accounts on a gemie, each as its session is now, and what can be linked. An account
76
- * whose Oxy task lapsed is renewed on the way (the provider link is kept; the person looking is the
77
- * verified requester); a renewal that fails leaves it typed inactive for the next visit to retry.
78
- */
79
- export function useGemieAccounts(gemieId: string) {
80
- const api = useGemieApi();
81
- const { isAuthenticated } = useOxy();
82
- return useQuery({
83
- queryKey: gemieQueryKeys.accounts.all(gemieId),
84
- queryFn: async (): Promise<GemieAccountsAnswer> => {
85
- const { data } = await api.get<GemieAccountsAnswer>(AGENT_ROUTES.accounts(gemieId));
86
- await Promise.all(
87
- data.accounts
88
- .filter((account) => account.oxyTaskState === 'reauth_required')
89
- .map(async (account) => {
90
- try {
91
- await api.post(`${AGENT_ROUTES.account(gemieId, account._id)}/reauthorize`);
92
- account.oxyTaskState = 'active';
93
- } catch {
94
- /* Remains typed inactive; the next verified visit may retry. */
95
- }
96
- }),
97
- );
98
- return data;
99
- },
100
- enabled: isAuthenticated && gemieId !== '',
101
- });
102
- }
103
-
104
- /**
105
- * The code of an account being linked, refreshed while it waits (WhatsApp rotates its code every
106
- * few seconds; Telegram's link is renewed when it expires, and is gone once Telegram knows who the
107
- * person is). It stops once the session leaves `qr-pending`, and the list is re-read then, so the
108
- * account shows as it is.
109
- */
110
- export function useGemieAccountQr(gemieId: string, link: GemieAccountLink | null) {
111
- const api = useGemieApi();
112
- const queryClient = useQueryClient();
113
- const accountId = link?.accountId ?? '';
114
- return useQuery({
115
- queryKey: gemieQueryKeys.accounts.qr(gemieId, accountId),
116
- queryFn: async (): Promise<{ status: GemieAccountStatus; qr: string | null }> => {
117
- const { data } = await api.get<{ status: GemieAccountStatus; qr: string | null }>(
118
- `${AGENT_ROUTES.account(gemieId, accountId)}/qr`,
119
- );
120
- if (data.status !== 'qr-pending') {
121
- await queryClient.invalidateQueries({ queryKey: gemieQueryKeys.accounts.all(gemieId) });
122
- }
123
- return data;
124
- },
125
- enabled: link !== null,
126
- initialData: link ? { status: 'qr-pending' as const, qr: link.qr } : undefined,
127
- initialDataUpdatedAt: 0,
128
- refetchInterval: (query) => (query.state.data?.status === 'qr-pending' ? 4000 : false),
129
- });
130
- }
131
-
132
- /** An account's recent chats, read while the person chooses which ones it answers. */
133
- export function useGemieAccountChats(gemieId: string, accountId: string) {
134
- const api = useGemieApi();
135
- return useQuery({
136
- queryKey: gemieQueryKeys.accounts.chats(gemieId, accountId),
137
- queryFn: async (): Promise<GemieAccountChat[]> => {
138
- try {
139
- const { data } = await api.get<{ chats: GemieAccountChat[] }>(
140
- `${AGENT_ROUTES.account(gemieId, accountId)}/chats`,
141
- );
142
- return data.chats;
143
- } catch (error) {
144
- if (errorStatus(error) === 404) return [];
145
- throw error;
146
- }
147
- },
148
- });
149
- }
150
-
151
- /** Linking, who it answers, and removing (its session ends and its task is revoked). */
152
- export function useGemieAccountMutations(gemieId: string) {
153
- const api = useGemieApi();
154
- const queryClient = useQueryClient();
155
- const invalidate = () =>
156
- queryClient.invalidateQueries({ queryKey: gemieQueryKeys.accounts.all(gemieId) });
157
-
158
- const link = useMutation({
159
- mutationFn: async (platform: GemieAccountPlatform): Promise<GemieAccountLink> => {
160
- const { data } = await api.post<GemieAccountLink>(AGENT_ROUTES.accounts(gemieId), {
161
- platform,
162
- });
163
- return data;
164
- },
165
- onSuccess: invalidate,
166
- });
167
-
168
- const setReplies = useMutation({
169
- mutationFn: async (input: {
170
- accountId: string;
171
- replies?: GemieAccountReplies;
172
- replyChatIds?: string[];
173
- groupReplies?: GemieAccountGroupReplies;
174
- }) => {
175
- const { accountId, ...patch } = input;
176
- await api.patch(AGENT_ROUTES.account(gemieId, accountId), patch);
177
- },
178
- onSuccess: invalidate,
179
- });
180
-
181
- const remove = useMutation({
182
- mutationFn: async (accountId: string) => {
183
- await api.delete(AGENT_ROUTES.account(gemieId, accountId));
184
- },
185
- onSuccess: invalidate,
186
- });
187
-
188
- return { link, setReplies, remove };
189
- }