mitra-interactions-sdk 1.0.58-beta.2 → 1.0.58-beta.3

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/dist/index.d.mts CHANGED
@@ -22,8 +22,6 @@ interface LoginResponse {
22
22
  baseURL: string;
23
23
  /** URL do serviço de integrações (opcional) */
24
24
  integrationURL?: string;
25
- /** URL do WebSocket do Agent Chat (opcional — vem do sdk-auth quando configurado) */
26
- agentWsUrl?: string;
27
25
  }
28
26
  interface EmailSignupOptions {
29
27
  /** URL da página de auth (ex: https://validacao.mitralab.io/sdk-auth/). Opcional se já configurado via configureSdkMitra. */
@@ -521,6 +519,7 @@ interface SetProfilePermissionResponse {
521
519
  [key: string]: unknown;
522
520
  };
523
521
  }
522
+ type AgentType = 'claudecode' | 'codex' | 'opencode-cli' | 'opencode-sdk';
524
523
  interface AgentChat {
525
524
  id: string;
526
525
  name: string;
@@ -541,65 +540,92 @@ interface GetAgentChatsOptions {
541
540
  /** Sobrescreve o projectId configurado globalmente. */
542
541
  projectId?: number;
543
542
  }
544
- interface GetAgentHistoryOptions {
545
- /** ID do chat cuja conversa será carregada. */
546
- taskId: string;
547
- /** Quantidade máxima de mensagens (default: tudo). */
548
- limit?: number;
543
+ interface GetAgentTaskCreateOptions {
544
+ /** Cria chat novo. taskId é preenchido depois do primeiro send(). */
545
+ create: true;
546
+ /** Sobrescreve projectId global. */
547
+ projectId?: number;
548
+ /** Tipo do agente. Default: 'claudecode'. */
549
+ agentType?: AgentType;
550
+ /** Nome do chat (default: derivado do prompt). */
551
+ name?: string;
549
552
  }
550
- interface AgentStreamDeltaEvent {
553
+ interface GetAgentTaskOpenOptions {
554
+ /** Abre chat existente. Detecta automático se stream está ativo. */
551
555
  taskId: string;
552
- /** Pedaço de texto que chegou. */
556
+ }
557
+ type GetAgentTaskOptions = GetAgentTaskCreateOptions | GetAgentTaskOpenOptions;
558
+ type AgentTaskStatus = 'opening' | 'idle' | 'streaming' | 'cancelled' | 'error' | 'closed';
559
+ interface QueuedItem {
560
+ id: string;
561
+ text: string;
562
+ agentType?: AgentType;
563
+ seq: number;
564
+ createdAt: number;
565
+ status: 'pending' | 'sending';
566
+ injected?: boolean;
567
+ }
568
+ interface SendOptions {
569
+ agentType?: AgentType;
570
+ }
571
+ interface AgentDeltaEvent {
553
572
  delta: string;
554
- /** Tipo do conteúdo: 'text' (resposta do agente) ou 'tool' (atividade de ferramenta). */
555
573
  kind: 'text' | 'tool';
556
574
  }
557
- interface AgentStreamToolEvent {
558
- taskId: string;
575
+ interface AgentToolEvent {
559
576
  tool: string;
560
577
  input?: string;
561
578
  content?: string;
562
579
  timestamp: number;
563
580
  }
564
- interface AgentStreamEndEvent {
565
- taskId: string;
566
- /** Conteúdo final acumulado (concatenação dos deltas). */
581
+ interface AgentTurnEndEvent {
582
+ /** Conteúdo final acumulado do turno. */
567
583
  content: string;
568
584
  }
569
585
  interface AgentTaskCreatedEvent {
570
586
  task: AgentChat;
571
587
  }
572
588
  interface AgentErrorEvent {
573
- taskId?: string;
574
589
  error: string;
575
590
  }
576
- interface SendAgentPromptOptions {
577
- /** Texto enviado ao agente. */
578
- prompt: string;
579
- /** ID do chat existente. Se ausente, cria um chat novo. */
580
- taskId?: string;
581
- /** Tipo do agente. Default: 'claudecode'. */
582
- agentType?: 'claudecode' | 'codex' | 'opencode-cli' | 'opencode-sdk';
583
- /** Sobrescreve projectId global. */
584
- projectId?: number;
585
- /** Nome do chat quando criando novo (default: derivado do prompt). */
586
- name?: string;
587
- /** Callback chamado a cada chunk de texto. */
588
- onDelta?: (event: AgentStreamDeltaEvent) => void;
589
- /** Callback chamado quando uma ferramenta é usada. */
590
- onTool?: (event: AgentStreamToolEvent) => void;
591
- /** Callback chamado quando um novo chat é criado (só dispara se taskId era ausente). */
592
- onTaskCreated?: (event: AgentTaskCreatedEvent) => void;
593
- /** Callback chamado quando ocorre erro durante o stream. */
594
- onError?: (event: AgentErrorEvent) => void;
595
- /** Permite cancelar o stream mid-flight. */
596
- signal?: AbortSignal;
597
- }
598
- interface SendAgentPromptResponse {
599
- /** ID do chat (existente ou recém-criado). */
600
- taskId: string;
601
- /** Texto completo acumulado dos deltas. */
602
- content: string;
591
+ interface AgentQueueChangeEvent {
592
+ queue: ReadonlyArray<QueuedItem>;
593
+ }
594
+ interface AgentStatusChangeEvent {
595
+ status: AgentTaskStatus;
596
+ previous: AgentTaskStatus;
597
+ }
598
+ type AgentTaskEventMap = {
599
+ historyLoaded: AgentMessage[];
600
+ turnStart: void;
601
+ delta: AgentDeltaEvent;
602
+ tool: AgentToolEvent;
603
+ turnEnd: AgentTurnEndEvent;
604
+ taskCreated: AgentTaskCreatedEvent;
605
+ cancelled: void;
606
+ error: AgentErrorEvent;
607
+ queueChange: AgentQueueChangeEvent;
608
+ statusChange: AgentStatusChangeEvent;
609
+ };
610
+ type AgentTaskEventName = keyof AgentTaskEventMap;
611
+ interface AgentTaskSession {
612
+ readonly taskId: string | null;
613
+ readonly task: AgentChat | null;
614
+ readonly isNew: boolean;
615
+ readonly status: AgentTaskStatus;
616
+ readonly history: ReadonlyArray<AgentMessage>;
617
+ readonly content: string;
618
+ readonly queue: ReadonlyArray<QueuedItem>;
619
+ loadHistory(options?: {
620
+ limit?: number;
621
+ }): Promise<AgentMessage[]>;
622
+ close(): void;
623
+ send(prompt: string, options?: SendOptions): void;
624
+ cancel(): Promise<void>;
625
+ editQueueItem(itemId: string, newText: string): boolean;
626
+ removeQueueItem(itemId: string): boolean;
627
+ clearQueue(): void;
628
+ on<E extends AgentTaskEventName>(event: E, handler: (payload: AgentTaskEventMap[E]) => void): () => void;
603
629
  }
604
630
 
605
631
  /**
@@ -649,8 +675,7 @@ interface MitraInstance {
649
675
  validatePasswordResetCode(options: ValidatePasswordResetCodeOptions): Promise<Record<string, unknown>>;
650
676
  resetPassword(options: ResetPasswordOptions): Promise<Record<string, unknown>>;
651
677
  getAgentChats(options?: GetAgentChatsOptions): Promise<AgentChat[]>;
652
- getAgentHistory(options: GetAgentHistoryOptions): Promise<AgentMessage[]>;
653
- sendAgentPrompt(options: SendAgentPromptOptions): Promise<SendAgentPromptResponse>;
678
+ getAgentTask(options: GetAgentTaskOptions): AgentTaskSession;
654
679
  disconnectAgentChat(): void;
655
680
  openChat(): void;
656
681
  closeChat(): void;
@@ -658,16 +683,14 @@ interface MitraInstance {
658
683
  declare function createMitraInstance(initialConfig: Partial<MitraConfig>): MitraInstance;
659
684
 
660
685
  interface MitraConfig {
661
- /** URL base da API (ex: https://api.mitra.com) */
662
- baseURL: string;
686
+ /** URL base da API (ex: https://api.mitra.com). Opcional se houver window.__mitraEnv.apiBaseURL (build-proxy). */
687
+ baseURL?: string;
663
688
  /** Token JWT para autenticação (opcional para Server Functions públicas) */
664
689
  token?: string;
665
690
  /** URL base do serviço de integrações (ex: https://api0.mitraecp.com:1003) */
666
691
  integrationURL?: string;
667
692
  /** URL da página de autenticação Mitra (ex: https://coder.mitralab.io/sdk-auth/) */
668
693
  authUrl?: string;
669
- /** URL do WebSocket do Agent Chat (ex: wss://agent.mitralab.io/sdk-ws ou ws://localhost:3456/sdk-ws) */
670
- agentWsUrl?: string;
671
694
  /** ID do projeto (usado como fallback nos métodos de login e serviços) */
672
695
  projectId?: number;
673
696
  /** Callback chamado quando o token é renovado automaticamente (após 401/403). Recebe a nova sessão. */
@@ -675,8 +698,12 @@ interface MitraConfig {
675
698
  }
676
699
  /**
677
700
  * Configura o SDK globalmente e retorna uma instância configurada.
701
+ *
702
+ * Em apps publicadas pelo Mitra (window.__mitraEnv presente), nenhum campo
703
+ * precisa ser passado — todas as URLs vêm da injeção do build-proxy.
704
+ * Em outros contextos, baseURL ainda é necessário (manual ou via login).
678
705
  */
679
- declare function configureSdkMitra(config: MitraConfig): MitraInstance;
706
+ declare function configureSdkMitra(config?: Partial<MitraConfig>): MitraInstance;
680
707
  /**
681
708
  * Obtém a configuração atual
682
709
  */
@@ -779,24 +806,35 @@ declare function validatePasswordResetCodeMitra(options: ValidatePasswordResetCo
779
806
  declare function resetPasswordMitra(options: ResetPasswordOptions): Promise<Record<string, unknown>>;
780
807
 
781
808
  /**
782
- * Mitra Interactions SDK - Agent Chat (embedded)
809
+ * Mitra Interactions SDK Agent Chat
783
810
  *
784
- * Conecta via WebSocket ao mitra-agent-websocket. Tudo (lista de chats,
785
- * histórico, envio de prompt + stream) trafega pela mesma conexão.
811
+ * Hub do WebSocket compartilhado e factories da API pública:
812
+ * - getAgentChatsMitra({ projectId? })
813
+ * - getAgentTaskMitra({ create | taskId, ... })
786
814
  *
787
- * - Open: lazy conecta na primeira chamada.
788
- * - Auth: JWT do config global passado como query param do handshake.
789
- * O backend valida o token e resolve userSpaceID server-side.
790
- * - Request/Response: cada chamada envia { type, requestId } e aguarda
791
- * { type: 'response', requestId, ok, data | error }.
792
- * - Stream: send_prompt dispara push events (stream_delta, stream_end, ...).
815
+ * O WS é singleton: todas as sessions usam UMA conexão. O roteamento
816
+ * de eventos é feito por taskId, despachando pra session correspondente.
817
+ *
818
+ * NÃO `sendAgentPromptMitra` ou `getAgentHistoryMitra` exportados
819
+ * essas operações vivem dentro de `AgentTaskSession`.
793
820
  */
794
821
 
822
+ /**
823
+ * Lista chats do user para um projeto.
824
+ */
795
825
  declare function getAgentChatsMitra(options?: GetAgentChatsOptions): Promise<AgentChat[]>;
796
- declare function getAgentHistoryMitra(options: GetAgentHistoryOptions): Promise<AgentMessage[]>;
797
- declare function sendAgentPromptMitra(options: SendAgentPromptOptions): Promise<SendAgentPromptResponse>;
798
826
  /**
799
- * Fecha o WebSocket do Agent Chat. Útil em testes ou no logout.
827
+ * Abre um handle de chat (session). Use:
828
+ * - `{ create: true }` para iniciar um chat novo
829
+ * - `{ taskId: 'X' }` para abrir um chat existente
830
+ *
831
+ * A session expõe histórico, streaming, fila, cancel e eventos. Se a
832
+ * mesma taskId for aberta duas vezes, retorna a MESMA instância (cache).
833
+ */
834
+ declare function getAgentTaskMitra(options: GetAgentTaskOptions): AgentTaskSession;
835
+ /**
836
+ * Fecha o WebSocket do Agent Chat. Sessions ativas devem chamar close()
837
+ * antes — esta função é destinada a teardown global (logout, testes).
800
838
  */
801
839
  declare function disconnectAgentChatMitra(): void;
802
840
 
@@ -955,4 +993,4 @@ declare function setProfileScreensMitra(options: SetProfileScreensOptions): Prom
955
993
  */
956
994
  declare function setProfileServerFunctionsMitra(options: SetProfileServerFunctionsOptions): Promise<SetProfilePermissionResponse>;
957
995
 
958
- export { type AgentChat, type AgentErrorEvent, type AgentMessage, type AgentStreamDeltaEvent, type AgentStreamEndEvent, type AgentStreamToolEvent, type AgentTaskCreatedEvent, type CallIntegrationOptions, type CallIntegrationResponse, type CreateProfileOptions, type CreateProfileResponse, type CreateRecordOptions, type CreateRecordsBatchOptions, type DeleteProfileOptions, type DeleteProfileResponse, type DeleteRecordOptions, type EmailLoginOptions, type EmailResendCodeOptions, type EmailSignupOptions, type EmailVerifyCodeOptions, type ExecuteDataLoaderOptions, type ExecuteDataLoaderResponse, type ExecuteDbActionOptions, type ExecuteDbActionResponse, type ExecutePublicServerFunctionAsyncResponse, type ExecutePublicServerFunctionOptions, type ExecutePublicServerFunctionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type GetAgentChatsOptions, type GetAgentHistoryOptions, type GetProfileDetailsOptions, type GetProfileDetailsResponse, type GetPublicServerFunctionExecutionOptions, type GetPublicServerFunctionExecutionResponse, type GetRecordOptions, type GetVariableOptions, type GetVariableResponse, type IntegrationResponse, type ListIntegrationsOptions, type ListProfilesOptions, type ListProfilesResponse, type ListRecordsOptions, type ListRecordsResponse, type ListVariablesOptions, type ListVariablesResponse, type LoginOptions, type LoginResponse, type MitraConfig, type MitraInstance, type PatchRecordOptions, type ProfileTableRef, type ResetPasswordOptions, type RunActionOptions, type RunActionResponse, type SendAgentPromptOptions, type SendAgentPromptResponse, type SendPasswordResetCodeOptions, type SetFileStatusOptions, type SetFileStatusResponse, type SetProfileActionsOptions, type SetProfileDmlTablesOptions, type SetProfilePermissionResponse, type SetProfileScreensOptions, type SetProfileSelectTablesOptions, type SetProfileServerFunctionsOptions, type SetProfileUsersOptions, type SetVariableOptions, type SetVariableResponse, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateProfileOptions, type UpdateProfileResponse, type UpdateRecordOptions, type UploadFileOptions, type UploadFileResponse, type ValidatePasswordResetCodeOptions, callIntegrationMitra, closeChatMitra, configureSdkMitra, createMitraInstance, createProfileMitra, createRecordMitra, createRecordsBatchMitra, deleteProfileMitra, deleteRecordMitra, disconnectAgentChatMitra, emailLoginMitra, emailResendCodeMitra, emailSignupMitra, emailVerifyCodeMitra, executeDataLoaderMitra, executeDbActionMitra, executePublicServerFunctionAsyncMitra, executePublicServerFunctionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, getAgentChatsMitra, getAgentHistoryMitra, getConfig, getProfileDetailsMitra, getPublicServerFunctionExecutionMitra, getRecordMitra, getVariableMitra, listIntegrationsMitra, listProfilesMitra, listRecordsMitra, listVariablesMitra, loginMitra, loginWithEmailMitra, loginWithGoogleMitra, loginWithMicrosoftMitra, openChatMitra, patchRecordMitra, refreshTokenSilently, resetPasswordMitra, resolveProjectId, runActionMitra, sendAgentPromptMitra, sendPasswordResetCodeMitra, setFileStatusMitra, setProfileActionsMitra, setProfileDmlTablesMitra, setProfileScreensMitra, setProfileSelectTablesMitra, setProfileServerFunctionsMitra, setProfileUsersMitra, setVariableMitra, stopServerFunctionExecutionMitra, updateProfileMitra, updateRecordMitra, uploadFileLoadableMitra, uploadFilePublicMitra, validatePasswordResetCodeMitra };
996
+ export { type AgentChat, type AgentDeltaEvent, type AgentErrorEvent, type AgentMessage, type AgentQueueChangeEvent, type AgentStatusChangeEvent, type AgentTaskCreatedEvent, type AgentTaskEventMap, type AgentTaskEventName, type AgentTaskSession, type AgentTaskStatus, type AgentToolEvent, type AgentTurnEndEvent, type AgentType, type CallIntegrationOptions, type CallIntegrationResponse, type CreateProfileOptions, type CreateProfileResponse, type CreateRecordOptions, type CreateRecordsBatchOptions, type DeleteProfileOptions, type DeleteProfileResponse, type DeleteRecordOptions, type EmailLoginOptions, type EmailResendCodeOptions, type EmailSignupOptions, type EmailVerifyCodeOptions, type ExecuteDataLoaderOptions, type ExecuteDataLoaderResponse, type ExecuteDbActionOptions, type ExecuteDbActionResponse, type ExecutePublicServerFunctionAsyncResponse, type ExecutePublicServerFunctionOptions, type ExecutePublicServerFunctionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type GetAgentChatsOptions, type GetAgentTaskCreateOptions, type GetAgentTaskOpenOptions, type GetAgentTaskOptions, type GetProfileDetailsOptions, type GetProfileDetailsResponse, type GetPublicServerFunctionExecutionOptions, type GetPublicServerFunctionExecutionResponse, type GetRecordOptions, type GetVariableOptions, type GetVariableResponse, type IntegrationResponse, type ListIntegrationsOptions, type ListProfilesOptions, type ListProfilesResponse, type ListRecordsOptions, type ListRecordsResponse, type ListVariablesOptions, type ListVariablesResponse, type LoginOptions, type LoginResponse, type MitraConfig, type MitraInstance, type PatchRecordOptions, type ProfileTableRef, type QueuedItem, type ResetPasswordOptions, type RunActionOptions, type RunActionResponse, type SendOptions, type SendPasswordResetCodeOptions, type SetFileStatusOptions, type SetFileStatusResponse, type SetProfileActionsOptions, type SetProfileDmlTablesOptions, type SetProfilePermissionResponse, type SetProfileScreensOptions, type SetProfileSelectTablesOptions, type SetProfileServerFunctionsOptions, type SetProfileUsersOptions, type SetVariableOptions, type SetVariableResponse, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateProfileOptions, type UpdateProfileResponse, type UpdateRecordOptions, type UploadFileOptions, type UploadFileResponse, type ValidatePasswordResetCodeOptions, callIntegrationMitra, closeChatMitra, configureSdkMitra, createMitraInstance, createProfileMitra, createRecordMitra, createRecordsBatchMitra, deleteProfileMitra, deleteRecordMitra, disconnectAgentChatMitra, emailLoginMitra, emailResendCodeMitra, emailSignupMitra, emailVerifyCodeMitra, executeDataLoaderMitra, executeDbActionMitra, executePublicServerFunctionAsyncMitra, executePublicServerFunctionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, getAgentChatsMitra, getAgentTaskMitra, getConfig, getProfileDetailsMitra, getPublicServerFunctionExecutionMitra, getRecordMitra, getVariableMitra, listIntegrationsMitra, listProfilesMitra, listRecordsMitra, listVariablesMitra, loginMitra, loginWithEmailMitra, loginWithGoogleMitra, loginWithMicrosoftMitra, openChatMitra, patchRecordMitra, refreshTokenSilently, resetPasswordMitra, resolveProjectId, runActionMitra, sendPasswordResetCodeMitra, setFileStatusMitra, setProfileActionsMitra, setProfileDmlTablesMitra, setProfileScreensMitra, setProfileSelectTablesMitra, setProfileServerFunctionsMitra, setProfileUsersMitra, setVariableMitra, stopServerFunctionExecutionMitra, updateProfileMitra, updateRecordMitra, uploadFileLoadableMitra, uploadFilePublicMitra, validatePasswordResetCodeMitra };
package/dist/index.d.ts CHANGED
@@ -22,8 +22,6 @@ interface LoginResponse {
22
22
  baseURL: string;
23
23
  /** URL do serviço de integrações (opcional) */
24
24
  integrationURL?: string;
25
- /** URL do WebSocket do Agent Chat (opcional — vem do sdk-auth quando configurado) */
26
- agentWsUrl?: string;
27
25
  }
28
26
  interface EmailSignupOptions {
29
27
  /** URL da página de auth (ex: https://validacao.mitralab.io/sdk-auth/). Opcional se já configurado via configureSdkMitra. */
@@ -521,6 +519,7 @@ interface SetProfilePermissionResponse {
521
519
  [key: string]: unknown;
522
520
  };
523
521
  }
522
+ type AgentType = 'claudecode' | 'codex' | 'opencode-cli' | 'opencode-sdk';
524
523
  interface AgentChat {
525
524
  id: string;
526
525
  name: string;
@@ -541,65 +540,92 @@ interface GetAgentChatsOptions {
541
540
  /** Sobrescreve o projectId configurado globalmente. */
542
541
  projectId?: number;
543
542
  }
544
- interface GetAgentHistoryOptions {
545
- /** ID do chat cuja conversa será carregada. */
546
- taskId: string;
547
- /** Quantidade máxima de mensagens (default: tudo). */
548
- limit?: number;
543
+ interface GetAgentTaskCreateOptions {
544
+ /** Cria chat novo. taskId é preenchido depois do primeiro send(). */
545
+ create: true;
546
+ /** Sobrescreve projectId global. */
547
+ projectId?: number;
548
+ /** Tipo do agente. Default: 'claudecode'. */
549
+ agentType?: AgentType;
550
+ /** Nome do chat (default: derivado do prompt). */
551
+ name?: string;
549
552
  }
550
- interface AgentStreamDeltaEvent {
553
+ interface GetAgentTaskOpenOptions {
554
+ /** Abre chat existente. Detecta automático se stream está ativo. */
551
555
  taskId: string;
552
- /** Pedaço de texto que chegou. */
556
+ }
557
+ type GetAgentTaskOptions = GetAgentTaskCreateOptions | GetAgentTaskOpenOptions;
558
+ type AgentTaskStatus = 'opening' | 'idle' | 'streaming' | 'cancelled' | 'error' | 'closed';
559
+ interface QueuedItem {
560
+ id: string;
561
+ text: string;
562
+ agentType?: AgentType;
563
+ seq: number;
564
+ createdAt: number;
565
+ status: 'pending' | 'sending';
566
+ injected?: boolean;
567
+ }
568
+ interface SendOptions {
569
+ agentType?: AgentType;
570
+ }
571
+ interface AgentDeltaEvent {
553
572
  delta: string;
554
- /** Tipo do conteúdo: 'text' (resposta do agente) ou 'tool' (atividade de ferramenta). */
555
573
  kind: 'text' | 'tool';
556
574
  }
557
- interface AgentStreamToolEvent {
558
- taskId: string;
575
+ interface AgentToolEvent {
559
576
  tool: string;
560
577
  input?: string;
561
578
  content?: string;
562
579
  timestamp: number;
563
580
  }
564
- interface AgentStreamEndEvent {
565
- taskId: string;
566
- /** Conteúdo final acumulado (concatenação dos deltas). */
581
+ interface AgentTurnEndEvent {
582
+ /** Conteúdo final acumulado do turno. */
567
583
  content: string;
568
584
  }
569
585
  interface AgentTaskCreatedEvent {
570
586
  task: AgentChat;
571
587
  }
572
588
  interface AgentErrorEvent {
573
- taskId?: string;
574
589
  error: string;
575
590
  }
576
- interface SendAgentPromptOptions {
577
- /** Texto enviado ao agente. */
578
- prompt: string;
579
- /** ID do chat existente. Se ausente, cria um chat novo. */
580
- taskId?: string;
581
- /** Tipo do agente. Default: 'claudecode'. */
582
- agentType?: 'claudecode' | 'codex' | 'opencode-cli' | 'opencode-sdk';
583
- /** Sobrescreve projectId global. */
584
- projectId?: number;
585
- /** Nome do chat quando criando novo (default: derivado do prompt). */
586
- name?: string;
587
- /** Callback chamado a cada chunk de texto. */
588
- onDelta?: (event: AgentStreamDeltaEvent) => void;
589
- /** Callback chamado quando uma ferramenta é usada. */
590
- onTool?: (event: AgentStreamToolEvent) => void;
591
- /** Callback chamado quando um novo chat é criado (só dispara se taskId era ausente). */
592
- onTaskCreated?: (event: AgentTaskCreatedEvent) => void;
593
- /** Callback chamado quando ocorre erro durante o stream. */
594
- onError?: (event: AgentErrorEvent) => void;
595
- /** Permite cancelar o stream mid-flight. */
596
- signal?: AbortSignal;
597
- }
598
- interface SendAgentPromptResponse {
599
- /** ID do chat (existente ou recém-criado). */
600
- taskId: string;
601
- /** Texto completo acumulado dos deltas. */
602
- content: string;
591
+ interface AgentQueueChangeEvent {
592
+ queue: ReadonlyArray<QueuedItem>;
593
+ }
594
+ interface AgentStatusChangeEvent {
595
+ status: AgentTaskStatus;
596
+ previous: AgentTaskStatus;
597
+ }
598
+ type AgentTaskEventMap = {
599
+ historyLoaded: AgentMessage[];
600
+ turnStart: void;
601
+ delta: AgentDeltaEvent;
602
+ tool: AgentToolEvent;
603
+ turnEnd: AgentTurnEndEvent;
604
+ taskCreated: AgentTaskCreatedEvent;
605
+ cancelled: void;
606
+ error: AgentErrorEvent;
607
+ queueChange: AgentQueueChangeEvent;
608
+ statusChange: AgentStatusChangeEvent;
609
+ };
610
+ type AgentTaskEventName = keyof AgentTaskEventMap;
611
+ interface AgentTaskSession {
612
+ readonly taskId: string | null;
613
+ readonly task: AgentChat | null;
614
+ readonly isNew: boolean;
615
+ readonly status: AgentTaskStatus;
616
+ readonly history: ReadonlyArray<AgentMessage>;
617
+ readonly content: string;
618
+ readonly queue: ReadonlyArray<QueuedItem>;
619
+ loadHistory(options?: {
620
+ limit?: number;
621
+ }): Promise<AgentMessage[]>;
622
+ close(): void;
623
+ send(prompt: string, options?: SendOptions): void;
624
+ cancel(): Promise<void>;
625
+ editQueueItem(itemId: string, newText: string): boolean;
626
+ removeQueueItem(itemId: string): boolean;
627
+ clearQueue(): void;
628
+ on<E extends AgentTaskEventName>(event: E, handler: (payload: AgentTaskEventMap[E]) => void): () => void;
603
629
  }
604
630
 
605
631
  /**
@@ -649,8 +675,7 @@ interface MitraInstance {
649
675
  validatePasswordResetCode(options: ValidatePasswordResetCodeOptions): Promise<Record<string, unknown>>;
650
676
  resetPassword(options: ResetPasswordOptions): Promise<Record<string, unknown>>;
651
677
  getAgentChats(options?: GetAgentChatsOptions): Promise<AgentChat[]>;
652
- getAgentHistory(options: GetAgentHistoryOptions): Promise<AgentMessage[]>;
653
- sendAgentPrompt(options: SendAgentPromptOptions): Promise<SendAgentPromptResponse>;
678
+ getAgentTask(options: GetAgentTaskOptions): AgentTaskSession;
654
679
  disconnectAgentChat(): void;
655
680
  openChat(): void;
656
681
  closeChat(): void;
@@ -658,16 +683,14 @@ interface MitraInstance {
658
683
  declare function createMitraInstance(initialConfig: Partial<MitraConfig>): MitraInstance;
659
684
 
660
685
  interface MitraConfig {
661
- /** URL base da API (ex: https://api.mitra.com) */
662
- baseURL: string;
686
+ /** URL base da API (ex: https://api.mitra.com). Opcional se houver window.__mitraEnv.apiBaseURL (build-proxy). */
687
+ baseURL?: string;
663
688
  /** Token JWT para autenticação (opcional para Server Functions públicas) */
664
689
  token?: string;
665
690
  /** URL base do serviço de integrações (ex: https://api0.mitraecp.com:1003) */
666
691
  integrationURL?: string;
667
692
  /** URL da página de autenticação Mitra (ex: https://coder.mitralab.io/sdk-auth/) */
668
693
  authUrl?: string;
669
- /** URL do WebSocket do Agent Chat (ex: wss://agent.mitralab.io/sdk-ws ou ws://localhost:3456/sdk-ws) */
670
- agentWsUrl?: string;
671
694
  /** ID do projeto (usado como fallback nos métodos de login e serviços) */
672
695
  projectId?: number;
673
696
  /** Callback chamado quando o token é renovado automaticamente (após 401/403). Recebe a nova sessão. */
@@ -675,8 +698,12 @@ interface MitraConfig {
675
698
  }
676
699
  /**
677
700
  * Configura o SDK globalmente e retorna uma instância configurada.
701
+ *
702
+ * Em apps publicadas pelo Mitra (window.__mitraEnv presente), nenhum campo
703
+ * precisa ser passado — todas as URLs vêm da injeção do build-proxy.
704
+ * Em outros contextos, baseURL ainda é necessário (manual ou via login).
678
705
  */
679
- declare function configureSdkMitra(config: MitraConfig): MitraInstance;
706
+ declare function configureSdkMitra(config?: Partial<MitraConfig>): MitraInstance;
680
707
  /**
681
708
  * Obtém a configuração atual
682
709
  */
@@ -779,24 +806,35 @@ declare function validatePasswordResetCodeMitra(options: ValidatePasswordResetCo
779
806
  declare function resetPasswordMitra(options: ResetPasswordOptions): Promise<Record<string, unknown>>;
780
807
 
781
808
  /**
782
- * Mitra Interactions SDK - Agent Chat (embedded)
809
+ * Mitra Interactions SDK Agent Chat
783
810
  *
784
- * Conecta via WebSocket ao mitra-agent-websocket. Tudo (lista de chats,
785
- * histórico, envio de prompt + stream) trafega pela mesma conexão.
811
+ * Hub do WebSocket compartilhado e factories da API pública:
812
+ * - getAgentChatsMitra({ projectId? })
813
+ * - getAgentTaskMitra({ create | taskId, ... })
786
814
  *
787
- * - Open: lazy conecta na primeira chamada.
788
- * - Auth: JWT do config global passado como query param do handshake.
789
- * O backend valida o token e resolve userSpaceID server-side.
790
- * - Request/Response: cada chamada envia { type, requestId } e aguarda
791
- * { type: 'response', requestId, ok, data | error }.
792
- * - Stream: send_prompt dispara push events (stream_delta, stream_end, ...).
815
+ * O WS é singleton: todas as sessions usam UMA conexão. O roteamento
816
+ * de eventos é feito por taskId, despachando pra session correspondente.
817
+ *
818
+ * NÃO `sendAgentPromptMitra` ou `getAgentHistoryMitra` exportados
819
+ * essas operações vivem dentro de `AgentTaskSession`.
793
820
  */
794
821
 
822
+ /**
823
+ * Lista chats do user para um projeto.
824
+ */
795
825
  declare function getAgentChatsMitra(options?: GetAgentChatsOptions): Promise<AgentChat[]>;
796
- declare function getAgentHistoryMitra(options: GetAgentHistoryOptions): Promise<AgentMessage[]>;
797
- declare function sendAgentPromptMitra(options: SendAgentPromptOptions): Promise<SendAgentPromptResponse>;
798
826
  /**
799
- * Fecha o WebSocket do Agent Chat. Útil em testes ou no logout.
827
+ * Abre um handle de chat (session). Use:
828
+ * - `{ create: true }` para iniciar um chat novo
829
+ * - `{ taskId: 'X' }` para abrir um chat existente
830
+ *
831
+ * A session expõe histórico, streaming, fila, cancel e eventos. Se a
832
+ * mesma taskId for aberta duas vezes, retorna a MESMA instância (cache).
833
+ */
834
+ declare function getAgentTaskMitra(options: GetAgentTaskOptions): AgentTaskSession;
835
+ /**
836
+ * Fecha o WebSocket do Agent Chat. Sessions ativas devem chamar close()
837
+ * antes — esta função é destinada a teardown global (logout, testes).
800
838
  */
801
839
  declare function disconnectAgentChatMitra(): void;
802
840
 
@@ -955,4 +993,4 @@ declare function setProfileScreensMitra(options: SetProfileScreensOptions): Prom
955
993
  */
956
994
  declare function setProfileServerFunctionsMitra(options: SetProfileServerFunctionsOptions): Promise<SetProfilePermissionResponse>;
957
995
 
958
- export { type AgentChat, type AgentErrorEvent, type AgentMessage, type AgentStreamDeltaEvent, type AgentStreamEndEvent, type AgentStreamToolEvent, type AgentTaskCreatedEvent, type CallIntegrationOptions, type CallIntegrationResponse, type CreateProfileOptions, type CreateProfileResponse, type CreateRecordOptions, type CreateRecordsBatchOptions, type DeleteProfileOptions, type DeleteProfileResponse, type DeleteRecordOptions, type EmailLoginOptions, type EmailResendCodeOptions, type EmailSignupOptions, type EmailVerifyCodeOptions, type ExecuteDataLoaderOptions, type ExecuteDataLoaderResponse, type ExecuteDbActionOptions, type ExecuteDbActionResponse, type ExecutePublicServerFunctionAsyncResponse, type ExecutePublicServerFunctionOptions, type ExecutePublicServerFunctionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type GetAgentChatsOptions, type GetAgentHistoryOptions, type GetProfileDetailsOptions, type GetProfileDetailsResponse, type GetPublicServerFunctionExecutionOptions, type GetPublicServerFunctionExecutionResponse, type GetRecordOptions, type GetVariableOptions, type GetVariableResponse, type IntegrationResponse, type ListIntegrationsOptions, type ListProfilesOptions, type ListProfilesResponse, type ListRecordsOptions, type ListRecordsResponse, type ListVariablesOptions, type ListVariablesResponse, type LoginOptions, type LoginResponse, type MitraConfig, type MitraInstance, type PatchRecordOptions, type ProfileTableRef, type ResetPasswordOptions, type RunActionOptions, type RunActionResponse, type SendAgentPromptOptions, type SendAgentPromptResponse, type SendPasswordResetCodeOptions, type SetFileStatusOptions, type SetFileStatusResponse, type SetProfileActionsOptions, type SetProfileDmlTablesOptions, type SetProfilePermissionResponse, type SetProfileScreensOptions, type SetProfileSelectTablesOptions, type SetProfileServerFunctionsOptions, type SetProfileUsersOptions, type SetVariableOptions, type SetVariableResponse, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateProfileOptions, type UpdateProfileResponse, type UpdateRecordOptions, type UploadFileOptions, type UploadFileResponse, type ValidatePasswordResetCodeOptions, callIntegrationMitra, closeChatMitra, configureSdkMitra, createMitraInstance, createProfileMitra, createRecordMitra, createRecordsBatchMitra, deleteProfileMitra, deleteRecordMitra, disconnectAgentChatMitra, emailLoginMitra, emailResendCodeMitra, emailSignupMitra, emailVerifyCodeMitra, executeDataLoaderMitra, executeDbActionMitra, executePublicServerFunctionAsyncMitra, executePublicServerFunctionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, getAgentChatsMitra, getAgentHistoryMitra, getConfig, getProfileDetailsMitra, getPublicServerFunctionExecutionMitra, getRecordMitra, getVariableMitra, listIntegrationsMitra, listProfilesMitra, listRecordsMitra, listVariablesMitra, loginMitra, loginWithEmailMitra, loginWithGoogleMitra, loginWithMicrosoftMitra, openChatMitra, patchRecordMitra, refreshTokenSilently, resetPasswordMitra, resolveProjectId, runActionMitra, sendAgentPromptMitra, sendPasswordResetCodeMitra, setFileStatusMitra, setProfileActionsMitra, setProfileDmlTablesMitra, setProfileScreensMitra, setProfileSelectTablesMitra, setProfileServerFunctionsMitra, setProfileUsersMitra, setVariableMitra, stopServerFunctionExecutionMitra, updateProfileMitra, updateRecordMitra, uploadFileLoadableMitra, uploadFilePublicMitra, validatePasswordResetCodeMitra };
996
+ export { type AgentChat, type AgentDeltaEvent, type AgentErrorEvent, type AgentMessage, type AgentQueueChangeEvent, type AgentStatusChangeEvent, type AgentTaskCreatedEvent, type AgentTaskEventMap, type AgentTaskEventName, type AgentTaskSession, type AgentTaskStatus, type AgentToolEvent, type AgentTurnEndEvent, type AgentType, type CallIntegrationOptions, type CallIntegrationResponse, type CreateProfileOptions, type CreateProfileResponse, type CreateRecordOptions, type CreateRecordsBatchOptions, type DeleteProfileOptions, type DeleteProfileResponse, type DeleteRecordOptions, type EmailLoginOptions, type EmailResendCodeOptions, type EmailSignupOptions, type EmailVerifyCodeOptions, type ExecuteDataLoaderOptions, type ExecuteDataLoaderResponse, type ExecuteDbActionOptions, type ExecuteDbActionResponse, type ExecutePublicServerFunctionAsyncResponse, type ExecutePublicServerFunctionOptions, type ExecutePublicServerFunctionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type GetAgentChatsOptions, type GetAgentTaskCreateOptions, type GetAgentTaskOpenOptions, type GetAgentTaskOptions, type GetProfileDetailsOptions, type GetProfileDetailsResponse, type GetPublicServerFunctionExecutionOptions, type GetPublicServerFunctionExecutionResponse, type GetRecordOptions, type GetVariableOptions, type GetVariableResponse, type IntegrationResponse, type ListIntegrationsOptions, type ListProfilesOptions, type ListProfilesResponse, type ListRecordsOptions, type ListRecordsResponse, type ListVariablesOptions, type ListVariablesResponse, type LoginOptions, type LoginResponse, type MitraConfig, type MitraInstance, type PatchRecordOptions, type ProfileTableRef, type QueuedItem, type ResetPasswordOptions, type RunActionOptions, type RunActionResponse, type SendOptions, type SendPasswordResetCodeOptions, type SetFileStatusOptions, type SetFileStatusResponse, type SetProfileActionsOptions, type SetProfileDmlTablesOptions, type SetProfilePermissionResponse, type SetProfileScreensOptions, type SetProfileSelectTablesOptions, type SetProfileServerFunctionsOptions, type SetProfileUsersOptions, type SetVariableOptions, type SetVariableResponse, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateProfileOptions, type UpdateProfileResponse, type UpdateRecordOptions, type UploadFileOptions, type UploadFileResponse, type ValidatePasswordResetCodeOptions, callIntegrationMitra, closeChatMitra, configureSdkMitra, createMitraInstance, createProfileMitra, createRecordMitra, createRecordsBatchMitra, deleteProfileMitra, deleteRecordMitra, disconnectAgentChatMitra, emailLoginMitra, emailResendCodeMitra, emailSignupMitra, emailVerifyCodeMitra, executeDataLoaderMitra, executeDbActionMitra, executePublicServerFunctionAsyncMitra, executePublicServerFunctionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, getAgentChatsMitra, getAgentTaskMitra, getConfig, getProfileDetailsMitra, getPublicServerFunctionExecutionMitra, getRecordMitra, getVariableMitra, listIntegrationsMitra, listProfilesMitra, listRecordsMitra, listVariablesMitra, loginMitra, loginWithEmailMitra, loginWithGoogleMitra, loginWithMicrosoftMitra, openChatMitra, patchRecordMitra, refreshTokenSilently, resetPasswordMitra, resolveProjectId, runActionMitra, sendPasswordResetCodeMitra, setFileStatusMitra, setProfileActionsMitra, setProfileDmlTablesMitra, setProfileScreensMitra, setProfileSelectTablesMitra, setProfileServerFunctionsMitra, setProfileUsersMitra, setVariableMitra, stopServerFunctionExecutionMitra, updateProfileMitra, updateRecordMitra, uploadFileLoadableMitra, uploadFilePublicMitra, validatePasswordResetCodeMitra };