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

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
@@ -627,6 +627,109 @@ interface AgentTaskSession {
627
627
  clearQueue(): void;
628
628
  on<E extends AgentTaskEventName>(event: E, handler: (payload: AgentTaskEventMap[E]) => void): () => void;
629
629
  }
630
+ /** Targets de subscription (OAuth/device flow). */
631
+ type AgentSubscriptionTarget = 'claude' | 'openai_oauth' | 'codex';
632
+ /** Targets de API key (8 providers suportados pelo backend). */
633
+ type AgentApiKeyTarget = 'anthropic' | 'openai' | 'gemini' | 'kimi' | 'minimax' | 'glm' | 'qwen' | 'openrouter';
634
+ /** Union — qualquer credencial. */
635
+ type CredentialTarget = AgentSubscriptionTarget | AgentApiKeyTarget;
636
+ /**
637
+ * Verbos aceitos por `manageAgentCredentialMitra`.
638
+ *
639
+ * Baixo nível (RPC direto contra o backend `credentials`):
640
+ * status | remove | list | validate | save
641
+ * oauth_start | oauth_exchange | device_start | device_poll | device_cancel
642
+ *
643
+ * Alto nível (orquestrado no browser, NÃO é um type WS — encadeia as actions
644
+ * de baixo nível + abre popup + espera autorização):
645
+ * connect
646
+ */
647
+ type CredentialAction = 'connect' | 'status' | 'remove' | 'list' | 'validate' | 'save' | 'oauth_start' | 'oauth_exchange' | 'device_start' | 'device_poll' | 'device_cancel';
648
+ /**
649
+ * Opções de baixo nível (RPC direto) de `manageAgentCredentialMitra`. Campos
650
+ * extras (key, code, codeVerifier, redirectUri, pollId, accessToken,
651
+ * refreshToken, expiresAt) são empacotados em `data` antes de enviar ao backend.
652
+ *
653
+ * NÃO use com action='connect' — para isso use ConnectAgentCredentialOptions.
654
+ */
655
+ interface ManageAgentCredentialOptions {
656
+ action: Exclude<CredentialAction, 'connect'>;
657
+ /** Obrigatório exceto para action='list'. */
658
+ target?: CredentialTarget;
659
+ /** Para `save` / `validate` de API key. */
660
+ key?: string;
661
+ /** Para `oauth_exchange`. */
662
+ code?: string;
663
+ /** Para `oauth_exchange`. */
664
+ state?: string;
665
+ /** Para `oauth_exchange`. */
666
+ codeVerifier?: string;
667
+ /** Para `oauth_start` (openai_oauth) e `oauth_exchange` (openai_oauth). */
668
+ redirectUri?: string;
669
+ /** Para `device_poll` / `device_cancel`. */
670
+ pollId?: string;
671
+ /** Para `save` (codex). */
672
+ accessToken?: string;
673
+ /** Para `save` (codex). */
674
+ refreshToken?: string;
675
+ /** Para `save` (codex). */
676
+ expiresAt?: number;
677
+ }
678
+ /** Tipo "ampliado" — o backend retorna shapes diferentes por (action, target). */
679
+ type ManageAgentCredentialResult = unknown;
680
+ interface AgentSubscriptionAccount {
681
+ email: string;
682
+ orgName: string;
683
+ }
684
+ /**
685
+ * Opções de alto nível de `manageAgentCredentialMitra` quando action='connect'.
686
+ * Orquestra o fluxo OAuth/device ponta-a-ponta no browser (abre popup, espera
687
+ * autorização, troca por tokens server-side).
688
+ */
689
+ interface ConnectAgentCredentialOptions {
690
+ action: 'connect';
691
+ target: AgentSubscriptionTarget;
692
+ /**
693
+ * Callback que retorna o código que o usuário copiou da página da Anthropic
694
+ * após autorizar. **Obrigatório** para target='claude'.
695
+ */
696
+ onCodeNeeded?: (info: {
697
+ authUrl: string;
698
+ state: string;
699
+ }) => Promise<string> | string;
700
+ /**
701
+ * URL no domínio do app publicado que captura o `?code=` da OAuth e faz
702
+ * `window.opener.postMessage({ mitraOpenAICode: code }, '*')`.
703
+ * **Obrigatório** para target='openai_oauth'.
704
+ */
705
+ redirectUri?: string;
706
+ /** Timeout esperando o postMessage (default 5min). */
707
+ messageTimeoutMs?: number;
708
+ /**
709
+ * Callback opcional que recebe o `userCode` e `verificationUrl` assim que
710
+ * o device flow inicia (use pra exibir na UI além do popup automático).
711
+ */
712
+ onDeviceCode?: (info: {
713
+ userCode: string | null;
714
+ verificationUrl: string | null;
715
+ }) => void;
716
+ /** Intervalo de poll do device flow (default 2000ms). */
717
+ pollIntervalMs?: number;
718
+ /** Timeout total do device flow (default 15min). */
719
+ deviceTimeoutMs?: number;
720
+ /** Nome da window do popup (default depende do target). */
721
+ windowName?: string;
722
+ /** `features` string passada para `window.open`. */
723
+ windowFeatures?: string;
724
+ }
725
+ interface ConnectAgentSubscriptionResult {
726
+ target: AgentSubscriptionTarget;
727
+ success: boolean;
728
+ /** Presente em claude / openai_oauth (epoch ms). */
729
+ expiresAt?: number;
730
+ /** Presente apenas em claude. */
731
+ account?: AgentSubscriptionAccount | null;
732
+ }
630
733
 
