mitra-interactions-sdk 1.0.60-beta.21 → 1.0.60-beta.23

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
@@ -244,6 +244,125 @@ const result2 = await listRecordsMitra({
244
244
  });
245
245
  ```
246
246
 
247
+ ## Agent Chat (embedded)
248
+
249
+ Chat com o agente de IA embarcado, sobre um WebSocket compartilhado. Uma única conexão atende todas as sessions — o roteamento de eventos é feito por `taskId`.
250
+
251
+ A URL do WebSocket é derivada da `baseURL` configurada: mesmo domínio/path, protocolo `http(s)` → `ws(s)`, endpoint `/sdk-ws`. Ex.: `baseURL: 'https://stg.mitralab.io/legacy'` → `wss://stg.mitralab.io/legacy/sdk-ws`. Precisa de `token` configurado (faça login antes ou passe em `configureSdkMitra`).
252
+
253
+ ### Gerenciar os chats — `manageAgentChatMitra`
254
+
255
+ Operações stateless sobre a coleção de chats do usuário: listar, renomear, deletar.
256
+
257
+ ```typescript
258
+ import { manageAgentChatMitra } from 'mitra-interactions-sdk';
259
+
260
+ const chats = await manageAgentChatMitra({ action: 'list' }); // AgentChat[]
261
+ const renamed = await manageAgentChatMitra({ action: 'rename', taskId, name: 'Novo nome' });
262
+ const deleted = await manageAgentChatMitra({ action: 'delete', taskId });
263
+ ```
264
+
265
+ - `action: 'list'` → `AgentChat[]` — `{ id, name, agentType?, provider?, createdAt, updatedAt }`. Aceita `projectId?` pra sobrescrever o global e `agentId?` pra filtrar os chats de um agente business (omitido = todos).
266
+ - `action: 'rename'` → `{ taskId, name }`
267
+ - `action: 'delete'` → `{ taskId, deleted }`
268
+
269
+ ### Abrir uma session — `getAgentTaskMitra`
270
+
271
+ Retorna uma `AgentTaskSession` que encapsula todo o ciclo de vida de um chat (histórico, streaming, fila, cancel, eventos). Abrir a mesma `taskId` duas vezes devolve a **mesma** instância (cache).
272
+
273
+ ```typescript
274
+ import { getAgentTaskMitra } from 'mitra-interactions-sdk';
275
+
276
+ // Chat novo — taskId é preenchido depois do primeiro send()
277
+ const session = getAgentTaskMitra({ create: true, agentType: 'claudecode', modelId: 'openai/gpt-5.5:medium' });
278
+
279
+ // Chat existente — detecta automaticamente se já há stream ativo
280
+ const existing = getAgentTaskMitra({ taskId: 'abc123' });
281
+ await existing.loadHistory({ limit: 50 });
282
+ ```
283
+
284
+ `getAgentTaskMitra({ create: true, projectId?, agentType?, modelId?, name?, agentId? })` ou `getAgentTaskMitra({ taskId })`.
285
+
286
+ **Agente business (`agentId`)**: passe o `id` de um agente business (CRUD via `mitra-sdk`: `listAgentsMitra` e família) pra sessão subir com o system prompt do agente e um token escopado — as tools enxergam só as Server Functions daquele agente. Sem `agentId`, é o chat de desenvolvimento de sempre.
287
+
288
+ ```typescript
289
+ // Chat com um agente business (prompt + SFs do agente)
290
+ const sales = getAgentTaskMitra({ create: true, agentId: 'uuid-do-agente' });
291
+ ```
292
+
293
+ #### Propriedades (somente leitura)
294
+
295
+ | Propriedade | Tipo | Descrição |
296
+ |-------------|------|-----------|
297
+ | `taskId` | `string \| null` | `null` até o primeiro `send()` num chat novo |
298
+ | `task` | `AgentChat \| null` | Metadados do chat após criado |
299
+ | `isNew` | `boolean` | Se foi aberto via `{ create: true }` |
300
+ | `status` | `AgentTaskStatus` | `opening` · `idle` · `streaming` · `cancelled` · `error` · `closed` |
301
+ | `history` | `AgentMessage[]` | Histórico carregado |
302
+ | `content` | `string` | Conteúdo acumulado do turno atual |
303
+ | `queue` | `QueuedItem[]` | Mensagens enfileiradas (enviadas enquanto streamava) |
304
+
305
+ #### Métodos
306
+
307
+ - `send(prompt, options?)` → `void` — dispara um turno. Se já está streamando, **enfileira** (FIFO, máx 10). `options`: `{ agentType?, modelId? }`.
308
+ - `cancel()` → `Promise<void>` — cancela o turno atual; resolve quando o backend confirma (ou safety net de 30s).
309
+ - `loadHistory({ limit? })` → `Promise<AgentMessage[]>` — carrega o histórico do chat.
310
+ - `editQueueItem(id, text)` / `removeQueueItem(id)` / `clearQueue()` — manipulam a fila.
311
+ - `on(event, handler)` → função de unsubscribe — assina eventos da session.
312
+ - `close()` — encerra a session e libera os listeners.
313
+
314
+ #### Eventos (`session.on`)
315
+
316
+ `statusChange` · `historyLoaded` · `taskCreated` · `turnStart` · `delta` · `tool` · `turnEnd` · `cancelled` · `queueChange` · `error`.
317
+
318
+ ```typescript
319
+ const session = getAgentTaskMitra({ create: true });
320
+
321
+ session.on('delta', ({ delta, kind }) => process.stdout.write(delta)); // kind: 'text' | 'tool'
322
+ session.on('tool', ({ tool, input }) => console.log('🔧', tool));
323
+ session.on('turnEnd', ({ content }) => console.log('\n✓ fim do turno'));
324
+ session.on('taskCreated', ({ task }) => console.log('chat criado:', task.id));
325
+ session.on('error', ({ error }) => console.error(error));
326
+
327
+ session.send('Analise estas vendas e gere um resumo');
328
+
329
+ // Modelo por turno (sobrescreve o default da session)
330
+ session.send('Refaça com mais detalhes', { modelId: 'subscription:anthropic:claude-opus-4-7' });
331
+ ```
332
+
333
+ ### Credenciais do agente — `manageAgentCredentialMitra`
334
+
335
+ Função única (sobre `/sdk-ws`) para API keys (8 providers: `anthropic`, `openai`, `gemini`, `kimi`, `minimax`, `glm`, `qwen`, `openrouter`) e subscriptions OAuth (Claude paste-código / OpenAI device flow via Codex).
336
+
337
+ > 🔒 Segurança: o token de subscription **nunca volta cru** pro cliente — fica server-side e é injetado no sandbox direto de lá.
338
+
339
+ ```typescript
340
+ import { manageAgentCredentialMitra } from 'mitra-interactions-sdk';
341
+
342
+ // Listar providers + status (pra montar a UI de conexão)
343
+ const { providers } = await manageAgentCredentialMitra({ action: 'list_providers' });
344
+
345
+ // Listar modelos disponíveis (só dos providers com credencial) → use o modelId em send()/getAgentTaskMitra
346
+ const { providers: groups } = await manageAgentCredentialMitra({ action: 'list_models' });
347
+
348
+ // API key
349
+ await manageAgentCredentialMitra({ action: 'validate', target: 'openai', key: 'sk-...' });
350
+ await manageAgentCredentialMitra({ action: 'save', target: 'glm', key: '...' });
351
+ await manageAgentCredentialMitra({ action: 'remove', target: 'anthropic' });
352
+ ```
353
+
354
+ Subscriptions (alto nível, sem redirect/callback page) — `auth` inicia e retorna o que mostrar; `connect` finaliza:
355
+
356
+ ```typescript
357
+ // Claude — abra a authUrl, colete o código que a Anthropic mostra
358
+ const { authUrl, state } = await manageAgentCredentialMitra({ action: 'auth', target: 'claude' });
359
+ await manageAgentCredentialMitra({ action: 'connect', target: 'claude', code, state });
360
+
361
+ // Codex (OpenAI device flow) — mostre verificationUrl + userCode; a SDK faz o polling
362
+ const { verificationUrl, userCode, pollId } = await manageAgentCredentialMitra({ action: 'auth', target: 'codex' });
363
+ await manageAgentCredentialMitra({ action: 'connect', target: 'codex', pollId });
364
+ ```
365
+
247
366
  ## Tipos TypeScript
