@allanfsouza/aether-sdk 2.4.11 → 2.5.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.
package/README.md CHANGED
@@ -1,9 +1,383 @@
1
- # Plataforma SDK (Cliente JS/TS)
1
+ # 🚀 Aether SDK
2
2
 
3
- Este é o SDK oficial para interagir com a sua "Plataforma BaaS" (clone do Firebase). Ele gerencia autenticação, banco de dados genérico (com tempo real) e storage.
3
+ SDK oficial JavaScript/TypeScript para a plataforma **Aether BaaS**.
4
+
5
+ [![npm version](https://badge.fury.io/js/%40allanfsouza%2Faether-sdk.svg)](https://www.npmjs.com/package/@allanfsouza/aether-sdk)
4
6
 
5
7
  ## Instalação
6
8
 
7
9
  ```bash
8
- npm install @seu-username/plataforma-sdk
10
+ npm install @allanfsouza/aether-sdk
11
+ ```
12
+
13
+ ## Inicialização
14
+
15
+ ```typescript
16
+ import { PlataformaClient } from '@allanfsouza/aether-sdk';
17
+
18
+ const aether = new PlataformaClient({
19
+ baseUrl: 'https://sua-api.aether.com',
20
+ apiKey: 'seu-project-id',
21
+ persistSession: true // Salva sessão no localStorage (padrão: true)
22
+ });
23
+ ```
24
+
25
+ ---
26
+
27
+ ## 📦 Database
28
+
29
+ ```typescript
30
+ const users = aether.db.collection('users');
31
+
32
+ // Listar
33
+ const list = await users.list({ limit: 10 });
34
+
35
+ // Buscar por ID
36
+ const user = await users.get('user-id');
37
+
38
+ // Criar
39
+ const newUser = await users.create({ name: 'João', email: 'joao@email.com' });
40
+
41
+ // Atualizar
42
+ await users.update('user-id', { name: 'Novo Nome' });
43
+
44
+ // Deletar
45
+ await users.delete('user-id');
46
+ ```
47
+
48
+ ### Query Builder
49
+
50
+ ```typescript
51
+ const adults = await aether.db.collection('users')
52
+ .query()
53
+ .eq('status', 'active')
54
+ .gt('age', 18)
55
+ .order('name', 'ASC')
56
+ .limit(50)
57
+ .get();
58
+ ```
59
+
60
+ ---
61
+
62
+ ## 🔐 Autenticação
63
+
64
+ ```typescript
65
+ // Login
66
+ const { accessToken, user } = await aether.auth.login('email@test.com', 'senha');
67
+
68
+ // Registro
69
+ await aether.auth.register({ name: 'João', email: 'joao@email.com', password: 'senha' });
70
+
71
+ // Logout
72
+ await aether.auth.logout();
73
+
74
+ // Sessão
75
+ const user = aether.auth.getCurrentUser();
76
+ ```
77
+
78
+ ---
79
+
80
+ ## 📁 Storage
81
+
82
+ ```typescript
83
+ // Upload
84
+ const { data } = await aether.storage.upload(file, 'avatar.png', 'image/png');
85
+ console.log(data.downloadUrl);
86
+
87
+ // Listar
88
+ const files = await aether.storage.list('folder');
89
+
90
+ // Deletar
91
+ await aether.storage.delete('file-id');
92
+ ```
93
+
94
+ ---
95
+
96
+ ## ⚡ Functions
97
+
98
+ ```typescript
99
+ // Invocar função
100
+ const result = await aether.functions.invoke('send-email', {
101
+ to: 'user@email.com',
102
+ subject: 'Olá!',
103
+ body: 'Bem-vindo!'
104
+ });
105
+ ```
106
+
107
+ ---
108
+
109
+ ## 📱 Push Notifications
110
+
111
+ ```typescript
112
+ // Registrar dispositivo
113
+ await aether.push.registerDevice({
114
+ token: 'fcm-token',
115
+ platform: 'android',
116
+ environment: 'prod'
117
+ });
118
+
119
+ // Enviar para usuário
120
+ await aether.push.sendToUser({
121
+ userId: 'user-id',
122
+ title: 'Olá!',
123
+ body: 'Nova mensagem'
124
+ });
125
+ ```
126
+
127
+ ---
128
+
129
+ ## 🤖 AI (Inteligência Artificial)
130
+
131
+ O módulo de IA permite adicionar capacidades de linguagem natural aos seus apps.
132
+ **Limites de uso são aplicados por plano** - veja a seção de [Monetização](#-monetização-e-quotas).
133
+
134
+ ### Chat Simples
135
+
136
+ ```typescript
137
+ // Pergunta simples (aguarda resposta completa)
138
+ const { text, conversationId } = await aether.ai.ask("Quais produtos estão em promoção?");
139
+ console.log(text);
140
+ ```
141
+
142
+ ### Chat com Streaming
143
+
144
+ ```typescript
145
+ // Resposta em tempo real (chunk por chunk)
146
+ await aether.ai.chat("Explique como funciona o sistema de pagamentos", {
147
+ conversationId: 'conv-id-opcional', // Mantém contexto
148
+ onChunk: (chunk) => {
149
+ // Atualiza UI em tempo real
150
+ setResponse(prev => prev + chunk);
151
+ },
152
+ onComplete: (fullResponse, meta) => {
153
+ console.log("Conversa:", meta.conversationId);
154
+ },
155
+ onError: (error) => {
156
+ console.error(error);
157
+ }
158
+ });
159
+ ```
160
+
161
+ ### Busca Semântica
162
+
163
+ ```typescript
164
+ // Encontra documentos similares usando embeddings
165
+ const results = await aether.ai.search("tênis confortável para corrida", {
166
+ collection: "products", // Opcional: filtrar por collection
167
+ limit: 10,
168
+ minScore: 0.7
169
+ });
170
+
171
+ results.forEach(r => console.log(r.content, r.similarity));
9
172
  ```
173
+
174
+ ### Geração de Conteúdo
175
+
176
+ ```typescript
177
+ // Gera texto baseado em dados e prompt
178
+ const descricao = await aether.ai.generate(
179
+ "Escreva uma descrição para o produto",
180
+ { name: "iPhone 15", price: 5999, features: ["5G", "48MP"] },
181
+ { tone: 'friendly', length: 'medium', language: 'pt-BR' }
182
+ );
183
+ ```
184
+
185
+ ### Análise de Dados
186
+
187
+ ```typescript
188
+ // Analisa dados e retorna insights em linguagem natural
189
+ const { insights, data } = await aether.ai.analyze("orders", {
190
+ question: "Como foram as vendas essa semana?",
191
+ period: "7d"
192
+ });
193
+ console.log(insights);
194
+ ```
195
+
196
+ ### Conversão de Linguagem Natural para Query
197
+
198
+ ```typescript
199
+ // Converte texto em filtros estruturados
200
+ const query = await aether.ai.parseQuery(
201
+ "produtos vermelhos acima de 100 reais ordenados por preço"
202
+ );
203
+ // Retorna: { filter: { color: 'vermelho', price: { $gt: 100 } }, sort: { price: 'ASC' } }
204
+ ```
205
+
206
+ ### Gerenciar Conversas
207
+
208
+ ```typescript
209
+ // Listar conversas
210
+ const conversas = await aether.ai.conversations.list();
211
+
212
+ // Histórico de mensagens
213
+ const mensagens = await aether.ai.conversations.getMessages(conversationId);
214
+
215
+ // Renomear conversa
216
+ await aether.ai.conversations.rename(conversationId, "Suporte Técnico");
217
+
218
+ // Deletar conversa
219
+ await aether.ai.conversations.delete(conversationId);
220
+ ```
221
+
222
+ ### Memória de Usuário (Pro+)
223
+
224
+ ```typescript
225
+ // Salvar preferências do usuário
226
+ await aether.ai.memory.set("user-123", "preferences", {
227
+ theme: "dark",
228
+ language: "pt-BR"
229
+ });
230
+
231
+ // Buscar memória
232
+ const prefs = await aether.ai.memory.get("user-123", "preferences");
233
+
234
+ // Listar chaves
235
+ const keys = await aether.ai.memory.listKeys("user-123");
236
+
237
+ // Deletar memória
238
+ await aether.ai.memory.delete("user-123", "preferences");
239
+ ```
240
+
241
+ ### Feedback
242
+
243
+ ```typescript
244
+ // Enviar feedback sobre resposta
245
+ await aether.ai.feedback(messageId, 'thumbs_up');
246
+ await aether.ai.feedback(messageId, 'thumbs_down', 'Resposta incorreta');
247
+ ```
248
+
249
+ ### Verificar Uso
250
+
251
+ ```typescript
252
+ // Retorna informações de quota
253
+ const usage = await aether.ai.getUsage();
254
+ console.log(`${usage.percentUsed}% do limite usado`);
255
+ console.log(`Requests: ${usage.requestsUsed}/${usage.requestsLimit}`);
256
+ console.log(`Tokens: ${usage.tokensUsed}/${usage.tokensLimit}`);
257
+ console.log(`Reset: ${usage.resetsAt}`);
258
+ ```
259
+
260
+ ### Funções Administrativas
261
+
262
+ ```typescript
263
+ // Configurar persona da IA
264
+ await aether.ai.admin.setPersona({
265
+ name: "Luna",
266
+ role: "Assistente de Vendas",
267
+ personality: "Amigável e usa emojis 🎉",
268
+ rules: ["Sempre sugira produtos relacionados", "Responda em português"],
269
+ temperature: 0.8
270
+ });
271
+
272
+ // Buscar persona
273
+ const persona = await aether.ai.admin.getPersona();
274
+
275
+ // Reindexa dados para RAG
276
+ await aether.ai.admin.reindex();
277
+
278
+ // Estatísticas de uso
279
+ const stats = await aether.ai.admin.stats();
280
+ console.log(stats.totalConversations, stats.totalMessages);
281
+
282
+ // Configurar collections indexadas
283
+ await aether.ai.admin.setIndexedCollections(['products', 'articles', 'faq']);
284
+
285
+ // Limpar embeddings (CUIDADO!)
286
+ await aether.ai.admin.clear();
287
+ ```
288
+
289
+ ---
290
+
291
+ ## 💰 Monetização e Quotas
292
+
293
+ O uso de IA é limitado por plano para controlar custos:
294
+
295
+ | Plano | Requests/mês | Tokens/mês | Features |
296
+ |-------|--------------|------------|----------|
297
+ | **FREE** | 100 | 50k | Chat, Search |
298
+ | **PRO** | 10.000 | 2M | + Generate, Analyze, Memory, Persona |
299
+ | **BUSINESS** | 100.000 | 20M | + Vision, Tudo liberado |
300
+
301
+ ### Quando o limite é atingido
302
+
303
+ ```typescript
304
+ try {
305
+ await aether.ai.ask("Pergunta...");
306
+ } catch (error) {
307
+ if (error.code === 'QUOTA_EXCEEDED') {
308
+ console.log(error.usage.percentUsed); // 100
309
+ console.log(error.upgradeUrl); // '/billing/upgrade'
310
+ }
311
+ }
312
+ ```
313
+
314
+ ### Features por plano
315
+
316
+ | Feature | Free | Pro | Business |
317
+ |---------|:----:|:---:|:--------:|
318
+ | Chat/Ask | ✅ | ✅ | ✅ |
319
+ | Search | ✅ | ✅ | ✅ |
320
+ | Streaming | ✅ | ✅ | ✅ |
321
+ | Generate | ❌ | ✅ | ✅ |
322
+ | Analyze | ❌ | ✅ | ✅ |
323
+ | ParseQuery | ❌ | ✅ | ✅ |
324
+ | Memory | ❌ | ✅ | ✅ |
325
+ | Persona | ❌ | ✅ | ✅ |
326
+ | Suggestions | ❌ | ✅ | ✅ |
327
+ | Vision | ❌ | ❌ | ✅ |
328
+
329
+ ---
330
+
331
+ ## 👥 Tenant Auth
332
+
333
+ Para apps que precisam de sistema de login para usuários finais:
334
+
335
+ ```typescript
336
+ // Registro de usuário no projeto
337
+ const { user } = await aether.tenantAuth.signUp('project-id', {
338
+ email: 'usuario@app.com',
339
+ password: 'senha123',
340
+ name: 'Nome'
341
+ });
342
+
343
+ // Login
344
+ const { accessToken, user } = await aether.tenantAuth.signIn('project-id', {
345
+ email: 'usuario@app.com',
346
+ password: 'senha123'
347
+ });
348
+
349
+ // Perfil
350
+ const profile = await aether.tenantAuth.getProfile();
351
+
352
+ // Logout
353
+ aether.tenantAuth.signOut();
354
+ ```
355
+
356
+ ---
357
+
358
+ ## 📖 Tipos Exportados
359
+
360
+ ```typescript
361
+ import type {
362
+ // Auth
363
+ LoginResponse, Session, User,
364
+ // Database
365
+ ListOptions,
366
+ // Push
367
+ PushDevice, PushStatus, PushStats,
368
+ // Tenant
369
+ TenantUser, TenantLoginResponse,
370
+ // AI
371
+ ChatOptions, ChatMetadata, AskResponse,
372
+ Conversation, Message, FeedbackType,
373
+ SemanticSearchOptions, SemanticSearchResult,
374
+ GenerateOptions, RetrievedSource,
375
+ UsageInfo, PersonaConfig
376
+ } from '@allanfsouza/aether-sdk';
377
+ ```
378
+
379
+ ---
380
+
381
+ ## 📝 Licença
382
+
383
+ MIT © Allan Felipe de Souza
package/dist/ai.d.ts CHANGED
@@ -102,11 +102,37 @@ export interface GenerateOptions {
102
102
  /** Contexto adicional para a geração */
103
103
  context?: string;
104
104
  }
105
+ /**
106
+ * Informações de uso/quota
107
+ */
108
+ export interface UsageInfo {
109
+ requestsUsed: number;
110
+ requestsLimit: number;
111
+ tokensUsed: number;
112
+ tokensLimit: number;
113
+ percentUsed: number;
114
+ plan: string;
115
+ resetsAt: string;
116
+ }
117
+ /**
118
+ * Configuração de persona
119
+ */
120
+ export interface PersonaConfig {
121
+ name: string;
122
+ role: string;
123
+ personality?: string;
124
+ language?: string;
125
+ rules?: string[];
126
+ knowledge?: string[];
127
+ temperature?: number;
128
+ }
105
129
  export declare class AIModule {
106
130
  private client;
107
131
  private http;
108
132
  /** Sub-módulo para gerenciar conversas */
109
133
  conversations: ConversationsAPI;
134
+ /** Sub-módulo para gerenciar memória de usuários */
135
+ memory: MemoryAPI;
110
136
  /** Sub-módulo para funções administrativas */
111
137
  admin: AIAdminAPI;
112
138
  constructor(client: PlataformaClient, http: AxiosInstance);
@@ -205,6 +231,14 @@ export declare class AIModule {
205
231
  filter?: Record<string, any>;
206
232
  sort?: Record<string, any>;
207
233
  }>;
234
+ /**
235
+ * Retorna informações de uso e quota.
236
+ *
237
+ * @example
238
+ * const usage = await aether.ai.getUsage();
239
+ * console.log(`${usage.percentUsed}% do limite usado`);
240
+ */
241
+ getUsage(): Promise<UsageInfo>;
208
242
  }
209
243
  declare class ConversationsAPI {
210
244
  private client;
@@ -241,6 +275,33 @@ declare class ConversationsAPI {
241
275
  */
242
276
  rename(conversationId: string, title: string): Promise<Conversation>;
243
277
  }
278
+ declare class MemoryAPI {
279
+ private client;
280
+ private http;
281
+ constructor(client: PlataformaClient, http: AxiosInstance);
282
+ /**
283
+ * Busca memória de um usuário.
284
+ *
285
+ * @example
286
+ * const prefs = await aether.ai.memory.get("user-123", "preferences");
287
+ */
288
+ get(userId: string, key: string): Promise<any>;
289
+ /**
290
+ * Salva memória de um usuário.
291
+ *
292
+ * @example
293
+ * await aether.ai.memory.set("user-123", "preferences", { theme: "dark" });
294
+ */
295
+ set(userId: string, key: string, value: any): Promise<void>;
296
+ /**
297
+ * Deleta memória de um usuário.
298
+ */
299
+ delete(userId: string, key?: string): Promise<void>;
300
+ /**
301
+ * Lista todas as chaves de memória de um usuário.
302
+ */
303
+ listKeys(userId: string): Promise<string[]>;
304
+ }
244
305
  declare class AIAdminAPI {
245
306
  private client;
246
307
  private http;
@@ -296,5 +357,21 @@ declare class AIAdminAPI {
296
357
  autoIndex: boolean;
297
358
  embeddingModel: string;
298
359
  }>;
360
+ /**
361
+ * Configura a persona da IA para o projeto.
362
+ *
363
+ * @example
364
+ * await aether.ai.admin.setPersona({
365
+ * name: "Luna",
366
+ * role: "Assistente de Vendas",
367
+ * personality: "Amigável e usa emojis",
368
+ * rules: ["Sempre sugira produtos relacionados"]
369
+ * });
370
+ */
371
+ setPersona(config: PersonaConfig): Promise<void>;
372
+ /**
373
+ * Busca a persona configurada.
374
+ */
375
+ getPersona(): Promise<PersonaConfig | null>;
299
376
  }
300
377
  export {};
package/dist/ai.js CHANGED
@@ -10,6 +10,7 @@ export class AIModule {
10
10
  this.client = client;
11
11
  this.http = http;
12
12
  this.conversations = new ConversationsAPI(client, http);
13
+ this.memory = new MemoryAPI(client, http);
13
14
  this.admin = new AIAdminAPI(client, http);
14
15
  }
15
16
  // ===========================================================================
@@ -243,6 +244,22 @@ export class AIModule {
243
244
  });
244
245
  return data;
245
246
  }
247
+ // ===========================================================================
248
+ // INFORMAÇÕES DE USO
249
+ // ===========================================================================
250
+ /**
251
+ * Retorna informações de uso e quota.
252
+ *
253
+ * @example
254
+ * const usage = await aether.ai.getUsage();
255
+ * console.log(`${usage.percentUsed}% do limite usado`);
256
+ */
257
+ async getUsage() {
258
+ const { data } = await this.http.get('/ai/usage', {
259
+ params: { projectId: this.client.projectId }
260
+ });
261
+ return data;
262
+ }
246
263
  }
247
264
  // =============================================================================
248
265
  // SUB-MÓDULO: CONVERSAS
@@ -298,6 +315,69 @@ class ConversationsAPI {
298
315
  }
299
316
  }
