Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

50.1 KB
Raw Blame
import { ENABLE_BEARER_TOKEN_AUTH } from '@core/constant/featureFlags';
import { SERVER_HOSTS } from '@core/constant/servers';
import { fetchWithToken } from '@core/util/fetchWithToken';
import { registerClient } from '@core/util/mockClient';
import type { ObjectLike } from '@core/util/result';
import {
  type ErrorResponseHandler,
  type SafeFetchInit,
  safeFetch,
  statusError,
} from '@core/util/safeFetch';
import { Telemetry } from '@macro-inc/observability';

import { makePersisted } from '@solid-primitives/storage';
import { ok } from 'neverthrow';
import { createSignal } from 'solid-js';
import type {
  AiCreditPurchaseResult,
  AiPlanCatalog,
  AiUsageSnapshot,
  PaidPlan,
  SubscriptionStatus,
  TeamMemberPlan,
} from './ai-billing-types';
import { fetchWithAuth as _fetchWithAuth } from './fetch';
import type {
  CheckoutSessionV2Response,
  CursorApiKeyStatus,
  CursorModelsResponse,
  EmailConnectionProviders,
  EnrichGithubPullRequestsProxyRequest,
  EnrichGithubPullRequestsResponse,
  GithubLinkStatusResponse,
  GithubPullRequestMergeabilityRequest,
  GithubPullRequestMergeabilityResponse,
  GmailLinkStatusResponse,
  InitGithubLinkResponse,
  InitGmailLinkResponse,
  InitOutlookLinkResponse,
  MergeGithubPullRequestRequest,
  MergeGithubPullRequestResponse,
  PatchUserTutorialRequest,
  SendMobileWelcomeEmailResponse,
  SetGithubPullRequestDraftRequest,
  SetGithubPullRequestDraftResponse,
  SetGithubPullRequestStateRequest,
  SetGithubPullRequestStateResponse,
  TrialEligibility,
  UserQuota,
} from './generated/schemas';
import type { AgentApiKey } from './generated/schemas/agentApiKey';
import type { AgentSetupResponse } from './generated/schemas/agentSetupResponse';
import type { AppleLoginRequest } from './generated/schemas/appleLoginRequest';
import type { CreatedTeamInviteLinkResponse } from './generated/schemas/createdTeamInviteLinkResponse';
import type { CreateGtmInviteLinkRequest } from './generated/schemas/createGtmInviteLinkRequest';
import type { CreateTeamRequest } from './generated/schemas/createTeamRequest';
import type { CurrentSystemStatus } from './generated/schemas/currentSystemStatus';
import type { EmptyResponse } from './generated/schemas/emptyResponse';
import type { GenericSuccessResponse } from './generated/schemas/genericSuccessResponse';
import type { GetLegacyUserPermissionsResponse } from './generated/schemas/getLegacyUserPermissionsResponse';
import type { GetProfilePicturesRequestBody } from './generated/schemas/getProfilePicturesRequestBody';
import type { GetUserInfo } from './generated/schemas/getUserInfo';
import type { GtmInviteLink } from './generated/schemas/gtmInviteLink';
import type { GtmInviteLinkList } from './generated/schemas/gtmInviteLinkList';
import type { GtmInviteOffer } from './generated/schemas/gtmInviteOffer';
import type { GtmInviteOfferStatus } from './generated/schemas/gtmInviteOfferStatus';
import type { InviteToTeamRequest } from './generated/schemas/inviteToTeamRequest';
import type { JoinTeamByInviteLinkResponse } from './generated/schemas/joinTeamByInviteLinkResponse';
import type { MacroApiTokenResponse } from './generated/schemas/macroApiTokenResponse';
import type { PasswordRequest } from './generated/schemas/passwordRequest';
import type { PatchTeamRequest } from './generated/schemas/patchTeamRequest';
import type { PatchUserGroupRequest } from './generated/schemas/patchUserGroupRequest';
import type { PatchUserOnboardingRequest } from './generated/schemas/patchUserOnboardingRequest';
import type { PostGetNamesRequestBody } from './generated/schemas/postGetNamesRequestBody';
import type { ProfilePictures } from './generated/schemas/profilePictures';
import type { PublicGtmInviteLink } from './generated/schemas/publicGtmInviteLink';
import type { PutProfilePictureParams } from './generated/schemas/putProfilePictureParams';
import type { PutUserNameQueryParams } from './generated/schemas/putUserNameQueryParams';
import type { SendDomainNoticeResponse } from './generated/schemas/sendDomainNoticeResponse';
import type { StatusUpdate } from './generated/schemas/statusUpdate';
import type { SystemStatus } from './generated/schemas/systemStatus';
import type { SystemStatusHistory } from './generated/schemas/systemStatusHistory';
import type { Team } from './generated/schemas/team';
import type { TeamInviteLinkResponse } from './generated/schemas/teamInviteLinkResponse';
import type { TeamInviteLinkTeam } from './generated/schemas/teamInviteLinkTeam';
import type { TeamInvitesResponse } from './generated/schemas/teamInvitesResponse';
import type { TeamWithMembers } from './generated/schemas/teamWithMembers';
import type { ToggleAutoJoinDomainResponse } from './generated/schemas/toggleAutoJoinDomainResponse';
import type { ToggleNonAdminInvitesResponse } from './generated/schemas/toggleNonAdminInvitesResponse';
import type { UserLanguage } from './generated/schemas/userLanguage';
import type { UserLinkResponse } from './generated/schemas/userLinkResponse';
import type { UserName } from './generated/schemas/userName';
import type { UserNames } from './generated/schemas/userNames';
import type { UserOrganizationResponse } from './generated/schemas/userOrganizationResponse';
import type { UserTokensResponse } from './generated/schemas/userTokensResponse';

const authHost = SERVER_HOSTS['auth-service'];

/**
 * Which permissions a Google consent screen asks for. `calendar` covers an
 * inbox that is already connected, so the screen lists calendar access alone.
 */
export type ConsentScopes = 'gmail' | 'gmail_and_calendar' | 'calendar';

const authApiFetch = <T extends ObjectLike>(
  input: string,
  init?: SafeFetchInit
) =>
  safeFetch<T>(`${authHost}${input}`, {
    ...init,
    credentials: 'include',
  });

const fetchWithAuth = ENABLE_BEARER_TOKEN_AUTH
  ? (_fetchWithAuth as typeof fetchWithToken)
  : fetchWithToken;

