mitra-interactions-sdk 1.0.57 → 1.0.58-beta.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/dist/index.d.mts CHANGED
@@ -22,6 +22,8 @@ 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;
25
27
  }
26
28
  interface EmailSignupOptions {
27
29
  /** URL da página de auth (ex: https://validacao.mitralab.io/sdk-auth/). Opcional se já configurado via configureSdkMitra. */
@@ -519,6 +521,86 @@ interface SetProfilePermissionResponse {
519
521
  [key: string]: unknown;
520
522
  };
521
523
  }
524
+ interface AgentChat {
525
+ id: string;
526
+ name: string;
527
+ agentType?: string;
528
+ provider?: string;
529
+ createdAt: string;
530
+ updatedAt: string;
531
+ }
532
+ interface AgentMessage {
533
+ id: string;
534
+ content: string;
535
+ type: string;
536
+ sender?: 'user' | 'agent';
537
+ createdAt: string;
538
+ metadata?: Record<string, unknown> | null;
539
+ }
540
+ interface GetAgentChatsOptions {
541
+ /** Sobrescreve o projectId configurado globalmente. */
542
+ projectId?: number;
543
+ }
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;
549
+ }
550
+ interface AgentStreamDeltaEvent {
551
+ taskId: string;
552
+ /** Pedaço de texto que chegou. */
553
+ delta: string;
554
+ /** Tipo do conteúdo: 'text' (resposta do agente) ou 'tool' (atividade de ferramenta). */
555
+ kind: 'text' | 'tool';
556
+ }
557
+ interface AgentStreamToolEvent {
558
+ taskId: string;
559
+ tool: string;
560
+ input?: string;
561
+ content?: string;
562
+ timestamp: number;
563
+ }
564
+ interface AgentStreamEndEvent {
565
+ taskId: string;
566
+ /** Conteúdo final acumulado (concatenação dos deltas). */
567
+ content: string;
568
+ }
569
+ interface AgentTaskCreatedEvent {
570
+ task: AgentChat;
571
+ }
572
+ interface AgentErrorEvent {
573
+ taskId?: string;
574
+ error: string;
575
+ }
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;
603
+ }
522
604
 
523
605
  /**
524
606
  * Mitra Interactions SDK - Instance
@@ -566,6 +648,10 @@ interface MitraInstance {
566
648
  sendPasswordResetCode(options: SendPasswordResetCodeOptions): Promise<Record<string, unknown>>;
567
649
  validatePasswordResetCode(options: ValidatePasswordResetCodeOptions): Promise<Record<string, unknown>>;
568
650
  resetPassword(options: ResetPasswordOptions): Promise<Record<string, unknown>>;
651
+ getAgentChats(options?: GetAgentChatsOptions): Promise<AgentChat[]>;
652
+ getAgentHistory(options: GetAgentHistoryOptions): Promise<AgentMessage[]>;
653
+ sendAgentPrompt(options: SendAgentPromptOptions): Promise<SendAgentPromptResponse>;
654
+ disconnectAgentChat(): void;
569
655
  openChat(): void;
570
656
  closeChat(): void;
571
657
  }
@@ -580,6 +666,8 @@ interface MitraConfig {
580
666
  integrationURL?: string;
581
667
  /** URL da página de autenticação Mitra (ex: https://coder.mitralab.io/sdk-auth/) */
582
668
  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;
583
671
  /** ID do projeto (usado como fallback nos métodos de login e serviços) */
584
672
  projectId?: number;
585
673
  /** Callback chamado quando o token é renovado automaticamente (após 401/403). Recebe a nova sessão. */