300
317
  // =============================================================================
318
+ // SUB-MÓDULO: MEMÓRIA DE USUÁRIO
319
+ // =============================================================================
320
+ class MemoryAPI {
321
+ constructor(client, http) {
322
+ this.client = client;
323
+ this.http = http;
324
+ }
325
+ /**
326
+ * Busca memória de um usuário.
327
+ *
328
+ * @example
329
+ * const prefs = await aether.ai.memory.get("user-123", "preferences");
330
+ */
331
+ async get(userId, key) {
332
+ const { data } = await this.http.get('/ai/memory', {
333
+ params: {
334
+ projectId: this.client.projectId,
335
+ userId,
336
+ key
337
+ }
338
+ });
339
+ return data.value;
340
+ }
341
+ /**
342
+ * Salva memória de um usuário.
343
+ *
344
+ * @example
345
+ * await aether.ai.memory.set("user-123", "preferences", { theme: "dark" });
346
+ */
347
+ async set(userId, key, value) {
348
+ await this.http.post('/ai/memory', {
349
+ projectId: this.client.projectId,
350
+ userId,
351
+ key,
352
+ value
353
+ });
354
+ }
355
+ /**
356
+ * Deleta memória de um usuário.
357
+ */
358
+ async delete(userId, key) {
359
+ await this.http.delete('/ai/memory', {
360
+ params: {
361
+ projectId: this.client.projectId,
362
+ userId,
363
+ key
364
+ }
365
+ });
366
+ }
367
+ /**
368
+ * Lista todas as chaves de memória de um usuário.
369
+ */
370
+ async listKeys(userId) {
371
+ const { data } = await this.http.get('/ai/memory/keys', {
372
+ params: {
373
+ projectId: this.client.projectId,
374
+ userId
375
+ }
376
+ });
377
+ return data.keys || [];
378
+ }
379
+ }
380
+ // =============================================================================
301
381
  // SUB-MÓDULO: ADMIN