631
734
  /**
632
735
  * Mitra Interactions SDK - Instance
@@ -676,7 +779,7 @@ interface MitraInstance {
676
779
  resetPassword(options: ResetPasswordOptions): Promise<Record<string, unknown>>;
677
780
  getAgentChats(options?: GetAgentChatsOptions): Promise<AgentChat[]>;
678
781
  getAgentTask(options: GetAgentTaskOptions): AgentTaskSession;
679
- disconnectAgentChat(): void;
782
+ manageAgentCredential(options: ManageAgentCredentialOptions | ConnectAgentCredentialOptions): Promise<unknown>;
680
783
  openChat(): void;
681
784
  closeChat(): void;
682
785
  }
@@ -832,11 +935,61 @@ declare function getAgentChatsMitra(options?: GetAgentChatsOptions): Promise<Age
832
935
  * mesma taskId for aberta duas vezes, retorna a MESMA instância (cache).
833
936
  */
834
937
  declare function getAgentTaskMitra(options: GetAgentTaskOptions): AgentTaskSession;
938
+
835
939
  /**
836
- * Fecha o WebSocket do Agent Chat. Sessions ativas devem chamar close()
837
- * antes — esta função é destinada a teardown global (logout, testes).
940
+ * Mitra Interactions SDK Agent Credentials
941
+ *
942
+ * Função ÚNICA `manageAgentCredentialMitra` sobre /sdk-ws para todas as
943
+ * operações de credencial do agente:
944
+ * - API keys (8 providers: anthropic, openai, gemini, kimi, minimax, glm, qwen, openrouter)
945
+ * - Subscriptions OAuth (Claude / OpenAI / Codex device flow)
946
+ *
947
+ * Actions de baixo nível (RPC direto contra o backend):
948
+ * status | remove | list | validate | save
949
+ * oauth_start | oauth_exchange | device_start | device_poll | device_cancel
950
+ *
951
+ * Action de alto nível (orquestra o fluxo ponta-a-ponta no browser):
952
+ * connect — abre popup, espera código/postMessage/poll, troca por tokens.
953
+ *
954
+ * SEGURANÇA: o token de subscription NUNCA volta cru pro cliente. É salvo
955
+ * server-side (Firestore) e injetado no sandbox E2B direto de lá. O retorno
956
+ * de `connect`/`oauth_exchange` traz só { connected, expiresAt, account }.
957
+ */
958
+
959
+ /**
960
+ * Conecta uma subscription ponta-a-ponta (abre popup, espera autorização,
961
+ * troca por tokens). Retorno tipado: { target, success, expiresAt?, account? }.
962
+ *
963
+ * @example
964
+ * // Claude — caller mostra modal pedindo o paste do código
965
+ * await manageAgentCredentialMitra({
966
+ * action: 'connect', target: 'claude',
967
+ * onCodeNeeded: async () => prompt('Cole o código:') ?? ''
968
+ * });
969
+ *
970
+ * @example
971
+ * // OpenAI — callback page no domínio do app faz postMessage
972
+ * await manageAgentCredentialMitra({
973
+ * action: 'connect', target: 'openai_oauth',
974
+ * redirectUri: window.location.origin + '/auth/openai-callback'
975
+ * });
976
+ *
977
+ * @example
978
+ * // Codex — device flow automático (abre verificação, polling)
979
+ * await manageAgentCredentialMitra({ action: 'connect', target: 'codex' });
980
+ */
981
+ declare function manageAgentCredentialMitra(options: ConnectAgentCredentialOptions): Promise<ConnectAgentSubscriptionResult>;
982
+ /**
983
+ * RPC direto contra o backend. Retorno depende de (action, target) — veja docs.
984
+ *
985
+ * @example
986
+ * await manageAgentCredentialMitra({ action: 'list' });
987
+ * await manageAgentCredentialMitra({ action: 'status', target: 'anthropic' });
988
+ * await manageAgentCredentialMitra({ action: 'validate', target: 'openai', key: 'sk-...' });
989
+ * await manageAgentCredentialMitra({ action: 'save', target: 'glm', key: '...' });
990
+ * await manageAgentCredentialMitra({ action: 'remove', target: 'claude' });
838
991
  */