@@ -690,6 +778,28 @@ declare function validatePasswordResetCodeMitra(options: ValidatePasswordResetCo
690
778
  */
691
779
  declare function resetPasswordMitra(options: ResetPasswordOptions): Promise<Record<string, unknown>>;
692
780
 
781
+ /**
782
+ * Mitra Interactions SDK - Agent Chat (embedded)
783
+ *
784
+ * Conecta via WebSocket ao mitra-agent-websocket. Tudo (lista de chats,
785
+ * histórico, envio de prompt + stream) trafega pela mesma conexão.
786
+ *
787
+ * - Open: lazy — só 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, ...).
793
+ */
794
+
795
+ declare function getAgentChatsMitra(options?: GetAgentChatsOptions): Promise<AgentChat[]>;
796
+ declare function getAgentHistoryMitra(options: GetAgentHistoryOptions): Promise<AgentMessage[]>;
797
+ declare function sendAgentPromptMitra(options: SendAgentPromptOptions): Promise<SendAgentPromptResponse>;
798
+ /**
799
+ * Fecha o WebSocket do Agent Chat. Útil em testes ou no logout.
800
+ */
801
+ declare function disconnectAgentChatMitra(): void;
802
+
693
803
  /**
694
804
  * Mitra Interactions SDK - Services
695
805
  */
@@ -845,4 +955,4 @@ declare function setProfileScreensMitra(options: SetProfileScreensOptions): Prom
845
955
  */
846
956
  declare function setProfileServerFunctionsMitra(options: SetProfileServerFunctionsOptions): Promise<SetProfilePermissionResponse>;
847
957
 
848
- export { 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 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 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, emailLoginMitra, emailResendCodeMitra, emailSignupMitra, emailVerifyCodeMitra, executeDataLoaderMitra, executeDbActionMitra, executePublicServerFunctionAsyncMitra, executePublicServerFunctionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, 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 };
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 };
package/dist/index.d.ts CHANGED
@@ -22,6 +22,8 @@ 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;
25
27
  }
26
28
  interface EmailSignupOptions {
27
29
  /** URL da página de auth (ex: https://validacao.mitralab.io/sdk-auth/). Opcional se já configurado via configureSdkMitra. */
@@ -519,6 +521,86 @@ interface SetProfilePermissionResponse {
519
521
  [key: string]: unknown;
520
522
  };
521
523
  }
524
+ interface AgentChat {
525
+ id: string;
526
+ name: string;
527
+ agentType?: string;
528
+ provider?: string;
529
+ createdAt: string;
530
+ updatedAt: string;
531
+ }
532
+ interface AgentMessage {
533
+ id: string;
534
+ content: string;
535
+ type: string;
536
+ sender?: 'user' | 'agent';
537
+ createdAt: string;
538
+ metadata?: Record<string, unknown> | null;
539
+ }
540
+ interface GetAgentChatsOptions {
541
+ /** Sobrescreve o projectId configurado globalmente. */
542
+ projectId?: number;
543
+ }
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;
549
+ }
550
+ interface AgentStreamDeltaEvent {
551
+ taskId: string;
552
+ /** Pedaço de texto que chegou. */
553
+ delta: string;
554
+ /** Tipo do conteúdo: 'text' (resposta do agente) ou 'tool' (atividade de ferramenta). */
555
+ kind: 'text' | 'tool';
556
+ }
557
+ interface AgentStreamToolEvent {
558
+ taskId: string;
559
+ tool: string;
560
+ input?: string;
561
+ content?: string;
562
+ timestamp: number;
563
+ }
564
+ interface AgentStreamEndEvent {
565
+ taskId: string;
566
+ /** Conteúdo final acumulado (concatenação dos deltas). */
567
+ content: string;
568
+ }
569
+ interface AgentTaskCreatedEvent {
570
+ task: AgentChat;
571
+ }
572
+ interface AgentErrorEvent {
573
+ taskId?: string;
574
+ error: string;
575
+ }
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;
603
+ }
522
604
 
523
605
  /**
524
606
  * Mitra Interactions SDK - Instance
@@ -566,6 +648,10 @@ interface MitraInstance {
566
648
  sendPasswordResetCode(options: SendPasswordResetCodeOptions): Promise<Record<string, unknown>>;
567
649
  validatePasswordResetCode(options: ValidatePasswordResetCodeOptions): Promise<Record<string, unknown>>;
568
650
  resetPassword(options: ResetPasswordOptions): Promise<Record<string, unknown>>;
651
+ getAgentChats(options?: GetAgentChatsOptions): Promise<AgentChat[]>;
652
+ getAgentHistory(options: GetAgentHistoryOptions): Promise<AgentMessage[]>;
653
+ sendAgentPrompt(options: SendAgentPromptOptions): Promise<SendAgentPromptResponse>;
654
+ disconnectAgentChat(): void;
569
655
  openChat(): void;
570
656
  closeChat(): void;
571
657
  }
@@ -580,6 +666,8 @@ interface MitraConfig {
580
666
  integrationURL?: string;
581
667
  /** URL da página de autenticação Mitra (ex: https://coder.mitralab.io/sdk-auth/) */