302
382
  // =============================================================================
303
383
  class AIAdminAPI {
@@ -367,4 +447,30 @@ class AIAdminAPI {
367
447
  });
368
448
  return data;
369
449
  }
450
+ /**
451
+ * Configura a persona da IA para o projeto.
452
+ *
453
+ * @example
454
+ * await aether.ai.admin.setPersona({
455
+ * name: "Luna",
456
+ * role: "Assistente de Vendas",
457
+ * personality: "Amigável e usa emojis",
458
+ * rules: ["Sempre sugira produtos relacionados"]
459
+ * });
460
+ */
461
+ async setPersona(config) {
462
+ await this.http.post('/ai/persona', {
463
+ projectId: this.client.projectId,
464
+ ...config
465
+ });
466
+ }
467
+ /**
468
+ * Busca a persona configurada.
469
+ */
470
+ async getPersona() {
471
+ const { data } = await this.http.get('/ai/persona', {
472
+ params: { projectId: this.client.projectId }
473
+ });
474
+ return data.persona || null;
475
+ }
370
476
  }
package/dist/index.d.ts CHANGED
@@ -5,6 +5,7 @@ import { StorageModule } from "./storage.js";
5
5
  import { FunctionsModule } from "./functions.js";
6
6
  import { PushModule } from "./push.js";
