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

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
@@ -547,6 +547,13 @@ interface GetAgentTaskCreateOptions {
547
547
  projectId?: number;
548
548
  /** Tipo do agente. Default: 'claudecode'. */
549
549
  agentType?: AgentType;
550
+ /**
551
+ * Modelo a usar (value vindo de manageAgentCredentialMitra({action:'list_models'})).
552
+ * Ex: 'openai/gpt-5.5:medium', 'glm/glm-5.1', 'subscription:anthropic:claude-opus-4-7'.
553
+ * O backend deriva agentType/provider/model a partir dele. Vira o default da
554
+ * task; cada send() pode sobrescrever via SendOptions.modelId.
555
+ */
556
+ modelId?: string;
550
557
  /** Nome do chat (default: derivado do prompt). */
551
558
  name?: string;
552
559
  }
@@ -567,6 +574,12 @@ interface QueuedItem {
567
574
  }
568
575
  interface SendOptions {
569
576
  agentType?: AgentType;
577
+ /**
578
+ * Modelo a usar neste turno (value de list_models). Ex: 'openai/gpt-5.5:medium',
579
+ * 'glm/glm-5.1', 'subscription:anthropic:claude-opus-4-7'. Sobrescreve o modelId
580
+ * default da session. Se omitido, usa o default da session / agentType.
581
+ */
582
+ modelId?: string;
570
583
  }
