@gemies/sdk 3.2.0 → 3.3.1

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.
@@ -150,6 +150,75 @@ 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.connectors.cancel': 'Cancel',
154
+ 'gemie.connectors.category.communication': 'Communication',
155
+ 'gemie.connectors.category.data': 'Data',
156
+ 'gemie.connectors.category.development': 'Development',
157
+ 'gemie.connectors.category.productivity': 'Productivity',
158
+ 'gemie.connectors.connected.browse': 'Browse connectors',
159
+ 'gemie.connectors.connected.description':
160
+ 'The accounts you connected. Alia can use every one; other gemies only the ones you give them in their editor.',
161
+ 'gemie.connectors.connected.emptyDescription':
162
+ 'Connect Notion, Linear, Slack and more so your gemies can work with them.',
163
+ 'gemie.connectors.connected.emptyTitle': 'Nothing connected yet',
164
+ 'gemie.connectors.connected.loadFailed': 'Your connectors could not be loaded.',
165
+ 'gemie.connectors.connected.title': 'Connected',
166
+ 'gemie.connectors.custom.add': 'Add server',
167
+ 'gemie.connectors.custom.adding': 'Adding…',
168
+ 'gemie.connectors.custom.advanced': 'Advanced',
169
+ 'gemie.connectors.custom.cancel': 'Cancel',
170
+ 'gemie.connectors.custom.description':
171
+ 'Your own remote MCP server, by its https address. If it asks you to sign in, you will be taken there.',
172
+ 'gemie.connectors.custom.failed': 'The server could not be added.',
173
+ 'gemie.connectors.custom.headerName': 'Header name',
174
+ 'gemie.connectors.custom.headerValue': 'Header value',
175
+ 'gemie.connectors.custom.name': 'Name',
176
+ 'gemie.connectors.custom.namePlaceholder': 'My server',
177
+ 'gemie.connectors.custom.title': 'Add a custom MCP server',
178
+ 'gemie.connectors.custom.url': 'Server URL',
179
+ 'gemie.connectors.disconnect': 'Disconnect',
180
+ 'gemie.connectors.disconnectDescription':
181
+ 'Gemies forgets this account and asks {{name}} to revoke its access. Gemies that used it lose its tools.',
182
+ 'gemie.connectors.disconnectFailed': 'It could not be disconnected right now. Try again.',
183
+ 'gemie.connectors.disconnectTitle': 'Disconnect {{name}}?',
184
+ 'gemie.connectors.disconnected': '{{name}} is disconnected.',
185
+ 'gemie.connectors.reconnect': 'Reconnect',
186
+ 'gemie.connectors.reconnectFailed': '{{name}} could not be reconnected.',
187
+ 'gemie.connectors.reconnected': '{{name}} is connected again.',
188
+ 'gemie.connectors.rename': 'Rename',
189
+ 'gemie.connectors.renameDescription': 'How you tell this {{name}} account apart from the others.',
190
+ 'gemie.connectors.renameFailed': 'The name could not be saved.',
191
+ 'gemie.connectors.renameLabel': 'Account name',
192
+ 'gemie.connectors.renameSave': 'Save',
193
+ 'gemie.connectors.renameTitle': 'Name this account',
194
+ 'gemie.connectors.signIn.connected': '{{name}} is connected.',
195
+ 'gemie.connectors.signIn.declined': 'Sign-in was cancelled.',
196
+ 'gemie.connectors.signIn.expired': 'The sign-in took too long. Try again.',
197
+ 'gemie.connectors.signIn.failed': '{{name}} could not be connected. Try again.',
198
+ 'gemie.connectors.signIn.failedGeneric': 'The connector could not be connected. Try again.',
199
+ 'gemie.connectors.status.error': 'Needs reconnecting',
200
+ 'gemie.connectors.status.installed': 'Not connected yet',
201
+ 'gemie.connectors.status.running': 'Connected',
202
+ 'gemie.connectors.store.all': 'All',
203
+ 'gemie.connectors.store.categories': 'Categories',
204
+ 'gemie.connectors.store.connect': 'Connect',
205
+ 'gemie.connectors.store.connectAnother': 'Add account',
206
+ 'gemie.connectors.store.connectedCount': {
207
+ one: 'Connected',
208
+ other: '{{count}} accounts connected',
209
+ },
210
+ 'gemie.connectors.store.description':
211
+ 'Connect the apps you work with. Each is the provider’s own MCP server: you sign in with them, and Gemies never sees your password.',
212
+ 'gemie.connectors.store.docs': 'About',
213
+ 'gemie.connectors.store.empty': 'No connector is available right now.',
214
+ 'gemie.connectors.store.featured': 'Featured',
215
+ 'gemie.connectors.store.loadFailed': 'Connectors could not be loaded.',
216
+ 'gemie.connectors.store.noResults': 'No connector matches “{{query}}”.',
217
+ 'gemie.connectors.store.retry': 'Retry',
218
+ 'gemie.connectors.store.search': 'Search connectors',
219
+ 'gemie.connectors.store.title': 'Connectors',
220
+ 'gemie.connectors.toolCount': { zero: 'No tools', one: '1 tool', other: '{{count}} tools' },
221
+ 'gemie.connectors.usedBy': 'Used by {{names}}',
153
222
  'gemie.accounts.answerChat': 'Answer {{name}}',