7
7
  import { TenantAuthModule } from "./tenant-auth.js";
8
+ import { AIModule } from "./ai.js";
8
9
  /**
9
10
  * Configuração usada para criar o cliente principal da plataforma.
10
11
  */
@@ -31,6 +32,7 @@ export declare class PlataformaClient {
31
32
  functions: FunctionsModule;
32
33
  push: PushModule;
33
34
  tenantAuth: TenantAuthModule;
35
+ ai: AIModule;
34
36
  database: DatabaseModule;
35
37
  apiUrl: string;
36
38
  projectId: string;
@@ -85,3 +87,4 @@ export type { LoginResponse, Session, User } from "./auth.js";
85
87
  export type { ListOptions } from "./database.js";
86
88
  export type { PushPlatform, PushEnvironment, PushDevice, RegisterDeviceParams, SendPushResponse, PushStatus, PushLogEntry, ListPushLogsOptions, PushStats, } from "./push.js";
87
89
  export type { TenantUser, TenantLoginResponse, TenantRegisterCredentials, TenantLoginCredentials, } from "./tenant-auth.js";
90
+ export type { ChatOptions, ChatMetadata, AskResponse, Conversation, Message, FeedbackType, SemanticSearchOptions, SemanticSearchResult, GenerateOptions, RetrievedSource, UsageInfo, PersonaConfig, } from "./ai.js";
package/dist/index.js CHANGED
@@ -5,6 +5,7 @@ import { StorageModule } from "./storage.js";
5
5
  import { FunctionsModule } from "./functions.js";
6
6
  import { PushModule } from "./push.js";
7
7
  import { TenantAuthModule } from "./tenant-auth.js";
8
+ import { AIModule } from "./ai.js";
8
9
  // =============================================================================
9
10
  // CONSTANTES DE STORAGE
10
11
  // Chaves padronizadas para localStorage - evita conflito com outros SDKs
@@ -48,6 +49,7 @@ export class PlataformaClient {
48
49
  this.functions = new FunctionsModule(this, this.http);
49
50
  this.push = new PushModule(this, this.http);
50
51
  this.tenantAuth = new TenantAuthModule(this, this.http);
52
+ this.ai = new AIModule(this, this.http);
51
53
  // Cria o alias que o Showcase App espera
52
54
  this.database = this.db;
53
55
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allanfsouza/aether-sdk",
3
- "version": "2.4.11",
3
+ "version": "2.5.1",
4
4
  "description": "SDK do Cliente para a Plataforma Aether",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/src/ai.ts CHANGED
@@ -132,6 +132,32 @@ export interface GenerateOptions {
132
132
  context?: string;
133
133
  }
134
134
 
135
+ /**
136
+ * Informações de uso/quota
137
+ */
138
+ export interface UsageInfo {
139
+ requestsUsed: number;
140
+ requestsLimit: number;
141
+ tokensUsed: number;
142
+ tokensLimit: number;
143
+ percentUsed: number;
144
+ plan: string;
145
+ resetsAt: string;
146
+ }
147
+
148
+ /**
149
+ * Configuração de persona
150
+ */
151
+ export interface PersonaConfig {
152
+ name: string;
153
+ role: string;
154
+ personality?: string;
155
+ language?: string;
156
+ rules?: string[];
157
+ knowledge?: string[];
158
+ temperature?: number;
159
+ }
160
+
135
161
  // =============================================================================
136
162
  // MÓDULO PRINCIPAL
137
163
  // =============================================================================
@@ -143,6 +169,9 @@ export class AIModule {
143
169
  /** Sub-módulo para gerenciar conversas */
144
170
  public conversations: ConversationsAPI;
145
171
 
172
+ /** Sub-módulo para gerenciar memória de usuários */
173
+ public memory: MemoryAPI;
174
+
146
175
  /** Sub-módulo para funções administrativas */
147
176
  public admin: AIAdminAPI;
148
177
 
@@ -150,6 +179,7 @@ export class AIModule {
150
179
  this.client = client;
151
180
  this.http = http;
152
181
  this.conversations = new ConversationsAPI(client, http);
182
+ this.memory = new MemoryAPI(client, http);
153
183
  this.admin = new AIAdminAPI(client, http);
154
184
  }
155
185
 
@@ -425,6 +455,24 @@ export class AIModule {
425
455
  });
426
456
  return data;
427
457
  }
458
+
459
+ // ===========================================================================
460
+ // INFORMAÇÕES DE USO
461
+ // ===========================================================================
462
+
463
+ /**
464
+ * Retorna informações de uso e quota.
465
+ *
466
+ * @example
467
+ * const usage = await aether.ai.getUsage();
468
+ * console.log(`${usage.percentUsed}% do limite usado`);
469
+ */
470
+ async getUsage(): Promise<UsageInfo> {
471
+ const { data } = await this.http.get('/ai/usage', {
472
+ params: { projectId: this.client.projectId }
473
+ });
474
+ return data;
475
+ }
428
476
  }