582
668
  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;
583
671
  /** ID do projeto (usado como fallback nos métodos de login e serviços) */
584
672
  projectId?: number;
585
673
  /** Callback chamado quando o token é renovado automaticamente (após 401/403). Recebe a nova sessão. */
@@ -690,6 +778,28 @@ declare function validatePasswordResetCodeMitra(options: ValidatePasswordResetCo
690
778
  */
691
779
  declare function resetPasswordMitra(options: ResetPasswordOptions): Promise<Record<string, unknown>>;
692
780
 
781
+ /**
782
+ * Mitra Interactions SDK - Agent Chat (embedded)
783
+ *
784
+ * Conecta via WebSocket ao mitra-agent-websocket. Tudo (lista de chats,
785
+ * histórico, envio de prompt + stream) trafega pela mesma conexão.
786
+ *
787
+ * - Open: lazy — só 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, ...).
793
+ */
794
+
795
+ declare function getAgentChatsMitra(options?: GetAgentChatsOptions): Promise<AgentChat[]>;
796
+ declare function getAgentHistoryMitra(options: GetAgentHistoryOptions): Promise<AgentMessage[]>;
797
+ declare function sendAgentPromptMitra(options: SendAgentPromptOptions): Promise<SendAgentPromptResponse>;
798
+ /**
799
+ * Fecha o WebSocket do Agent Chat. Útil em testes ou no logout.
800
+ */
801
+ declare function disconnectAgentChatMitra(): void;
802
+
693
803
  /**
694
804
  * Mitra Interactions SDK - Services
695
805
  */
@@ -845,4 +955,4 @@ declare function setProfileScreensMitra(options: SetProfileScreensOptions): Prom
845
955
  */
846
956
  declare function setProfileServerFunctionsMitra(options: SetProfileServerFunctionsOptions): Promise<SetProfilePermissionResponse>;
847
957
 
848
- export { 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 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 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, emailLoginMitra, emailResendCodeMitra, emailSignupMitra, emailVerifyCodeMitra, executeDataLoaderMitra, executeDbActionMitra, executePublicServerFunctionAsyncMitra, executePublicServerFunctionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, 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 };
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 };
package/dist/index.js CHANGED
@@ -55,7 +55,8 @@ function autoConfigureFromLogin(response, authUrl, projectId) {
55
55
  token: response.token,
56
56
  authUrl,
57
57
  projectId,
58
- ...response.integrationURL ? { integrationURL: response.integrationURL } : {}
58
+ ...response.integrationURL ? { integrationURL: response.integrationURL } : {},
59
+ ...response.agentWsUrl ? { agentWsUrl: response.agentWsUrl } : {}
59
60
  });
60
61
  }
61
62
  function buildAuthUrl(authUrl, method, projectId, opts) {
@@ -361,6 +362,270 @@ async function resetPasswordMitra(options) {
361
362
  });
362
363
  }
363
364
 