154
223
  'gemie.accounts.cancel': 'Cancel',
155
224
  'gemie.accounts.description':
@@ -146,6 +146,79 @@ 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.connectors.cancel': 'Cancelar',
150
+ 'gemie.connectors.category.communication': 'Comunicación',
151
+ 'gemie.connectors.category.data': 'Datos',
152
+ 'gemie.connectors.category.development': 'Desarrollo',
153
+ 'gemie.connectors.category.productivity': 'Productividad',
154
+ 'gemie.connectors.connected.browse': 'Explorar conectores',
155
+ 'gemie.connectors.connected.description':
156
+ 'Las cuentas que conectaste. Alia puede usarlas todas; los demás gemies solo las que les des en su editor.',
157
+ 'gemie.connectors.connected.emptyDescription':
158
+ 'Conecta Notion, Linear, Slack y más para que tus gemies trabajen con ellos.',
159
+ 'gemie.connectors.connected.emptyTitle': 'Todavía no hay nada conectado',
160
+ 'gemie.connectors.connected.loadFailed': 'No se pudieron cargar tus conectores.',
161
+ 'gemie.connectors.connected.title': 'Conectados',
162
+ 'gemie.connectors.custom.add': 'Añadir servidor',
163
+ 'gemie.connectors.custom.adding': 'Añadiendo…',
164
+ 'gemie.connectors.custom.advanced': 'Avanzado',
165
+ 'gemie.connectors.custom.cancel': 'Cancelar',
166
+ 'gemie.connectors.custom.description':
167
+ 'Tu propio servidor MCP remoto, por su dirección https. Si te pide iniciar sesión, te llevará allí.',
168
+ 'gemie.connectors.custom.failed': 'No se pudo añadir el servidor.',
169
+ 'gemie.connectors.custom.headerName': 'Nombre de la cabecera',
170
+ 'gemie.connectors.custom.headerValue': 'Valor de la cabecera',
171
+ 'gemie.connectors.custom.name': 'Nombre',
172
+ 'gemie.connectors.custom.namePlaceholder': 'Mi servidor',
173
+ 'gemie.connectors.custom.title': 'Añadir un servidor MCP propio',
174
+ 'gemie.connectors.custom.url': 'URL del servidor',
175
+ 'gemie.connectors.disconnect': 'Desconectar',
176
+ 'gemie.connectors.disconnectDescription':
177
+ 'Gemies olvida esta cuenta y pide a {{name}} que retire su acceso. Los gemies que la usaban pierden sus herramientas.',
178
+ 'gemie.connectors.disconnectFailed': 'Ahora mismo no se pudo desconectar. Vuelve a intentarlo.',
179
+ 'gemie.connectors.disconnectTitle': '¿Desconectar {{name}}?',
180
+ 'gemie.connectors.disconnected': '{{name}} está desconectado.',
181
+ 'gemie.connectors.reconnect': 'Volver a conectar',
182
+ 'gemie.connectors.reconnectFailed': 'No se pudo volver a conectar {{name}}.',
183
+ 'gemie.connectors.reconnected': '{{name}} vuelve a estar conectado.',
184
+ 'gemie.connectors.rename': 'Cambiar nombre',
185
+ 'gemie.connectors.renameDescription': 'Cómo distingues esta cuenta de {{name}} de las demás.',
186
+ 'gemie.connectors.renameFailed': 'No se pudo guardar el nombre.',
187
+ 'gemie.connectors.renameLabel': 'Nombre de la cuenta',
188
+ 'gemie.connectors.renameSave': 'Guardar',
189
+ 'gemie.connectors.renameTitle': 'Pon nombre a esta cuenta',
190
+ 'gemie.connectors.signIn.connected': '{{name}} está conectado.',
191
+ 'gemie.connectors.signIn.declined': 'Se canceló el inicio de sesión.',
192
+ 'gemie.connectors.signIn.expired': 'El inicio de sesión tardó demasiado. Vuelve a intentarlo.',
193
+ 'gemie.connectors.signIn.failed': 'No se pudo conectar {{name}}. Vuelve a intentarlo.',
194
+ 'gemie.connectors.signIn.failedGeneric': 'No se pudo conectar el conector. Vuelve a intentarlo.',
195
+ 'gemie.connectors.status.error': 'Hay que volver a conectarlo',
196
+ 'gemie.connectors.status.installed': 'Aún sin conectar',
197
+ 'gemie.connectors.status.running': 'Conectado',
198
+ 'gemie.connectors.store.all': 'Todos',
199
+ 'gemie.connectors.store.categories': 'Categorías',
200
+ 'gemie.connectors.store.connect': 'Conectar',
201
+ 'gemie.connectors.store.connectAnother': 'Añadir cuenta',
202
+ 'gemie.connectors.store.connectedCount': {
203
+ one: 'Conectado',
204
+ other: '{{count}} cuentas conectadas',
205
+ },
206
+ 'gemie.connectors.store.description':
207
+ 'Conecta las apps con las que trabajas. Cada una es el servidor MCP del propio proveedor: inicias sesión con ellos y Gemies nunca ve tu contraseña.',
208
+ 'gemie.connectors.store.docs': 'Más información',
209
+ 'gemie.connectors.store.empty': 'Ahora mismo no hay conectores disponibles.',
210
+ 'gemie.connectors.store.featured': 'Destacados',
211
+ 'gemie.connectors.store.loadFailed': 'No se pudieron cargar los conectores.',
212
+ 'gemie.connectors.store.noResults': 'Ningún conector coincide con «{{query}}».',
213
+ 'gemie.connectors.store.retry': 'Reintentar',
214
+ 'gemie.connectors.store.search': 'Buscar conectores',
215
+ 'gemie.connectors.store.title': 'Conectores',
216
+ 'gemie.connectors.toolCount': {
217
+ zero: 'Sin herramientas',
218
+ one: '1 herramienta',
219
+ other: '{{count}} herramientas',
220
+ },
221
+ 'gemie.connectors.usedBy': 'Lo usan {{names}}',
149
222
  'gemie.accounts.answerChat': 'Responder a {{name}}',