429
477
 
430
478
  // =============================================================================
@@ -489,6 +537,78 @@ class ConversationsAPI {
489
537
  }
490
538
  }
491
539
 
540
+ // =============================================================================
541
+ // SUB-MÓDULO: MEMÓRIA DE USUÁRIO
542
+ // =============================================================================
543
+
544
+ class MemoryAPI {
545
+ private client: PlataformaClient;
546
+ private http: AxiosInstance;
547
+
548
+ constructor(client: PlataformaClient, http: AxiosInstance) {
549
+ this.client = client;
550
+ this.http = http;
551
+ }
552
+
553
+ /**
554
+ * Busca memória de um usuário.
555
+ *
556
+ * @example
557
+ * const prefs = await aether.ai.memory.get("user-123", "preferences");
558
+ */
559
+ async get(userId: string, key: string): Promise<any> {
560
+ const { data } = await this.http.get('/ai/memory', {
561
+ params: {
562
+ projectId: this.client.projectId,
563
+ userId,
564
+ key
565
+ }
566
+ });
567
+ return data.value;
568
+ }
569
+
570
+ /**
571
+ * Salva memória de um usuário.
572
+ *
573
+ * @example
574
+ * await aether.ai.memory.set("user-123", "preferences", { theme: "dark" });
575
+ */
576
+ async set(userId: string, key: string, value: any): Promise<void> {
577
+ await this.http.post('/ai/memory', {
578
+ projectId: this.client.projectId,
579
+ userId,
580
+ key,
581
+ value
582
+ });
583
+ }
584
+
585
+ /**
586
+ * Deleta memória de um usuário.
587
+ */
588
+ async delete(userId: string, key?: string): Promise<void> {
589
+ await this.http.delete('/ai/memory', {
590
+ params: {
591
+ projectId: this.client.projectId,
592
+ userId,
593
+ key
594
+ }
595
+ });
596
+ }
597
+
598
+ /**
599
+ * Lista todas as chaves de memória de um usuário.
600
+ */
601
+ async listKeys(userId: string): Promise<string[]> {
602
+ const { data } = await this.http.get('/ai/memory/keys', {
603
+ params: {
604
+ projectId: this.client.projectId,
605
+ userId
606
+ }
607
+ });
608
+ return data.keys || [];
609
+ }
610
+ }
611
+
492
612
  // =============================================================================