365
+ // src/agent-chat.ts
366
+ var ws = null;
367
+ var connectPromise = null;
368
+ var requestSeq = 0;
369
+ var pendingRequests = /* @__PURE__ */ new Map();
370
+ var activeStreams = /* @__PURE__ */ new Map();
371
+ function nextRequestId() {
372
+ return `req-${Date.now()}-${++requestSeq}`;
373
+ }
374
+ function getRawToken() {
375
+ const config = getConfig();
376
+ if (!config.token) {
377
+ throw new Error("Agent Chat: token n\xE3o configurado. Fa\xE7a login primeiro ou passe token em configureSdkMitra.");
378
+ }
379
+ return config.token.startsWith("Bearer ") ? config.token.slice(7) : config.token;
380
+ }
381
+ function getProjectId(override) {
382
+ const config = getConfig();
383
+ const pid = override != null ? override : config.projectId;
384
+ if (pid == null) {
385
+ throw new Error("Agent Chat: projectId \xE9 obrigat\xF3rio. Passe nas options ou configure via configureSdkMitra({ projectId }).");
386
+ }
387
+ return pid;
388
+ }
389
+ function getWsUrl() {
390
+ const config = getConfig();
391
+ if (!config.agentWsUrl) {
392
+ throw new Error("Agent Chat: agentWsUrl n\xE3o configurado. Passe em configureSdkMitra({ agentWsUrl }).");
393
+ }
394
+ return config.agentWsUrl;
395
+ }
396
+ function connect() {
397
+ if (ws && ws.readyState === WebSocket.OPEN) {
398
+ return Promise.resolve(ws);
399
+ }
400
+ if (connectPromise) return connectPromise;
401
+ const baseUrl = getWsUrl();
402
+ const token = getRawToken();
403
+ const separator = baseUrl.includes("?") ? "&" : "?";
404
+ const url = `${baseUrl}${separator}token=${encodeURIComponent(token)}`;
405
+ connectPromise = new Promise((resolve, reject) => {
406
+ const socket = new WebSocket(url);
407
+ let opened = false;
408
+ const timer = setTimeout(() => {
409
+ if (!opened) {
410
+ try {
411
+ socket.close();
412
+ } catch (e) {
413
+ }
414
+ connectPromise = null;
415
+ reject(new Error("Agent Chat: timeout ao conectar no WebSocket"));
416
+ }
417
+ }, 15e3);
418
+ socket.onopen = () => {
419
+ opened = true;
420
+ clearTimeout(timer);
421
+ ws = socket;
422
+ connectPromise = null;
423
+ resolve(socket);
424
+ };
425
+ socket.onerror = () => {
426
+ if (!opened) {
427
+ clearTimeout(timer);
428
+ connectPromise = null;
429
+ reject(new Error("Agent Chat: erro ao conectar no WebSocket"));
430
+ }
431
+ };
432
+ socket.onclose = () => {
433
+ if (ws === socket) ws = null;
434
+ for (const [id, pending] of pendingRequests) {
435
+ pending.reject(new Error("Agent Chat: conex\xE3o fechada"));
436
+ pendingRequests.delete(id);
437
+ }
438
+ for (const [key, stream] of activeStreams) {
439
+ stream.reject(new Error("Agent Chat: conex\xE3o fechada durante stream"));
440
+ activeStreams.delete(key);
441
+ }
442
+ };
443
+ socket.onmessage = (event) => handleMessage(event.data);
444
+ });
445
+ return connectPromise;
446
+ }
447
+ function handleMessage(raw) {
448
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
449
+ let msg;
450
+ try {
451
+ msg = typeof raw === "string" ? JSON.parse(raw) : raw;
452
+ } catch (e) {
453
+ return;
454
+ }
455
+ if (!(msg == null ? void 0 : msg.type)) return;
456
+ if (msg.type === "response" && msg.requestId) {
457
+ const pending = pendingRequests.get(msg.requestId);
458
+ if (!pending) return;
459
+ pendingRequests.delete(msg.requestId);
460
+ if (msg.ok) {
461
+ pending.resolve(msg.data);
462
+ } else {
463
+ pending.reject(new Error(msg.error || "Erro desconhecido"));
464
+ }
465
+ return;
466
+ }
467
+ const payload = (_a = msg.payload) != null ? _a : {};
468
+ switch (msg.type) {
469
+ case "task_update": {
470
+ if (payload.action !== "created") return;
471
+ const task = payload.task;
472
+ if (!task) return;
473
+ for (const [key, stream] of activeStreams) {
474
+ if (key.startsWith("__pending:") && !stream.taskId) {
475
+ stream.taskId = task.id;
476
+ activeStreams.delete(key);
477
+ activeStreams.set(task.id, stream);
478
+ (_b = stream.onTaskCreated) == null ? void 0 : _b.call(stream, { task });
479
+ break;
480
+ }
481
+ }
482
+ break;
483
+ }
484
+ case "stream_delta": {
485
+ const taskId = msg.taskId;
486
+ const stream = activeStreams.get(taskId);
487
+ if (!stream) return;
488
+ const kind = payload.subtype === "thinking" ? "tool" : "text";
489
+ const delta = String((_c = payload.delta) != null ? _c : "");
490
+ if (kind === "text") stream.content += delta;
491
+ (_d = stream.onDelta) == null ? void 0 : _d.call(stream, { taskId, delta, kind });
492
+ break;
493
+ }
494
+ case "stream_tool_activity": {
495
+ const taskId = msg.taskId;
496
+ const stream = activeStreams.get(taskId);
497
+ if (!stream) return;
498
+ (_g = stream.onTool) == null ? void 0 : _g.call(stream, {
499
+ taskId,
500
+ tool: String((_e = payload.tool) != null ? _e : ""),
501
+ input: payload.input,
502
+ content: payload.content,
503
+ timestamp: Number((_f = msg.timestamp) != null ? _f : Date.now())
504
+ });
505
+ break;
506
+ }
507
+ case "stream_end": {
508
+ const taskId = msg.taskId;
509
+ const stream = activeStreams.get(taskId);
510
+ if (!stream) return;
511
+ const final = { taskId, content: stream.content };
512
+ activeStreams.delete(taskId);
513
+ stream.resolve(final);
514
+ break;
515
+ }
516
+ case "error": {
517
+ const taskId = msg.taskId;
518
+ const error = String((_i = (_h = payload.error) != null ? _h : msg.error) != null ? _i : "Erro desconhecido");
519
+ if (taskId && activeStreams.has(taskId)) {
520
+ const stream = activeStreams.get(taskId);
521
+ activeStreams.delete(taskId);
522
+ (_j = stream.onError) == null ? void 0 : _j.call(stream, { taskId, error });
523
+ stream.reject(new Error(error));
524
+ } else {
525
+ for (const [key, stream] of activeStreams) {
526
+ if (key.startsWith("__pending:")) {
527
+ activeStreams.delete(key);
528
+ (_k = stream.onError) == null ? void 0 : _k.call(stream, { error });
529
+ stream.reject(new Error(error));
530
+ }
531
+ }
532
+ }
533
+ break;
534
+ }
535
+ }
536
+ }
537
+ async function sendRequest(type, payload) {
538
+ const socket = await connect();
539
+ const requestId = nextRequestId();
540
+ return new Promise((resolve, reject) => {
541
+ pendingRequests.set(requestId, {
542
+ resolve: (data) => resolve(data),
543
+ reject
544
+ });
545
+ try {
546
+ socket.send(JSON.stringify({ type, requestId, payload }));
547
+ } catch (err) {
548
+ pendingRequests.delete(requestId);
549
+ reject(err instanceof Error ? err : new Error(String(err)));
550
+ }
551
+ });
552
+ }
553
+ async function getAgentChatsMitra(options) {
554
+ const projectId = getProjectId(options == null ? void 0 : options.projectId);
555
+ return sendRequest("get_chats", { projectId });
556
+ }
557
+ async function getAgentHistoryMitra(options) {
558
+ if (!(options == null ? void 0 : options.taskId)) throw new Error("Agent Chat: taskId \xE9 obrigat\xF3rio.");
559
+ const payload = { taskId: options.taskId };
560
+ if (options.limit != null) payload.limit = options.limit;
561
+ return sendRequest("get_history", payload);
562
+ }
563
+ async function sendAgentPromptMitra(options) {
564
+ var _a;
565
+ if (!(options == null ? void 0 : options.prompt)) throw new Error("Agent Chat: prompt \xE9 obrigat\xF3rio.");
566
+ const projectId = getProjectId(options.projectId);
567
+ const socket = await connect();
568
+ const requestId = nextRequestId();
569
+ const isNewChat = !options.taskId;
570
+ const payload = {
571
+ prompt: options.prompt,
572
+ projectId,
573
+ agentType: (_a = options.agentType) != null ? _a : "claudecode"
574
+ };
575
+ if (options.taskId) payload.taskId = options.taskId;
576
+ if (options.name) payload.name = options.name;
577
+ return new Promise((resolve, reject) => {
578
+ var _a2;
579
+ const streamKey = isNewChat ? `__pending:${requestId}` : options.taskId;
580
+ const handlers = {
581
+ onDelta: options.onDelta,
582
+ onTool: options.onTool,
583
+ onTaskCreated: options.onTaskCreated,
584
+ onError: options.onError,
585
+ content: "",
586
+ resolve,
587
+ reject,
588
+ taskId: (_a2 = options.taskId) != null ? _a2 : null
589
+ };
590
+ activeStreams.set(streamKey, handlers);
591
+ if (options.signal) {
592
+ const onAbort = () => {
593
+ const tid = handlers.taskId;
594
+ if (tid) {
595
+ try {
596
+ socket.send(JSON.stringify({ type: "task_cancel", requestId: nextRequestId(), payload: { taskId: tid } }));
597
+ } catch (e) {
598
+ }
599
+ activeStreams.delete(tid);
600
+ } else {
601
+ activeStreams.delete(streamKey);
602
+ }
603
+ reject(new Error("Agent Chat: prompt cancelado"));
604
+ };
605
+ if (options.signal.aborted) {
606
+ onAbort();
607
+ return;
608
+ }
609
+ options.signal.addEventListener("abort", onAbort, { once: true });
610
+ }
611
+ try {
612
+ socket.send(JSON.stringify({ type: "send_prompt", requestId, payload }));
613
+ } catch (err) {
614
+ activeStreams.delete(streamKey);
615
+ reject(err instanceof Error ? err : new Error(String(err)));
616
+ }
617
+ });
618
+ }
619
+ function disconnectAgentChatMitra() {
620
+ if (ws) {
621
+ try {
622
+ ws.close();
623
+ } catch (e) {
624
+ }
625
+ ws = null;
626
+ }
627
+ }
628
+
364
629
  // src/instance.ts