248
367
 
249
368
  Todos os tipos estão incluídos:
@@ -254,9 +373,6 @@ import type {
254
373
  // Login
255
374
  LoginOptions,
256
375
  LoginResponse,
257
- // Email Auth
258
- EmailSignupOptions,
259
- EmailLoginOptions,
260
376
  // Options
261
377
  ExecuteServerFunctionOptions,
262
378
  ExecuteServerFunctionAsyncOptions,
@@ -272,7 +388,19 @@ import type {
272
388
  ExecuteServerFunctionResponse,
273
389
  ExecuteServerFunctionAsyncResponse,
274
390
  StopServerFunctionExecutionResponse,
275
- ListRecordsResponse
391
+ ListRecordsResponse,
392
+ // Agent Chat
393
+ AgentChat,
394
+ AgentMessage,
395
+ AgentTaskSession,
396
+ AgentTaskStatus,
397
+ SendOptions,
398
+ ManageAgentChatOptions,
399
+ GetAgentTaskOptions,
400
+ // Agent Credentials
401
+ ManageAgentCredentialOptions,
402
+ ListAgentModelsResult,
403
+ ListAgentProvidersResult
276
404
  } from 'mitra-interactions-sdk';
277
405
  ```
278
406
 
package/dist/index.d.mts CHANGED
@@ -195,6 +195,318 @@ interface StopServerFunctionExecutionResponse {
195
195
  executionStatus: string;
196
196
  };
197
197
  }
198
+ type AgentType = 'claudecode' | 'codex' | 'opencode-cli' | 'opencode-sdk';
199
+ interface AgentChat {
200
+ id: string;
201
+ name: string;
202
+ agentType?: string;
203
+ provider?: string;
204
+ createdAt: string;
205
+ updatedAt: string;
206
+ }
207
+ interface AgentMessage {
208
+ id: string;
209
+ content: string;
210
+ type: string;
211
+ sender?: 'user' | 'agent';
212
+ createdAt: string;
213
+ metadata?: Record<string, unknown> | null;
214
+ }
215
+ type ChatManageAction = 'list' | 'rename' | 'delete';
216
+ interface ManageAgentChatListOptions {
217
+ action: 'list';
218
+ /** Sobrescreve o projectId configurado globalmente. */
219
+ projectId?: number | string;
220
+ /** Filtra os chats de um agente business específico. Omitido = todos os chats. */
221
+ agentId?: string;
222
+ }
223
+ interface ManageAgentChatRenameOptions {
224
+ action: 'rename';
225
+ taskId: string;
226
+ name: string;
227
+ }
228
+ interface ManageAgentChatDeleteOptions {
229
+ action: 'delete';
230
+ taskId: string;
231
+ }
232
+ type ManageAgentChatOptions = ManageAgentChatListOptions | ManageAgentChatRenameOptions | ManageAgentChatDeleteOptions;
233
+ interface RenameAgentChatResult {
234
+ taskId: string;
235
+ name: string;
236
+ }
237
+ interface DeleteAgentChatResult {
238
+ taskId: string;
239
+ deleted: boolean;
240
+ }
241
+ interface GetAgentTaskCreateOptions {
242
+ /** Cria chat novo. taskId é preenchido depois do primeiro send(). */
243
+ create: true;
244
+ /** Sobrescreve projectId global. */
245
+ projectId?: number | string;
246
+ /** Tipo do agente. Default: 'claudecode'. */
247
+ agentType?: AgentType;
248
+ /**
249
+ * Modelo a usar (value vindo de manageAgentCredentialMitra({action:'list_models'})).
250
+ * Ex: 'openai/gpt-5.5:medium', 'glm/glm-5.1', 'subscription:anthropic:claude-opus-4-7'.
251
+ * O backend deriva agentType/provider/model a partir dele. Vira o default da
252
+ * task; cada send() pode sobrescrever via SendOptions.modelId.
253
+ */
254
+ modelId?: string;
255
+ /** Nome do chat (default: derivado do prompt). */
256
+ name?: string;
257
+ /**
258
+ * ID de um agente business (CRUD via mitra-sdk: listAgentsMitra e família).
259
+ * Com agentId, a sessão sobe com o system prompt do agente e um token escopado —
260
+ * as tools enxergam só as Server Functions daquele agente. Sem agentId, é o
261
+ * chat de desenvolvimento de sempre.
262
+ */
263
+ agentId?: string;
264
+ }
265
+ interface GetAgentTaskOpenOptions {
266
+ /** Abre chat existente. Detecta automático se stream está ativo. */
267
+ taskId: string;
268
+ }
269
+ type GetAgentTaskOptions = GetAgentTaskCreateOptions | GetAgentTaskOpenOptions;
270
+ type AgentTaskStatus = 'opening' | 'idle' | 'streaming' | 'cancelled' | 'error' | 'closed';
271
+ interface QueuedItem {
272
+ id: string;
273
+ text: string;
274
+ agentType?: AgentType;
275
+ seq: number;
276
+ createdAt: number;
277
+ status: 'pending' | 'sending';
278
+ injected?: boolean;
279
+ }
280
+ interface SendOptions {
281
+ agentType?: AgentType;
282
+ /**
283
+ * Modelo a usar neste turno (value de list_models). Ex: 'openai/gpt-5.5:medium',
284
+ * 'glm/glm-5.1', 'subscription:anthropic:claude-opus-4-7'. Sobrescreve o modelId
285
+ * default da session. Se omitido, usa o default da session / agentType.
286
+ */
287
+ modelId?: string;
288
+ }
289
+ interface AgentDeltaEvent {
290
+ delta: string;
291
+ kind: 'text' | 'tool';
292
+ }
293
+ interface AgentToolEvent {
294
+ tool: string;
295
+ input?: string;
296
+ content?: string;
297
+ timestamp: number;
298
+ }
299
+ interface AgentTurnEndEvent {
300
+ /** Conteúdo final acumulado do turno. */
301
+ content: string;
302
+ }
303
+ interface AgentTaskCreatedEvent {
304
+ task: AgentChat;
305
+ }
306
+ interface AgentErrorEvent {
307
+ error: string;
308
+ }
309
+ interface AgentQueueChangeEvent {
310
+ queue: ReadonlyArray<QueuedItem>;
311
+ }
312
+ interface AgentStatusChangeEvent {
313
+ status: AgentTaskStatus;
314
+ previous: AgentTaskStatus;
315
+ }
316
+ type AgentTaskEventMap = {
317
+ historyLoaded: AgentMessage[];
318
+ turnStart: void;
319
+ delta: AgentDeltaEvent;
320
+ tool: AgentToolEvent;
321
+ turnEnd: AgentTurnEndEvent;
322
+ taskCreated: AgentTaskCreatedEvent;
323
+ cancelled: void;
324
+ error: AgentErrorEvent;
325
+ queueChange: AgentQueueChangeEvent;
326
+ statusChange: AgentStatusChangeEvent;
327
+ };
328
+ type AgentTaskEventName = keyof AgentTaskEventMap;
329
+ interface AgentTaskSession {
330
+ readonly taskId: string | null;
331
+ readonly task: AgentChat | null;
332
+ readonly isNew: boolean;
333
+ readonly status: AgentTaskStatus;
334
+ readonly history: ReadonlyArray<AgentMessage>;
335
+ readonly content: string;
336
+ readonly queue: ReadonlyArray<QueuedItem>;
337
+ loadHistory(options?: {
338
+ limit?: number;
339
+ }): Promise<AgentMessage[]>;
340
+ close(): void;
341
+ send(prompt: string, options?: SendOptions): void;
342
+ cancel(): Promise<void>;
343
+ editQueueItem(itemId: string, newText: string): boolean;
344
+ removeQueueItem(itemId: string): boolean;
345
+ clearQueue(): void;
346
+ on<E extends AgentTaskEventName>(event: E, handler: (payload: AgentTaskEventMap[E]) => void): () => void;
347
+ }
348
+ /** Targets de subscription (OAuth/device flow). */
349
+ type AgentSubscriptionTarget = 'claude' | 'openai_oauth' | 'codex';
350
+ /** Targets de API key (8 providers suportados pelo backend). */
351
+ type AgentApiKeyTarget = 'anthropic' | 'openai' | 'gemini' | 'kimi' | 'minimax' | 'glm' | 'qwen' | 'openrouter';
352
+ /** Union — qualquer credencial. */
353
+ type CredentialTarget = AgentSubscriptionTarget | AgentApiKeyTarget;
354
+ /**
355
+ * Verbos aceitos por `manageAgentCredentialMitra`.
356
+ *
357
+ * Baixo nível (RPC direto contra o backend `credentials`):
358
+ * status | remove | list | validate | save
359
+ * oauth_start | oauth_exchange | device_start | device_poll | device_cancel
360
+ *
361
+ * Alto nível (orquestrado no browser, NÃO é um type WS — encadeia as actions
362
+ * de baixo nível + abre popup + espera autorização):
363
+ * connect
364
+ */
365
+ type CredentialAction = 'auth' | 'connect' | 'status' | 'remove' | 'list' | 'list_models' | 'list_providers' | 'validate' | 'save' | 'oauth_start' | 'oauth_exchange' | 'device_start' | 'device_poll' | 'device_cancel';
366
+ /** Forma de acesso a uma credencial. */
367
+ type CredentialAccessType = 'subscription' | 'api_key';
368
+ /** Método de conexão — diz ao app/agent qual UI montar. */
369
+ type AuthMethod = 'api_key' | 'paste_code' | 'device';
370
+ /** Metadados pra montar a UI de conexão (vem em cada provider de list_providers). */
371
+ interface AgentAuthMeta {
372
+ method: AuthMethod;
373
+ /** Só para method='api_key'. */
374
+ keyLabel?: string;
375
+ /** Só para method='api_key'. */
376
+ keyPlaceholder?: string;
377
+ }
378
+ /** Um modelo selecionável (retornado por action='list_models'). */
379
+ interface AgentModelOption {
380
+ /** Passe direto em send({ modelId }) ou getAgentTaskMitra({ create, modelId }). */
381
+ modelId: string;
382
+ /** Label exibível. */
383
+ name: string;
384
+ }
385
+ /** Grupo de modelos por (tipo × provedor) — só grupos com credencial. */
386
+ interface AgentModelGroup {
387
+ id: string;
388
+ name: string;
389
+ type: CredentialAccessType;
390
+ models: AgentModelOption[];
391
+ }
392
+ /** Retorno de manageAgentCredentialMitra({ action: 'list_models' }). */
393
+ interface ListAgentModelsResult {
394
+ providers: AgentModelGroup[];
395
+ }
396
+ /** Um provedor suportado + status (retornado por action='list_providers'). */
397
+ interface AgentProviderListItem {
398
+ id: string;
399
+ name: string;
400
+ type: CredentialAccessType;
401
+ /** Passe direto em auth/connect/save/remove. */
402
+ target: string;
403
+ /** Como conectar: method (api_key|paste_code|device) + label/placeholder. */
404
+ auth: AgentAuthMeta;
405
+ connected: boolean;
406
+ /** Presente em subscription Claude conectada. */
407
+ account?: AgentSubscriptionAccount;
408
+ expiresAt?: number;
409
+ /** Presente em API key conectada. */
410
+ maskedKey?: string;
411
+ updatedAt?: string | Date;
412
+ }
413
+ /** Retorno de manageAgentCredentialMitra({ action: 'list_providers' }). */
414
+ interface ListAgentProvidersResult {
415
+ providers: AgentProviderListItem[];
416
+ }
417
+ /**
418
+ * Opções de baixo nível (RPC direto) de `manageAgentCredentialMitra`. Campos
419
+ * extras (key, code, codeVerifier, redirectUri, pollId, accessToken,
420
+ * refreshToken, expiresAt) são empacotados em `data` antes de enviar ao backend.
421
+ *
422
+ * NÃO use com action='connect' — para isso use ConnectAgentCredentialOptions.
423
+ */
424
+ interface ManageAgentCredentialOptions {
425
+ action: Exclude<CredentialAction, 'connect' | 'auth'>;
426
+ /** Obrigatório exceto para action='list' / 'list_models'. */
427
+ target?: CredentialTarget;
428
+ /** Para `save` / `validate` de API key. */
429
+ key?: string;
430
+ /** Para `oauth_exchange`. */
431
+ code?: string;
432
+ /** Para `oauth_exchange`. */
433
+ state?: string;
434
+ /** Para `oauth_exchange`. */
435
+ codeVerifier?: string;
436
+ /** Para `oauth_start` (openai_oauth) e `oauth_exchange` (openai_oauth). */
437
+ redirectUri?: string;
438
+ /** Para `device_poll` / `device_cancel`. */
439
+ pollId?: string;
440
+ /** Para `save` (codex). */
441
+ accessToken?: string;
442
+ /** Para `save` (codex). */
443
+ refreshToken?: string;
444
+ /** Para `save` (codex). */
445
+ expiresAt?: number;
446
+ }
447
+ /** Tipo "ampliado" — o backend retorna shapes diferentes por (action, target). */
448
+ type ManageAgentCredentialResult = unknown;
449
+ interface AgentSubscriptionAccount {
450
+ email: string;
451
+ orgName: string;
452
+ }
453
+ /**
454
+ * Opções de alto nível de `manageAgentCredentialMitra` quando action='connect'.
455
+ * Orquestra o fluxo OAuth/device ponta-a-ponta no browser (abre popup, espera
456
+ * autorização, troca por tokens server-side).
457
+ */
458
+ /**
459
+ * Targets que conectam SEM redirect (paste código / device flow). O
460
+ * 'openai_oauth' fica de fora porque depende de redirect localhost:1455
461
+ * (client OAuth compartilhado da OpenAI) — inviável em domínio de cliente.
462
+ * OpenAI subscription conecta via 'codex' (device flow).
463
+ */
464
+ type ConnectableSubscriptionTarget = 'claude' | 'codex';
465
+ interface AuthAgentCredentialOptions {
466
+ action: 'auth';
467
+ target: ConnectableSubscriptionTarget;
468
+ }
469
+ /** Resultado de auth(claude): abra a authUrl, depois connect com o código. */
470
+ interface AuthClaudeResult {
471
+ target: 'claude';
472
+ /** URL pra abrir (a Anthropic mostra o código na própria tela). */
473
+ authUrl: string;
474
+ /** Passe de volta no connect junto com o código. */
475
+ state: string;
476
+ }
477
+ /** Resultado de auth(codex): mostre userCode/verificationUrl, depois connect com pollId. */
478
+ interface AuthCodexResult {
479
+ target: 'codex';
480
+ /** Código que o user digita no site da OpenAI. */
481
+ userCode: string | null;
482
+ /** URL que o user abre pra autorizar. */
483
+ verificationUrl: string | null;
484
+ /** Passe de volta no connect; a SDK faz o polling. */
485
+ pollId: string;
486
+ }
487
+ type AuthAgentCredentialResult = AuthClaudeResult | AuthCodexResult;
488
+ interface ConnectAgentCredentialOptions {
489
+ action: 'connect';
490
+ target: ConnectableSubscriptionTarget;
491
+ /** Código que o user copiou da página da Anthropic. Obrigatório p/ claude. */
492
+ code?: string;
493
+ /** O `state` devolvido por auth(claude). Obrigatório p/ claude. */
494
+ state?: string;
495
+ /** O `pollId` devolvido por auth(codex). Obrigatório p/ codex. */
496
+ pollId?: string;
497
+ /** Intervalo de poll do device flow (default 2000ms). */
498
+ pollIntervalMs?: number;
499
+ /** Timeout total do device flow (default 15min). */
500
+ deviceTimeoutMs?: number;
501
+ }
502
+ interface ConnectAgentSubscriptionResult {
503
+ target: ConnectableSubscriptionTarget;
504
+ success: boolean;
505
+ /** Presente em claude (epoch ms). */
506
+ expiresAt?: number;
507
+ /** Presente apenas em claude. */
508
+ account?: AgentSubscriptionAccount | null;
509
+ }
198
510
 
199
511
  /**
200
512
  * Mitra Interactions SDK - Instance
@@ -219,6 +531,9 @@ interface MitraInstance {
219
531
  patchRecord(options: PatchRecordOptions): Promise<Record<string, any>>;
220
532
  deleteRecord(options: DeleteRecordOptions): Promise<void>;
221
533
  createRecordsBatch(options: CreateRecordsBatchOptions): Promise<Record<string, any>[]>;
534
+ getAgentTask(options: GetAgentTaskOptions): AgentTaskSession;
535
+ manageAgentChat(options: ManageAgentChatOptions): Promise<unknown>;
536
+ manageAgentCredential(options: ManageAgentCredentialOptions | ConnectAgentCredentialOptions): Promise<unknown>;
222
537
  }
223
538
  declare function createMitraInstance(initialConfig: Partial<MitraConfig>): MitraInstance;
224
539
 
@@ -282,6 +597,97 @@ declare function exchangeSsoCodeMitra(options: {
282
597
  state: string;
283
598
  }): Promise<LoginResponse>;
284
599
 
600
+ /**
601
+ * Mitra Interactions SDK — Agent Chat
602
+ *
603
+ * Hub do WebSocket compartilhado e factories da API pública:
604
+ * - manageAgentChatMitra({ action: 'list' | 'rename' | 'delete', ... })
605
+ * - getAgentTaskMitra({ create | taskId, ... })
606
+ *
607
+ * O WS é singleton: todas as sessions usam UMA conexão. O roteamento
608
+ * de eventos é feito por taskId, despachando pra session correspondente.
609
+ *
610
+ * NÃO há `sendAgentPromptMitra` ou `getAgentHistoryMitra` exportados —
611
+ * essas operações vivem dentro de `AgentTaskSession`.
612
+ */
613
+
614
+ /**
615
+ * Gerencia os chats do user (coleção) — espelha `manageAgentCredentialMitra`.
616
+ * Operações stateless: listar, renomear, deletar.
617
+ *
618
+ * @example
619
+ * const chats = await manageAgentChatMitra({ action: 'list' });
620
+ * await manageAgentChatMitra({ action: 'rename', taskId, name: 'Novo nome' });
621
+ * await manageAgentChatMitra({ action: 'delete', taskId });
622
+ */
623
+ declare function manageAgentChatMitra(options: ManageAgentChatListOptions): Promise<AgentChat[]>;
624
+ declare function manageAgentChatMitra(options: ManageAgentChatRenameOptions): Promise<RenameAgentChatResult>;
625
+ declare function manageAgentChatMitra(options: ManageAgentChatDeleteOptions): Promise<DeleteAgentChatResult>;
626
+ /**
627
+ * Abre um handle de chat (session). Use:
628
+ * - `{ create: true }` para iniciar um chat novo
629
+ * - `{ taskId: 'X' }` para abrir um chat existente
630
+ *
631
+ * A session expõe histórico, streaming, fila, cancel e eventos. Se a
632
+ * mesma taskId for aberta duas vezes, retorna a MESMA instância (cache).
633
+ */
634
+ declare function getAgentTaskMitra(options: GetAgentTaskOptions): AgentTaskSession;
635
+
636
+ /**
637
+ * Mitra Interactions SDK — Agent Credentials
638
+ *
639
+ * Função ÚNICA `manageAgentCredentialMitra` sobre /sdk-ws para todas as
640
+ * operações de credencial do agente:
641
+ * - API keys (8 providers: anthropic, openai, gemini, kimi, minimax, glm, qwen, openrouter)
642
+ * - Subscriptions OAuth (Claude paste-código / OpenAI device flow via Codex)
643
+ *
644
+ * Actions de baixo nível (RPC direto contra o backend):
645
+ * status | remove | list | list_models | validate | save
646
+ * oauth_start | oauth_exchange | device_start | device_poll | device_cancel
647
+ *
648
+ * Actions de alto nível (orquestradas na SDK — o app controla UI/popup/timing):
649
+ * auth — inicia o fluxo e retorna o que a UI mostra (sem efeito colateral
650
+ * de janela). claude → { authUrl, state }; codex → { userCode,
651
+ * verificationUrl, pollId }.
652
+ * connect — finaliza/salva. claude → passa { code, state }; codex → passa
653
+ * { pollId } e a SDK faz o polling até autorizar.
654
+ *
655
+ * Fluxo típico (sem callbacks, sem redirect, sem callback page):
656
+ * const { authUrl, state } = await manageAgentCredentialMitra({ action:'auth', target:'claude' });
657
+ * // app abre authUrl + coleta o código do user
658
+ * await manageAgentCredentialMitra({ action:'connect', target:'claude', code, state });
659
+ *
660
+ * const { userCode, verificationUrl, pollId } = await manageAgentCredentialMitra({ action:'auth', target:'codex' });
661
+ * // app mostra "abra {verificationUrl}, digite {userCode}"
662
+ * await manageAgentCredentialMitra({ action:'connect', target:'codex', pollId });
663
+ *
664
+ * SEGURANÇA: o token de subscription NUNCA volta cru pro cliente. É salvo
665
+ * server-side (Firestore) e injetado no sandbox E2B direto de lá.
666
+ */
667
+
668
+ /**
669
+ * Inicia um fluxo de subscription. Não abre janelas — retorna os dados pra UI:
670
+ * claude → { authUrl, state } codex → { userCode, verificationUrl, pollId }
671
+ */
672
+ declare function manageAgentCredentialMitra(options: AuthAgentCredentialOptions): Promise<AuthAgentCredentialResult>;
673
+ /**
674
+ * Finaliza/salva uma subscription:
675
+ * claude → { code, state } codex → { pollId } (a SDK faz o polling)
676
+ */
677
+ declare function manageAgentCredentialMitra(options: ConnectAgentCredentialOptions): Promise<ConnectAgentSubscriptionResult>;
678
+ /**
679
+ * RPC direto contra o backend. Retorno depende de (action, target).
680
+ *
681
+ * @example
682
+ * await manageAgentCredentialMitra({ action: 'list' });
683
+ * await manageAgentCredentialMitra({ action: 'list_models' });
684
+ * await manageAgentCredentialMitra({ action: 'status', target: 'anthropic' });
685
+ * await manageAgentCredentialMitra({ action: 'validate', target: 'openai', key: 'sk-...' });
686
+ * await manageAgentCredentialMitra({ action: 'save', target: 'glm', key: '...' });
687
+ * await manageAgentCredentialMitra({ action: 'remove', target: 'claude' });
688
+ */
689
+ declare function manageAgentCredentialMitra<R = ManageAgentCredentialResult>(options: ManageAgentCredentialOptions): Promise<R>;
690
+
285
691
  /**
286
692
  * Mitra Interactions SDK - Services
287
693
  */
@@ -337,4 +743,4 @@ declare function patchRecordMitra(options: PatchRecordOptions): Promise<Record<s
337
743
  declare function deleteRecordMitra(options: DeleteRecordOptions): Promise<void>;
338
744
  declare function createRecordsBatchMitra(options: CreateRecordsBatchOptions): Promise<Record<string, any>[]>;
339
745
 
340
- export { type CallIntegrationOptions, type CallIntegrationResponse, type CreateRecordOptions, type CreateRecordsBatchOptions, type DeleteRecordOptions, type ExecutePublicServerFunctionAsyncResponse, type ExecutePublicServerFunctionOptions, type ExecutePublicServerFunctionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type GetPublicServerFunctionExecutionOptions, type GetPublicServerFunctionExecutionResponse, type GetRecordOptions, type IntegrationResponse, type ListIntegrationsOptions, type ListRecordsOptions, type ListRecordsResponse, type LoginOptions, type LoginResponse, type MitraConfig, type MitraInstance, type PatchRecordOptions, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateRecordOptions, callIntegrationMitra, configureSdkMitra, createMitraInstance, createRecordMitra, createRecordsBatchMitra, deleteRecordMitra, exchangeSsoCodeMitra, executePublicServerFunctionAsyncMitra, executePublicServerFunctionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, getConfig, getPublicServerFunctionExecutionMitra, getRecordMitra, listIntegrationsMitra, listRecordsMitra, loginMitra, loginWithGoogleMitra, loginWithMicrosoftMitra, patchRecordMitra, refreshTokenSilently, resolveProjectId, stopServerFunctionExecutionMitra, updateRecordMitra };
746
+ export { type AgentApiKeyTarget, type AgentAuthMeta, type AgentChat, type AgentDeltaEvent, type AgentErrorEvent, type AgentMessage, type AgentModelGroup, type AgentModelOption, type AgentProviderListItem, type AgentQueueChangeEvent, type AgentStatusChangeEvent, type AgentSubscriptionAccount, type AgentSubscriptionTarget, type AgentTaskCreatedEvent, type AgentTaskEventMap, type AgentTaskEventName, type AgentTaskSession, type AgentTaskStatus, type AgentToolEvent, type AgentTurnEndEvent, type AgentType, type AuthAgentCredentialOptions, type AuthAgentCredentialResult, type AuthClaudeResult, type AuthCodexResult, type AuthMethod, type CallIntegrationOptions, type CallIntegrationResponse, type ChatManageAction, type ConnectAgentCredentialOptions, type ConnectAgentSubscriptionResult, type ConnectableSubscriptionTarget, type CreateRecordOptions, type CreateRecordsBatchOptions, type CredentialAccessType, type CredentialAction, type CredentialTarget, type DeleteAgentChatResult, type DeleteRecordOptions, type ExecutePublicServerFunctionAsyncResponse, type ExecutePublicServerFunctionOptions, type ExecutePublicServerFunctionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type GetAgentTaskCreateOptions, type GetAgentTaskOpenOptions, type GetAgentTaskOptions, type GetPublicServerFunctionExecutionOptions, type GetPublicServerFunctionExecutionResponse, type GetRecordOptions, type IntegrationResponse, type ListAgentModelsResult, type ListAgentProvidersResult, type ListIntegrationsOptions, type ListRecordsOptions, type ListRecordsResponse, type LoginOptions, type LoginResponse, type ManageAgentChatDeleteOptions, type ManageAgentChatListOptions, type ManageAgentChatOptions, type ManageAgentChatRenameOptions, type ManageAgentCredentialOptions, type ManageAgentCredentialResult, type MitraConfig, type MitraInstance, type PatchRecordOptions, type QueuedItem, type RenameAgentChatResult, type SendOptions, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateRecordOptions, callIntegrationMitra, configureSdkMitra, createMitraInstance, createRecordMitra, createRecordsBatchMitra, deleteRecordMitra, exchangeSsoCodeMitra, executePublicServerFunctionAsyncMitra, executePublicServerFunctionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, getAgentTaskMitra, getConfig, getPublicServerFunctionExecutionMitra, getRecordMitra, listIntegrationsMitra, listRecordsMitra, loginMitra, loginWithGoogleMitra, loginWithMicrosoftMitra, manageAgentChatMitra, manageAgentCredentialMitra, patchRecordMitra, refreshTokenSilently, resolveProjectId, stopServerFunctionExecutionMitra, updateRecordMitra };