493
613
  // SUB-MÓDULO: ADMIN
494
614
  // =============================================================================
@@ -577,4 +697,32 @@ class AIAdminAPI {
577
697
  });
578
698
  return data;
579
699
  }
700
+
701
+ /**
702
+ * Configura a persona da IA para o projeto.
703
+ *
704
+ * @example
705
+ * await aether.ai.admin.setPersona({
706
+ * name: "Luna",
707
+ * role: "Assistente de Vendas",
708
+ * personality: "Amigável e usa emojis",
709
+ * rules: ["Sempre sugira produtos relacionados"]
710
+ * });
711
+ */
712
+ async setPersona(config: PersonaConfig): Promise<void> {
713
+ await this.http.post('/ai/persona', {
714
+ projectId: this.client.projectId,
715
+ ...config
716
+ });
717
+ }
718
+
719
+ /**
720
+ * Busca a persona configurada.
721
+ */
722
+ async getPersona(): Promise<PersonaConfig | null> {
723
+ const { data } = await this.http.get('/ai/persona', {
724
+ params: { projectId: this.client.projectId }
725
+ });
726
+ return data.persona || null;
727
+ }
580
728
  }
package/src/index.ts CHANGED
@@ -7,6 +7,7 @@ import { StorageModule } from "./storage.js";
7
7
  import { FunctionsModule } from "./functions.js";