type Token = {
  accessToken: string;
  refreshToken: string;
  expiresAt: number;
};
const [accessTokenData, setAccessTokenData] = makePersisted(
  createSignal<Token | null>(null),
  {
    name: 'macroAccessToken',
  }
);

export function getExpiresAt(token: string) {
  try {
    const payload: unknown = JSON.parse(atob(token.split('.')[1]));
    if (
      typeof payload !== 'object' ||
      payload === null ||
      !('exp' in payload)
    ) {
      return 0;
    }

    const expValue = payload.exp;
    if (typeof expValue !== 'number' && typeof expValue !== 'string') {
      return 0;
    }

    const exp = Number(expValue) * 1000;
    return Number.isFinite(exp) ? exp : 0;
  } catch {
    return 0;
  }
}

// Promise to track ongoing refresh operations to prevent multiple concurrent refreshes
let ongoingRefresh: Promise<string | null> | null = null;
async function getAccessToken(): Promise<string | null> {
  const data = accessTokenData();
  if (!data) {
    return null;
  }

  const { accessToken, refreshToken, expiresAt } = data;
  if (expiresAt < Date.now()) {
    // If there's already an ongoing refresh, wait for it to complete
    if (ongoingRefresh) {
      return await ongoingRefresh;
    }

    // Start a new refresh operation
    ongoingRefresh = (async () => {
      try {
        const result = await authServiceClient.refreshToken({
          accessToken,
          refreshToken,
        });

        if (result.isOk()) {
          // After successful refresh, get the updated access token from storage
          setAccessTokenData({
            accessToken: result.value.access_token,
            refreshToken: result.value.refresh_token,
            expiresAt: getExpiresAt(result.value.access_token),
          });
          return result.value.access_token;
        } else {
          // Refresh failed
          return null;
        }
      } catch (error) {
        Telemetry.error('Error refreshing access token', {
          error: error instanceof Error ? error.message : String(error),
        });
        return null;
      } finally {
        // Clear the ongoing refresh promise so future calls can start a new refresh
        ongoingRefresh = null;
      }
    })();

    return await ongoingRefresh;
  }

  return accessToken;
}

export type GithubReauthenticationErrorCode = 'REAUTHENTICATION_REQUIRED';

/** The team owner's email domain is a generic provider (e.g. gmail.com),
 *  so auto-join cannot be enabled for it. */
export type ToggleAutoJoinDomainErrorCode = 'GENERIC_DOMAIN_NOT_ALLOWED';

/**
 * Surfaces the Cursor API key endpoints' own error message instead of a generic
 * one derived from the status code.
 *
 * These endpoints answer with a body that already says what went wrong and is
 * written to be safe to show a user — "value does not look like a Cursor API
 * key", "Cursor agents are only available to Macro staff". The default handler
 * throws that away and reports `HTTP error! status: 403`, which tells the user
 * nothing they can act on.
 */
const cursorApiKeyErrorResponseHandler: ErrorResponseHandler<'CURSOR_API_KEY_ERROR'> =
  async function handleCursorApiKeyErrorResponse(response) {
    // Falls back to the status when the body is not the shape we expect: a
    // failure to parse an error must not replace the error.
    const message = await response
      .json()
      .then((body: unknown) =>
        typeof body === 'object' && body !== null && 'message' in body
          ? String((body as { message: unknown }).message)
          : undefined
      )
      .catch(() => undefined);

    return {
      code: 'CURSOR_API_KEY_ERROR',
      message: message ?? `HTTP error! status: ${response.status}`,
    };
  };

const agentApiKeyErrorResponseHandler: ErrorResponseHandler<'AGENT_API_KEY_ERROR'> =
  async function handleAgentApiKeyErrorResponse(response) {
    const { message } = await cursorApiKeyErrorResponseHandler(response);
    return { code: 'AGENT_API_KEY_ERROR', message };
  };

/**
 * Errors a merge can end in beyond the shared GitHub ones: the user has no
 * GitHub account linked, or GitHub declined the merge and said why.
 */
export type GithubMergeErrorCode =
  | GithubReauthenticationErrorCode
  | 'NO_GITHUB_LINK'
  | 'MERGE_REJECTED';

/** The body the merge route answers with when the user has not linked GitHub. */
const NO_GITHUB_LINK_MESSAGE = 'no github link found';

/** The `message` of an error body, or nothing when the body is not that shape. */
async function readErrorMessage(
  response: Response
): Promise<string | undefined> {
  try {
    const body: unknown = await response.json();
    return typeof body === 'object' && body !== null && 'message' in body
      ? String((body as { message: unknown }).message)
      : undefined;
  } catch {
    return undefined;
  }
}

/**
 * Keeps GitHub's own words when it declines a change. GitHub names the
 * failing check, the missing review, or the missing permission; the status
 * alone ("409") tells the user nothing they can act on.
 */
function githubChangeErrorResponseHandler(copy: {
  noLink: string;
  rejected: string;
}): ErrorResponseHandler<GithubMergeErrorCode> {
  return async function handleGithubChangeErrorResponse(response) {
    if (response.status === 428) {
      return {
        code: 'REAUTHENTICATION_REQUIRED',
        message: 'GitHub reauthentication required',
      };
    }
    if (![403, 404, 409, 422].includes(response.status)) {
      return githubErrorResponseHandler(response);
    }
    const message = await readErrorMessage(response);
    if (response.status === 404 && message === NO_GITHUB_LINK_MESSAGE) {
      return { code: 'NO_GITHUB_LINK', message: copy.noLink };
    }
    return { code: 'MERGE_REJECTED', message: message ?? copy.rejected };
  };
}

const githubMergeErrorResponseHandler = githubChangeErrorResponseHandler({
  noLink: 'Connect GitHub in Settings to merge pull requests',
  rejected: 'GitHub declined to merge the pull request',
});

/** Shared by the draft and open/closed state routes, which fail the same ways. */
const githubUpdateErrorResponseHandler = githubChangeErrorResponseHandler({
  noLink: 'Connect GitHub in Settings to change pull requests',
  rejected: 'GitHub declined to change the pull request',
});