571
584
  interface AgentDeltaEvent {
572
585
  delta: string;
@@ -627,6 +640,127 @@ interface AgentTaskSession {
627
640
  clearQueue(): void;
628
641
  on<E extends AgentTaskEventName>(event: E, handler: (payload: AgentTaskEventMap[E]) => void): () => void;
629
642
  }
643
+ /** Targets de subscription (OAuth/device flow). */
644
+ type AgentSubscriptionTarget = 'claude' | 'openai_oauth' | 'codex';
645
+ /** Targets de API key (8 providers suportados pelo backend). */
646
+ type AgentApiKeyTarget = 'anthropic' | 'openai' | 'gemini' | 'kimi' | 'minimax' | 'glm' | 'qwen' | 'openrouter';
647
+ /** Union — qualquer credencial. */
648
+ type CredentialTarget = AgentSubscriptionTarget | AgentApiKeyTarget;
649
+ /**
650
+ * Verbos aceitos por `manageAgentCredentialMitra`.
651
+ *
652
+ * Baixo nível (RPC direto contra o backend `credentials`):
653
+ * status | remove | list | validate | save
654
+ * oauth_start | oauth_exchange | device_start | device_poll | device_cancel
655
+ *
656
+ * Alto nível (orquestrado no browser, NÃO é um type WS — encadeia as actions
657
+ * de baixo nível + abre popup + espera autorização):
658
+ * connect
659
+ */
660
+ type CredentialAction = 'connect' | 'status' | 'remove' | 'list' | 'list_models' | 'validate' | 'save' | 'oauth_start' | 'oauth_exchange' | 'device_start' | 'device_poll' | 'device_cancel';
661
+ /** Um modelo selecionável (retornado por action='list_models'). */
662
+ interface AgentModelOption {
663
+ /** Passe direto em send({ modelId }) ou getAgentTaskMitra({ create, modelId }). */
664
+ modelId: string;
665
+ /** Label exibível. */
666
+ name: string;
667
+ }
668
+ /** Grupo de modelos por (tipo × provedor) — só grupos com credencial. */
669
+ interface AgentModelGroup {
670
+ id: string;
671
+ name: string;
672
+ kind: 'subscription' | 'api_key';
673
+ models: AgentModelOption[];
674
+ }
675
+ /** Retorno de manageAgentCredentialMitra({ action: 'list_models' }). */
676
+ interface ListAgentModelsResult {
677
+ providers: AgentModelGroup[];
678
+ }
679
+ /**
680
+ * Opções de baixo nível (RPC direto) de `manageAgentCredentialMitra`. Campos
681
+ * extras (key, code, codeVerifier, redirectUri, pollId, accessToken,
682
+ * refreshToken, expiresAt) são empacotados em `data` antes de enviar ao backend.
683
+ *
684
+ * NÃO use com action='connect' — para isso use ConnectAgentCredentialOptions.
685
+ */
686
+ interface ManageAgentCredentialOptions {
687
+ action: Exclude<CredentialAction, 'connect'>;
688
+ /** Obrigatório exceto para action='list'. */
689
+ target?: CredentialTarget;
690
+ /** Para `save` / `validate` de API key. */
691
+ key?: string;
692
+ /** Para `oauth_exchange`. */
693
+ code?: string;
694
+ /** Para `oauth_exchange`. */
695
+ state?: string;
696
+ /** Para `oauth_exchange`. */
697
+ codeVerifier?: string;
698
+ /** Para `oauth_start` (openai_oauth) e `oauth_exchange` (openai_oauth). */
699
+ redirectUri?: string;
700
+ /** Para `device_poll` / `device_cancel`. */
701
+ pollId?: string;
702
+ /** Para `save` (codex). */
703
+ accessToken?: string;
704
+ /** Para `save` (codex). */
705
+ refreshToken?: string;
706
+ /** Para `save` (codex). */
707
+ expiresAt?: number;
708
+ }
709
+ /** Tipo "ampliado" — o backend retorna shapes diferentes por (action, target). */
710
+ type ManageAgentCredentialResult = unknown;
711
+ interface AgentSubscriptionAccount {
712
+ email: string;
713
+ orgName: string;
714
+ }
715
+ /**
716
+ * Opções de alto nível de `manageAgentCredentialMitra` quando action='connect'.
717
+ * Orquestra o fluxo OAuth/device ponta-a-ponta no browser (abre popup, espera
718
+ * autorização, troca por tokens server-side).
719
+ */
720
+ interface ConnectAgentCredentialOptions {
721
+ action: 'connect';
722
+ target: AgentSubscriptionTarget;
723
+ /**
724
+ * Callback que retorna o código que o usuário copiou da página da Anthropic
725
+ * após autorizar. **Obrigatório** para target='claude'.
726
+ */
727
+ onCodeNeeded?: (info: {
728
+ authUrl: string;
729
+ state: string;
730
+ }) => Promise<string> | string;
731
+ /**
732
+ * URL no domínio do app publicado que captura o `?code=` da OAuth e faz
733
+ * `window.opener.postMessage({ mitraOpenAICode: code }, '*')`.
734
+ * **Obrigatório** para target='openai_oauth'.
735
+ */
736
+ redirectUri?: string;
737
+ /** Timeout esperando o postMessage (default 5min). */
738
+ messageTimeoutMs?: number;
739
+ /**
740
+ * Callback opcional que recebe o `userCode` e `verificationUrl` assim que
741
+ * o device flow inicia (use pra exibir na UI além do popup automático).
742
+ */
743
+ onDeviceCode?: (info: {
744
+ userCode: string | null;
745
+ verificationUrl: string | null;
746
+ }) => void;
747
+ /** Intervalo de poll do device flow (default 2000ms). */
748
+ pollIntervalMs?: number;
749
+ /** Timeout total do device flow (default 15min). */
750
+ deviceTimeoutMs?: number;
751
+ /** Nome da window do popup (default depende do target). */
752
+ windowName?: string;
753
+ /** `features` string passada para `window.open`. */
754
+ windowFeatures?: string;
755
+ }
756
+ interface ConnectAgentSubscriptionResult {
757
+ target: AgentSubscriptionTarget;
758
+ success: boolean;
759
+ /** Presente em claude / openai_oauth (epoch ms). */
760
+ expiresAt?: number;
761
+ /** Presente apenas em claude. */
762
+ account?: AgentSubscriptionAccount | null;
763
+ }
630
764
 
631
765
  /**
632
766
  * Mitra Interactions SDK - Instance
@@ -676,7 +810,7 @@ interface MitraInstance {
676
810
  resetPassword(options: ResetPasswordOptions): Promise<Record<string, unknown>>;
677
811
  getAgentChats(options?: GetAgentChatsOptions): Promise<AgentChat[]>;
678
812
  getAgentTask(options: GetAgentTaskOptions): AgentTaskSession;
679
- disconnectAgentChat(): void;
813
+ manageAgentCredential(options: ManageAgentCredentialOptions | ConnectAgentCredentialOptions): Promise<unknown>;
680
814
  openChat(): void;
681
815
  closeChat(): void;
682
816
  }
@@ -832,11 +966,61 @@ declare function getAgentChatsMitra(options?: GetAgentChatsOptions): Promise<Age
832
966
  * mesma taskId for aberta duas vezes, retorna a MESMA instância (cache).
833
967
  */
834
968
  declare function getAgentTaskMitra(options: GetAgentTaskOptions): AgentTaskSession;
969
+
970
+ /**
971
+ * Mitra Interactions SDK — Agent Credentials
972
+ *
973
+ * Função ÚNICA `manageAgentCredentialMitra` sobre /sdk-ws para todas as
974
+ * operações de credencial do agente:
975
+ * - API keys (8 providers: anthropic, openai, gemini, kimi, minimax, glm, qwen, openrouter)
976
+ * - Subscriptions OAuth (Claude / OpenAI / Codex device flow)
977
+ *
978
+ * Actions de baixo nível (RPC direto contra o backend):
979
+ * status | remove | list | validate | save
980
+ * oauth_start | oauth_exchange | device_start | device_poll | device_cancel
981
+ *
982
+ * Action de alto nível (orquestra o fluxo ponta-a-ponta no browser):
983
+ * connect — abre popup, espera código/postMessage/poll, troca por tokens.
984
+ *
985
+ * SEGURANÇA: o token de subscription NUNCA volta cru pro cliente. É salvo
986
+ * server-side (Firestore) e injetado no sandbox E2B direto de lá. O retorno
987
+ * de `connect`/`oauth_exchange` traz só { connected, expiresAt, account }.
988
+ */
989
+
990
+ /**
991
+ * Conecta uma subscription ponta-a-ponta (abre popup, espera autorização,
992
+ * troca por tokens). Retorno tipado: { target, success, expiresAt?, account? }.
993
+ *
994
+ * @example
995
+ * // Claude — caller mostra modal pedindo o paste do código
996
+ * await manageAgentCredentialMitra({
997
+ * action: 'connect', target: 'claude',
998
+ * onCodeNeeded: async () => prompt('Cole o código:') ?? ''
999
+ * });
1000
+ *
1001
+ * @example
1002
+ * // OpenAI — callback page no domínio do app faz postMessage
1003
+ * await manageAgentCredentialMitra({
1004
+ * action: 'connect', target: 'openai_oauth',
1005
+ * redirectUri: window.location.origin + '/auth/openai-callback'
1006
+ * });
1007
+ *
1008
+ * @example
1009
+ * // Codex — device flow automático (abre verificação, polling)
1010
+ * await manageAgentCredentialMitra({ action: 'connect', target: 'codex' });
1011
+ */
1012
+ declare function manageAgentCredentialMitra(options: ConnectAgentCredentialOptions): Promise<ConnectAgentSubscriptionResult>;
835
1013
  /**
836
- * Fecha o WebSocket do Agent Chat. Sessions ativas devem chamar close()
837
- * antes — esta função é destinada a teardown global (logout, testes).
1014
+ * RPC direto contra o backend. Retorno depende de (action, target) veja docs.
1015
+ *
1016
+ * @example
1017
+ * await manageAgentCredentialMitra({ action: 'list' });
1018
+ * await manageAgentCredentialMitra({ action: 'status', target: 'anthropic' });
1019
+ * await manageAgentCredentialMitra({ action: 'validate', target: 'openai', key: 'sk-...' });
1020
+ * await manageAgentCredentialMitra({ action: 'save', target: 'glm', key: '...' });
1021
+ * await manageAgentCredentialMitra({ action: 'remove', target: 'claude' });
838
1022
  */
839
- declare function disconnectAgentChatMitra(): void;
1023
+ declare function manageAgentCredentialMitra<R = ManageAgentCredentialResult>(options: ManageAgentCredentialOptions): Promise<R>;
840
1024
 
841
1025
  /**
842
1026
  * Mitra Interactions SDK - Services
@@ -993,4 +1177,4 @@ declare function setProfileScreensMitra(options: SetProfileScreensOptions): Prom
993
1177
  */
994
1178
  declare function setProfileServerFunctionsMitra(options: SetProfileServerFunctionsOptions): Promise<SetProfilePermissionResponse>;
995
1179
 
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 };
1180
+ export { type AgentApiKeyTarget, type AgentChat, type AgentDeltaEvent, type AgentErrorEvent, type AgentMessage, type AgentModelGroup, type AgentModelOption, 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 ListAgentModelsResult, 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
@@ -547,6 +547,13 @@ interface GetAgentTaskCreateOptions {
547
547
  projectId?: number;
548
548
  /** Tipo do agente. Default: 'claudecode'. */
549
549
  agentType?: AgentType;
550
+ /**
551
+ * Modelo a usar (value vindo de manageAgentCredentialMitra({action:'list_models'})).
552
+ * Ex: 'openai/gpt-5.5:medium', 'glm/glm-5.1', 'subscription:anthropic:claude-opus-4-7'.
553
+ * O backend deriva agentType/provider/model a partir dele. Vira o default da
554
+ * task; cada send() pode sobrescrever via SendOptions.modelId.
555
+ */
556
+ modelId?: string;
550
557
  /** Nome do chat (default: derivado do prompt). */
551
558
  name?: string;
552
559
  }
@@ -567,6 +574,12 @@ interface QueuedItem {
567
574
  }
568
575
  interface SendOptions {
569
576
  agentType?: AgentType;
577
+ /**
578
+ * Modelo a usar neste turno (value de list_models). Ex: 'openai/gpt-5.5:medium',
579
+ * 'glm/glm-5.1', 'subscription:anthropic:claude-opus-4-7'. Sobrescreve o modelId
580
+ * default da session. Se omitido, usa o default da session / agentType.
581
+ */
582
+ modelId?: string;
570
583
  }
571
584
  interface AgentDeltaEvent {
572
585
  delta: string;
@@ -627,6 +640,127 @@ interface AgentTaskSession {
627
640
  clearQueue(): void;
628
641
  on<E extends AgentTaskEventName>(event: E, handler: (payload: AgentTaskEventMap[E]) => void): () => void;
629
642
  }
643
+ /** Targets de subscription (OAuth/device flow). */
644
+ type AgentSubscriptionTarget = 'claude' | 'openai_oauth' | 'codex';
645
+ /** Targets de API key (8 providers suportados pelo backend). */
646
+ type AgentApiKeyTarget = 'anthropic' | 'openai' | 'gemini' | 'kimi' | 'minimax' | 'glm' | 'qwen' | 'openrouter';
647
+ /** Union — qualquer credencial. */
648
+ type CredentialTarget = AgentSubscriptionTarget | AgentApiKeyTarget;
649
+ /**
650
+ * Verbos aceitos por `manageAgentCredentialMitra`.
651
+ *
652
+ * Baixo nível (RPC direto contra o backend `credentials`):
653
+ * status | remove | list | validate | save
654
+ * oauth_start | oauth_exchange | device_start | device_poll | device_cancel
655
+ *
656
+ * Alto nível (orquestrado no browser, NÃO é um type WS — encadeia as actions
657
+ * de baixo nível + abre popup + espera autorização):
658
+ * connect
659
+ */
660
+ type CredentialAction = 'connect' | 'status' | 'remove' | 'list' | 'list_models' | 'validate' | 'save' | 'oauth_start' | 'oauth_exchange' | 'device_start' | 'device_poll' | 'device_cancel';
661
+ /** Um modelo selecionável (retornado por action='list_models'). */
662
+ interface AgentModelOption {
663
+ /** Passe direto em send({ modelId }) ou getAgentTaskMitra({ create, modelId }). */
664
+ modelId: string;
665
+ /** Label exibível. */
666
+ name: string;
667
+ }
668
+ /** Grupo de modelos por (tipo × provedor) — só grupos com credencial. */
669
+ interface AgentModelGroup {
670
+ id: string;
671
+ name: string;
672
+ kind: 'subscription' | 'api_key';
673
+ models: AgentModelOption[];
674
+ }
675
+ /** Retorno de manageAgentCredentialMitra({ action: 'list_models' }). */
676
+ interface ListAgentModelsResult {
677
+ providers: AgentModelGroup[];
678
+ }
679
+ /**
680
+ * Opções de baixo nível (RPC direto) de `manageAgentCredentialMitra`. Campos
681
+ * extras (key, code, codeVerifier, redirectUri, pollId, accessToken,
682
+ * refreshToken, expiresAt) são empacotados em `data` antes de enviar ao backend.
683
+ *
684
+ * NÃO use com action='connect' — para isso use ConnectAgentCredentialOptions.
685
+ */
686
+ interface ManageAgentCredentialOptions {
687
+ action: Exclude<CredentialAction, 'connect'>;
688
+ /** Obrigatório exceto para action='list'. */
689
+ target?: CredentialTarget;
690
+ /** Para `save` / `validate` de API key. */
691
+ key?: string;
692
+ /** Para `oauth_exchange`. */
693
+ code?: string;
694
+ /** Para `oauth_exchange`. */
695
+ state?: string;
696
+ /** Para `oauth_exchange`. */
697
+ codeVerifier?: string;
698
+ /** Para `oauth_start` (openai_oauth) e `oauth_exchange` (openai_oauth). */
699
+ redirectUri?: string;
700
+ /** Para `device_poll` / `device_cancel`. */
701
+ pollId?: string;
702
+ /** Para `save` (codex). */
703
+ accessToken?: string;
704
+ /** Para `save` (codex). */
705
+ refreshToken?: string;
706
+ /** Para `save` (codex). */
707
+ expiresAt?: number;
708
+ }
709
+ /** Tipo "ampliado" — o backend retorna shapes diferentes por (action, target). */
710
+ type ManageAgentCredentialResult = unknown;
711
+ interface AgentSubscriptionAccount {
712
+ email: string;
713
+ orgName: string;
714
+ }
715
+ /**
716
+ * Opções de alto nível de `manageAgentCredentialMitra` quando action='connect'.
717
+ * Orquestra o fluxo OAuth/device ponta-a-ponta no browser (abre popup, espera
718
+ * autorização, troca por tokens server-side).
719
+ */
720
+ interface ConnectAgentCredentialOptions {
721
+ action: 'connect';
722
+ target: AgentSubscriptionTarget;
723
+ /**
724
+ * Callback que retorna o código que o usuário copiou da página da Anthropic
725
+ * após autorizar. **Obrigatório** para target='claude'.
726
+ */
727
+ onCodeNeeded?: (info: {
728
+ authUrl: string;
729
+ state: string;
730
+ }) => Promise<string> | string;
731
+ /**
732
+ * URL no domínio do app publicado que captura o `?code=` da OAuth e faz
733
+ * `window.opener.postMessage({ mitraOpenAICode: code }, '*')`.
734
+ * **Obrigatório** para target='openai_oauth'.
735
+ */
736
+ redirectUri?: string;
737
+ /** Timeout esperando o postMessage (default 5min). */
738
+ messageTimeoutMs?: number;
739
+ /**
740
+ * Callback opcional que recebe o `userCode` e `verificationUrl` assim que
741
+ * o device flow inicia (use pra exibir na UI além do popup automático).
742
+ */
743
+ onDeviceCode?: (info: {
744
+ userCode: string | null;
745
+ verificationUrl: string | null;
746
+ }) => void;
747
+ /** Intervalo de poll do device flow (default 2000ms). */
748
+ pollIntervalMs?: number;
749
+ /** Timeout total do device flow (default 15min). */
750
+ deviceTimeoutMs?: number;
751
+ /** Nome da window do popup (default depende do target). */
752
+ windowName?: string;
753
+ /** `features` string passada para `window.open`. */
754
+ windowFeatures?: string;
755
+ }
756
+ interface ConnectAgentSubscriptionResult {
757
+ target: AgentSubscriptionTarget;
758
+ success: boolean;
759
+ /** Presente em claude / openai_oauth (epoch ms). */
760
+ expiresAt?: number;
761
+ /** Presente apenas em claude. */
762
+ account?: AgentSubscriptionAccount | null;
763
+ }
630
764
 
631
765
  /**
632
766
  * Mitra Interactions SDK - Instance
@@ -676,7 +810,7 @@ interface MitraInstance {
676
810
  resetPassword(options: ResetPasswordOptions): Promise<Record<string, unknown>>;
677
811
  getAgentChats(options?: GetAgentChatsOptions): Promise<AgentChat[]>;
678
812
  getAgentTask(options: GetAgentTaskOptions): AgentTaskSession;
679
- disconnectAgentChat(): void;
813
+ manageAgentCredential(options: ManageAgentCredentialOptions | ConnectAgentCredentialOptions): Promise<unknown>;
680
814
  openChat(): void;
681
815
  closeChat(): void;
682
816
  }
@@ -832,11 +966,61 @@ declare function getAgentChatsMitra(options?: GetAgentChatsOptions): Promise<Age
832
966
  * mesma taskId for aberta duas vezes, retorna a MESMA instância (cache).
833
967
  */
834
968
  declare function getAgentTaskMitra(options: GetAgentTaskOptions): AgentTaskSession;
969
+
970
+ /**
971
+ * Mitra Interactions SDK — Agent Credentials
972
+ *
973
+ * Função ÚNICA `manageAgentCredentialMitra` sobre /sdk-ws para todas as
974
+ * operações de credencial do agente:
975
+ * - API keys (8 providers: anthropic, openai, gemini, kimi, minimax, glm, qwen, openrouter)
976
+ * - Subscriptions OAuth (Claude / OpenAI / Codex device flow)
977
+ *
978
+ * Actions de baixo nível (RPC direto contra o backend):
979
+ * status | remove | list | validate | save
980
+ * oauth_start | oauth_exchange | device_start | device_poll | device_cancel
981
+ *
982
+ * Action de alto nível (orquestra o fluxo ponta-a-ponta no browser):
983
+ * connect — abre popup, espera código/postMessage/poll, troca por tokens.
984
+ *
985
+ * SEGURANÇA: o token de subscription NUNCA volta cru pro cliente. É salvo
986
+ * server-side (Firestore) e injetado no sandbox E2B direto de lá. O retorno
987
+ * de `connect`/`oauth_exchange` traz só { connected, expiresAt, account }.
988
+ */
989
+
990
+ /**
991
+ * Conecta uma subscription ponta-a-ponta (abre popup, espera autorização,
992
+ * troca por tokens). Retorno tipado: { target, success, expiresAt?, account? }.
993
+ *
994
+ * @example
995
+ * // Claude — caller mostra modal pedindo o paste do código
996
+ * await manageAgentCredentialMitra({
997
+ * action: 'connect', target: 'claude',
998
+ * onCodeNeeded: async () => prompt('Cole o código:') ?? ''
999
+ * });
1000
+ *
1001
+ * @example
1002
+ * // OpenAI — callback page no domínio do app faz postMessage
1003
+ * await manageAgentCredentialMitra({
1004
+ * action: 'connect', target: 'openai_oauth',
1005
+ * redirectUri: window.location.origin + '/auth/openai-callback'
1006
+ * });
1007
+ *
1008
+ * @example
1009
+ * // Codex — device flow automático (abre verificação, polling)
1010
+ * await manageAgentCredentialMitra({ action: 'connect', target: 'codex' });
1011
+ */
1012
+ declare function manageAgentCredentialMitra(options: ConnectAgentCredentialOptions): Promise<ConnectAgentSubscriptionResult>;
835
1013
  /**
836
- * Fecha o WebSocket do Agent Chat. Sessions ativas devem chamar close()
837
- * antes — esta função é destinada a teardown global (logout, testes).
1014
+ * RPC direto contra o backend. Retorno depende de (action, target) veja docs.
1015
+ *
1016
+ * @example
1017
+ * await manageAgentCredentialMitra({ action: 'list' });
1018
+ * await manageAgentCredentialMitra({ action: 'status', target: 'anthropic' });
1019
+ * await manageAgentCredentialMitra({ action: 'validate', target: 'openai', key: 'sk-...' });
1020
+ * await manageAgentCredentialMitra({ action: 'save', target: 'glm', key: '...' });
1021
+ * await manageAgentCredentialMitra({ action: 'remove', target: 'claude' });
838
1022
  */
839
- declare function disconnectAgentChatMitra(): void;
1023
+ declare function manageAgentCredentialMitra<R = ManageAgentCredentialResult>(options: ManageAgentCredentialOptions): Promise<R>;
840
1024
 
841
1025
  /**
842
1026
  * Mitra Interactions SDK - Services
@@ -993,4 +1177,4 @@ declare function setProfileScreensMitra(options: SetProfileScreensOptions): Prom
993
1177
  */
994
1178
  declare function setProfileServerFunctionsMitra(options: SetProfileServerFunctionsOptions): Promise<SetProfilePermissionResponse>;
995
1179
 
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 };
1180
+ export { type AgentApiKeyTarget, type AgentChat, type AgentDeltaEvent, type AgentErrorEvent, type AgentMessage, type AgentModelGroup, type AgentModelOption, 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 ListAgentModelsResult, 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 };