8
8
  import { PushModule } from "./push.js";
9
9
  import { TenantAuthModule, TenantUser, TenantLoginResponse, TenantRegisterCredentials, TenantLoginCredentials } from "./tenant-auth.js";
10
+ import { AIModule } from "./ai.js";
10
11
 
11
12
  // =============================================================================
12
13
  // CONSTANTES DE STORAGE
@@ -59,6 +60,7 @@ export class PlataformaClient {
59
60
  public functions: FunctionsModule;
60
61
  public push: PushModule;
61
62
  public tenantAuth: TenantAuthModule;
63
+ public ai: AIModule;
62
64
 
63
65
  // Alias para 'db' que o showcase tenta usar como 'database'
64
66
  public database: DatabaseModule;
@@ -101,6 +103,7 @@ export class PlataformaClient {
101
103
  this.functions = new FunctionsModule(this, this.http);
102
104
  this.push = new PushModule(this, this.http);
103
105
  this.tenantAuth = new TenantAuthModule(this, this.http);
106
+ this.ai = new AIModule(this, this.http);
104
107
 
105
108
  // Cria o alias que o Showcase App espera
106
109
  this.database = this.db;
@@ -258,4 +261,18 @@ export type {
258
261
  TenantLoginResponse,
259
262
  TenantRegisterCredentials,
260
263
  TenantLoginCredentials,
261
- } from "./tenant-auth.js";
264
+ } from "./tenant-auth.js";
265
+ export type {
266
+ ChatOptions,
267
+ ChatMetadata,
268
+ AskResponse,
269
+ Conversation,
270
+ Message,
271
+ FeedbackType,
272
+ SemanticSearchOptions,
273
+ SemanticSearchResult,
274
+ GenerateOptions,
275
+ RetrievedSource,
276
+ UsageInfo,
277
+ PersonaConfig,
278
+ } from "./ai.js";