mitra-interactions-sdk 1.0.60-beta.1 → 1.0.60

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
@@ -483,6 +483,126 @@ await setProfileSelectTablesMitra({
483
483
  await setProfileServerFunctionsMitra({ projectId: 123, profileId: 1, serverFunctionIds: [5, 8, 12] });
484
484
  ```
485
485
 
486
+ ## Agent Chat (embedded)
487
+
488
+ Chat com o agente de IA embarcado, sobre um WebSocket compartilhado (`/sdk-ws`). Uma única conexão atende todas as sessions — o roteamento de eventos é feito por `taskId`.
489
+
490
+ > ⚙️ Requisitos: roda **apenas em apps publicadas pela plataforma Mitra** (o build-proxy injeta `window.__mitraEnv.agentWsUrl`) e precisa de `token` configurado (faça login antes ou passe em `configureSdkMitra`).
491
+
492
+ ### Gerenciar os chats — `manageAgentChatMitra`
493
+
494
+ Operações stateless sobre a coleção de chats do usuário: listar, renomear, deletar.
495
+
496
+ ```typescript
497
+ import { manageAgentChatMitra } from 'mitra-interactions-sdk';
498
+
499
+ const chats = await manageAgentChatMitra({ action: 'list' }); // AgentChat[]
500
+ const renamed = await manageAgentChatMitra({ action: 'rename', taskId, name: 'Novo nome' });
501
+ const deleted = await manageAgentChatMitra({ action: 'delete', taskId });
502
+ ```
503
+
504
+ - `action: 'list'` → `AgentChat[]` — `{ id, name, agentType?, provider?, createdAt, updatedAt }`. Aceita `projectId?` pra sobrescrever o global.
505
+ - `action: 'rename'` → `{ taskId, name }`
506
+ - `action: 'delete'` → `{ taskId, deleted }`
507
+
508
+ ### Abrir uma session — `getAgentTaskMitra`
509
+
510
+ 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).
511
+
512
+ ```typescript
513
+ import { getAgentTaskMitra } from 'mitra-interactions-sdk';
514
+
515
+ // Chat novo — taskId é preenchido depois do primeiro send()
516
+ const session = getAgentTaskMitra({ create: true, agentType: 'claudecode', modelId: 'openai/gpt-5.5:medium' });
517
+
518
+ // Chat existente — detecta automaticamente se já há stream ativo
519
+ const existing = getAgentTaskMitra({ taskId: 'abc123' });
520
+ await existing.loadHistory({ limit: 50 });
521
+ ```
522
+
523
+ `getAgentTaskMitra({ create: true, projectId?, agentType?, modelId?, name? })` ou `getAgentTaskMitra({ taskId })`.
524
+
525
+ #### Propriedades (somente leitura)
526
+
527
+ | Propriedade | Tipo | Descrição |
528
+ |-------------|------|-----------|
529
+ | `taskId` | `string \| null` | `null` até o primeiro `send()` num chat novo |
530
+ | `task` | `AgentChat \| null` | Metadados do chat após criado |
531
+ | `isNew` | `boolean` | Se foi aberto via `{ create: true }` |
532
+ | `status` | `AgentTaskStatus` | `opening` · `idle` · `uploading` · `streaming` · `cancelled` · `error` · `closed` |
533
+ | `history` | `AgentMessage[]` | Histórico carregado |
534
+ | `content` | `string` | Conteúdo acumulado do turno atual |
535
+ | `queue` | `QueuedItem[]` | Mensagens enfileiradas (enviadas enquanto streamava) |
536
+
537
+ #### Métodos
538
+
539
+ - `send(prompt, options?)` → `void` — dispara um turno. Se já está streamando, **enfileira** (FIFO, máx 10). `options`: `{ agentType?, modelId?, files? }`.
540
+ - `cancel()` → `Promise<void>` — cancela o turno atual; resolve quando o backend confirma (ou safety net de 30s).
541
+ - `loadHistory({ limit? })` → `Promise<AgentMessage[]>` — carrega o histórico do chat.
542
+ - `editQueueItem(id, text)` / `removeQueueItem(id)` / `clearQueue()` — manipulam a fila.
543
+ - `on(event, handler)` → função de unsubscribe — assina eventos da session.
544
+ - `close()` — encerra a session e libera os listeners.
545
+
546
+ #### Eventos (`session.on`)
547
+
548
+ `statusChange` · `historyLoaded` · `taskCreated` · `turnStart` · `delta` · `tool` · `turnEnd` · `cancelled` · `queueChange` · `error`.
549
+
550
+ ```typescript
551
+ const session = getAgentTaskMitra({ create: true });
552
+
553
+ session.on('delta', ({ delta, kind }) => process.stdout.write(delta)); // kind: 'text' | 'tool'
554
+ session.on('tool', ({ tool, input }) => console.log('🔧', tool));
555
+ session.on('turnEnd', ({ content }) => console.log('\n✓ fim do turno'));
556
+ session.on('taskCreated', ({ task }) => console.log('chat criado:', task.id));
557
+ session.on('error', ({ error }) => console.error(error));
558
+
559
+ session.send('Analise estas vendas e gere um resumo');
560
+ ```
561
+
562
+ #### Anexos e seleção de modelo
563
+
564
+ ```typescript
565
+ // Anexos: passe os File crus (drop/input). A SDK sobe cada um (URL pública),
566
+ // detecta o tipo e monta os anexos. Status vai pra 'uploading'; falha sai no evento 'error'.
567
+ session.send('O que tem nesta planilha?', { files: [xlsxFile, pngFile] });
568
+
569
+ // Modelo por turno (sobrescreve o default da session)
570
+ session.send('Refaça com mais detalhes', { modelId: 'subscription:anthropic:claude-opus-4-7' });
571
+ ```
572
+
573
+ ### Credenciais do agente — `manageAgentCredentialMitra`
574
+
575
+ 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).
576
+
577
+ > 🔒 Segurança: o token de subscription **nunca volta cru** pro cliente — fica server-side e é injetado no sandbox direto de lá.
578
+
579
+ ```typescript
580
+ import { manageAgentCredentialMitra } from 'mitra-interactions-sdk';
581
+
582
+ // Listar providers + status (pra montar a UI de conexão)
583
+ const { providers } = await manageAgentCredentialMitra({ action: 'list_providers' });
584
+
585
+ // Listar modelos disponíveis (só dos providers com credencial) → use o modelId em send()/getAgentTaskMitra
586
+ const { providers: groups } = await manageAgentCredentialMitra({ action: 'list_models' });
587
+
588
+ // API key
589
+ await manageAgentCredentialMitra({ action: 'validate', target: 'openai', key: 'sk-...' });
590
+ await manageAgentCredentialMitra({ action: 'save', target: 'glm', key: '...' });
591
+ await manageAgentCredentialMitra({ action: 'remove', target: 'anthropic' });
592
+ ```
593
+
594
+ Subscriptions (alto nível, sem redirect/callback page) — `auth` inicia e retorna o que mostrar; `connect` finaliza:
595
+
596
+ ```typescript
597
+ // Claude — abra a authUrl, colete o código que a Anthropic mostra
598
+ const { authUrl, state } = await manageAgentCredentialMitra({ action: 'auth', target: 'claude' });
599
+ await manageAgentCredentialMitra({ action: 'connect', target: 'claude', code, state });
600
+
601
+ // Codex (OpenAI device flow) — mostre verificationUrl + userCode; a SDK faz o polling
602
+ const { verificationUrl, userCode, pollId } = await manageAgentCredentialMitra({ action: 'auth', target: 'codex' });
603
+ await manageAgentCredentialMitra({ action: 'connect', target: 'codex', pollId });
604
+ ```
605
+
486
606
  ## Tipos TypeScript
487
607
 
488
608
  Todos os tipos estão incluídos:
@@ -534,7 +654,27 @@ import type {
534
654
  SetProfileScreensOptions,
535
655
  SetProfileServerFunctionsOptions,
536
656
  ProfileTableRef,
537
- SetProfilePermissionResponse
657
+ SetProfilePermissionResponse,
658
+ // Agent Chat
659
+ AgentChat,
660
+ AgentMessage,
661
+ AgentType,
662
+ AgentTaskSession,
663
+ AgentTaskStatus,
664
+ AgentTaskEventMap,
665
+ AgentAttachment,
666
+ QueuedItem,
667
+ SendOptions,
668
+ GetAgentTaskOptions,
669
+ ManageAgentChatOptions,
670
+ // Agent Credentials
671
+ CredentialTarget,
672
+ CredentialAction,
673
+ ManageAgentCredentialOptions,
674
+ AuthAgentCredentialOptions,
675
+ ConnectAgentCredentialOptions,
676
+ ListAgentModelsResult,
677
+ ListAgentProvidersResult
538
678
  } from 'mitra-interactions-sdk';
539
679
  ```
540
680