365
630
  function formatToken(token) {
366
631
  return token.startsWith("Bearer ") ? token : `Bearer ${token}`;
@@ -708,6 +973,19 @@ function createMitraInstance(initialConfig) {
708
973
  var _a2;
709
974
  return resetPasswordMitra({ ...options, authUrl: (_a2 = options.authUrl) != null ? _a2 : _config.authUrl });
710
975
  },
976
+ // Agent Chat (embedded)
977
+ getAgentChats(options) {
978
+ return getAgentChatsMitra(options);
979
+ },
980
+ getAgentHistory(options) {
981
+ return getAgentHistoryMitra(options);
982
+ },
983
+ sendAgentPrompt(options) {
984
+ return sendAgentPromptMitra(options);
985
+ },
986
+ disconnectAgentChat() {
987
+ disconnectAgentChatMitra();
988
+ },
711
989
  // Chat
712
990
  openChat() {
713
991
  openChatMitra();
@@ -1211,6 +1489,7 @@ exports.createRecordMitra = createRecordMitra;
1211
1489
  exports.createRecordsBatchMitra = createRecordsBatchMitra;
1212
1490
  exports.deleteProfileMitra = deleteProfileMitra;
1213
1491
  exports.deleteRecordMitra = deleteRecordMitra;
1492
+ exports.disconnectAgentChatMitra = disconnectAgentChatMitra;
1214
1493
  exports.emailLoginMitra = emailLoginMitra;
1215
1494
  exports.emailResendCodeMitra = emailResendCodeMitra;
1216
1495
  exports.emailSignupMitra = emailSignupMitra;
@@ -1221,6 +1500,8 @@ exports.executePublicServerFunctionAsyncMitra = executePublicServerFunctionAsync
1221
1500
  exports.executePublicServerFunctionMitra = executePublicServerFunctionMitra;
1222
1501
  exports.executeServerFunctionAsyncMitra = executeServerFunctionAsyncMitra;
1223
1502
  exports.executeServerFunctionMitra = executeServerFunctionMitra;
1503
+ exports.getAgentChatsMitra = getAgentChatsMitra;
1504
+ exports.getAgentHistoryMitra = getAgentHistoryMitra;
1224
1505
  exports.getConfig = getConfig;
1225
1506
  exports.getProfileDetailsMitra = getProfileDetailsMitra;
1226
1507
  exports.getPublicServerFunctionExecutionMitra = getPublicServerFunctionExecutionMitra;
@@ -1240,6 +1521,7 @@ exports.refreshTokenSilently = refreshTokenSilently;
1240
1521
  exports.resetPasswordMitra = resetPasswordMitra;
1241
1522
  exports.resolveProjectId = resolveProjectId2;
1242
1523
  exports.runActionMitra = runActionMitra;
1524
+ exports.sendAgentPromptMitra = sendAgentPromptMitra;
1243
1525
  exports.sendPasswordResetCodeMitra = sendPasswordResetCodeMitra;
1244
1526
  exports.setFileStatusMitra = setFileStatusMitra;
1245
1527
  exports.setProfileActionsMitra = setProfileActionsMitra;