150
223
  'gemie.accounts.cancel': 'Cancelar',
151
224
  'gemie.accounts.description':
@@ -0,0 +1,324 @@
1
+ import { useOxy } from '@oxy.so/services/ui/client';
2
+ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
3
+ import * as WebBrowser from 'expo-web-browser';
4
+ import { useCallback, useEffect, useRef } from 'react';
5
+ import { Platform } from 'react-native';
6
+ import { useGemieApi } from './api';
7
+ import { useGemieRuntime } from './config';
8
+
9
+ /**
10
+ * Connectors (`@gemies/sdk/connectors`): the providers' own remote MCP servers a person connects —
11
+ * Notion, Linear, Slack… — and their own MCP servers by URL. One person may connect several
12
+ * accounts of one connector; each account is its own connection, with its own tools
13
+ * (`mcp_notion__…`, `mcp_notion_2__…`) and its own grants to gemies, so which account a tool acts
14
+ * on is always explicit.
15
+ *
16
+ * The store (`GemieConnectorsStore`) is where a person finds and connects one; Settings
17
+ * (`GemieConnectedConnectors`) lists only what they connected. Both, and every logo
18
+ * (`ConnectorLogo`), are the same in the Gemies and the Alia apps.
19
+ */
20
+
21
+ /** The routes, on the Gemies API (credentialed, the Gemies and Alia origins). */
22
+ export const CONNECTOR_ROUTES = {
23
+ catalogue: '/mcp/registry',
24
+ connected: '/mcp/installed',
25
+ connect: '/mcp/connect',
26
+ custom: '/mcp/custom',
27
+ complete: '/mcp/oauth/complete',
28
+ connection: (id: string) => `/mcp/${encodeURIComponent(id)}`,
29
+ reconnect: (id: string) => `/mcp/${encodeURIComponent(id)}/reconnect`,
30
+ } as const;
31
+
32
+ export const connectorQueryKeys = {
33
+ catalogue: ['gemie-connectors', 'catalogue'] as const,
34
+ connected: ['gemie-connectors', 'connected'] as const,
35
+ };
36
+
37
+ export const CONNECTOR_CATEGORIES = [
38
+ 'productivity',
39
+ 'development',
40
+ 'communication',
41
+ 'data',
42
+ ] as const;
43
+ export type ConnectorCategory = (typeof CONNECTOR_CATEGORIES)[number];
44
+
45
+ /** A connector of the catalogue: a provider's hosted MCP server this deployment can connect. */
46
+ export interface ConnectorEntry {
47
+ id: string;
48
+ name: string;
49
+ description: string;
50
+ category: ConnectorCategory;
51
+ featured: boolean;
52
+ docsUrl: string;
53
+ /** On the API's origin; `null` draws a monogram. */
54
+ logoUrl: string | null;
55
+ }
56
+
57
+ export type ConnectionStatus = 'installed' | 'running' | 'error';
58
+
59
+ /** One account a person connected. */
60
+ export interface Connection {
61
+ _id: string;
62
+ /** Its slug, which names its tools (`mcp_<name>__…`). */
63
+ name: string;
64
+ displayName: string;
65
+ description: string | null;
66
+ /** Which account of the provider (`ana@acme.com`, "Work"); `null` when the only one has none. */
67
+ accountLabel: string | null;
68
+ source: 'registry' | 'custom';
69
+ registryId: string | null;
70
+ config: { url?: string; requiresOAuth?: boolean };
71
+ /** `running` is connected; `error` needs reconnecting; `installed` never finished connecting. */
72
+ status: ConnectionStatus;
73
+ statusMessage: string | null;
74
+ tools: { name: string; description: string }[];
75
+ logoUrl: string | null;
76
+ /** The person's gemies that may use it: Alia every one, the others as granted. */
77
+ usedBy: { id: string; name: string }[];
78
+ }
79
+
80
+ /** The catalogue, as this deployment can connect it. */
81
+ export function useConnectorCatalogue() {
82
+ const api = useGemieApi();
83
+ const { isAuthenticated } = useOxy();
84
+ return useQuery({
85
+ queryKey: connectorQueryKeys.catalogue,
86
+ queryFn: async () =>
87
+ (await api.get<{ servers: ConnectorEntry[] }>(CONNECTOR_ROUTES.catalogue)).data.servers,
88
+ enabled: isAuthenticated,
89
+ staleTime: 5 * 60_000,
90
+ });
91
+ }
92
+
93
+ /**
94
+ * What the person connected, each account on its own. `enabled: false` reads nothing: the chat is
95
+ * embedded in apps whose origin the connector routes do not answer, and asks only for a turn that
96
+ * used a connector.
97
+ */
98
+ export function useConnections({ enabled = true }: { enabled?: boolean } = {}) {
99
+ const api = useGemieApi();
100
+ const { isAuthenticated } = useOxy();
101
+ return useQuery({
102
+ queryKey: connectorQueryKeys.connected,
103
+ queryFn: async () =>
104
+ (await api.get<{ servers: Connection[] }>(CONNECTOR_ROUTES.connected)).data.servers,
105
+ enabled: isAuthenticated && enabled,
106
+ staleTime: 30_000,
107
+ });
108
+ }
109
+
110
+ /** A logo path the API answered, as a URL on its origin. */
111
+ export function useConnectorLogoUrl(logoUrl: string | null | undefined): string | null {
112
+ const { apiUrl } = useGemieRuntime();
113
+ if (!logoUrl) return null;
114
+ return logoUrl.startsWith('/') ? `${apiUrl.replace(/\/$/, '')}${logoUrl}` : null;
115
+ }
116
+
117
+ /**
118
+ * Open the provider's sign-in. On the web the page itself goes there, and comes back to `returnTo`
119
+ * with the result in its query (read by `useCompleteConnectorSignIn`). In the native app an auth
120
+ * session waits for the app's own scheme and hands back the URL it returned to.
121
+ */
122
+ async function openSignIn(authorizationUrl: string, returnTo: string): Promise<string | null> {
123
+ if (Platform.OS === 'web') {
124
+ window.location.assign(authorizationUrl);
125
+ return null;
126
+ }
127
+ const result = await WebBrowser.openAuthSessionAsync(authorizationUrl, returnTo);
128
+ return result.type === 'success' ? result.url : null;
129
+ }
130
+
131
+ /** `state` and `code` (or the error) from the URL a sign-in returned to. */
132
+ export function signInResult(
133
+ params: Record<string, string | string[] | undefined> | URLSearchParams,
134
+ ): { state: string; code: string } | { error: string } | null {
135
+ const read = (key: string) => {
136
+ const value = params instanceof URLSearchParams ? params.get(key) : params[key];
137
+ return typeof value === 'string' && value ? value : undefined;
138
+ };
139
+ const error = read('mcp_oauth_error');
140
+ if (error) return { error };
141
+ const state = read('mcp_oauth_state');
142
+ const code = read('mcp_oauth_code');
143
+ return state && code ? { state, code } : null;
144
+ }
145
+
146
+ export interface ConnectorActionsOptions {
147
+ /**
148
+ * Where the provider sends the person back: on the web a page of this app (the current one by
149
+ * default), in the native app its scheme (`gemies://connectors`, `alia://connectors`).
150
+ */
151
+ returnTo: string;
152
+ }
153
+
154
+ /**
155
+ * Connecting, adding a custom server, reconnecting, renaming and disconnecting. Each ends with the
156
+ * lists read again, so every screen that shows a connector shows it as it is.
157
+ */
158
+ export function useConnectorActions({ returnTo }: ConnectorActionsOptions) {
159
+ const api = useGemieApi();
160
+ const queryClient = useQueryClient();
161
+ const refresh = useCallback(
162
+ () => queryClient.invalidateQueries({ queryKey: connectorQueryKeys.connected }),
163
+ [queryClient],
164
+ );
165
+
166
+ const complete = useMutation({
167
+ mutationFn: async (input: { state: string; code: string }) =>
168
+ (await api.post<{ server: Connection }>(CONNECTOR_ROUTES.complete, input)).data.server,
169
+ onSuccess: refresh,
170
+ });
171
+
172
+ /** Sign in at the provider, and finish here when the native session hands the result back. */
173
+ const signIn = async (authorizationUrl: string): Promise<Connection | null> => {
174
+ const returned = await openSignIn(authorizationUrl, returnTo);
175
+ if (!returned) return null;
176
+ const result = signInResult(new URL(returned).searchParams);
177
+ if (!result) return null;
178
+ if ('error' in result) throw new Error(result.error);
179
+ return complete.mutateAsync(result);
180
+ };
181
+
182
+ const connect = useMutation({
183
+ mutationFn: async (registryId: string) => {
184
+ const { data } = await api.post<{ authorizationUrl: string }>(CONNECTOR_ROUTES.connect, {
185
+ registryId,
186
+ returnTo,
187
+ });
188
+ return signIn(data.authorizationUrl);
189
+ },
190
+ });
191
+
192
+ const addCustom = useMutation({
193
+ mutationFn: async (input: { name: string; url: string; headers?: Record<string, string> }) => {
194
+ const { data } = await api.post<{ server: Connection; authorizationUrl?: string }>(
195
+ CONNECTOR_ROUTES.custom,
196
+ { ...input, returnTo },
197
+ );
198
+ await refresh();
199
+ return data.authorizationUrl ? signIn(data.authorizationUrl) : data.server;
200
+ },
201
+ });
202
+
203
+ const reconnect = useMutation({
204
+ mutationFn: async (id: string) => {
205
+ const { data } = await api.post<{ server: Connection; authorizationUrl?: string }>(
206
+ CONNECTOR_ROUTES.reconnect(id),
207
+ { returnTo },
208
+ );
209
+ if (!data.authorizationUrl) {
210
+ await refresh();
211
+ return data.server;
212
+ }
213
+ return signIn(data.authorizationUrl);
214
+ },
215
+ });
216
+
217
+ const rename = useMutation({
218
+ mutationFn: async (input: { id: string; accountLabel: string | null }) => {
219
+ await api.patch(CONNECTOR_ROUTES.connection(input.id), { accountLabel: input.accountLabel });
220
+ },
221
+ onSuccess: refresh,
222
+ });
223
+
224
+ const disconnect = useMutation({
225
+ mutationFn: async (id: string) => {
226
+ await api.delete(CONNECTOR_ROUTES.connection(id));
227
+ },
228
+ onSuccess: refresh,
229
+ });
230
+
231
+ return { connect, addCustom, reconnect, rename, disconnect, complete };
232
+ }
233
+
234
+ /** The connector slug a tool name carries: `mcp_notion_2__search` → `notion_2`. */
235
+ function toolSlug(toolName: string | undefined): string | undefined {
236
+ if (!toolName?.startsWith('mcp_')) return undefined;
237
+ const end = toolName.indexOf('__');
238
+ return end > 4 ? toolName.slice(4, end) : undefined;
239
+ }
240
+
241
+ /**
242
+ * The account a tool name belongs to: `mcp_notion_2__search` is the connection whose slug is
243
+ * `notion_2` (the API builds tool names from the slug with every other character as `_`).
244
+ */
245
+ export function connectionOfTool(
246
+ connections: readonly Connection[] | undefined,
247
+ toolName: string | undefined,
248
+ ): Connection | undefined {
249
+ const slug = toolSlug(toolName);
250
+ if (!slug) return undefined;
251
+ return connections?.find((connection) => connection.name.replace(/[^a-zA-Z0-9]/g, '_') === slug);
252
+ }
253
+
254
+ /**
255
+ * The connector, and which of the person's accounts, a tool name belongs to; `undefined` for a
256
+ * tool that is not a connector's, or while the list is unread. The list is read only for a
257
+ * connector's tool.
258
+ */
259
+ export function useConnectionOfTool(toolName: string | undefined): Connection | undefined {
260
+ const { data } = useConnections({ enabled: toolSlug(toolName) !== undefined });
261
+ return connectionOfTool(data, toolName);
262
+ }
263
+
264
+ /** The copy key that says why a sign-in did not connect (`mcp_oauth_error`, or `failed`). */
265
+ export function signInErrorKey(error: string): string {
266
+ if (error === 'access_denied') return 'gemie.connectors.signIn.declined';
267
+ if (error === 'expired') return 'gemie.connectors.signIn.expired';
268
+ return 'gemie.connectors.signIn.failedGeneric';
269
+ }
270
+
271
+ /** The store's path in every app that draws it: where a web sign-in comes back to. */
272
+ export const CONNECTORS_PATH = '/connectors';
273
+
274
+ /**
275
+ * Where the provider sends the person back after signing in: the connectors store, which finishes
276
+ * it (`useWebSignInReturn`). On the web its page on this origin; in the native app its deep link
277
+ * on the app's own scheme (`gemies://connectors`), which the auth session is waiting for.
278
+ */
279
+ export function connectorReturnTo(nativeScheme: string): string {
280
+ if (Platform.OS === 'web' && typeof window !== 'undefined') {
281
+ return `${window.location.origin}${CONNECTORS_PATH}`;
282
+ }
283
+ return `${nativeScheme}:/${CONNECTORS_PATH}`;
284
+ }
285
+
286
+ /**
287
+ * On the web, finish the sign-in the store's page came back from: the provider returned the person here
288
+ * with `mcp_oauth_state` and `mcp_oauth_code` (or `mcp_oauth_error`) in the query. Each is finished
289
+ * once, the query is cleared, and `onDone` hears how it went. Native sign-ins finish in place
290
+ * (`useConnectorActions`), so this does nothing there.
291
+ */
292
+ export function useWebSignInReturn(
293
+ onDone: (outcome: { ok: true; connection: Connection } | { ok: false; error: string }) => void,
294
+ ) {
295
+ const api = useGemieApi();
296
+ const queryClient = useQueryClient();
297
+ const handled = useRef(false);
298
+ useEffect(() => {
299
+ if (Platform.OS !== 'web' || typeof window === 'undefined' || handled.current) return;
300
+ const query = new URLSearchParams(window.location.search);
301
+ const result = signInResult(query);
302
+ if (!result) return;
303
+ handled.current = true;
304
+ for (const key of ['mcp_oauth_state', 'mcp_oauth_code', 'mcp_oauth_error']) query.delete(key);
305
+ const rest = query.toString();
306
+ window.history.replaceState(
307
+ window.history.state,
308
+ '',
309
+ `${window.location.pathname}${rest ? `?${rest}` : ''}${window.location.hash}`,
310
+ );
311
+ if ('error' in result) {
312
+ onDone({ ok: false, error: result.error });
313
+ return;
314
+ }
315
+ api
316
+ .post<{ server: Connection }>(CONNECTOR_ROUTES.complete, result)
317
+ .then(async ({ data }) => {
318
+ await queryClient.invalidateQueries({ queryKey: connectorQueryKeys.connected });
319
+ onDone({ ok: true, connection: data.server });
320
+ })
321
+ .catch(() => onDone({ ok: false, error: 'failed' }));
322
+ // Once per page load: the query is cleared as soon as it is read.
323
+ }, []);
324
+ }
@@ -51,10 +51,17 @@ export function useAgentActivity(
51
51
  // Socket updates still provide live progress; hydration is best-effort.
52
52
  });
53
53
 
54
+ // The API's own token, refreshed when due (the session's base token is not, for this origin).
55
+ const linked = oxyServices.createLinkedClient({ baseURL: apiUrl });
54
56
  const socket = io(apiUrl, {
55
57
  transports: ['websocket'],
56
- // The function form reads a fresh token on every (re)connect, so it survives rotation.
57
- auth: (cb) => cb({ token: oxyServices.session.accessToken }),
58
+ // The function form asks for a token on every (re)connect, so it survives rotation.
59
+ auth: (cb) => {
60
+ linked.getAccessToken(apiUrl).then(
61
+ (token) => cb({ token }),
62
+ () => cb({}),
63
+ );
64
+ },
58
65
  reconnection: true,
59
66
  reconnectionAttempts: Infinity,
60
67
  reconnectionDelay: 1000,
@@ -73,6 +80,7 @@ export function useAgentActivity(
73
80
  return () => {
74
81
  cancelled = true;
75
82
  socket.disconnect();
83
+ linked.dispose();
76
84
  };
77
85
  }, [sessionId, agentId, handleEvent, api, apiUrl, oxyServices]);
78
86