const githubErrorResponseHandler: ErrorResponseHandler<GithubReauthenticationErrorCode> =
  async function handleGithubErrorResponse(response) {
    switch (response.status) {
      case 428:
        return {
          code: 'REAUTHENTICATION_REQUIRED',
          message: 'GitHub reauthentication required',
        };
      case 401:
        return { code: 'UNAUTHORIZED', message: 'Unauthorized access' };
      case 403:
        return { code: 'FORBIDDEN', message: 'Forbidden' };
      case 404:
        return { code: 'NOT_FOUND', message: 'Resource not found' };
      case 409:
        return { code: 'CONFLICT', message: 'Resource conflict' };
      case 410:
        return { code: 'GONE', message: 'Resource deleted' };
      case 500:
        return { code: 'SERVER_ERROR', message: 'Internal server error' };
      // GitHub, Google, or the sign-in service is down or throttling. The
      // body names which and says to retry later, in words for the user.
      case 502:
      case 503:
        return {
          code: 'HTTP_ERROR',
          message:
            (await readErrorMessage(response)) ??
            `HTTP error! status: ${response.status}`,
        };
      default:
        return {
          code: 'HTTP_ERROR',
          message: `HTTP error! status: ${response.status}`,
        };
    }
  };

export const authServiceClient = {
  /**
   * Which providers this deployment can connect. Pass `originalUrl` to also
   * receive the Microsoft tenant-wide admin-consent URL that returns there.
   */
  async emailConnectionProviders(originalUrl?: string) {
    const params = new URLSearchParams();
    if (originalUrl) params.set('original_url', originalUrl);
    const query = params.size > 0 ? `?${params}` : '';
    return fetchWithAuth<EmailConnectionProviders>(
      `${authHost}/link/email/providers${query}`,
      { method: 'GET' }
    );
  },
  async logout() {
    setAccessTokenData(null);
    return (
      await authApiFetch<EmptyResponse>(`/logout`, { method: 'POST' })
    ).map((result) => result);
  },
  async getUserInfo() {
    return (
      await fetchWithAuth<Partial<GetUserInfo>>(`${authHost}/user/me`, {
        method: 'GET',
      })
    ).map((data) => ({
      authenticated: !!data.user_id,
      permissions: data.permissions || [],
      userId: data.user_id,
      organizationId: data.organization_id ?? undefined,
    }));
  },
  async sessionLogin(args: { session_code: string }) {
    // The session code stays valid server-side for 5 minutes and is
    // replayable, so retrying transient failures is safe.
    const result = await authApiFetch<UserTokensResponse>(
      `/session/login/${args.session_code}`,
      { retry: { maxTries: 3, delay: 'exponential' } }
    );
    if (result.isOk()) {
      setAccessTokenData({
        accessToken: result.value.access_token,
        refreshToken: result.value.refresh_token,
        expiresAt: getExpiresAt(result.value.access_token),
      });
    }
    return result;
  },
  async deleteUser() {
    const result = await fetchWithAuth<GenericSuccessResponse>(
      `${authHost}/user/me`,
      {
        method: 'DELETE',
      }
    );

    if (result.isOk()) {
      setAccessTokenData(null);
    }

    return result;
  },
  async appleLogin(args: AppleLoginRequest) {
    return authApiFetch<EmptyResponse>(`/login/apple`, {
      method: 'POST',
      body: JSON.stringify(args),
    });
  },
  async passwordLogin(args: PasswordRequest) {
    return authApiFetch<UserTokensResponse>(`/login/password`, {
      method: 'POST',
      body: JSON.stringify(args),
    });
  },
  async passwordlessCallback({ code, email }: { code: string; email: string }) {
    const result = await safeFetch<UserTokensResponse, 'RATE_LIMITED'>(
      `${authHost}/oauth/passwordless/${code}?email=${encodeURIComponent(email)}&disable_redirect=true`,
      { cache: 'no-store', credentials: 'include' },
      async (response) => {
        if (response.status === 401) {
          return { code: 'UNAUTHORIZED', message: await response.text() };
        }
        if (response.status === 429) {
          return { code: 'RATE_LIMITED', message: 'Rate limit exceeded' };
        }
        return statusError(response.status);
      }
    );
    if (result.isOk()) {
      setAccessTokenData({
        accessToken: result.value.access_token,
        refreshToken: result.value.refresh_token,
        expiresAt: getExpiresAt(result.value.access_token),
      });
    }
    return result;
  },
  async refreshToken(args: { accessToken: string; refreshToken: string }) {
    return authApiFetch<UserTokensResponse>('/jwt/refresh', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${args.accessToken}`,
        'x-macro-refresh-token': args.refreshToken,
      },
    });
  },
  async postProfilePictures(
    args: GetProfilePicturesRequestBody,
    init?: SafeFetchInit
  ) {
    return (
      await fetchWithAuth<ProfilePictures>(
        `${authHost}/user/profile_pictures`,
        {
          ...init,
          method: 'POST',
          body: JSON.stringify(args),
        }
      )
    ).map((result) => result);
  },
  async agentSetup() {
    return await fetchWithAuth<AgentSetupResponse>(
      `${authHost}/user/agent_setup`,
      { method: 'POST' }
    );
  },
  async putProfilePicture(args: PutProfilePictureParams) {
    return (
      await fetchWithAuth<EmptyResponse>(
        `${authHost}/user/profile_picture?url=${encodeURIComponent(args.url)}`,
        {
          method: 'PUT',
        }
      )
    ).map((result) => result);
  },
  async getUserName() {
    return (
      await fetchWithAuth<UserName>(`${authHost}/user/name`, {
        method: 'GET',
      })
    ).map((result) => result);
  },
  async putUserName(args: PutUserNameQueryParams) {
    const queryParams: string[] = [];

    if (args.first_name !== undefined && args.first_name !== null) {
      queryParams.push(`first_name=${encodeURIComponent(args.first_name)}`);
    }

    if (args.last_name !== undefined && args.last_name !== null) {
      queryParams.push(`last_name=${encodeURIComponent(args.last_name)}`);
    }
    const queryString = queryParams.join('&');
    return (
      await fetchWithAuth<UserName>(`${authHost}/user/name?${queryString}`, {
        method: 'PUT',
      })
    ).map((result) => result);
  },
  async getUserLanguage() {
    return (
      await fetchWithAuth<UserLanguage>(`${authHost}/user/language`, {
        method: 'GET',
      })
    ).map((result) => result);
  },
  async putUserLanguage(args: UserLanguage) {
    return (
      await fetchWithAuth<EmptyResponse>(`${authHost}/user/language`, {
        method: 'PUT',
        body: JSON.stringify(args),
      })
    ).map((result) => result);
  },
  async getUserNames(args: PostGetNamesRequestBody) {
    return (
      await fetchWithAuth<UserNames>(`${authHost}/user/get_names`, {
        method: 'POST',
        body: JSON.stringify(args),
      })
    ).map((result) => result);
  },
  async getUserNamesWithEmail(args: PostGetNamesRequestBody) {
    return (
      await fetchWithAuth<UserNames>(`${authHost}/user/get_names_with_email`, {
        method: 'POST',
        body: JSON.stringify(args),
      })
    ).map((result) => result);
  },
  async checkLinkExists(args: { idp_name?: string; idp_id?: string }) {
    const queryParams: string[] = [];
    if (args.idp_name !== undefined && args.idp_name !== null) {
      queryParams.push(`idp_name=${args.idp_name}`);
    }

    if (args.idp_id !== undefined && args.idp_id !== null) {
      queryParams.push(`idp_id=${args.idp_id}`);
    }
    const queryString = queryParams.join('&');
    return (
      await fetchWithAuth<UserLinkResponse>(
        `${authHost}/user/link_exists?${queryString}`,
        {
          method: 'GET',
        }
      )
    ).map((result) => result);
  },
  async macroApiToken() {
    const accessToken = await getAccessToken();
    if (!accessToken) {
      Telemetry.warn('No access token found, fetching with cookies');
      return authApiFetch<MacroApiTokenResponse>('/jwt/macro_api_token');
    }

    return await authApiFetch<MacroApiTokenResponse>('/jwt/macro_api_token', {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });
  },
  async userQuota() {
    const result = await (
      await fetchWithAuth<UserQuota>(`${authHost}/user/quota`, {
        method: 'GET',
      })
    ).map((result) => result);

    return result;
  },

  async enrichGithubPullRequests(args: EnrichGithubPullRequestsProxyRequest) {
    return (
      await fetchWithAuth<
        EnrichGithubPullRequestsResponse,
        GithubReauthenticationErrorCode
      >(`${authHost}/github_pull_requests/enrich`, {
        method: 'POST',
        body: JSON.stringify(args),
        errorResponseHandler: githubErrorResponseHandler,
      })
    ).map((result) => result);
  },
  async mergeGithubPullRequest(args: MergeGithubPullRequestRequest) {
    return (
      await fetchWithAuth<MergeGithubPullRequestResponse, GithubMergeErrorCode>(
        `${authHost}/github_pull_requests/merge`,
        {
          method: 'POST',
          body: JSON.stringify(args),
          errorResponseHandler: githubMergeErrorResponseHandler,
        }
      )
    ).map((result) => result);
  },
  async setGithubPullRequestDraft(args: SetGithubPullRequestDraftRequest) {
    return (
      await fetchWithAuth<
        SetGithubPullRequestDraftResponse,
        GithubMergeErrorCode
      >(`${authHost}/github_pull_requests/draft`, {
        method: 'POST',
        body: JSON.stringify(args),
        errorResponseHandler: githubUpdateErrorResponseHandler,
      })
    ).map((result) => result);
  },
  async setGithubPullRequestState(args: SetGithubPullRequestStateRequest) {
    return (
      await fetchWithAuth<
        SetGithubPullRequestStateResponse,
        GithubMergeErrorCode
      >(`${authHost}/github_pull_requests/state`, {
        method: 'POST',
        body: JSON.stringify(args),
        errorResponseHandler: githubUpdateErrorResponseHandler,
      })
    ).map((result) => result);
  },
  async getGithubPullRequestMergeability(
    args: GithubPullRequestMergeabilityRequest
  ) {
    return (
      await fetchWithAuth<
        GithubPullRequestMergeabilityResponse,
        GithubReauthenticationErrorCode
      >(`${authHost}/github_pull_requests/mergeability`, {
        method: 'POST',
        body: JSON.stringify(args),
        errorResponseHandler: githubErrorResponseHandler,
      })
    ).map((result) => result);
  },
  async patchUserTutorial(args: PatchUserTutorialRequest) {
    return (
      await fetchWithAuth<EmptyResponse>(`${authHost}/user/tutorial`, {
        method: 'PATCH',
        body: JSON.stringify(args),
      })
    ).map((result) => result);
  },

  async patchAiConsent(args: { aiDataConsent: boolean }) {
    return (
      await fetchWithAuth<EmptyResponse>(`${authHost}/user/ai_consent`, {
        method: 'PATCH',
        body: JSON.stringify(args),
      })
    ).map((result) => result);
  },

  // HTTP methods (migrated from RPC)
  async getLegacyUserPermissions() {
    const result = await fetchWithAuth<GetLegacyUserPermissionsResponse>(
      `${authHost}/user/legacy_user_permissions`,
      { method: 'GET' }
    );

    return result.map((data) => ({
      id: data.userId,
      permissions: data.permissions,
      email: data.email,
      name: data.name,
      licenseStatus: data.licenseStatus,
      tutorialComplete: data.tutorialComplete,
      isAgent: data.isAgent,
      group: data.group,
      hasChromeExt: data.hasChromeExt,
      authenticated: !!data.userId,
      userId: data.userId,
      hasTrialed: data.hasTrialed,
      aiDataConsent: data.aiDataConsent,
      referralCode: data.referralCode,
      createdAt: data.createdAt,
    }));
  },

  async getOrganization() {
    const response = await fetchWithAuth<UserOrganizationResponse>(
      `${authHost}/user/organization`,
      { method: 'GET' }
    );

    // If the response is an error, treat as no organization (204 No Content or other errors)
    if (!response.isOk()) {
      return ok({
        organizationId: undefined as string | undefined,
        organizationName: undefined as string | undefined,
      });
    }

    return ok({
      organizationId: response.value.organizationId
        ? String(response.value.organizationId)
        : undefined,
      organizationName: response.value.organizationName as string | undefined,
    });
  },

  async completeOnboarding(args: PatchUserOnboardingRequest) {
    return (
      await fetchWithAuth<EmptyResponse>(`${authHost}/user/onboarding`, {
        method: 'PATCH',
        body: JSON.stringify(args),
      })
    ).map(() => undefined);
  },

  async setGroup(args: PatchUserGroupRequest) {
    return (
      await fetchWithAuth<EmptyResponse>(`${authHost}/user/group`, {
        method: 'PATCH',
        body: JSON.stringify(args),
      })
    ).map(() => undefined);
  },

  async sendReferralInvite(recipient: string) {
    return (
      await fetchWithAuth<EmptyResponse>(`${authHost}/referral/send`, {
        method: 'POST',
        body: JSON.stringify({ recipient }),
      })
    ).map(() => undefined);
  },

  // GTM invite links: personal, time-limited signup links Macro staff hand
  // to prospects. Staff endpoints are gated server-side on a @macro.com account.
  async createGtmInviteLink(args: CreateGtmInviteLinkRequest) {
    return (
      await fetchWithAuth<GtmInviteLink>(`${authHost}/gtm-invite/links`, {
        method: 'POST',
        body: JSON.stringify(args),
      })
    ).map((link) => link);
  },

  async listGtmInviteLinks(args: { mine: boolean }) {
    return (
      await fetchWithAuth<GtmInviteLinkList>(
        `${authHost}/gtm-invite/links?mine=${args.mine ? 'true' : 'false'}`,
        { method: 'GET' }
      )
    ).map((result) => result.links);
  },

  async revokeGtmInviteLink(id: string) {
    return (
      await fetchWithAuth<GtmInviteLink>(
        `${authHost}/gtm-invite/links/${encodeURIComponent(id)}`,
        { method: 'DELETE' }
      )
    ).map((link) => link);
  },

  /** Public: the recipient has no account yet, so nothing is sent for auth. */
  async resolveGtmInviteLink(token: string) {
    return (
      await authApiFetch<PublicGtmInviteLink>(
        `/gtm-invite/public/${encodeURIComponent(token)}`,
        { method: 'GET', trace: { expectedStatusCodes: [404] } }
      )
    ).map((link) => link);
  },

  /** Attributes the signed-in account to the link and grants its offer. */
  async redeemGtmInviteLink(token: string) {
    return (
      await fetchWithAuth<GtmInviteOffer>(`${authHost}/gtm-invite/redeem`, {
        method: 'POST',
        body: JSON.stringify({ token }),
      })
    ).map((offer) => offer);
  },

  /** The promotion this account holds from an invite link, or null. */
  async getGtmInviteOffer() {
    return (
      await fetchWithAuth<GtmInviteOfferStatus>(
        `${authHost}/gtm-invite/offer`,
        { method: 'GET' }
      )
    ).map((result) => result.offer ?? null);
  },

  /** Public: the status banner shows signed in or not. */
  async getSystemStatus() {
    return (
      await authApiFetch<CurrentSystemStatus>('/system-status', {
        method: 'GET',
      })
    ).map((status) => status);
  },

  /** Macro staff only; the server rejects everyone else. */
  async setSystemStatus(status: SystemStatus) {
    return (
      await fetchWithAuth<StatusUpdate>(`${authHost}/system-status`, {
        method: 'POST',
        body: JSON.stringify(status),
      })
    ).map((update) => update);
  },

  /** Macro staff only. */
  async listSystemStatusHistory() {
    return (
      await fetchWithAuth<SystemStatusHistory>(
        `${authHost}/system-status/history`,
        { method: 'GET' }
      )
    ).map((result) => result.updates);
  },

  // Stripe HTTP methods (replacing RPC calls)
  async getTrialEligibility() {
    return await fetchWithAuth<TrialEligibility>(
      `${authHost}/user/stripe/trial_eligibility`,
      { method: 'GET' }
    );
  },

  async createCheckoutSessionV2(args: {
    successUrl: string;
    cancelUrl: string;
    discount?: string | null;
    metadata?: {
      gaClientId?: string | null;
      fbp?: string | null;
      fbc?: string | null;
    };
    /** The plan to subscribe to. The backend defaults to Premium. */
    plan?: PaidPlan;
    /** Request the server-validated first-subscription trial. */
    onboardingTrial?: boolean;
  }) {
    return await fetchWithAuth<CheckoutSessionV2Response>(
      `${authHost}/user/stripe/checkoutv2`,
      {
        method: 'POST',
        body: JSON.stringify({
          successUrl: args.successUrl,
          cancelUrl: args.cancelUrl,
          discount: args.discount ?? undefined,
          metadata: args.metadata,
          plan: args.plan,
          onboardingTrial: args.onboardingTrial,
        }),
        errorResponseHandler: async (response) => {
          if (response.status === 409) {
            const body: unknown = await response.json().catch(() => null);
            return {
              code: 'CONFLICT',
              message:
                body &&
                typeof body === 'object' &&
                'message' in body &&
                typeof body.message === 'string'
                  ? body.message
                  : 'Your subscription status changed. Please refresh your plans.',
            };
          }
          return statusError(response.status);
        },
      }
    );
  },

  /**
   * Upgrades immediately, schedules downgrades for renewal, or keeps the active
   * plan by canceling its pending downgrade.
   */
  async changePlan(args: { plan: PaidPlan }) {
    return (
      await fetchWithAuth<{ plan: PaidPlan }>(`${authHost}/user/stripe/plan`, {
        method: 'POST',
        body: JSON.stringify({ plan: args.plan }),
      })
    ).map((result) => result.plan);
  },

  async getSubscriptionStatus() {
    return await fetchWithAuth<SubscriptionStatus>(
      `${authHost}/user/stripe/plan`,
      { method: 'GET' }
    );
  },

  // AI billing: allowance, credits, overage.
  async getAiBillingSummary() {
    return await fetchWithAuth<AiUsageSnapshot>(
      `${authHost}/ai-billing/summary`,
      { method: 'GET' }
    );
  },

  async getAiBillingPlans() {
    return await fetchWithAuth<AiPlanCatalog>(`${authHost}/ai-billing/plans`, {
      method: 'GET',
    });
  },

  async updateAiOverage(args: { enabled: boolean; limitCents: number }) {
    return await fetchWithAuth<AiUsageSnapshot>(
      `${authHost}/ai-billing/overage`,
      {
        method: 'PATCH',
        body: JSON.stringify({
          enabled: args.enabled,
          limitCents: args.limitCents,
        }),
      }
    );
  },

  async updateAiAutoReload(args: {
    enabled: boolean;
    minimumBalanceCents: number;
    targetBalanceCents: number;
    monthlySpendLimitCents: number | null;
  }) {
    return await fetchWithAuth<AiUsageSnapshot>(
      `${authHost}/ai-billing/auto-reload`,
      {
        method: 'PATCH',
        body: JSON.stringify({
          enabled: args.enabled,
          minimumBalanceCents: args.minimumBalanceCents,
          targetBalanceCents: args.targetBalanceCents,
          monthlySpendLimitCents: args.monthlySpendLimitCents,
        }),
      }
    );
  },

  /** Buy a credit pack now on the payer's card on file. */
  async purchaseAiCredits(args: { amountCents: number }) {
    return await fetchWithAuth<
      AiCreditPurchaseResult,
      'PAID_PLAN_REQUIRED' | 'CREDIT_PURCHASE_REJECTED'
    >(`${authHost}/ai-billing/credits/purchase`, {
      method: 'POST',
      body: JSON.stringify({ amountCents: args.amountCents }),
      errorResponseHandler: async (response) => {
        if (response.status === 402) {
          return {
            code: 'PAID_PLAN_REQUIRED',
            message: 'A paid plan is required',
          };
        }
        // Over the monthly credit limit, or an earlier purchase is still
        // processing; the body says which.
        if (response.status === 409) {
          const body: unknown = await response.json().catch(() => undefined);
          return {
            code: 'CREDIT_PURCHASE_REJECTED',
            message:
              typeof body === 'object' &&
              body !== null &&
              'error' in body &&
              typeof body.error === 'string'
                ? body.error
                : 'Credit purchase rejected',
          };
        }
        return statusError(response.status);
      },
    });
  },

  /** Stripe Checkout for a credit pack, for a payer with no card on file. */
  async createAiCreditCheckout(args: {
    amountCents: number;
    successUrl: string;
    cancelUrl: string;
  }) {
    return (
      await fetchWithAuth<{ url: string }, 'PAID_PLAN_REQUIRED'>(
        `${authHost}/ai-billing/credits/checkout`,
        {
          method: 'POST',
          body: JSON.stringify({
            amountCents: args.amountCents,
            successUrl: args.successUrl,
            cancelUrl: args.cancelUrl,
          }),
          errorResponseHandler: async (response) => {
            if (response.status === 402) {
              return {
                code: 'PAID_PLAN_REQUIRED',
                message: 'A paid plan is required',
              };
            }
            return statusError(response.status);
          },
        }
      )
    ).map((result) => result.url);
  },

  async createPortalSession(args: { returnUrl: string }) {
    return (
      await fetchWithAuth<{ url: string }>(`${authHost}/user/stripe/portal`, {
        method: 'POST',
        body: JSON.stringify({
          returnUrl: args.returnUrl,
        }),
      })
    ).map((result) => result.url);
  },

  /**
   * Whether the signed-in user has a Cursor API key stored, and whether this
   * deployment accepts one at all.
   *
   * Never returns the key or any part of it — not even masked. There is no
   * screen that needs it, and a masked key still leaks its length.
   */
  async getCursorApiKeyStatus() {
    return (
      await fetchWithAuth<CursorApiKeyStatus, 'CURSOR_API_KEY_ERROR'>(
        `${authHost}/cursor-api-key`,
        {
          method: 'GET',
          errorResponseHandler: cursorApiKeyErrorResponseHandler,
        }
      )
    ).map((result) => result);
  },

  /**
   * The agent's own API key, if it has one, and whether its owner's plan
   * lets it run on one. Never returns a key or any part of one.
   */
  async getAgentApiKey(agentId: string) {
    return (
      await fetchWithAuth<AgentApiKey, 'AGENT_API_KEY_ERROR'>(
        `${authHost}/agents/${agentId}/api-key`,
        {
          method: 'GET',
          errorResponseHandler: agentApiKeyErrorResponseHandler,
        }
      )
    ).map((result) => result);
  },

  /** Stores the agent's own API key, for its model's provider, replacing any. */
  async putAgentApiKey(agentId: string, apiKey: string) {
    return (
      await fetchWithAuth<AgentApiKey, 'AGENT_API_KEY_ERROR'>(
        `${authHost}/agents/${agentId}/api-key`,
        {
          method: 'PUT',
          body: JSON.stringify({ apiKey }),
          errorResponseHandler: agentApiKeyErrorResponseHandler,
        }
      )
    ).map((result) => result);
  },

  /** Forgets the agent's API key. Does not revoke it at the provider. */
  async deleteAgentApiKey(agentId: string) {
    return (
      await fetchWithAuth<AgentApiKey, 'AGENT_API_KEY_ERROR'>(
        `${authHost}/agents/${agentId}/api-key`,
        {
          method: 'DELETE',
          errorResponseHandler: agentApiKeyErrorResponseHandler,
        }
      )
    ).map((result) => result);
  },

  /**
   * Stores a Cursor API key for the signed-in user, replacing any existing one.
   *
   * The key is validated on shape alone, so a typo that still starts with
   * `grok_` or `crsr_` is accepted here and only fails when a session tries to
   * use it.
   */
  async putCursorApiKey(apiKey: string) {
    return (
      await fetchWithAuth<CursorApiKeyStatus, 'CURSOR_API_KEY_ERROR'>(
        `${authHost}/cursor-api-key`,
        {
          method: 'PUT',
          body: JSON.stringify({ apiKey }),
          errorResponseHandler: cursorApiKeyErrorResponseHandler,
        }
      )
    ).map((result) => result);
  },

  /**
   * Forgets the signed-in user's Cursor API key.
   *
   * Does not revoke it at Cursor — the key keeps working everywhere else, and
   * only Cursor can revoke it. The UI has to say so.
   */
  async deleteCursorApiKey() {
    return (
      await fetchWithAuth<CursorApiKeyStatus, 'CURSOR_API_KEY_ERROR'>(
        `${authHost}/cursor-api-key`,
        {
          method: 'DELETE',
          errorResponseHandler: cursorApiKeyErrorResponseHandler,
        }
      )
    ).map((result) => result);
  },

  /**
   * The models the signed-in user's Cursor account offers, for the settings
   * dropdown. Asks Cursor live through the stored key, so it needs a connected
   * account — a caller with none gets the endpoint's own `409` message.
   */
  async listCursorModels() {
    return (
      await fetchWithAuth<CursorModelsResponse, 'CURSOR_API_KEY_ERROR'>(
        `${authHost}/cursor-api-key/models`,
        {
          method: 'GET',
          errorResponseHandler: cursorApiKeyErrorResponseHandler,
        }
      )
    ).map((result) => result);
  },

  /**
   * Chooses the model the user's sessions start on.
   */
  async putCursorDefaultModel(modelId: string) {
    return (
      await fetchWithAuth<CursorApiKeyStatus, 'CURSOR_API_KEY_ERROR'>(
        `${authHost}/cursor-api-key/default-model`,
        {
          method: 'PUT',
          body: JSON.stringify({ modelId }),
          errorResponseHandler: cursorApiKeyErrorResponseHandler,
        }
      )
    ).map((result) => result);
  },

  async checkGithubLinkStatus() {
    return (
      await fetchWithAuth<
        GithubLinkStatusResponse,
        GithubReauthenticationErrorCode
      >(`${authHost}/link/github/status`, {
        method: 'GET',
        errorResponseHandler: githubErrorResponseHandler,
      })
    ).map((result) => result);
  },

  async checkGmailLinkStatus() {
    return (
      await fetchWithAuth<
        GmailLinkStatusResponse,
        GithubReauthenticationErrorCode
      >(`${authHost}/link/gmail/status`, {
        method: 'GET',
        errorResponseHandler: githubErrorResponseHandler,
      })
    ).map((result) => result);
  },

  /**
   * Initializes the github account link for the user.
   * Returns the url you need to redirect user to to start the link.
   */
  async initGithubLink(originalUrl?: string) {
    const url = originalUrl
      ? `${authHost}/link/github?original_url=${encodeURIComponent(originalUrl)}`
      : `${authHost}/link/github`;
    return (
      await fetchWithAuth<InitGithubLinkResponse>(url, {
        method: 'POST',
      })
    ).map((result) => result.authorization_url);
  },

  /**
   * Initializes a gmail account link for the already-authenticated user (multi-inbox flow).
   * Returns the OAuth authorization URL to redirect the browser to.
   * After Google consent, the user is redirected back to `originalUrl` with `?link_id=<uuid>`
   * appended; the frontend then calls `emailClient.init({ linkId })` to provision the inbox.
   *
   * `scopes` selects which permissions the consent screen asks for. A healthy
   * mailbox adding calendar requests `calendar`; reconnecting an account that
   * used calendar requests `gmail_and_calendar` to repair both capabilities.
   */
  async initGmailLink(
    originalUrl?: string,
    options?: { scopes?: ConsentScopes; reconnectLinkId?: string }
  ) {
    const params = new URLSearchParams();
    if (originalUrl) {
      params.set('original_url', encodeURIComponent(originalUrl));
    }
    if (options?.scopes) {
      params.set('scopes', options.scopes);
    }
    if (options?.reconnectLinkId)
      params.set('reconnect_link_id', options.reconnectLinkId);
    const query = params.toString();
    const url = query
      ? `${authHost}/link/gmail?${query}`
      : `${authHost}/link/gmail`;
    return (
      await fetchWithAuth<
        InitGmailLinkResponse,
        'PAYMENT_REQUIRED' | 'TOO_MANY_PENDING_LINKS'
      >(url, {
        method: 'POST',
        // The backend returns 402 when the user isn't entitled to additional
        // inboxes, and 429 when they have too many incomplete link attempts in
        // flight. Surface each as a distinct code so the add-inbox flow can open
        // the paywall or explain the wait instead of a generic failure.
        errorResponseHandler: async (response) => {
          if (response.status === 402) {
            return { code: 'PAYMENT_REQUIRED', message: 'Payment required' };
          }
          if (response.status === 429) {
            return {
              code: 'TOO_MANY_PENDING_LINKS',
              message: 'Too many pending inbox connections',
            };
          }
          return {
            code: 'HTTP_ERROR',
            message: `HTTP error! status: ${response.status}`,
          };
        },
      })
    ).map((result) => result);
  },

  /** Connect a personal Outlook.com or Microsoft 365 inbox. */
  async initOutlookLink(
    originalUrl: string,
    options?: { calendar?: boolean; reconnectLinkId?: string }
  ) {
    const params = new URLSearchParams({
      original_url: encodeURIComponent(originalUrl),
      scopes: options?.calendar ? 'mail_and_calendar' : 'mail',
    });
    if (options?.reconnectLinkId)
      params.set('reconnect_link_id', options.reconnectLinkId);
    return fetchWithAuth<
      InitOutlookLinkResponse,
      'PAYMENT_REQUIRED' | 'TOO_MANY_PENDING_LINKS'
    >(`${authHost}/link/outlook?${params}`, {
      method: 'POST',
      errorResponseHandler: async (response) => {
        if (response.status === 402) {
          return { code: 'PAYMENT_REQUIRED', message: 'Payment required' };
        }
        if (response.status === 429) {
          return {
            code: 'TOO_MANY_PENDING_LINKS',
            message: 'Too many pending inbox connections',
          };
        }
        return {
          code: 'HTTP_ERROR',
          message: `HTTP error! status: ${response.status}`,
        };
      },
    });
  },

  /**
   * Deletes a github link for a user
   * NOTE: this does not delete the github application from being installed on a teams repository
   */
  async deleteGithubLink() {
    return (
      await fetchWithAuth<{}>(`${authHost}/link/github`, {
        method: 'DELETE',
      })
    ).map((_result) => {});
  },

  async reauthenticateGithub(originalUrl?: string) {
    // The OAuth callback refreshes the grant after verifying the GitHub account.
    return authServiceClient.initGithubLink(originalUrl);
  },

  async sendMobileWelcomeEmail(
    email: string,
    attribution?: Record<string, string>
  ) {
    const body: { email: string; attribution?: Record<string, string> } = {
      email,
    };
    if (attribution && Object.keys(attribution).length > 0) {
      body.attribution = attribution;
    }
    return safeFetch<
      SendMobileWelcomeEmailResponse,
      'RATE_LIMITED' | 'INVALID_EMAIL'
    >(
      `${authHost}/mobile-welcome-email`,
      {
        method: 'POST',
        body: JSON.stringify(body),
        credentials: 'include',
      },
      async (response) => {
        if (response.status === 429) {
          return { code: 'RATE_LIMITED', message: 'Rate limit exceeded' };
        }
        if (response.status === 400) {
          return { code: 'INVALID_EMAIL', message: 'Invalid email address' };
        }
        return {
          code: 'HTTP_ERROR',
          message: `HTTP error! status: ${response.status}`,
        };
      }
    );
  },

  async getUserTeams() {
    return (
      await fetchWithAuth<Team[]>(`${authHost}/team/user`, { method: 'GET' })
    ).map((result) => result);
  },

  async getUserInvites() {
    return (
      await fetchWithAuth<TeamInvitesResponse>(
        `${authHost}/team/user/invites`,
        {
          method: 'GET',
        }
      )
    ).map((result) => result);
  },

  async getTeam() {
    return (
      (
        await fetchWithAuth<TeamWithMembers>(`${authHost}/team`, {
          method: 'GET',
        })
      )
        // A user with no team gets a 204 No Content, which `safeFetch`
        // surfaces as an empty object. Normalize that to `null` so callers
        // don't dereference a non-existent `team`/`members`.
        .map((result): TeamWithMembers | null =>
          'team' in result ? result : null
        )
    );
  },

  async getTeamInvites() {
    return (
      await fetchWithAuth<TeamInvitesResponse>(`${authHost}/team/invites`, {
        method: 'GET',
      })
    ).map((result) => result);
  },

  async createTeam(args: CreateTeamRequest) {
    return (
      await fetchWithAuth<Team>(`${authHost}/team`, {
        method: 'POST',
        body: JSON.stringify(args),
      })
    ).map((result) => result);
  },

  async joinTeam(teamInviteId: string) {
    return (
      await fetchWithAuth<{}>(`${authHost}/team/join/${teamInviteId}`, {
        method: 'GET',
      })
    ).map(() => undefined);
  },

  async rejectInvitation(teamInviteId: string) {
    return (
      await fetchWithAuth<{}>(`${authHost}/team/join/${teamInviteId}`, {
        method: 'DELETE',
      })
    ).map(() => undefined);
  },

  async patchTeam(args: PatchTeamRequest) {
    return (
      await fetchWithAuth<{}>(`${authHost}/team`, {
        method: 'PATCH',
        body: JSON.stringify(args),
      })
    ).map(() => undefined);
  },

  /**
   * Emails the caller's same-domain contacts who aren't on Macro yet that
   * the caller's team exists. Call it after inviting, so invitees are
   * skipped. Admin/Owner only; the server caps a team at 25 recipients.
   */
  async sendTeamDomainNotice() {
    return (
      await fetchWithAuth<SendDomainNoticeResponse>(
        `${authHost}/team/domain-notice`,
        { method: 'POST' }
      )
    ).map((result) => result);
  },

  async inviteToTeam(args: InviteToTeamRequest) {
    return (
      await fetchWithAuth<{}>(`${authHost}/team/invite`, {
        method: 'POST',
        body: JSON.stringify(args),
      })
    ).map(() => undefined);
  },

  /**
   * Toggles automatic domain joining for the caller's team: sets the
   * auto-join domain from the team owner's email domain when unset,
   * removes it when set. Returns the domain after the toggle (null when
   * it was just disabled). Admin/Owner only.
   */
  async toggleTeamAutoJoinDomain() {
    return (
      await fetchWithAuth<
        ToggleAutoJoinDomainResponse,
        ToggleAutoJoinDomainErrorCode
      >(`${authHost}/team/auto-join-domain/toggle`, {
        method: 'POST',
        // The backend rejects enabling auto-join for generic email
        // provider domains (e.g. gmail.com) with a 400 whose message
        // names the domain — keep that message so the UI can toast it
        // verbatim.
        errorResponseHandler: async (response) => {
          if (response.status === 400) {
            const message = await response
              .json()
              .then((body) => body?.message)
              .catch(() => undefined);
            return {
              code: 'GENERIC_DOMAIN_NOT_ALLOWED',
              message:
                typeof message === 'string'
                  ? message
                  : "Auto-join isn't available for this domain",
            };
          }
          return {
            code: 'HTTP_ERROR',
            message: `HTTP error! status: ${response.status}`,
          };
        },
      })
    ).map((result) => result);
  },

  /**
   * Toggles whether non-admin members may invite users to the caller's
   * team. Teams start with this on (any member can invite); turning it
   * off restricts inviting to team admins and owners. Admin/Owner only.
   */
  async toggleTeamNonAdminInvites() {
    return (
      await fetchWithAuth<ToggleNonAdminInvitesResponse>(
        `${authHost}/team/non-admin-invites/toggle`,
        {
          method: 'POST',
        }
      )
    ).map((result) => result);
  },

  /**
   * The caller's team invite link token, or null when the team has none.
   * Anyone who may invite people to the team may read it.
   */
  async getTeamInviteLink() {
    return (
      await fetchWithAuth<TeamInviteLinkResponse>(
        `${authHost}/team/invite-link`,
        { method: 'GET' }
      )
    ).map((result) => result);
  },

  /**
   * Creates the team's invite link, replacing any existing one so links
   * already shared stop working. Replacing a link is admin-only.
   */
  async createTeamInviteLink() {
    return (
      await fetchWithAuth<CreatedTeamInviteLinkResponse>(
        `${authHost}/team/invite-link`,
        { method: 'POST' }
      )
    ).map((result) => result);
  },

  /** Turns off the team's invite link. Admin/Owner only. */
  async deleteTeamInviteLink() {
    return (
      await fetchWithAuth<{}>(`${authHost}/team/invite-link`, {
        method: 'DELETE',
      })
    ).map(() => undefined);
  },

  /** The team an invite link joins, shown before the user joins it. */
  async getTeamByInviteLink(token: string) {
    return (
      await fetchWithAuth<TeamInviteLinkTeam>(
        `${authHost}/team/invite-link/team`,
        {
          method: 'POST',
          // In the body, not the path, so request telemetry never records it.
          body: JSON.stringify({ token }),
        }
      )
    ).map((result) => result);
  },

  /**
   * Joins the team an invite link belongs to. Fails with NOT_FOUND when the
   * link was reset or turned off, and CONFLICT when the user is on another
   * team.
   */
  async joinTeamByInviteLink(token: string) {
    return (
      await fetchWithAuth<JoinTeamByInviteLinkResponse>(
        `${authHost}/team/invite-link/join`,
        { method: 'POST', body: JSON.stringify({ token }) }
      )
    ).map((result) => result);
  },

  async deleteTeamInvite(teamInviteId: string) {
    return (
      await fetchWithAuth<{}>(`${authHost}/team/invite/${teamInviteId}`, {
        method: 'DELETE',
      })
    ).map(() => undefined);
  },

  /** Move one team member's seat between paid plans (team admins only). */
  async setTeamMemberPlan(userId: string, plan: PaidPlan) {
    return await fetchWithAuth<TeamMemberPlan>(
      `${authHost}/team/members/${encodeURIComponent(userId)}/plan`,
      {
        method: 'PATCH',
        body: JSON.stringify({ plan }),
      }
    );
  },

  async removeUserFromTeam(userId: string) {
    return (
      await fetchWithAuth<{}>(`${authHost}/team/remove/${userId}`, {
        method: 'DELETE',
      })
    ).map(() => undefined);
  },

  async deleteTeam() {
    return (
      await fetchWithAuth<{}>(`${authHost}/team`, {
        method: 'DELETE',
      })
    ).map(() => undefined);
  },
};

registerClient('auth', authServiceClient);