839
- declare function disconnectAgentChatMitra(): void;
992
+ declare function manageAgentCredentialMitra<R = ManageAgentCredentialResult>(options: ManageAgentCredentialOptions): Promise<R>;
840
993
 
841
994
  /**
842
995
  * Mitra Interactions SDK - Services
@@ -993,4 +1146,4 @@ declare function setProfileScreensMitra(options: SetProfileScreensOptions): Prom
993
1146
  */
994
1147
  declare function setProfileServerFunctionsMitra(options: SetProfileServerFunctionsOptions): Promise<SetProfilePermissionResponse>;
995
1148
 
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 };
1149
+ export { type AgentApiKeyTarget, type AgentChat, type AgentDeltaEvent, type AgentErrorEvent, type AgentMessage, 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 CallIntegrationOptions, type CallIntegrationResponse, type ConnectAgentCredentialOptions, type ConnectAgentSubscriptionResult, type CreateProfileOptions, type CreateProfileResponse, type CreateRecordOptions, type CreateRecordsBatchOptions, type CredentialAction, type CredentialTarget, 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 ManageAgentCredentialOptions, type ManageAgentCredentialResult, 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, 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, manageAgentCredentialMitra, 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
@@ -627,6 +627,109 @@ interface AgentTaskSession {
627
627
  clearQueue(): void;
628
628
  on<E extends AgentTaskEventName>(event: E, handler: (payload: AgentTaskEventMap[E]) => void): () => void;
629
629
  }
630
+ /** Targets de subscription (OAuth/device flow). */
631
+ type AgentSubscriptionTarget = 'claude' | 'openai_oauth' | 'codex';
632
+ /** Targets de API key (8 providers suportados pelo backend). */
633
+ type AgentApiKeyTarget = 'anthropic' | 'openai' | 'gemini' | 'kimi' | 'minimax' | 'glm' | 'qwen' | 'openrouter';
634
+ /** Union — qualquer credencial. */
635
+ type CredentialTarget = AgentSubscriptionTarget | AgentApiKeyTarget;
636
+ /**
637
+ * Verbos aceitos por `manageAgentCredentialMitra`.
638
+ *
639
+ * Baixo nível (RPC direto contra o backend `credentials`):
640
+ * status | remove | list | validate | save
641
+ * oauth_start | oauth_exchange | device_start | device_poll | device_cancel
642
+ *
643
+ * Alto nível (orquestrado no browser, NÃO é um type WS — encadeia as actions
644
+ * de baixo nível + abre popup + espera autorização):
645
+ * connect
646
+ */
647
+ type CredentialAction = 'connect' | 'status' | 'remove' | 'list' | 'validate' | 'save' | 'oauth_start' | 'oauth_exchange' | 'device_start' | 'device_poll' | 'device_cancel';
648
+ /**
649
+ * Opções de baixo nível (RPC direto) de `manageAgentCredentialMitra`. Campos
650
+ * extras (key, code, codeVerifier, redirectUri, pollId, accessToken,
651
+ * refreshToken, expiresAt) são empacotados em `data` antes de enviar ao backend.
652
+ *
653
+ * NÃO use com action='connect' — para isso use ConnectAgentCredentialOptions.
654
+ */
655
+ interface ManageAgentCredentialOptions {
656
+ action: Exclude<CredentialAction, 'connect'>;
657
+ /** Obrigatório exceto para action='list'. */
658
+ target?: CredentialTarget;
659
+ /** Para `save` / `validate` de API key. */
660
+ key?: string;
661
+ /** Para `oauth_exchange`. */
662
+ code?: string;
663
+ /** Para `oauth_exchange`. */
664
+ state?: string;
665
+ /** Para `oauth_exchange`. */
666
+ codeVerifier?: string;
667
+ /** Para `oauth_start` (openai_oauth) e `oauth_exchange` (openai_oauth). */
668
+ redirectUri?: string;
669
+ /** Para `device_poll` / `device_cancel`. */
670
+ pollId?: string;
671
+ /** Para `save` (codex). */
672
+ accessToken?: string;
673
+ /** Para `save` (codex). */
674
+ refreshToken?: string;
675
+ /** Para `save` (codex). */
676
+ expiresAt?: number;
677
+ }
678
+ /** Tipo "ampliado" — o backend retorna shapes diferentes por (action, target). */
679
+ type ManageAgentCredentialResult = unknown;
680
+ interface AgentSubscriptionAccount {
681
+ email: string;
682
+ orgName: string;
683
+ }
684
+ /**
685
+ * Opções de alto nível de `manageAgentCredentialMitra` quando action='connect'.
686
+ * Orquestra o fluxo OAuth/device ponta-a-ponta no browser (abre popup, espera
687
+ * autorização, troca por tokens server-side).
688
+ */
689
+ interface ConnectAgentCredentialOptions {
690
+ action: 'connect';
691
+ target: AgentSubscriptionTarget;
692
+ /**
693
+ * Callback que retorna o código que o usuário copiou da página da Anthropic
694
+ * após autorizar. **Obrigatório** para target='claude'.
695
+ */
696
+ onCodeNeeded?: (info: {
697
+ authUrl: string;
698
+ state: string;
699
+ }) => Promise<string> | string;
700
+ /**
701
+ * URL no domínio do app publicado que captura o `?code=` da OAuth e faz
702
+ * `window.opener.postMessage({ mitraOpenAICode: code }, '*')`.
703
+ * **Obrigatório** para target='openai_oauth'.
704
+ */
705
+ redirectUri?: string;
706
+ /** Timeout esperando o postMessage (default 5min). */
707
+ messageTimeoutMs?: number;
708
+ /**
709
+ * Callback opcional que recebe o `userCode` e `verificationUrl` assim que
710
+ * o device flow inicia (use pra exibir na UI além do popup automático).
711
+ */
712
+ onDeviceCode?: (info: {
713
+ userCode: string | null;
714
+ verificationUrl: string | null;
715
+ }) => void;
716
+ /** Intervalo de poll do device flow (default 2000ms). */
717
+ pollIntervalMs?: number;
718
+ /** Timeout total do device flow (default 15min). */
719
+ deviceTimeoutMs?: number;
720
+ /** Nome da window do popup (default depende do target). */
721
+ windowName?: string;
722
+ /** `features` string passada para `window.open`. */
723
+ windowFeatures?: string;
724
+ }
725
+ interface ConnectAgentSubscriptionResult {
726
+ target: AgentSubscriptionTarget;
727
+ success: boolean;
728
+ /** Presente em claude / openai_oauth (epoch ms). */
729
+ expiresAt?: number;
730
+ /** Presente apenas em claude. */
731
+ account?: AgentSubscriptionAccount | null;
732
+ }
630
733
 
631
734
  /**
632
735
  * Mitra Interactions SDK - Instance
@@ -676,7 +779,7 @@ interface MitraInstance {
676
779
  resetPassword(options: ResetPasswordOptions): Promise<Record<string, unknown>>;
677
780
  getAgentChats(options?: GetAgentChatsOptions): Promise<AgentChat[]>;
678
781
  getAgentTask(options: GetAgentTaskOptions): AgentTaskSession;
679
- disconnectAgentChat(): void;
782
+ manageAgentCredential(options: ManageAgentCredentialOptions | ConnectAgentCredentialOptions): Promise<unknown>;
680
783
  openChat(): void;
681
784
  closeChat(): void;
682
785
  }
@@ -832,11 +935,61 @@ declare function getAgentChatsMitra(options?: GetAgentChatsOptions): Promise<Age
832
935
  * mesma taskId for aberta duas vezes, retorna a MESMA instância (cache).
833
936
  */
834
937
  declare function getAgentTaskMitra(options: GetAgentTaskOptions): AgentTaskSession;
938
+
835
939
  /**
836
- * Fecha o WebSocket do Agent Chat. Sessions ativas devem chamar close()
837
- * antes — esta função é destinada a teardown global (logout, testes).
940
+ * Mitra Interactions SDK Agent Credentials
941
+ *
942
+ * Função ÚNICA `manageAgentCredentialMitra` sobre /sdk-ws para todas as
943
+ * operações de credencial do agente:
944
+ * - API keys (8 providers: anthropic, openai, gemini, kimi, minimax, glm, qwen, openrouter)
945
+ * - Subscriptions OAuth (Claude / OpenAI / Codex device flow)
946
+ *
947
+ * Actions de baixo nível (RPC direto contra o backend):
948
+ * status | remove | list | validate | save
949
+ * oauth_start | oauth_exchange | device_start | device_poll | device_cancel
950
+ *
951
+ * Action de alto nível (orquestra o fluxo ponta-a-ponta no browser):
952
+ * connect — abre popup, espera código/postMessage/poll, troca por tokens.
953
+ *
954
+ * SEGURANÇA: o token de subscription NUNCA volta cru pro cliente. É salvo
955
+ * server-side (Firestore) e injetado no sandbox E2B direto de lá. O retorno
956
+ * de `connect`/`oauth_exchange` traz só { connected, expiresAt, account }.
957
+ */
958
+
959
+ /**
960
+ * Conecta uma subscription ponta-a-ponta (abre popup, espera autorização,
961
+ * troca por tokens). Retorno tipado: { target, success, expiresAt?, account? }.
962
+ *
963
+ * @example
964
+ * // Claude — caller mostra modal pedindo o paste do código
965
+ * await manageAgentCredentialMitra({
966
+ * action: 'connect', target: 'claude',
967
+ * onCodeNeeded: async () => prompt('Cole o código:') ?? ''
968
+ * });
969
+ *
970
+ * @example
971
+ * // OpenAI — callback page no domínio do app faz postMessage
972
+ * await manageAgentCredentialMitra({
973
+ * action: 'connect', target: 'openai_oauth',
974
+ * redirectUri: window.location.origin + '/auth/openai-callback'
975
+ * });
976
+ *
977
+ * @example
978
+ * // Codex — device flow automático (abre verificação, polling)
979
+ * await manageAgentCredentialMitra({ action: 'connect', target: 'codex' });
980
+ */
981
+ declare function manageAgentCredentialMitra(options: ConnectAgentCredentialOptions): Promise<ConnectAgentSubscriptionResult>;
982
+ /**
983
+ * RPC direto contra o backend. Retorno depende de (action, target) — veja docs.
984
+ *
985
+ * @example
986
+ * await manageAgentCredentialMitra({ action: 'list' });
987
+ * await manageAgentCredentialMitra({ action: 'status', target: 'anthropic' });
988
+ * await manageAgentCredentialMitra({ action: 'validate', target: 'openai', key: 'sk-...' });
989
+ * await manageAgentCredentialMitra({ action: 'save', target: 'glm', key: '...' });
990
+ * await manageAgentCredentialMitra({ action: 'remove', target: 'claude' });
838
991
  */
839
- declare function disconnectAgentChatMitra(): void;
992
+ declare function manageAgentCredentialMitra<R = ManageAgentCredentialResult>(options: ManageAgentCredentialOptions): Promise<R>;
840
993
 
841
994
  /**
842
995
  * Mitra Interactions SDK - Services
@@ -993,4 +1146,4 @@ declare function setProfileScreensMitra(options: SetProfileScreensOptions): Prom
993
1146
  */
994
1147
  declare function setProfileServerFunctionsMitra(options: SetProfileServerFunctionsOptions): Promise<SetProfilePermissionResponse>;
995
1148
 
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 };
1149
+ export { type AgentApiKeyTarget, type AgentChat, type AgentDeltaEvent, type AgentErrorEvent, type AgentMessage, 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 CallIntegrationOptions, type CallIntegrationResponse, type ConnectAgentCredentialOptions, type ConnectAgentSubscriptionResult, type CreateProfileOptions, type CreateProfileResponse, type CreateRecordOptions, type CreateRecordsBatchOptions, type CredentialAction, type CredentialTarget, 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 ManageAgentCredentialOptions, type ManageAgentCredentialResult, 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, 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, manageAgentCredentialMitra, openChatMitra, patchRecordMitra, refreshTokenSilently, resetPasswordMitra, resolveProjectId, runActionMitra, sendPasswordResetCodeMitra, setFileStatusMitra, setProfileActionsMitra, setProfileDmlTablesMitra, setProfileScreensMitra, setProfileSelectTablesMitra, setProfileServerFunctionsMitra, setProfileUsersMitra, setVariableMitra, stopServerFunctionExecutionMitra, updateProfileMitra, updateRecordMitra, uploadFileLoadableMitra, uploadFilePublicMitra, validatePasswordResetCodeMitra };
package/dist/index.js CHANGED
@@ -912,6 +912,9 @@ var transport = {
912
912
  if (taskId) sessionsByTaskId.delete(taskId);
913
913
  }
914
914
  };
915
+ function getTransport() {
916
+ return transport;
917
+ }
915
918
  async function getAgentChatsMitra(options) {
916
919
  const projectId = resolveProjectId2(options == null ? void 0 : options.projectId);
917
920
  return transport.request("get_chats", { projectId });
@@ -938,18 +941,151 @@ function getAgentTaskMitra(options) {
938
941
  }
939
942
  throw new Error("getAgentTaskMitra: passe { create: true } ou { taskId }.");
940
943
  }
941
- function disconnectAgentChatMitra() {
942
- if (ws) {
943
- try {
944
- ws.close();
945
- } catch (e) {
944
+
945
+ // src/agent-credentials.ts
946
+ var SUB_TARGETS = ["claude", "openai_oauth", "codex"];
947
+ function isSubscriptionTarget(t) {
948
+ return !!t && SUB_TARGETS.includes(t);
949
+ }
950
+ function manageAgentCredentialMitra(options) {
951
+ if (options.action === "connect") {
952
+ return connectSubscription(options);
953
+ }
954
+ return rpc(options);
955
+ }
956
+ function rpc(options) {
957
+ const transport2 = getTransport();
958
+ const { action, target, ...rest } = options;
959
+ const data = {};
960
+ for (const [k, v] of Object.entries(rest)) {
961
+ if (v !== void 0) data[k] = v;
962
+ }
963
+ return transport2.request("credentials", { action, target, data });
964
+ }
965
+ function connectSubscription(options) {
966
+ const { target } = options;
967
+ if (!isSubscriptionTarget(target)) {
968
+ throw new Error(`manageAgentCredentialMitra(connect): target inv\xE1lido (${target}). Use 'claude' | 'openai_oauth' | 'codex'.`);
969
+ }
970
+ if (target === "claude") return connectClaude(options);
971
+ if (target === "openai_oauth") return connectOpenAIOAuth(options);
972
+ return connectCodexDevice(options);
973
+ }
974
+ async function connectClaude(options) {
975
+ var _a, _b;
976
+ if (!options.onCodeNeeded) {
977
+ throw new Error("manageAgentCredentialMitra(connect, claude): onCodeNeeded \xE9 obrigat\xF3rio.");
978
+ }
979
+ const start = await rpc({
980
+ action: "oauth_start",
981
+ target: "claude"
982
+ });
983
+ openPopup(start.authUrl, (_a = options.windowName) != null ? _a : "mitra-claude-auth", options.windowFeatures);
984
+ const code = await options.onCodeNeeded({ authUrl: start.authUrl, state: start.state });
985
+ if (!code) throw new Error("manageAgentCredentialMitra(connect, claude): c\xF3digo vazio.");
986
+ const exchange = await rpc({
987
+ action: "oauth_exchange",
988
+ target: "claude",
989
+ code,
990
+ state: start.state,
991
+ codeVerifier: start.codeVerifier
992
+ });
993
+ return {
994
+ target: "claude",
995
+ success: exchange.success === true,
996
+ expiresAt: exchange.expiresAt,
997
+ account: (_b = exchange.account) != null ? _b : null
998
+ };
999
+ }
1000
+ async function connectOpenAIOAuth(options) {
1001
+ var _a, _b;
1002
+ if (!options.redirectUri) {
1003
+ throw new Error("manageAgentCredentialMitra(connect, openai_oauth): redirectUri \xE9 obrigat\xF3rio.");
1004
+ }
1005
+ const start = await rpc({
1006
+ action: "oauth_start",
1007
+ target: "openai_oauth",
1008
+ redirectUri: options.redirectUri
1009
+ });
1010
+ const popup = openPopup(start.authUrl, (_a = options.windowName) != null ? _a : "mitra-openai-auth", options.windowFeatures);
1011
+ const code = await waitForPostMessageCode(popup, (_b = options.messageTimeoutMs) != null ? _b : 5 * 6e4);
1012
+ const exchange = await rpc({
1013
+ action: "oauth_exchange",
1014
+ target: "openai_oauth",
1015
+ code,
1016
+ state: start.state,
1017
+ codeVerifier: start.codeVerifier,
1018
+ redirectUri: options.redirectUri
1019
+ });
1020
+ return {
1021
+ target: "openai_oauth",
1022
+ success: exchange.success === true,
1023
+ expiresAt: exchange.expiresAt
1024
+ };
1025
+ }
1026
+ async function connectCodexDevice(options) {
1027
+ var _a, _b, _c, _d;
1028
+ const start = await rpc({ action: "device_start", target: "codex" });
1029
+ if (start.verificationUrl) {
1030
+ openPopup(start.verificationUrl, (_a = options.windowName) != null ? _a : "mitra-codex-auth", options.windowFeatures);
1031
+ }
1032
+ (_b = options.onDeviceCode) == null ? void 0 : _b.call(options, { userCode: start.userCode, verificationUrl: start.verificationUrl });
1033
+ const pollInterval = (_c = options.pollIntervalMs) != null ? _c : 2e3;
1034
+ const deadline = Date.now() + ((_d = options.deviceTimeoutMs) != null ? _d : 15 * 6e4);
1035
+ while (Date.now() < deadline) {
1036
+ const result = await rpc({ action: "device_poll", target: "codex", pollId: start.pollId });
1037
+ if (result.status === "completed") {
1038
+ return { target: "codex", success: true };
1039
+ }
1040
+ if (result.status === "failed" || result.status === "expired" || result.status === "not_found") {
1041
+ throw new Error(`manageAgentCredentialMitra(connect, codex): ${result.status}${result.error ? ` \u2014 ${result.error}` : ""}`);
946
1042
  }
947
- ws = null;
1043
+ await sleep(pollInterval);
948
1044
  }
949
- sessionsByTaskId.clear();
950
- handlersByTaskId.clear();
951
- pendingHandlers.clear();
952
- streamingTaskIds.clear();
1045
+ await rpc({ action: "device_cancel", target: "codex", pollId: start.pollId }).catch(() => {
1046
+ });
1047
+ throw new Error("manageAgentCredentialMitra(connect, codex): timeout.");
1048
+ }
1049
+ function openPopup(url, name, features) {
1050
+ if (typeof window === "undefined") return null;
1051
+ const defaults = "width=600,height=720,menubar=no,toolbar=no,location=no,status=no";
1052
+ return window.open(url, name, features != null ? features : defaults);
1053
+ }
1054
+ function waitForPostMessageCode(popup, timeoutMs) {
1055
+ return new Promise((resolve, reject) => {
1056
+ let done = false;
1057
+ const handler = (event) => {
1058
+ var _a;
1059
+ const data = event.data;
1060
+ if (!data || typeof data !== "object") return;
1061
+ const code = (_a = data.mitraOpenAICode) != null ? _a : (data == null ? void 0 : data.type) === "mitra-openai-code" ? data.code : void 0;
1062
+ if (typeof code === "string" && code.length > 0) {
1063
+ finish();
1064
+ resolve(code);
1065
+ }
1066
+ };
1067
+ const timer = setTimeout(() => {
1068
+ finish();
1069
+ reject(new Error("manageAgentCredentialMitra(connect): timeout esperando c\xF3digo do popup."));
1070
+ }, timeoutMs);
1071
+ const closedPoll = setInterval(() => {
1072
+ if (popup && popup.closed) {
1073
+ finish();
1074
+ reject(new Error("manageAgentCredentialMitra(connect): popup fechado antes de receber c\xF3digo."));
1075
+ }
1076
+ }, 500);
1077
+ function finish() {
1078
+ if (done) return;
1079
+ done = true;
1080
+ window.removeEventListener("message", handler);
1081
+ clearTimeout(timer);
1082
+ clearInterval(closedPoll);
1083
+ }
1084
+ window.addEventListener("message", handler);
1085
+ });
1086
+ }
1087
+ function sleep(ms) {
1088
+ return new Promise((r) => setTimeout(r, ms));
953
1089
  }
954
1090
 
955
1091
  // src/instance.ts
@@ -1306,8 +1442,8 @@ function createMitraInstance(initialConfig) {
1306
1442
  getAgentTask(options) {
1307
1443
  return getAgentTaskMitra(options);
1308
1444
  },
1309
- disconnectAgentChat() {
1310
- disconnectAgentChatMitra();
1445
+ manageAgentCredential(options) {
1446
+ return manageAgentCredentialMitra(options);
1311
1447
  },
1312
1448
  // Chat
1313
1449
  openChat() {
@@ -1824,7 +1960,6 @@ exports.createRecordMitra = createRecordMitra;
1824
1960
  exports.createRecordsBatchMitra = createRecordsBatchMitra;
1825
1961
  exports.deleteProfileMitra = deleteProfileMitra;
1826
1962
  exports.deleteRecordMitra = deleteRecordMitra;
1827
- exports.disconnectAgentChatMitra = disconnectAgentChatMitra;
1828
1963
  exports.emailLoginMitra = emailLoginMitra;
1829
1964
  exports.emailResendCodeMitra = emailResendCodeMitra;
1830
1965
  exports.emailSignupMitra = emailSignupMitra;
@@ -1850,6 +1985,7 @@ exports.loginMitra = loginMitra;
1850
1985
  exports.loginWithEmailMitra = loginWithEmailMitra;
1851
1986
  exports.loginWithGoogleMitra = loginWithGoogleMitra;
1852
1987
  exports.loginWithMicrosoftMitra = loginWithMicrosoftMitra;
1988
+ exports.manageAgentCredentialMitra = manageAgentCredentialMitra;
1853
1989
  exports.openChatMitra = openChatMitra;
1854
1990
  exports.patchRecordMitra = patchRecordMitra;
1855
1991
  exports.refreshTokenSilently = refreshTokenSilently;