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.

96.1 KB
Raw Blame
import {
  PdfCoParseSchema as CoParseSchema,
  type PdfCoParse as ICoParse,
  type PdfModificationDataOnServer as IModificationDataOnServer,
  PdfModificationDataOnServerSchema as IModificationDataOnServerSchema,
  modificationDataReplacer,
  type PdfSegment as TSegment,
} from '@coparse/document-processing-types';
import { ENABLE_DOCX_TO_PDF } from '@core/constant/featureFlags';
import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';
import {
  SERVER_HOSTS,
  SYNC_PERMISSION_TOKEN_DSS_HOST,
  SYNC_SERVICE_HOSTS,
} from '@core/constant/servers';
import type { DatabaseOp } from '@core/database-sql/generated/types';
import type { FetchError } from '@core/service';
import { cache } from '@core/util/cache';
import {
  type FetchWithTokenErrorCode,
  fetchWithToken,
} from '@core/util/fetchWithToken';
import { registerClient } from '@core/util/mockClient';
import { isTauri } from '@core/util/platform';
import { platformFetch } from '@core/util/platformFetch';
import type { ResultError } from '@core/util/result';
import type { SafeFetchInit } from '@core/util/safeFetch';
import type { IDocumentStorageServiceFile } from '@filesystem/file';
import type { SerializedEditorState } from 'lexical';
import { err, ok, type Result } from 'neverthrow';
import type { ApiChannelListPage } from './channel-list-types';
import { fetchDatabaseOps } from './databases';
import type { AccessiblePipeline as PipelineResponse } from './generated/schemas/accessiblePipeline';
import type { AccessLevel } from './generated/schemas/accessLevel';
import type { AccountManagerDecision } from './generated/schemas/accountManagerDecision';
import type { AccountManagerGrant } from './generated/schemas/accountManagerGrant';
import type { AccountManagersList } from './generated/schemas/accountManagersList';
import type { AddFavoriteRequest } from './generated/schemas/addFavoriteRequest';
import type { AddParticipantsRequest } from './generated/schemas/addParticipantsRequest';
import type { AddPinRequest } from './generated/schemas/addPinRequest';
import type { Agent } from './generated/schemas/agent';
import type { AnchorResponse } from './generated/schemas/anchorResponse';
import type { ApiActivity } from './generated/schemas/apiActivity';
import type { ApiChannelAttachmentsPage } from './generated/schemas/apiChannelAttachmentsPage';
import type { ApiChannelParticipant } from './generated/schemas/apiChannelParticipant';
import type { Bot } from './generated/schemas/bot';
import type { BotChannel } from './generated/schemas/botChannel';
import type { BotOwnerProfile } from './generated/schemas/botOwnerProfile';
import type { BotToken } from './generated/schemas/botToken';
import type { CalendarJoinRequest } from './generated/schemas/calendarJoinRequest';
import { CalendarJoinRequestErrorCode } from './generated/schemas/calendarJoinRequestErrorCode';
import type { CalendarJoinRequestsResponse } from './generated/schemas/calendarJoinRequestsResponse';
import type { CalendarMentionPreviewRequest } from './generated/schemas/calendarMentionPreviewRequest';
import type { CalendarMentionPreviewResponse } from './generated/schemas/calendarMentionPreviewResponse';
import type { CalendarOccurrenceResponse } from './generated/schemas/calendarOccurrenceResponse';
import type { CallRecordPreview } from './generated/schemas/callRecordPreview';
import type { CardPosition } from './generated/schemas/cardPosition';
import type { ChannelAccessDecision } from './generated/schemas/channelAccessDecision';
import type { ChannelAccessRequest } from './generated/schemas/channelAccessRequest';
import type { ChannelAccessRequestState } from './generated/schemas/channelAccessRequestState';
import type { ChannelJoinCodeResponse } from './generated/schemas/channelJoinCodeResponse';
import type { ChannelLabel } from './generated/schemas/channelLabel';
import type { ChannelLabelRule } from './generated/schemas/channelLabelRule';
import type { ChannelLabelScopeSelection } from './generated/schemas/channelLabelScopeSelection';
import type { ChannelLabelsList } from './generated/schemas/channelLabelsList';
import { ChannelType } from './generated/schemas/channelType';
import type { ClaimedAccountManagerToken } from './generated/schemas/claimedAccountManagerToken';
import {
  type CloudStorageItemType,
  CloudStorageItemType as CloudStorageItemTypeMap,
} from './generated/schemas/cloudStorageItemType';
import type { CreateAgentRequest } from './generated/schemas/createAgentRequest';
import type { CreateCanvasDocumentRequest } from './generated/schemas/createCanvasDocumentRequest';
import type { CreateCanvasDocumentResponse } from './generated/schemas/createCanvasDocumentResponse';
import type { CreateChannelLabelRequest } from './generated/schemas/createChannelLabelRequest';
import type { CreateChannelRequest } from './generated/schemas/createChannelRequest';
import type { CreateChannelResponse } from './generated/schemas/createChannelResponse';
import type { CreateChannelScopedBotRequest } from './generated/schemas/createChannelScopedBotRequest';
import type { CreateChannelScopedBotResponse } from './generated/schemas/createChannelScopedBotResponse';
import type { CreateCrmCompanyRequest } from './generated/schemas/createCrmCompanyRequest';
import type { CreateCrmContactRequest } from './generated/schemas/createCrmContactRequest';
import type { CreateCrmTeamContactRequest } from './generated/schemas/createCrmTeamContactRequest';
import type { CreateDocument200 as CreateDocumentResponse } from './generated/schemas/createDocument200';
import type { CreateDocumentRequest } from './generated/schemas/createDocumentRequest';
import type { CreatedUserApiKey } from './generated/schemas/createdUserApiKey';
import type { CreateEntityMentionRequest } from './generated/schemas/createEntityMentionRequest';
import type { CreateEntityMentionResponse } from './generated/schemas/createEntityMentionResponse';
import type { CreateMarkdownDocumentRequest } from './generated/schemas/createMarkdownDocumentRequest';
import type { CreateMarkdownHandler200 } from './generated/schemas/createMarkdownHandler200';
import type { CreateProjectResponse } from './generated/schemas/createProjectResponse';
import type { CreateSkillHandler200 } from './generated/schemas/createSkillHandler200';
import type { CreateSkillRequest } from './generated/schemas/createSkillRequest';
import type { CreateSnippetHandler200 } from './generated/schemas/createSnippetHandler200';
import type { CreateSnippetRequest } from './generated/schemas/createSnippetRequest';
import type { CreateTaskHandler200 } from './generated/schemas/createTaskHandler200';
import type { CreateTaskRequest } from './generated/schemas/createTaskRequest';
import type { CreateUnthreadedAnchorResponse } from './generated/schemas/createUnthreadedAnchorResponse';
import type { CrmBlockedDomainResponse } from './generated/schemas/crmBlockedDomainResponse';
import type { CrmCompanyResponse } from './generated/schemas/crmCompanyResponse';
import type { CrmContactResponse } from './generated/schemas/crmContactResponse';
import type { CrmStagesResponse } from './generated/schemas/crmStagesResponse';
import type { CrmTeamSettingsResponse } from './generated/schemas/crmTeamSettingsResponse';
import type { DeleteEntityMentionResponse } from './generated/schemas/deleteEntityMentionResponse';
import type { DeleteUnthreadedAnchorResponse } from './generated/schemas/deleteUnthreadedAnchorResponse';
import type { DocumentMetadata } from './generated/schemas/documentMetadata';
import type { DocumentPreview } from './generated/schemas/documentPreview';
import type { DocumentResponseMetadataWithContent } from './generated/schemas/documentResponseMetadataWithContent';
import type { DocumentTeamShareResponse } from './generated/schemas/documentTeamShareResponse';
import type { EditAnchorResponse } from './generated/schemas/editAnchorResponse';
import type { EmailFollowup } from './generated/schemas/emailFollowup';
import type { EmailFollowupCommand } from './generated/schemas/emailFollowupCommand';
import type { EmailReminderPage } from './generated/schemas/emailReminderPage';
import type { ExportDocumentResponse } from './generated/schemas/exportDocumentResponse';
import type { Favorite } from './generated/schemas/favorite';
import type { FavoritesList } from './generated/schemas/favoritesList';
import type { ForeignEntity } from './generated/schemas/foreignEntity';
import type { GetAttachmentReferencesResponse } from './generated/schemas/getAttachmentReferencesResponse';
import type { GetBatchChannelPreviewRequest } from './generated/schemas/getBatchChannelPreviewRequest';
import type { GetBatchChannelPreviewResponse } from './generated/schemas/getBatchChannelPreviewResponse';
import type { GetBatchProjectPreviewResponse } from './generated/schemas/getBatchProjectPreviewResponse';
import type { GetContactByEmailParams } from './generated/schemas/getContactByEmailParams';
import type { GetContactByEmailResponse } from './generated/schemas/getContactByEmailResponse';
import type { GetDocumentPermissionsResponseDataV2 } from './generated/schemas/getDocumentPermissionsResponseDataV2';
import type { GetDocumentProcessingResultResponse } from './generated/schemas/getDocumentProcessingResultResponse';
import type { GetDocumentResponseData } from './generated/schemas/getDocumentResponseData';
import type { GetDocumentSearchResponse } from './generated/schemas/getDocumentSearchResponse';
import type { GetOrCreateChannelResponse } from './generated/schemas/getOrCreateChannelResponse';
import type { GetOrCreateDmRequest } from './generated/schemas/getOrCreateDmRequest';
import type { GetOrCreatePrivateRequest } from './generated/schemas/getOrCreatePrivateRequest';
import type { GetPendingProjectsHandler200 } from './generated/schemas/getPendingProjectsHandler200';
import type { GetProjectContentResponse } from './generated/schemas/getProjectContentResponse';
import type { GetProjectResponse } from './generated/schemas/getProjectResponse';
import type { GetSystemSkillsHandler200 } from './generated/schemas/getSystemSkillsHandler200';
import type { GithubPullRequestChangesPatchResponse } from './generated/schemas/githubPullRequestChangesPatchResponse';
import type { GithubPullRequestChangesResponse } from './generated/schemas/githubPullRequestChangesResponse';
import type { GithubPullRequestFacets } from './generated/schemas/githubPullRequestFacets';
import type { GithubPullRequestsResponse } from './generated/schemas/githubPullRequestsResponse';
import type { GithubPullRequestTasksResponse } from './generated/schemas/githubPullRequestTasksResponse';
import type { GroupedSoupGroupPage } from './generated/schemas/groupedSoupGroupPage';
import type { GroupedSoupInitialPage } from './generated/schemas/groupedSoupInitialPage';
import type { GroupedSoupSort } from './generated/schemas/groupedSoupSort';
import type { ImportPage } from './generated/schemas/importPage';
import type { ImportProgress } from './generated/schemas/importProgress';
import type { Item } from './generated/schemas/item';
import type { JobId } from './generated/schemas/jobId';
import type { ListEmailRemindersParams } from './generated/schemas/listEmailRemindersParams';
import type { ListFavoritesParams } from './generated/schemas/listFavoritesParams';
import type { ListOccurrencesParams } from './generated/schemas/listOccurrencesParams';
import type { ListSlackImportsParams } from './generated/schemas/listSlackImportsParams';
import type { ListTeamOutOfOfficeParams } from './generated/schemas/listTeamOutOfOfficeParams';
import type { LocationResponseV3 } from './generated/schemas/locationResponseV3';
import type { PairingDetails } from './generated/schemas/pairingDetails';
import type { PatchChannelRequest } from './generated/schemas/patchChannelRequest';
import type { PatchHarnessRequest } from './generated/schemas/patchHarnessRequest';
import type { PinRequest } from './generated/schemas/pinRequest';
import type { PostActivityRequest } from './generated/schemas/postActivityRequest';
import type { PostGroupedSoupAstGroupPageRequest } from './generated/schemas/postGroupedSoupAstGroupPageRequest';
import type { PostGroupedSoupAstInitialRequest } from './generated/schemas/postGroupedSoupAstInitialRequest';
import type { PostGroupedSoupAstRequest } from './generated/schemas/postGroupedSoupAstRequest';
import type { PostSoupAstRequest } from './generated/schemas/postSoupAstRequest';
import type { PostSoupRequest } from './generated/schemas/postSoupRequest';
import type { Project } from './generated/schemas/project';
import type { RemoveParticipantsRequest } from './generated/schemas/removeParticipantsRequest';
import type { RenameChannelLabelRequest } from './generated/schemas/renameChannelLabelRequest';
import type { ReorderFavoritesRequest } from './generated/schemas/reorderFavoritesRequest';
import type { ReorderPinRequest } from './generated/schemas/reorderPinRequest';
import type { ReplaceCrmStagesRequest } from './generated/schemas/replaceCrmStagesRequest';
import type { RequestAccountManagerBody } from './generated/schemas/requestAccountManagerBody';
import type { SaveDocumentResponseData } from './generated/schemas/saveDocumentResponseData';
import type { SearchContactsParams } from './generated/schemas/searchContactsParams';
import type { SearchContactsResponse } from './generated/schemas/searchContactsResponse';
import type { SetChannelLabelRequest } from './generated/schemas/setChannelLabelRequest';
import type { SetChannelPictureRequest } from './generated/schemas/setChannelPictureRequest';
import type { SetCompanyNameRequest } from './generated/schemas/setCompanyNameRequest';
import type { SetContactNameRequest } from './generated/schemas/setContactNameRequest';
import type { SharePermissionV2 } from './generated/schemas/sharePermissionV2';
import type { SkillDescriptionBody } from './generated/schemas/skillDescriptionBody';
import type { SlackCompleteRequest } from './generated/schemas/slackCompleteRequest';
import type { SlackCreateRequest } from './generated/schemas/slackCreateRequest';
import type { SlackRegisterRequest } from './generated/schemas/slackRegisterRequest';
import type { SmartTagPreview } from './generated/schemas/smartTagPreview';
import type { SoupPage } from './generated/schemas/soupPage';
import type { StageRequirement } from './generated/schemas/stageRequirement';
import type { StorageRows } from './generated/schemas/storageRows';
import type { StorageRowsQuery } from './generated/schemas/storageRowsQuery';
import type { StoredGithubPullRequest } from './generated/schemas/storedGithubPullRequest';
import type { SyncServiceVersionID } from './generated/schemas/syncServiceVersionID';
import type { TableDetail } from './generated/schemas/tableDetail';
import type { TeamOutOfOfficeResponse } from './generated/schemas/teamOutOfOfficeResponse';
import type { TypedSuccessResponse } from './generated/schemas/typedSuccessResponse';
import type { UpdateAgentRequest } from './generated/schemas/updateAgentRequest';
import type { UpdateCrmTeamSettingsRequest } from './generated/schemas/updateCrmTeamSettingsRequest';
import type { UpdateSharePermissionRequestV2 } from './generated/schemas/updateSharePermissionRequestV2';
import type { UploadExtractFolderHandler200 } from './generated/schemas/uploadExtractFolderHandler200';
import type { UploadGrant } from './generated/schemas/uploadGrant';
import type { UserApiKeysList } from './generated/schemas/userApiKeysList';
import type { UserPinsResponse } from './generated/schemas/userPinsResponse';
import type { UserViewsResponse } from './generated/schemas/userViewsResponse';
import type { View } from './generated/schemas/view';
import type { ViewsResponse } from './generated/schemas/viewsResponse';
import { saveDocumentHandlerResponse } from './generated/zod';
import type { ItemType } from './itemType';

export type { HistoryItemType, ItemType } from './itemType';
export {
  blockNameToItemType,
  DEFAULT_ITEM_TYPE,
  itemTypeToReferenceEntityType,
  stringToItemType,
} from './itemType';

import { databasesClient } from './databases';
import { formsClient } from './forms';
import type {
  CollabSurfaceResponse,
  CollabSurfaceTokenResponse,
  GetDocumentPermissionsTokenResponse,
  ProcessingResultType,
  StorageServiceClient,
  ValidateDocumentPermissionsTokenResponse,
} from './service';
import { fetchPresigned } from './util/fetchPresigned';
import {
  type GetDocxFileResponse,
  getDocxExpandedParts,
} from './util/getDocxFile';

function normalizeLocationResponseV3(response: LocationResponseV3) {
  return response;
}

// the server is set to expire at 15 minutes, so expire just before that
const MINUTES_BEFORE_PRESIGNED_EXPIRES = 14;

const dssHost = SERVER_HOSTS['document-storage-service'];
const syncServiceWorkerHost = SYNC_SERVICE_HOSTS.worker;
const syncOrigin =
  import.meta.env.MODE === 'development'
    ? 'https://dev.macro.com'
    : 'https://macro.com';

export function dssFetch(
  url: string,
  init?: SafeFetchInit
): Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>>;
export function dssFetch<T extends Record<string, any>>(
  url: string,
  init?: SafeFetchInit
): Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>;
export function dssFetch<T extends Record<string, any> = never>(
  url: string,
  init?: SafeFetchInit
):
  | Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>
  | Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>> {
  return fetchWithToken<T>(`${dssHost}${url}`, init);
}

/**
 * Join-request failures carry a machine-readable `{ code, message }` body;
 * surface it so callers can explain a refusal.
 */
async function calendarJoinRequestErrorHandler(response: Response) {
  const body = (await response.json().catch(() => null)) as {
    code?: string;
    message?: string;
  } | null;
  const code =
    body?.code && body.code in CalendarJoinRequestErrorCode
      ? (body.code as CalendarJoinRequestErrorCode)
      : undefined;
  if (code) {
    return { code, message: body?.message ?? '' };
  }
  return {
    code: 'HTTP_ERROR' as const,
    message: `HTTP error! status: ${response.status}`,
  };
}

export async function getDocumentPermissionToken(
  documentId: string
): Promise<string> {
  const token = await fetchWithToken<GetDocumentPermissionsTokenResponse>(
    `${SYNC_PERMISSION_TOKEN_DSS_HOST}/documents/permissions_token/${documentId}`,
    {
      method: 'POST',
    }
  );

  if (token.isErr()) {
    console.error('Failed to create permission token:', token.error);
    throw new Error('Failed to create permission token');
  }

  return token.value.token;
}

type Success = {
  id: string | null | undefined;
  success: boolean;
};
type SuccessResponse = { data: Success };

export type { ApiAttachmentChannelReference } from './generated/schemas/apiAttachmentChannelReference';
export type { ApiAttachmentEntityReference } from './generated/schemas/apiAttachmentEntityReference';
export type { ApiAttachmentGenericReference } from './generated/schemas/apiAttachmentGenericReference';
export type { ApiChannelAttachment } from './generated/schemas/apiChannelAttachment';
export type { ApiChannelAttachmentsPage as ChannelAttachmentsPage } from './generated/schemas/apiChannelAttachmentsPage';
export type { ApiChannelParticipant } from './generated/schemas/apiChannelParticipant';
export type { GetOrCreateChannelResponse } from './generated/schemas/getOrCreateChannelResponse';

export type IdResponse = { id: string };
export type MessageResponse = { message: string };

export type TaskDuplicate = {
  id: string;
  taskId: string;
  taskName: string;
  vectorScore: number;
  judgeReason?: string | null;
};

export type TaskDuplicatesResponse = {
  duplicates: TaskDuplicate[];
};

export type TaskSimilarityResult = {
  taskId: string;
  taskName: string;
  vectorScore: number;
};

export type TaskSimilaritySearchResponse = {
  results: TaskSimilarityResult[];
};

type WithBotId = { bot_id: string };
type WithAgentId = { agent_id: string };
type WithChannelId = { channel_id: string };

/** Who owns a registered harness: the registering user or their team. */
export type HarnessOwner =
  | { type: 'user'; user_id: string }
  | { type: 'team'; team_id: string };

/** A macrod harness registered with the workspace. */
export type Harness = {
  allow_permission_bypass: boolean;
  id: string;
  kind: 'macrod';
  name: string;
  owner: HarnessOwner;
  created_by: string;
  created_at: string;
  updated_at: string;
  connected: boolean;
  last_connected_at: string | null;
};

/** A pending macrod pairing request, looked up by its printed code. */
export type HarnessPairing = PairingDetails;

type ApproveHarnessPairingRequest = {
  allow_permission_bypass?: boolean;
  name?: string;
  team_id?: string;
};

/**
 * The optional macrod harness binding on agent requests/responses. The backend
 * field is not yet in the generated schemas, so it is layered on here.
 */
type WithHarnessId = { harness_id?: string | null };

type CreateBotRequest = {
  team_id?: string;
  name: string;
  handle: string;
  description?: string;
  avatar_url?: string;
  /** Whether mentioning this bot opens a coding-agent session. Defaults to false. */
  has_agent?: boolean;
};

type PatchBotRequest = {
  name?: string;
  handle?: string;
  description?: string;
  avatar_url?: string;
  /** Whether mentioning this bot opens a coding-agent session. Omit to leave unchanged. */
  has_agent?: boolean;
};

type CreateBotTokenRequest = {
  label?: string;
  expires_at?: string;
};

type CreateBotTokenResponse = {
  token: BotToken;
  bearer_token: string;
};

type WithMentionId = { mention_id: string };
type WithEntity = { entity_type: string; entity_id: string };
export type ChannelAttachmentType = 'static' | 'dss';

export const ChannelTypeEnum = {
  Public: ChannelType.public,
  Private: ChannelType.private,
  DirectMessage: ChannelType.direct_message,
  Team: ChannelType.team,
} as const satisfies Record<string, ChannelType>;

export function isCloudStorageItem(
  item: ItemType
): item is CloudStorageItemType {
  return Object.values(CloudStorageItemTypeMap).includes(item as any);
}

export type ProcessingResultResponseType<T extends ProcessingResultType> =
  T extends 'PREPROCESS'
    ? ICoParse
    : T extends 'SPLIT_TEXTS'
      ? TSegment[]
      : never;
type UserPins = UserPinsResponse;

function withVersionId(version_id?: string | undefined | null): string {
  return version_id ? `?version_id=${version_id}` : '';
}

// the output of enhancements are not JSON-serializable, so they cannot be added to the service
const enhancements = {
  getDocxExpandedParts,
} as const;

const { showPaywall } = usePaywallState();

/** Machine-readable code the backend returns when a document name is too long. */
export const DOCUMENT_NAME_TOO_LONG_CODE = 'DOCUMENT_NAME_TOO_LONG' as const;

type SlackImportJobArgs = { jobId: JobId; signal?: AbortSignal };

export const storageServiceClient = {
  listCrmPipelines: () =>
    dssFetch<PipelineResponse[]>('/crm/pipelines', { method: 'GET' }),
  getCrmPipeline: (id: string) =>
    dssFetch<PipelineResponse>(`/crm/pipelines/${id}`, { method: 'GET' }),
  getCrmPipelineStageRequirements: (id: string) =>
    dssFetch<StageRequirement[]>(`/crm/pipelines/${id}/stage-requirements`, {
      method: 'GET',
    }),
  setCrmPipelineStageRequirement: (id: string, rule: StageRequirement) =>
    dssFetch(`/crm/pipelines/${id}/stage-requirements`, {
      method: 'PUT',
      body: JSON.stringify(rule),
    }),
  getCrmPipelineTable: (id: string) =>
    dssFetch<TableDetail>(`/crm/pipelines/${id}/table`, { method: 'GET' }),
  getCrmPipelineViewPositions: (id: string, viewId: string) =>
    dssFetch<CardPosition[]>(`/crm/pipelines/${id}/views/${viewId}/positions`, {
      method: 'GET',
    }),
  getCrmPipelineRows: (id: string, after?: string) =>
    dssFetch<StorageRows>(
      `/crm/pipelines/${id}/rows${after ? `?after=${encodeURIComponent(after)}` : ''}`,
      { method: 'GET' }
    ),
  queryCrmPipelineRows: (id: string, request: StorageRowsQuery) =>
    dssFetch<StorageRows>(`/crm/pipelines/${id}/rows`, {
      method: 'POST',
      body: JSON.stringify(request),
    }),
  applyCrmPipelineOps: (
    id: string,
    request: { ops: DatabaseOp[]; baseVersions?: Record<string, number> }
  ) => fetchDatabaseOps(`/crm/pipelines/${id}/ops`, request),
  createCrmPipeline: (
    input: Pick<PipelineResponse, 'name' | 'recordType' | 'sharing'>
  ) =>
    dssFetch<PipelineResponse>('/crm/pipelines', {
      method: 'POST',
      body: JSON.stringify(input),
    }),
  renameCrmPipeline: (id: string, name: string) =>
    dssFetch(`/crm/pipelines/${id}/name`, {
      method: 'PUT',
      body: JSON.stringify({ name }),
    }),
  shareCrmPipeline: (id: string, sharing: PipelineResponse['sharing']) =>
    dssFetch(`/crm/pipelines/${id}/sharing`, {
      method: 'PUT',
      body: JSON.stringify({ sharing }),
    }),
  getCrmPipelinePermissions: (id: string) =>
    dssFetch<SharePermissionV2>(`/crm/pipelines/${id}/permissions`, {
      method: 'GET',
    }),
  updateCrmPipelinePermissions: (
    id: string,
    request: UpdateSharePermissionRequestV2
  ) =>
    dssFetch<SharePermissionV2>(`/crm/pipelines/${id}/permissions`, {
      method: 'PATCH',
      body: JSON.stringify(request),
    }),
  trashCrmPipeline: (id: string) =>
    dssFetch(`/crm/pipelines/${id}/trash`, {
      method: 'PUT',
      body: JSON.stringify({ trashed: true }),
    }),
  /** Macro Databases — see `./databases.ts`. */
  databases: databasesClient,
  /** Macro Forms — see `./forms.ts`. */
  forms: formsClient,

  async createSlackImport(args: {
    body: SlackCreateRequest;
    signal?: AbortSignal;
  }) {
    return dssFetch<ImportProgress>('/slack/imports', {
      method: 'POST',
      body: JSON.stringify(args.body),
      signal: args.signal,
    });
  },

  async listSlackImports(
    args: ListSlackImportsParams & { signal?: AbortSignal } = {}
  ) {
    const params = new URLSearchParams();
    if (args.before) params.set('before', args.before);
    const query = params.toString();
    return dssFetch<ImportPage>(`/slack/imports${query ? `?${query}` : ''}`, {
      method: 'GET',
      signal: args.signal,
    });
  },

  async getSlackImport(args: SlackImportJobArgs) {
    return dssFetch<ImportProgress>(
      `/slack/imports/${encodeURIComponent(args.jobId)}`,
      {
        method: 'GET',
        signal: args.signal,
      }
    );
  },

  async registerSlackImportUploads(
    args: SlackImportJobArgs & { body: SlackRegisterRequest }
  ) {
    return dssFetch<UploadGrant[]>(
      `/slack/imports/${encodeURIComponent(args.jobId)}/uploads`,
      {
        method: 'POST',
        body: JSON.stringify(args.body),
        signal: args.signal,
      }
    );
  },

  async completeSlackImportUploads(
    args: SlackImportJobArgs & { body: SlackCompleteRequest }
  ) {
    return dssFetch<ImportProgress>(
      `/slack/imports/${encodeURIComponent(args.jobId)}/uploads/complete`,
      {
        method: 'POST',
        body: JSON.stringify(args.body),
        signal: args.signal,
      }
    );
  },

  async finalizeSlackImport(args: SlackImportJobArgs) {
    return dssFetch<ImportProgress>(
      `/slack/imports/${encodeURIComponent(args.jobId)}/finalize`,
      {
        method: 'POST',
        signal: args.signal,
      }
    );
  },

  async cancelSlackImport(args: SlackImportJobArgs) {
    return dssFetch<ImportProgress>(
      `/slack/imports/${encodeURIComponent(args.jobId)}/cancel`,
      {
        method: 'POST',
        signal: args.signal,
      }
    );
  },

  async ping() {
    return (await dssFetch<SuccessResponse>(`/ping`)).map(
      (result) => result.data
    );
  },

  async bulkWakeupSyncServiceDocuments(args: { document_ids: string[] }) {
    return (
      await dssFetch<{ dispatched: number }>(`/sync_service/wakeup`, {
        method: 'POST',
        body: JSON.stringify({ document_ids: args.document_ids }),
      })
    ).map((result) => result);
  },

  async listCalendarOccurrences(
    args: ListOccurrencesParams & { signal?: AbortSignal }
  ) {
    const { cursor, end, endDate, limit, signal, start, startDate } = args;
    const params = new URLSearchParams({ end, start });

    if (startDate) params.set('startDate', startDate);
    if (endDate) params.set('endDate', endDate);
    if (limit !== undefined) params.set('limit', String(limit));
    if (cursor) params.set('cursor', cursor);

    return (
      await dssFetch<CalendarOccurrenceResponse>(
        `/calendar-events?${params.toString()}`,
        { method: 'GET', signal }
      )
    ).map((result) => result);
  },

  async listTeamOutOfOffice(
    args: ListTeamOutOfOfficeParams & { signal?: AbortSignal }
  ) {
    const { end, endDate, limit, signal, start, startDate } = args;
    const params = new URLSearchParams({ end, start });

    if (startDate) params.set('startDate', startDate);
    if (endDate) params.set('endDate', endDate);
    if (limit !== undefined) params.set('limit', String(limit));

    return (
      await dssFetch<TeamOutOfOfficeResponse>(
        `/calendar-events/team-out-of-office?${params.toString()}`,
        { method: 'GET', signal }
      )
    ).map((result) => result);
  },

  async requestToJoinCalendarEvent(eventId: string) {
    return await fetchWithToken<
      CalendarJoinRequest,
      CalendarJoinRequestErrorCode
    >(`${dssHost}/calendar-events/${eventId}/join-requests`, {
      method: 'POST',
      errorResponseHandler: calendarJoinRequestErrorHandler,
    });
  },

  async listCalendarEventJoinRequests(eventId: string) {
    return await dssFetch<CalendarJoinRequestsResponse>(
      `/calendar-events/${eventId}/join-requests`,
      { method: 'GET' }
    );
  },

  async getCalendarEventIcs(eventId: string) {
    return await dssFetch<Uint8Array<ArrayBuffer>>(
      `/calendar-events/${eventId}/ics`,
      { method: 'GET' }
    );
  },

  async getBatchCalendarEventPreviews(args: CalendarMentionPreviewRequest) {
    return (
      await dssFetch<CalendarMentionPreviewResponse>(
        `/calendar-events/preview`,
        {
          method: 'POST',
          body: JSON.stringify(args),
        }
      )
    ).map((result) => result);
  },

  async getSoupItems(args: {
    params: { cursor?: string | null };
    body: PostSoupRequest;
  }) {
    // Could use URLSearchParams?
    const searchParams = args.params.cursor
      ? `?cursor=${args.params.cursor}`
      : '';

    return await dssFetch<SoupPage>(`/items/soup${searchParams}`, {
      method: 'POST',
      body: JSON.stringify(args.body),
    });
  },

  async getSoupAstItems(args: {
    params: { cursor?: string | null };
    body: PostSoupAstRequest;
    signal?: AbortSignal;
  }) {
    const searchParams = args.params.cursor
      ? `?cursor=${args.params.cursor}`
      : '';

    return await dssFetch<SoupPage>(`/items/soup/ast${searchParams}`, {
      method: 'POST',
      body: JSON.stringify(args.body),
      signal: args.signal,
    });
  },

  async getGroupedSoupAstItems(args: {
    params: {
      group_by: PostGroupedSoupAstInitialRequest['group_by'];
      per_group_limit?: number | null;
      sort_method?: GroupedSoupSort;
      sort_property_definition_id?: string | null;
      sort_direction?: PostGroupedSoupAstInitialRequest['sort_direction'];
    };
    body: PostSoupAstRequest;
    signal?: AbortSignal;
  }) {
    const { limit: _limit, ...filters } = args.body;
    const body = {
      ...filters,
      mode: 'initial',
      group_by: args.params.group_by,
      sort_method: args.params.sort_method,
      sort_property_definition_id: args.params.sort_property_definition_id,
      sort_direction: args.params.sort_direction,
      ...(args.params.per_group_limit != null && {
        per_group_limit: args.params.per_group_limit,
      }),
    } satisfies PostGroupedSoupAstRequest;

    return await dssFetch<GroupedSoupInitialPage>(`/items/soup/ast/grouped`, {
      method: 'POST',
      body: JSON.stringify(body),
      signal: args.signal,
    });
  },

  async getGroupedSoupAstGroupPage(args: {
    params: {
      cursor?: string | null;
      group_by: PostGroupedSoupAstGroupPageRequest['group_by'];
      group_key: string;
      limit?: number | null;
      sort_method?: GroupedSoupSort;
      sort_property_definition_id?: string | null;
      sort_direction?: PostGroupedSoupAstGroupPageRequest['sort_direction'];
    };
    body: PostSoupAstRequest;
  }) {
    const params = new URLSearchParams();
    if (args.params.cursor) params.set('cursor', args.params.cursor);
    const searchParams = params.toString() ? `?${params.toString()}` : '';

    const { limit: _limit, ...filters } = args.body;
    const body = {
      ...filters,
      mode: 'group_page',
      group_by: args.params.group_by,
      sort_method: args.params.sort_method,
      sort_property_definition_id: args.params.sort_property_definition_id,
      sort_direction: args.params.sort_direction,
      group_key: args.params.group_key,
      ...(args.params.limit != null && { limit: args.params.limit }),
    } satisfies PostGroupedSoupAstRequest;

    return await dssFetch<GroupedSoupGroupPage>(
      `/items/soup/ast/grouped${searchParams}`,
      {
        method: 'POST',
        body: JSON.stringify(body),
      }
    );
  },

  async createChannel(args: CreateChannelRequest) {
    return (
      await dssFetch<CreateChannelResponse>(`/channels`, {
        method: 'POST',
        body: JSON.stringify(args),
      })
    ).map((result) => result);
  },

  // The channel list is still served by the comms hex, mounted at
  // `/comms/channels` on the same DSS host. Repoint to `/channels` once the
  // list moves into the channels hex (alongside the comms teardown).
  async getChannels(args: {
    cursor?: string;
    limit?: number;
    signal?: AbortSignal;
  }) {
    const params = new URLSearchParams();
    if (args.cursor) params.set('cursor', args.cursor);
    if (args.limit != null) params.set('limit', String(args.limit));
    const query = params.toString();

    return (
      await dssFetch<ApiChannelListPage>(
        `/comms/channels${query ? `?${query}` : ''}`,
        {
          method: 'GET',
          signal: args.signal,
        }
      )
    ).map((result) => result);
  },

  async getBots() {
    return (
      await dssFetch<Bot[]>(`/bots`, {
        method: 'GET',
      })
    ).map((result) => result);
  },

  async getAgents() {
    return (
      await dssFetch<(Agent & WithHarnessId)[]>(`/agents`, {
        method: 'GET',
      })
    ).map((result) => result);
  },

  async createAgent(args: CreateAgentRequest & WithHarnessId) {
    return (
      await dssFetch<Agent & WithHarnessId>(`/agents`, {
        method: 'POST',
        body: JSON.stringify(args),
      })
    ).map((result) => result);
  },

  async updateAgent(args: WithAgentId & UpdateAgentRequest & WithHarnessId) {
    const { agent_id, ...request } = args;
    return (
      await dssFetch<Agent & WithHarnessId>(`/agents/${agent_id}`, {
        method: 'PUT',
        body: JSON.stringify(request),
      })
    ).map((result) => result);
  },

  async getHarnesses() {
    return (
      await dssFetch<Harness[]>(`/harnesses`, {
        method: 'GET',
      })
    ).map((result) => result);
  },

  async getHarnessPairing(args: { code: string }) {
    return (
      await dssFetch<HarnessPairing>(
        `/harness-pairings/${encodeURIComponent(args.code)}`,
        {
          method: 'GET',
        }
      )
    ).map((result) => result);
  },

  async approveHarnessPairing(
    args: { code: string } & ApproveHarnessPairingRequest
  ) {
    const { code, ...request } = args;
    return (
      await dssFetch<Harness>(
        `/harness-pairings/${encodeURIComponent(code)}/approve`,
        {
          method: 'POST',
          body: JSON.stringify(request),
        }
      )
    ).map((result) => result);
  },

  async patchHarness(args: { harness_id: string } & PatchHarnessRequest) {
    const { harness_id, ...request } = args;
    return (
      await dssFetch<Harness>(`/harnesses/${harness_id}`, {
        method: 'PATCH',
        body: JSON.stringify(request),
      })
    ).map((result) => result);
  },

  async deleteHarness(args: { harness_id: string }) {
    return await dssFetch(`/harnesses/${args.harness_id}`, {
      method: 'DELETE',
    });
  },

  async createBot(args: CreateBotRequest) {
    return (
      await dssFetch<Bot>(`/bots`, {
        method: 'POST',
        body: JSON.stringify(args),
      })
    ).map((result) => result);
  },

  async getBot(args: WithBotId) {
    return (
      await dssFetch<Bot>(`/bots/${args.bot_id}`, {
        method: 'GET',
      })
    ).map((result) => result);
  },

  async getBotOwnerProfiles(args: { ids: string[]; signal?: AbortSignal }) {
    const query = new URLSearchParams();
    args.ids.forEach((id) => query.append('ids', id));
    const qs = query.toString();
    return (
      await dssFetch<BotOwnerProfile[]>(`/bots/profiles${qs ? `?${qs}` : ''}`, {
        method: 'GET',
        signal: args.signal,
      })
    ).map((result) => result);
  },

  async patchBot(args: WithBotId & PatchBotRequest) {
    const { bot_id, ...request } = args;
    return (
      await dssFetch<Bot>(`/bots/${bot_id}`, {
        method: 'PATCH',
        body: JSON.stringify(request),
      })
    ).map((result) => result);
  },

  async deleteBot(args: WithBotId) {
    return await dssFetch(`/bots/${args.bot_id}`, {
      method: 'DELETE',
    });
  },

  async createBotToken(args: WithBotId & CreateBotTokenRequest) {
    const { bot_id, ...request } = args;
    return (
      await dssFetch<CreateBotTokenResponse>(`/bots/${bot_id}/tokens`, {
        method: 'POST',
        body: JSON.stringify(request),
      })
    ).map((result) => result);
  },

  async getBotTokens(args: WithBotId) {
    return (
      await dssFetch<BotToken[]>(`/bots/${args.bot_id}/tokens`, {
        method: 'GET',
      })
    ).map((result) => result);
  },

  async revokeBotToken(args: WithBotId & { token_id: string }) {
    return await dssFetch(`/bots/${args.bot_id}/tokens/${args.token_id}`, {
      method: 'DELETE',
    });
  },

  async listAccountManagers() {
    return (
      await dssFetch<AccountManagersList>(`/account-managers`, {
        method: 'GET',
      })
    ).map((result) => result.grants);
  },

  async getAccountManagerGrant(args: { id: string }) {
    return await dssFetch<AccountManagerGrant>(
      `/account-managers/${encodeURIComponent(args.id)}`,
      { method: 'GET' }
    );
  },

  async requestAccountManager(args: RequestAccountManagerBody) {
    return await dssFetch<AccountManagerGrant>(`/account-managers`, {
      method: 'POST',
      body: JSON.stringify(args),
    });
  },

  async respondToAccountManagerRequest(args: {
    id: string;
    decision: AccountManagerDecision;
  }) {
    return await dssFetch<AccountManagerGrant>(
      `/account-managers/${encodeURIComponent(args.id)}/response`,
      { method: 'POST', body: JSON.stringify({ decision: args.decision }) }
    );
  },

  async claimAccountManagerToken(args: { id: string }) {
    return await dssFetch<ClaimedAccountManagerToken>(
      `/account-managers/${encodeURIComponent(args.id)}/token`,
      { method: 'POST' }
    );
  },

  async revokeAccountManagerGrant(args: { id: string }) {
    return await dssFetch<AccountManagerGrant>(
      `/account-managers/${encodeURIComponent(args.id)}`,
      { method: 'DELETE' }
    );
  },

  async listUserApiKeys() {
    return (
      await dssFetch<UserApiKeysList>(`/user-api-keys`, {
        method: 'GET',
      })
    ).map((result) => result.keys);
  },

  async createUserApiKey(args: { name: string }) {
    return (
      await dssFetch<CreatedUserApiKey>(`/user-api-keys`, {
        method: 'POST',
        body: JSON.stringify({ name: args.name }),
      })
    ).map((result) => result);
  },

  async deleteUserApiKey(args: { id: string }) {
    return await dssFetch(`/user-api-keys/${encodeURIComponent(args.id)}`, {
      method: 'DELETE',
    });
  },

  async getBotChannels(args: WithBotId) {
    const { bot_id } = args;
    return (
      await dssFetch<BotChannel[]>(`/bots/${bot_id}/channels`, {
        method: 'GET',
      })
    ).map((result) => result);
  },

  async getChannelBots(args: WithChannelId) {
    return (
      await dssFetch<Bot[]>(`/channels/${args.channel_id}/bots`, {
        method: 'GET',
      })
    ).map((result) => result);
  },

  async addBotToChannel(args: WithChannelId & WithBotId) {
    return await dssFetch(`/channels/${args.channel_id}/bots`, {
      method: 'POST',
      body: JSON.stringify({ bot_id: args.bot_id }),
    });
  },

  async removeBotFromChannel(args: WithBotId & WithChannelId) {
    const { bot_id, channel_id } = args;
    return await dssFetch(`/bots/${bot_id}/channels/${channel_id}`, {
      method: 'DELETE',
    });
  },

  async createChannelScopedBot(
    args: WithChannelId &
      CreateChannelScopedBotRequest & {
        /** Whether mentioning this bot opens a coding-agent session. Defaults to false. */
        has_agent?: boolean;
      }
  ) {
    const { channel_id, ...request } = args;
    return (
      await dssFetch<CreateChannelScopedBotResponse>(
        `/channels/${channel_id}/bots/scoped`,
        {
          method: 'POST',
          body: JSON.stringify(request),
        }
      )
    ).map((result) => result);
  },

  async getOrCreateDirectMessage(args: GetOrCreateDmRequest) {
    const { recipient_id } = args;
    return (
      await dssFetch<GetOrCreateChannelResponse>(`/channels/get_or_create_dm`, {
        method: 'POST',
        body: JSON.stringify({ recipient_id }),
      })
    ).map((result) => result);
  },

  async getOrCreatePrivateChannel(args: GetOrCreatePrivateRequest) {
    const { recipients } = args;
    return (
      await dssFetch<GetOrCreateChannelResponse>(
        `/channels/get_or_create_private`,
        {
          method: 'POST',
          body: JSON.stringify({ recipients }),
        }
      )
    ).map((result) => result);
  },

  async setChannelPicture(args: WithChannelId & SetChannelPictureRequest) {
    const { channel_id, ...request } = args;
    return await dssFetch(`/channels/${channel_id}/profile_picture`, {
      method: 'PUT',
      body: JSON.stringify(request),
    });
  },

  async patchChannel(args: WithChannelId & PatchChannelRequest) {
    const { channel_id, ...request } = args;
    return (
      await dssFetch<MessageResponse>(`/channels/${channel_id}`, {
        method: 'PATCH',
        body: JSON.stringify(request),
      })
    ).map((result) => result);
  },

  async deleteChannel(args: WithChannelId) {
    const { channel_id } = args;
    return (
      await dssFetch<MessageResponse>(`/channels/${channel_id}`, {
        method: 'DELETE',
      })
    ).map((result) => result);
  },

  async addParticipantsToChanenl(args: AddParticipantsRequest & WithChannelId) {
    const { channel_id, participants } = args;
    return (
      await dssFetch<MessageResponse>(`/channels/${channel_id}/participants`, {
        method: 'POST',
        body: JSON.stringify({ participants }),
      })
    ).map((result) => result);
  },

  async addParticipantsToChannel(args: AddParticipantsRequest & WithChannelId) {
    const { channel_id, participants } = args;
    return (
      await dssFetch<MessageResponse>(`/channels/${channel_id}/participants`, {
        method: 'POST',
        body: JSON.stringify({ participants }),
      })
    ).map((result) => result);
  },

  async removeParticipantsFromChannel(
    args: RemoveParticipantsRequest & WithChannelId
  ) {
    const { channel_id, participants } = args;
    return (
      await dssFetch<MessageResponse>(`/channels/${channel_id}/participants`, {
        method: 'DELETE',
        body: JSON.stringify({ participants }),
      })
    ).map((result) => result);
  },

  async joinChannel(args: WithChannelId) {
    const { channel_id } = args;
    return (
      await dssFetch<MessageResponse>(`/channels/${channel_id}/join`, {
        method: 'POST',
      })
    ).map((result) => result);
  },

  async getChannelJoinLink(args: WithChannelId) {
    return await dssFetch<ChannelJoinCodeResponse>(
      `/channels/${args.channel_id}/join-link`,
      { method: 'GET' }
    );
  },

  async joinChannelByCode(args: { join_code: string }) {
    return await dssFetch(`/channels/join/${args.join_code}`, {
      method: 'POST',
    });
  },

  async getMyChannelAccessRequest(args: WithChannelId) {
    return await dssFetch<ChannelAccessRequestState>(
      `/channels/${args.channel_id}/access-requests/mine`
    );
  },

  async requestChannelAccess(args: WithChannelId) {
    return await dssFetch<ChannelAccessRequest>(
      `/channels/${args.channel_id}/access-requests/mine`,
      { method: 'PUT' }
    );
  },

  async cancelChannelAccessRequest(args: WithChannelId) {
    return await dssFetch(`/channels/${args.channel_id}/access-requests/mine`, {
      method: 'DELETE',
    });
  },

  async getChannelAccessRequest(args: WithChannelId & { request_id: string }) {
    return await dssFetch<ChannelAccessRequest>(
      `/channels/${args.channel_id}/access-requests/${args.request_id}`
    );
  },

  async resolveChannelAccessRequest(
    args: WithChannelId & {
      request_id: string;
      decision: ChannelAccessDecision;
    }
  ) {
    return await dssFetch<ChannelAccessRequest>(
      `/channels/${args.channel_id}/access-requests/${args.request_id}/resolve`,
      {
        method: 'POST',
        body: JSON.stringify({ decision: args.decision }),
      }
    );
  },

  async leaveChannel(args: WithChannelId) {
    const { channel_id } = args;
    return (
      await dssFetch<MessageResponse>(`/channels/${channel_id}/leave`, {
        method: 'POST',
      })
    ).map((result) => result);
  },

  async getBatchChannelPreviews(args: GetBatchChannelPreviewRequest) {
    const { channel_ids } = args;
    return (
      await dssFetch<GetBatchChannelPreviewResponse>(`/channels/preview`, {
        method: 'POST',
        body: JSON.stringify({ channel_ids }),
      })
    ).map((result) => result);
  },

  async getChannelAttachments(
    args: WithChannelId & {
      limit: number;
      cursor: string | null;
      attachment_type?: ChannelAttachmentType;
      signal?: AbortSignal;
    }
  ) {
    const { channel_id, limit, cursor, attachment_type, signal } = args;
    const params = new URLSearchParams();
    params.append('limit', limit.toString());
    if (cursor) params.append('cursor', cursor);
    if (attachment_type) params.append('attachment_type', attachment_type);
    return (
      await dssFetch<ApiChannelAttachmentsPage>(
        `/channels/${channel_id}/attachments?${params.toString()}`,
        { method: 'GET', signal }
      )
    ).map((result) => result);
  },

  async getChannelParticipants(args: WithChannelId) {
    const { channel_id } = args;
    return (
      await dssFetch<ApiChannelParticipant[]>(
        `/channels/${channel_id}/participants`,
        { method: 'GET' }
      )
    ).map((result) => result);
  },

  async createEntityMention(args: CreateEntityMentionRequest, token?: string) {
    return (
      await dssFetch<CreateEntityMentionResponse>(`/channels/mentions`, {
        method: 'POST',
        body: JSON.stringify(args),
        headers: token ? { 'x-permissions-token': token } : undefined,
      })
    ).map((result) => result);
  },

  async deleteEntityMention(args: WithMentionId, token?: string) {
    return (
      await dssFetch<DeleteEntityMentionResponse>(
        `/channels/mentions/${args.mention_id}`,
        {
          method: 'DELETE',
          headers: token ? { 'x-permissions-token': token } : undefined,
        }
      )
    ).map((result) => result);
  },

  async attachmentReferences(args: WithEntity) {
    const { entity_type, entity_id } = args;
    return (
      await dssFetch<GetAttachmentReferencesResponse>(
        `/channels/attachments/${entity_type}/${entity_id}/references`,
        { method: 'GET' }
      )
    ).map((result) => result);
  },

  async getActivity() {
    return (
      await dssFetch<Array<ApiActivity>>(`/channels/activity`, {
        method: 'GET',
      })
    ).map((result) => result);
  },

  async postActivity(args: PostActivityRequest) {
    const { activity_type, channel_id } = args;
    return (
      await dssFetch<ApiActivity>(`/channels/activity`, {
        method: 'POST',
        body: JSON.stringify({ activity_type, channel_id }),
      })
    ).map((result) => result);
  },

  permissionsTokens: {
    // Uses SYNC_PERMISSION_TOKEN_DSS_HOST instead of dssFetch so that tokens are
    // always signed by the DSS whose JWT secret matches the sync service's secret.
    async createPermissionToken(args) {
      return await fetchWithToken<GetDocumentPermissionsTokenResponse>(
        `${SYNC_PERMISSION_TOKEN_DSS_HOST}/documents/permissions_token/${args.document_id}`,
        {
          method: 'POST',
        }
      );
    },
    async validatePermissionToken(args) {
      return await dssFetch<ValidateDocumentPermissionsTokenResponse>(
        `/documents/permissions_token`,
        {
          method: 'POST',
          body: JSON.stringify(args),
        }
      );
    },
  },

  collabSurfaces: {
    async ensure(args) {
      return await dssFetch<CollabSurfaceResponse>(
        `/collab_surfaces/${args.id}`,
        {
          method: 'PUT',
          body: JSON.stringify({
            parentEntityType: args.parentEntityType,
            parentEntityId: args.parentEntityId,
            initialMarkdown: args.initialMarkdown ?? '',
          }),
        }
      );
    },
    async get(args) {
      return await dssFetch<CollabSurfaceResponse>(
        `/collab_surfaces/${args.id}`
      );
    },
    // Uses SYNC_PERMISSION_TOKEN_DSS_HOST (like createPermissionToken) so the
    // token is always signed by the DSS whose JWT secret matches the sync
    // service's secret.
    async createToken(args) {
      return await fetchWithToken<CollabSurfaceTokenResponse>(
        `${SYNC_PERMISSION_TOKEN_DSS_HOST}/collab_surfaces/${args.id}/token`,
        {
          method: 'POST',
        }
      );
    },
    async delete(args) {
      return await dssFetch(`/collab_surfaces/${args.id}`, {
        method: 'DELETE',
      });
    },
  },
  async getUsersHistory() {
    return (await dssFetch<{ data: Item[] }>(`/history`)).map((result) => ({
      data: result.data,
    }));
  },

  async upsertItemToUserHistory({ itemType, itemId }) {
    return (
      await dssFetch<SuccessResponse>(`/history/${itemType}/${itemId}`, {
        method: 'POST',
      })
    ).map((result) => result.data);
  },

  async removeItemFromUserHistory(params: {
    itemId: string;
    itemType: ItemType;
  }) {
    return (
      await dssFetch<SuccessResponse>(
        `/history/${params.itemType}/${params.itemId}`,
        {
          method: 'DELETE',
        }
      )
    ).map((result) => result.data);
  },

  async editDocument(params) {
    const { documentId, ...body } = params;
    return (
      await dssFetch<SuccessResponse>(`/documents/${documentId}`, {
        method: 'PATCH',
        body: JSON.stringify(body),
      })
    ).map((result) => result.data);
  },

  async getUserDocuments(params: { limit: number; offset: number }) {
    return (
      await dssFetch<{
        data: {
          documents: DocumentMetadata[];
          total: number;
          next_offset: number;
        };
      }>(`/documents?limit=${params.limit}&offset=${params.offset}`)
    ).map((result) => ({
      documents: result.data.documents,
      total: result.data.total,
      nextOffset: result.data.next_offset,
    }));
  },

  async initializeUserDocuments() {
    return (
      await dssFetch<{ success: boolean }>(
        '/documents/initialize_user_documents',
        {
          method: 'POST',
        }
      )
    ).map((result) => result);
  },

  async deleteDocument(params: { documentId: string }) {
    return (
      await dssFetch<SuccessResponse>(`/documents/${params.documentId}`, {
        method: 'DELETE',
      })
    ).map((result) => result.data);
  },

  async getPins() {
    return (await dssFetch<{ data: UserPins }>('/pins')).map(
      (result) => result.data
    );
  },

  async pinItem(params: { id: string } & AddPinRequest) {
    const { id, ...body } = params;
    return (
      await dssFetch<SuccessResponse>(`/pins/${id}`, {
        method: 'POST',
        body: JSON.stringify(body),
      })
    ).map((result) => result.data);
  },

  async removePin(params: { id: string } & PinRequest) {
    const { id, ...body } = params;
    return (
      await dssFetch<SuccessResponse>(`/pins/${id}`, {
        method: 'DELETE',
        body: JSON.stringify(body),
      })
    ).map((result) => result.data);
  },

  async reorderPins(params: { pins: Array<ReorderPinRequest> }) {
    return (
      await dssFetch<SuccessResponse>(`/pins`, {
        method: 'PATCH',
        body: JSON.stringify(params.pins),
      })
    ).map((result) => result.data);
  },

  async getDocumentMetadata(params: {
    documentId: string;
    documentVersionId?: number;
    init?: SafeFetchInit;
  }) {
    const versionSuffix = params.documentVersionId
      ? `/${params.documentVersionId}`
      : '';
    const fetchOptions: SafeFetchInit = {
      ...params.init,
      retry: {
        delay: 'exponential',
        maxTries: 5,
      },
    };
    return (
      await dssFetch<{
        data: GetDocumentResponseData;
      }>(`/documents/${params.documentId}${versionSuffix}`, fetchOptions)
    ).map((result) => {
      const data = result.data;
      return {
        ...data,
        documentMetadata: data.documentMetadata,
      };
    });
  },

  async getDocumentByTeamSlug(params: { slug: string; signal?: AbortSignal }) {
    return (
      await dssFetch<{
        data: GetDocumentResponseData;
      }>(`/documents/slug/${encodeURIComponent(params.slug)}`, {
        signal: params.signal,
      })
    ).map((result) => result.data);
  },

  async createDocument(request: CreateDocumentRequest) {
    const result = await fetchWithToken<
      CreateDocumentResponse,
      typeof DOCUMENT_NAME_TOO_LONG_CODE
    >(`${dssHost}/documents`, {
      method: 'POST',
      body: JSON.stringify(request),
      // A custom handler replaces safeFetch's default status mapping. For an
      // over-length name the backend returns a machine-readable code plus the
      // limit; forward both (limit carried as JSON in message, since ResultError
      // is only { code, message }) so the UI can render its own copy without
      // hardcoding the number. 403 is preserved explicitly; other statuses keep
      // the HTTP_ERROR shape callers branch on.
      errorResponseHandler: async (response) => {
        const body = (await response.json().catch(() => null)) as {
          code?: string;
          maxLength?: number;
        } | null;
        if (body?.code === DOCUMENT_NAME_TOO_LONG_CODE) {
          return {
            code: DOCUMENT_NAME_TOO_LONG_CODE,
            message: JSON.stringify({ maxLength: body.maxLength }),
          };
        }
        if (response.status === 403) {
          return { code: 'FORBIDDEN', message: 'Forbidden' };
        }
        return {
          code: 'HTTP_ERROR',
          message: `HTTP error! status: ${response.status}`,
        };
      },
    });

    if (!result.isOk()) {
      // The DOCUMENT_NAME_TOO_LONG code is carried at runtime for callers to
      // branch on, but it is not part of the generated client's error union, so
      // narrow back to it to satisfy StorageServiceClient.
      const errors = result.error as ResultError<FetchWithTokenErrorCode>[];

      if (errors[0].message.includes('403')) {
        showPaywall(PaywallKey.FILE_LIMIT);
      }
      return err(errors);
    }

    const { data } = result.value;

    if (!data.presignedUrl) {
      console.error('no presigned url found for upload');
      return err([{ code: 'SERVER_ERROR', message: 'Failed to upload file' }]);
    }

    return ok({
      metadata: data.documentMetadata,
      presignedUrl: data.presignedUrl,
      contentType: data.contentType,
      fileType: data.fileType ?? undefined,
    });
  },

  async createSpreadsheetDocument(request: {
    documentName: string;
    projectId?: string;
    sha: string;
  }) {
    const result = await dssFetch<CreateDocumentResponse>('/documents', {
      method: 'POST',
      body: JSON.stringify({ ...request, fileType: 'spreadsheet' }),
    });
    return result.andThen(({ data }) => {
      if (data.presignedUrl) {
        return err([
          {
            code: 'INVALID_RESPONSE' as const,
            message: 'The server does not support native spreadsheets yet.',
          },
        ]);
      }
      return ok({ metadata: data.documentMetadata });
    });
  },

  /**
   * Creates a native Canvas with durable shared content ready before returning.
   */
  async createCanvasDocument(request: CreateCanvasDocumentRequest) {
    return dssFetch<CreateCanvasDocumentResponse>('/documents/create_canvas', {
      method: 'POST',
      body: JSON.stringify(request),
    });
  },

  /** Creates a markdown document and initializes its sync-service content on the backend. */
  async createMarkdownDocument(request: CreateMarkdownDocumentRequest) {
    const result = await dssFetch<CreateMarkdownHandler200>(
      `/documents/create_markdown`,
      {
        method: 'POST',
        body: JSON.stringify(request),
      }
    );

    if (!result.isOk()) {
      const errors = result.error;
      if (errors[0].message.includes('403')) {
        showPaywall(PaywallKey.FILE_LIMIT);
      }
      return err(result.error);
    }

    const response = result.value;
    return ok({
      documentId: response.documentId,
      documentMetadata: response.documentMetadata,
      token: response.token,
    });
  },

  /**
   * Creates a task with properties and initializes its sync-service content on the backend.
   */
  async createTask(request: CreateTaskRequest) {
    const result = await dssFetch<CreateTaskHandler200>(
      `/documents/create_task`,
      {
        method: 'POST',
        body: JSON.stringify(request),
      }
    );

    if (!result.isOk()) {
      const errors = result.error;
      if (errors[0].message.includes('403')) {
        showPaywall(PaywallKey.FILE_LIMIT);
      }
      return err(result.error);
    }

    const response = result.value;
    return ok(response);
  },

  /**
   * Creates a snippet and initializes its sync-service content on the backend.
   * Snippets are created personal; team sharing is toggled separately via
   * setDocumentTeamShare.
   */
  async createSnippet(request: CreateSnippetRequest) {
    const result = await dssFetch<CreateSnippetHandler200>(
      `/documents/create_snippet`,
      {
        method: 'POST',
        body: JSON.stringify(request),
      }
    );

    if (!result.isOk()) {
      const errors = result.error;
      if (errors[0].message.includes('403')) {
        showPaywall(PaywallKey.FILE_LIMIT);
      }
      return err(result.error);
    }

    const response = result.value;
    return ok(response);
  },

  /**
   * Creates a skill and initializes its sync-service content on the backend.
   * Skills are markdown documents containing instructions that AI reads and
   * follows when the skill is referenced in an AI input.
   */
  async createSkill(request: CreateSkillRequest) {
    const result = await dssFetch<CreateSkillHandler200>(
      `/documents/create_skill`,
      {
        method: 'POST',
        body: JSON.stringify(request),
      }
    );

    if (!result.isOk()) {
      const errors = result.error;
      if (errors[0].message.includes('403')) {
        showPaywall(PaywallKey.FILE_LIMIT);
      }
      return err(result.error);
    }

    const response = result.value;
    return ok(response);
  },

  /**
   * Lists the built-in system skills. System skills are static, code-defined
   * AI instructions with well-known ids; they surface like skill documents
   * but have no document behind them and must not be opened as documents.
   */
  async getSystemSkills() {
    return dssFetch<GetSystemSkillsHandler200>(`/documents/system_skills`, {
      method: 'GET',
    });
  },

  async getSnippetRaw(args: {
    documentId: string;
  }): Promise<SerializedEditorState> {
    const token = await getDocumentPermissionToken(args.documentId);
    const response = await platformFetch(
      `${syncServiceWorkerHost}/document/${args.documentId}/raw`,
      {
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
          ...(isTauri() && { Origin: syncOrigin }),
        },
        method: 'GET',
      }
    );

    if (!response.ok) {
      try {
        console.error('Failed to fetch raw snippet', await response.text());
      } catch (_e) {
        console.error('Failed to fetch raw snippet');
      }
      throw new Error('Failed to fetch raw snippet');
    }

    return await response.json();
  },

  /**
   * Gets the team-share state of a document (resolved against the owner's team).
   */
  /** When to use a skill; `description` is absent for older skills. */
  async getSkillDescription(args: { documentId: string }) {
    return await dssFetch<SkillDescriptionBody>(
      `/documents/${args.documentId}/skill_description`
    );
  },

  /** Sets when to use a skill: one line starting "Use when". */
  async setSkillDescription(args: { documentId: string; description: string }) {
    return await dssFetch<SkillDescriptionBody>(
      `/documents/${args.documentId}/skill_description`,
      {
        method: 'PUT',
        body: JSON.stringify({ description: args.description }),
      }
    );
  },

  async getDocumentTeamShare(args: { documentId: string }) {
    return await dssFetch<DocumentTeamShareResponse>(
      `/documents/${args.documentId}/team_share`
    );
  },

  /**
   * Shares or unshares a document with the owner's team. Sharing grants the
   * team Edit access.
   */
  async setDocumentTeamShare(args: {
    documentId: string;
    shareWithTeam: boolean;
  }) {
    return await dssFetch<DocumentTeamShareResponse>(
      `/documents/${args.documentId}/team_share`,
      {
        method: 'PUT',
        body: JSON.stringify({ shareWithTeam: args.shareWithTeam }),
      }
    );
  },

  async getTaskDuplicates(params: { documentId: string }) {
    return (
      await dssFetch<TaskDuplicatesResponse>(
        `/documents/${params.documentId}/duplicates`
      )
    ).map((result) => result.duplicates);
  },

  async searchSimilarTasks(params: { taskName: string; markdown?: string }) {
    return (
      await dssFetch<TaskSimilaritySearchResponse>(
        `/documents/similarity_search`,
        {
          method: 'POST',
          body: JSON.stringify({
            taskName: params.taskName,
            markdown: params.markdown,
          }),
        }
      )
    ).map((result) => result.results);
  },

  async dismissTaskDuplicates(params: {
    documentId: string;
    matchIds: string[];
  }) {
    return (
      await dssFetch<SuccessResponse>(
        `/documents/${params.documentId}/duplicates/dismiss`,
        {
          method: 'POST',
          body: JSON.stringify({ matchIds: params.matchIds }),
        }
      )
    ).map((result) => result.data);
  },

  async deleteThisDuplicateTask(params: {
    documentId: string;
    matchId: string;
  }) {
    return (
      await dssFetch<SuccessResponse>(
        `/documents/${params.documentId}/duplicates/${params.matchId}/delete_this`,
        {
          method: 'POST',
        }
      )
    ).map((result) => result.data);
  },

  async copyDocument(params: {
    documentId: string;
    documentVersionId?: number;
    documentName: string;
    syncServiceVersion?: SyncServiceVersionID;
  }) {
    const { documentId, documentVersionId, syncServiceVersion, ...body } =
      params;
    const copyResult = await dssFetch<{
      data: { documentMetadata: DocumentResponseMetadataWithContent };
    }>(
      `/documents/${documentId}/copy${documentVersionId ? `?version_id=${documentVersionId}` : ''}`,
      {
        method: 'POST',
        body: JSON.stringify({
          ...body,
          versionId: syncServiceVersion,
        }),
      }
    );

    const result: Result<
      DocumentResponseMetadataWithContent,
      ResultError<FetchWithTokenErrorCode>[]
    > = copyResult.map((result) => result.data.documentMetadata);

    if (result.isErr()) {
      const errors = result.error;

      if (errors[0].message.includes('403')) {
        showPaywall(PaywallKey.FILE_LIMIT);
      }
      return err(result.error);
    }
    return result;
  },

  async permanentlyDeleteDocument({ documentId }) {
    return (
      await dssFetch<SuccessResponse>(`/documents/${documentId}/permanent`, {
        method: 'DELETE',
      })
    ).map((result) => result.data);
  },

  async revertDocumentDelete({ documentId }) {
    return (
      await dssFetch<SuccessResponse>(
        `/documents/${documentId}/revert_delete`,
        {
          method: 'PUT',
        }
      )
    ).map((result) => result.data);
  },

  async fetchCachedSnapshot(
    documentId: string
  ): Promise<Result<Uint8Array, ResultError<FetchWithTokenErrorCode>[]>> {
    return dssFetch<Uint8Array>(
      `/documents/${documentId}/cached_snapshot_url`,
      { trace: { expectedStatusCodes: [404] } }
    );
  },

  async getDocumentShortId({
    documentId,
  }: {
    documentId: string;
  }): Promise<Result<string, ResultError<FetchWithTokenErrorCode>[]>> {
    return (
      await dssFetch<{ shortId: string }>(`/documents/${documentId}/short_id`, {
        method: 'GET',
      })
    ).map((result) => result.shortId);
  },

  async getDocumentBranchName({
    documentId,
  }: {
    documentId: string;
  }): Promise<
    Result<
      { shortId: string; branchName: string },
      ResultError<FetchWithTokenErrorCode>[]
    >
  > {
    return (
      await dssFetch<{ shortId: string; branchName: string }>(
        `/documents/${documentId}/branch_name`,
        { method: 'GET' }
      )
    ).map((result) => ({
      shortId: result.shortId,
      branchName: result.branchName,
    }));
  },

  async getDocumentGithubPullRequests({
    documentId,
  }: {
    documentId: string;
  }): Promise<
    Result<GithubPullRequestsResponse, ResultError<FetchWithTokenErrorCode>[]>
  > {
    return await dssFetch<GithubPullRequestsResponse>(
      `/documents/${documentId}/github_prs`,
      { method: 'GET' }
    );
  },

  /** The tasks each pull request (`owner/repo/pull/number`, at most 100) references. */
  async getGithubPullRequestTasks({
    githubKeys,
  }: {
    githubKeys: string[];
  }): Promise<
    Result<
      GithubPullRequestTasksResponse,
      ResultError<FetchWithTokenErrorCode>[]
    >
  > {
    return await dssFetch<GithubPullRequestTasksResponse>(
      '/documents/github_prs/tasks',
      { method: 'POST', body: JSON.stringify({ githubKeys }) }
    );
  },

  async getForeignEntity({
    id,
  }: {
    id: string;
  }): Promise<Result<ForeignEntity, ResultError<FetchWithTokenErrorCode>[]>> {
    return await dssFetch<ForeignEntity>(
      `/foreign_entity/${encodeURIComponent(id)}`,
      {
        method: 'GET',
      }
    );
  },

  /**
   * Look a foreign entity up by the identifier its source system assigned,
   * e.g. `owner/repo/pull/12` for `github_pull_request`. The identifier is a
   * wildcard path segment, so its slashes are kept and only the segments
   * themselves are escaped.
   */
  async getForeignEntityBySource({
    source,
    foreignEntityId,
  }: {
    source: string;
    foreignEntityId: string;
  }): Promise<Result<ForeignEntity, ResultError<FetchWithTokenErrorCode>[]>> {
    const encodedForeignEntityId = foreignEntityId
      .split('/')
      .map((segment) => encodeURIComponent(segment))
      .join('/');

    return await dssFetch<ForeignEntity>(
      `/foreign_entity/by_source/${encodeURIComponent(source)}/${encodedForeignEntityId}`,
      { method: 'GET' }
    );
  },

  /**
   * Repositories and authors among the GitHub pull requests visible to the
   * caller and their team, most pull requests first.
   */
  async getGithubPullRequestFacets(): Promise<
    Result<GithubPullRequestFacets, ResultError<FetchWithTokenErrorCode>[]>
  > {
    return await dssFetch<GithubPullRequestFacets>(
      '/github_pull_requests/facets',
      { method: 'GET' }
    );
  },

  /** The pull request behind a foreign entity record the caller can view. */
  async getGithubPullRequest({
    id,
  }: {
    id: string;
  }): Promise<
    Result<StoredGithubPullRequest, ResultError<FetchWithTokenErrorCode>[]>
  > {
    return await dssFetch<StoredGithubPullRequest>(
      `/github_pull_requests/${id}`,
      { method: 'GET' }
    );
  },

  /**
   * The changes of that pull request at its current base and head, or why
   * GitHub could not provide them.
   */
  async getGithubPullRequestChanges({
    id,
  }: {
    id: string;
  }): Promise<
    Result<
      GithubPullRequestChangesResponse,
      ResultError<FetchWithTokenErrorCode>[]
    >
  > {
    return await dssFetch<GithubPullRequestChangesResponse>(
      `/github_pull_requests/${id}/changes`,
      { method: 'GET' }
    );
  },

  /** The patch of one changeset of that pull request. */
  async getGithubPullRequestChangesPatch({
    id,
    changeset,
  }: {
    id: string;
    changeset: string;
  }): Promise<
    Result<
      GithubPullRequestChangesPatchResponse,
      ResultError<FetchWithTokenErrorCode>[]
    >
  > {
    return await dssFetch<GithubPullRequestChangesPatchResponse>(
      `/github_pull_requests/${id}/changes/patch?changeset=${encodeURIComponent(changeset)}`,
      { method: 'GET' }
    );
  },

  async exportDocument({ documentId }) {
    return (
      await dssFetch<ExportDocumentResponse>(
        `/documents/${documentId}/export`,
        {
          method: 'GET',
        }
      )
    ).map((result) => result);
  },

  async uploadModificationData(uploadData: unknown) {
    return (
      await dssFetch<SuccessResponse>(`/documents/metadata/modification-data`, {
        method: 'PATCH',
        body: JSON.stringify(uploadData, modificationDataReplacer),
      })
    ).map((result) => result.data);
  },

  async getBatchDocumentPreviews(args: { document_ids: string[] }) {
    return (
      await dssFetch<{ previews: DocumentPreview[] }>(`/documents/preview`, {
        method: 'POST',
        body: JSON.stringify({ document_ids: args.document_ids }),
      })
    ).map((result) => ({
      previews: result.previews,
    }));
  },

  async getBatchCallPreviews(args: { call_ids: string[] }) {
    return (
      await dssFetch<{ previews: CallRecordPreview[] }>(
        `/call/record/preview`,
        {
          method: 'POST',
          body: JSON.stringify({ callIds: args.call_ids }),
        }
      )
    ).map((result) => ({
      previews: result.previews,
    }));
  },

  async getDocumentProcessingResult<T extends ProcessingResultType>(params: {
    documentId: string;
    type: T;
  }) {
    const result = await dssFetch<GetDocumentProcessingResultResponse>(
      `/documents/${params.documentId}/processing`
    );
    if (!result.isOk()) return err(result.error);

    const { data } = result.value;

    if (!data?.result) {
      return err([
        { code: 'INVALID_RESPONSE', message: 'Processing result is missing' },
      ]);
    }
    switch (params.type) {
      case 'PREPROCESS': {
        const parseResult = CoParseSchema.safeParse(JSON.parse(data.result));
        return parseResult.success
          ? ok({
              preprocess: parseResult.data,
            })
          : err([
              {
                code: 'INVALID_RESPONSE',
                message: 'Invalid PREPROCESS result',
              },
            ]);
      }
      default:
        return err([
          { code: 'INVALID_RESPONSE', message: `Invalid type ${params.type}` },
        ]);
    }
  },
  async getJobProcessingResult<T extends ProcessingResultType>(params: {
    jobId: string;
    documentId: string;
    type: T;
  }) {
    const result = await dssFetch<GetDocumentProcessingResultResponse>(
      `/documents/${params.documentId}/processing/${params.jobId}`
    );
    if (!result.isOk()) return err(result.error);

    const { data } = result.value;

    if (!data?.result) {
      return err([
        { code: 'INVALID_RESPONSE', message: 'Processing result is missing' },
      ]);
    }
    switch (params.type) {
      case 'PREPROCESS': {
        const parseResult = CoParseSchema.safeParse(JSON.parse(data.result));
        return parseResult.success
          ? ok({
              preprocess: parseResult.data,
            })
          : err([
              {
                code: 'INVALID_RESPONSE',
                message: 'Invalid PREPROCESS result',
              },
            ]);
      }
      default:
        return err([
          { code: 'INVALID_RESPONSE', message: `Invalid type ${params.type}` },
        ]);
    }
  },

  async listDocuments() {
    return (await dssFetch<GetDocumentSearchResponse>(`/documents/list`)).map(
      (result) => ({ documents: result.data })
    );
  },

  async pdfSave(params: {
    documentId: string;
    modificationData: IModificationDataOnServer;
    sha: string;
  }) {
    const { documentId, modificationData, sha } = params;
    const modificationDataString = JSON.stringify(
      modificationData,
      modificationDataReplacer
    );
    const attemptParse = IModificationDataOnServerSchema.safeParse(
      JSON.parse(modificationDataString)
    );
    if (!attemptParse.success) {
      return err([
        { code: 'INVALID_DATA', message: 'Invalid modification data to save' },
      ]);
    }

    const body = `{ "sha": "${sha}", "modificationData": ${modificationDataString} }`;
    const result = await dssFetch<{ data: SaveDocumentResponseData }>(
      `/documents/${documentId}`,
      {
        method: 'PUT',
        body,
      }
    );
    if (!result.isOk()) return err(result.error);

    const { data } = result.value;

    const metadata =
      saveDocumentHandlerResponse.shape.data.shape.documentMetadata.safeParse(
        data.documentMetadata
      );
    if (!metadata.success) {
      return err([
        {
          code: 'INVALID_RESPONSE',
          message: 'Invalid document metadata in server response',
        },
      ]);
    }
    return ok(metadata.data);
  },

  async simpleSave(params) {
    const formData = new FormData();
    formData.append('file', params.file);

    const result = await dssFetch<{ data: SaveDocumentResponseData }>(
      `/documents/${params.documentId}/simple_save`,
      {
        method: 'PUT',
        body: formData,
      }
    );
    if (!result.isOk()) return err(result.error);

    const { data } = result.value;

    const metadata =
      saveDocumentHandlerResponse.shape.data.shape.documentMetadata.safeParse(
        data.documentMetadata
      );
    if (!metadata.success) {
      return err([
        {
          code: 'INVALID_RESPONSE',
          message: 'Invalid document metatdata in server response',
        },
      ]);
    }
    return ok(metadata.data);
  },

  annotations: {
    async getAnchors({ documentId }) {
      return (
        await dssFetch<AnchorResponse>(
          `/annotations/anchors/document/${documentId}`,
          {
            method: 'GET',
          }
        )
      ).map((result) => ({ data: result.data }));
    },
    async createAnchor({ documentId, body }) {
      return (
        await dssFetch<CreateUnthreadedAnchorResponse>(
          `/annotations/anchors/document/${documentId}`,
          {
            method: 'POST',
            body: JSON.stringify(body),
          }
        )
      ).map((result) => result);
    },
    async deleteAnchor({ body }) {
      return (
        await dssFetch<DeleteUnthreadedAnchorResponse>(`/annotations/anchors`, {
          method: 'DELETE',
          body: JSON.stringify(body),
        })
      ).map((result) => result);
    },
    async editAnchor({ body }) {
      return (
        await dssFetch<EditAnchorResponse>(`/annotations/anchors`, {
          method: 'PATCH',
          body: JSON.stringify(body),
        })
      ).map((result) => result);
    },
  },

  getDocxFile: cache(
    async function getDocxFile(
      args
    ): Promise<
      Result<
        GetDocxFileResponse,
        ResultError<FetchError | 'INVALID_FILETYPE' | 'INVALID_DOCUMENT'>[]
      >
    > {
      const { documentId, documentVersionId } = args;
      let metadataResult, locationResult;
      // avoids running requests sequentially if the version ID is known
      if (documentVersionId != null) {
        const versionId = documentVersionId.toString();
        [metadataResult, locationResult] = await Promise.all([
          storageServiceClient.getDocumentMetadata({
            documentId,
            documentVersionId,
          }),
          args.withoutParts
            ? (Promise.resolve(ok({ presignedUrls: [] })) as ReturnType<
                typeof storageServiceClient.getWriterPartUrls
              >)
            : storageServiceClient.getWriterPartUrls({
                uuid: documentId,
                versionId,
              }),
        ]);
      } else {
        metadataResult = await storageServiceClient.getDocumentMetadata(args);
        if (metadataResult.isErr()) return err(metadataResult.error);
        const { documentMetadata: metadata } = metadataResult.value;
        const versionId = metadata.documentVersionId.toString();
        locationResult = args.withoutParts
          ? await (Promise.resolve(ok({ presignedUrls: [] })) as ReturnType<
              typeof storageServiceClient.getWriterPartUrls
            >)
          : await storageServiceClient.getWriterPartUrls({
              uuid: documentId,
              versionId,
            });
      }

      if (locationResult.isErr()) {
        return err(locationResult.error);
      }

      if (metadataResult.isErr()) {
        return err(metadataResult.error);
      }

      const info = locationResult.value;
      const { documentMetadata: metadata, userAccessLevel } =
        metadataResult.value;

      if (metadata.fileType !== 'docx') {
        return err([
          { code: 'INVALID_FILETYPE', message: metadata.fileType ?? 'unknown' },
        ]);
      }

      if (
        !args.withoutParts &&
        (info.presignedUrls == null || metadata.documentBom == null)
      ) {
        return err([
          { code: 'INVALID_DOCUMENT', message: 'Document has no parts' },
        ]);
      }

      return ok<GetDocxFileResponse>({
        parts: info.presignedUrls ?? [],
        metadata: metadata as any,
        canEdit: userAccessLevel !== 'view',
        userAccessLevel,
      });
    },
    {
      seconds: 10,
    }
  ),

  getTextDocument: cache(
    async function getTextDocument(args) {
      const metadataResult =
        await storageServiceClient.getDocumentMetadata(args);
      if (metadataResult.isErr()) return err(metadataResult.error);
      const { documentMetadata, userAccessLevel } = metadataResult.value;
      const locationResult = await storageServiceClient.getDocumentLocation({
        documentId: documentMetadata.documentId,
        versionId: documentMetadata.documentVersionId,
      });
      if (
        locationResult.isErr() &&
        locationResult.error.some((error) => error.code === 'GONE')
      )
        return err([
          {
            code: 'NOT_FOUND',
            message: 'The document resource is no longer available',
          },
        ]);
      else if (locationResult.isErr()) return err(locationResult.error);
      const { data } = locationResult.value;
      if (data.type !== 'presignedUrl') {
        return err([
          {
            code: 'INVALID_DOCUMENT',
            message: 'Document location is missing presignedUrl',
          },
        ]);
      }

      const result = await fetchPresigned(data.presignedUrl, 'text');
      if (result.isErr()) return err(result.error);
      const text = result.value;
      return ok({
        text,
        documentMetadata,
        userAccessLevel,
      });
    } as StorageServiceClient['getTextDocument'],
    {
      seconds: 2, // arbitrarily short, but long enough to preload
    }
  ),

  async getBinaryDocument(
    args
  ): Promise<
    Result<
      GetDocumentResponseData & { blobUrl: string },
      ResultError<FetchError | 'INVALID_DOCUMENT'>[]
    >
  > {
    const maybeDocument = await storageServiceClient.getDocumentMetadata(args);

    if (maybeDocument.isErr()) {
      console.error('error in getDocument', maybeDocument);
      return err(maybeDocument.error);
    }
    const documentData = maybeDocument.value;
    const {
      documentMetadata: { documentId, documentVersionId: versionId },
    } = documentData;

    const maybeLocation = await storageServiceClient.getDocumentLocation({
      documentId,
      versionId,
    });
    if (maybeLocation.isErr()) {
      console.error('error in getLocation', maybeLocation);
      return err(maybeLocation.error);
    }

    const { data } = maybeLocation.value;
    if (data.type !== 'presignedUrl') {
      return err([
        {
          code: 'INVALID_DOCUMENT',
          message: 'Document location is missing presignedUrl',
        },
      ]);
    }

    return ok({
      ...documentData,
      blobUrl: data.presignedUrl,
    });
  },

  async simpleSaveText(params) {
    const formData = new FormData();
    formData.append('file', new Blob([params.text], { type: params.mimeType }));

    const result = await dssFetch<{ data: SaveDocumentResponseData }>(
      `/documents/${params.documentId}/simple_save`,
      {
        method: 'PUT',
        body: formData,
      }
    );
    if (!result.isOk()) return err(result.error);

    const { data } = result.value;

    const metadata =
      saveDocumentHandlerResponse.shape.data.shape.documentMetadata.safeParse(
        data.documentMetadata
      );
    if (!metadata.success) {
      return err([
        {
          code: 'INVALID_RESPONSE',
          message: 'Invalid document metatdata in server response',
        },
      ]);
    }
    return ok(metadata.data);
  },

  getWriterPartUrls: cache(
    // this can be cached because it requires the version ID
    async function getWriterPartUrls(args) {
      const { uuid, versionId } = args;
      return (
        await dssFetch<{
          presignedUrls: Array<{ sha: string; presignedUrl: string }>;
        }>(`/documents/${uuid}/location${withVersionId(versionId)}`)
      ).map((result) => ({
        presignedUrls: result.presignedUrls.map((x) => ({
          url: x.presignedUrl,
          sha: x.sha,
        })),
      }));
    },
    {
      minutes: MINUTES_BEFORE_PRESIGNED_EXPIRES,
    }
  ),

  getDocumentLocation: cache(
    async function getDocumentLocation(args) {
      const { documentId, versionId } = args;
      // we want to ensure we get the converted docx url if we have enabled the DOCX to PDF feature flag
      const params = new URLSearchParams({
        get_converted_docx_url: String(ENABLE_DOCX_TO_PDF),
      });
      if (versionId != null)
        params.set('document_version_id', String(versionId));

      const result = await dssFetch<LocationResponseV3>(
        `/documents/${documentId}/location_v3?${params.toString()}`
      );

      return result.map((result) => ({
        data: normalizeLocationResponseV3(result),
      }));
    },
    {
      minutes: MINUTES_BEFORE_PRESIGNED_EXPIRES,
    }
  ),

  getDocumentViewers: cache(
    async function getDocumentViewers(args) {
      const { document_id } = args;
      return await dssFetch<UserViewsResponse>(
        `/documents/${document_id}/views`
      );
    },
    {
      seconds: 5,
    }
  ),

  async getDocumentPermissions(args) {
    const { document_id } = args;
    return (
      await dssFetch<GetDocumentPermissionsResponseDataV2>(
        `/documents/${document_id}/permissions`
      )
    ).map((result) => result.documentPermissions);
  },

  getDocxExpandedParts,

  async upsertDocumentViewLocation({ documentId, location }) {
    return await dssFetch<{}>(`/user_document_view_location/${documentId}`, {
      method: 'POST',
      body: JSON.stringify({ location }),
    });
  },

  async deleteDocumentViewLocation({ documentId }) {
    return await dssFetch<{}>(`/user_document_view_location/${documentId}`, {
      method: 'DELETE',
    });
  },

  projects: {
    async getAll() {
      return (await dssFetch<{ data: Project[] }>('/projects')).map(
        (result) => ({ data: result.data })
      );
    },

    async getProject({ id }) {
      return (await dssFetch<GetProjectResponse>(`/projects/${id}`)).map(
        (result) => result.data
      );
    },

    async getPending() {
      return (
        await dssFetch<GetPendingProjectsHandler200>('/projects/pending')
      ).map((result) => ({ data: result.data }));
    },

    async create(params: {
      name: string;
      projectParentId?: string;
      sharePermission?: null;
    }) {
      return (
        await dssFetch<CreateProjectResponse>('/projects', {
          method: 'POST',
          body: JSON.stringify(params),
        })
      ).map((result) => result.data);
    },

    async delete({ id }: { id: string }) {
      return (
        await dssFetch<SuccessResponse>(`/projects/${id}`, {
          method: 'DELETE',
        })
      ).map((result) => result.data);
    },

    async edit(args) {
      const { id, ...body } = args;
      return (
        await dssFetch<SuccessResponse>(`/projects/${id}`, {
          method: 'PATCH',
          body: JSON.stringify(body),
        })
      ).map((result) => result.data);
    },

    async getContent({ id }: { id: string }) {
      return (
        await dssFetch<GetProjectContentResponse>(`/projects/${id}/content`)
      ).map((result) => result);
    },

    async getPermissions({ id }) {
      return (
        await dssFetch<SharePermissionV2>(`/projects/${id}/permissions`)
      ).map((result) => result);
    },

    async getUserAccessLevel({
      id,
    }): Promise<Result<AccessLevel, ResultError<FetchWithTokenErrorCode>[]>> {
      return await dssFetch<any>(`/projects/${id}/access_level`);
    },

    async getPreview(args) {
      return (
        await dssFetch<GetBatchProjectPreviewResponse>(`/projects/preview`, {
          method: 'POST',
          body: JSON.stringify(args),
        })
      ).map((result) => result);
    },

    async createUploadZipRequest(args) {
      return (
        await dssFetch<UploadExtractFolderHandler200>(
          `/projects/upload_extract`,
          {
            method: 'POST',
            body: JSON.stringify(args),
          }
        )
      ).map((result) => result.data);
    },
    async permanentlyDelete({ id }) {
      return (
        await dssFetch<SuccessResponse>(`/projects/${id}/permanent`, {
          method: 'DELETE',
        })
      ).map((result) => result.data);
    },

    async revertDelete({ id }) {
      return (
        await dssFetch<SuccessResponse>(`/projects/${id}/revert_delete`, {
          method: 'PUT',
        })
      ).map((result) => result.data);
    },
  },
  async getDeletedItems() {
    return (
      await dssFetch<TypedSuccessResponse>('/recents/deleted', {
        method: 'GET',
      })
    ).map((result) => result.data);
  },

  views: {
    async getSavedViews() {
      return (await dssFetch<ViewsResponse>('/saved_views')).map(
        (result) => result
      );
    },
    async createSavedView(params) {
      return (
        await dssFetch<View>('/saved_views', {
          method: 'POST',
          body: JSON.stringify(params),
        })
      ).map((result) => result);
    },
    async excludeDefaultView(params) {
      return await dssFetch('/saved_views/exclude_default', {
        method: 'POST',
        body: JSON.stringify(params),
      });
    },
    async patchView(params) {
      return await dssFetch(`/saved_views/${params.saved_view_id}`, {
        method: 'PATCH',
        body: JSON.stringify(params),
      });
    },
    async deleteView(params) {
      return await dssFetch(`/saved_views/${params.savedViewId}`, {
        method: 'DELETE',
        body: JSON.stringify(params),
      });
    },
  },

  channelLabels: {
    async preview(
      rule: ChannelLabelRule,
      signal?: AbortSignal,
      scope?: ChannelLabelScopeSelection
    ) {
      return await dssFetch<SmartTagPreview>(
        `/channel-labels/preview${scope ? `?scope=${scope}` : ''}`,
        { method: 'POST', body: JSON.stringify(rule), signal }
      );
    },
    /** Omitted scope selects the caller's team when available, otherwise personal labels. */
    async list(scope?: ChannelLabelScopeSelection) {
      return await dssFetch<ChannelLabelsList>(
        `/channel-labels${scope ? `?scope=${scope}` : ''}`
      );
    },
    async create(
      params: CreateChannelLabelRequest,
      scope?: ChannelLabelScopeSelection
    ) {
      return await dssFetch<ChannelLabel>(
        `/channel-labels${scope ? `?scope=${scope}` : ''}`,
        { method: 'POST', body: JSON.stringify(params) }
      );
    },
    async rename(
      labelId: string,
      params: RenameChannelLabelRequest,
      scope?: ChannelLabelScopeSelection
    ) {
      return await dssFetch<ChannelLabel>(
        `/channel-labels/${encodeURIComponent(labelId)}${scope ? `?scope=${scope}` : ''}`,
        { method: 'PATCH', body: JSON.stringify(params) }
      );
    },
    async remove(labelId: string, scope?: ChannelLabelScopeSelection) {
      return await dssFetch(
        `/channel-labels/${encodeURIComponent(labelId)}${scope ? `?scope=${scope}` : ''}`,
        { method: 'DELETE' }
      );
    },
    async setChannelLabel(
      channelId: string,
      params: SetChannelLabelRequest,
      scope?: ChannelLabelScopeSelection
    ) {
      return await dssFetch(
        `/channel-labels/channels/${encodeURIComponent(channelId)}${scope ? `?scope=${scope}` : ''}`,
        { method: 'PUT', body: JSON.stringify(params) }
      );
    },
  },
  favorites: {
    async getFavorites(params?: ListFavoritesParams) {
      const query = new URLSearchParams();
      // Each dimension repeats its key once per value; the two combine with AND.
      params?.entityType?.forEach((entityType) =>
        query.append('entityType', entityType)
      );
      params?.entityId?.forEach((entityId) =>
        query.append('entityId', entityId)
      );
      const qs = query.toString();
      return await dssFetch<FavoritesList>(`/favorites${qs ? `?${qs}` : ''}`);
    },
    async addFavorite(params: AddFavoriteRequest) {
      return await dssFetch<Favorite>('/favorites', {
        method: 'POST',
        body: JSON.stringify(params),
      });
    },
    async removeFavoriteByEntity(params: {
      entityType: AddFavoriteRequest['entityType'];
      entityId: string;
    }) {
      return await dssFetch(
        `/favorites/${params.entityType}/${encodeURIComponent(params.entityId)}`,
        { method: 'DELETE' }
      );
    },
    async reorderFavorites(params: ReorderFavoritesRequest) {
      return await dssFetch('/favorites/reorder', {
        method: 'PATCH',
        body: JSON.stringify(params),
      });
    },
  },
  reminders: {
    async listEmailReminders(params: ListEmailRemindersParams) {
      const query = new URLSearchParams();
      for (const [key, value] of Object.entries(params)) {
        if (Array.isArray(value)) {
          for (const item of value) query.append(key, item);
        } else if (value !== undefined && value !== null) {
          query.set(key, String(value));
        }
      }
      return await dssFetch<EmailReminderPage>(
        `/reminders/email/collection?${query}`,
        { method: 'GET' }
      );
    },
    async getEmailFollowup(threadId: string) {
      return (
        await dssFetch<{ followup: EmailFollowup | null }>(
          `/reminders/email/${threadId}`,
          { method: 'GET' }
        )
      ).map((response) => response.followup);
    },
    async setEmailFollowup(threadId: string, command: EmailFollowupCommand) {
      return await dssFetch<EmailFollowup>(`/reminders/email/${threadId}`, {
        method: 'PUT',
        body: JSON.stringify(command),
      });
    },
  },
  async editThread(params) {
    const { threadId, ...body } = params;

    return (
      await dssFetch<SuccessResponse>(`/threads/${threadId}`, {
        method: 'PATCH',
        body: JSON.stringify(body),
      })
    ).map((result) => result.data);
  },
  async createCompany(body: CreateCrmCompanyRequest) {
    return await dssFetch<CrmCompanyResponse>('/crm/companies', {
      method: 'POST',
      body: JSON.stringify(body),
    });
  },
  async getCompany({ companyId }: { companyId: string }) {
    return await dssFetch<CrmCompanyResponse>(`/crm/companies/${companyId}`, {
      method: 'GET',
    });
  },
  async getCompanyContacts({ companyId }: { companyId: string }) {
    return await dssFetch<CrmContactResponse[]>(
      `/crm/companies/${companyId}/contacts`,
      { method: 'GET' }
    );
  },
  async createContact({
    companyId,
    ...body
  }: { companyId: string } & CreateCrmContactRequest) {
    return await dssFetch<CrmContactResponse>(
      `/crm/companies/${companyId}/contacts`,
      {
        method: 'POST',
        body: JSON.stringify(body),
      }
    );
  },
  async createTeamContact(body: CreateCrmTeamContactRequest) {
    return await dssFetch<CrmContactResponse>('/crm/contacts', {
      method: 'POST',
      body: JSON.stringify(body),
    });
  },
  async listCrmBlockedDomains() {
    return await dssFetch<CrmBlockedDomainResponse[]>('/crm/blocked-domains', {
      method: 'GET',
    });
  },
  async blockCrmDomain({ domain }: { domain: string }) {
    return await dssFetch(
      `/crm/blocked-domains/${encodeURIComponent(domain)}`,
      { method: 'PUT' }
    );
  },
  async unblockCrmDomain({ domain }: { domain: string }) {
    return await dssFetch(
      `/crm/blocked-domains/${encodeURIComponent(domain)}`,
      { method: 'DELETE' }
    );
  },
  async getContact({ contactId }: { contactId: string }) {
    return await dssFetch<CrmContactResponse>(`/crm/contacts/${contactId}`, {
      method: 'GET',
    });
  },
  async getContactByEmail({
    email,
    signal,
  }: GetContactByEmailParams & { signal?: AbortSignal }) {
    const query = new URLSearchParams({ email });
    return await dssFetch<GetContactByEmailResponse>(
      `/crm/contacts/by-email?${query.toString()}`,
      { method: 'GET', signal }
    );
  },
  async searchContacts({
    query,
    limit,
    signal,
  }: SearchContactsParams & { signal?: AbortSignal }) {
    const params = new URLSearchParams({ query: query ?? '' });
    if (limit) params.set('limit', String(limit));
    return await dssFetch<SearchContactsResponse>(
      `/crm/contacts?${params.toString()}`,
      { method: 'GET', signal }
    );
  },
  async setContactName({
    contactId,
    ...body
  }: { contactId: string } & SetContactNameRequest) {
    return await dssFetch(`/crm/contacts/${contactId}/name`, {
      method: 'PUT',
      body: JSON.stringify(body),
    });
  },
  async setContactHidden({
    contactId,
    hidden,
  }: {
    contactId: string;
    hidden: boolean;
  }) {
    return await dssFetch(`/crm/contacts/${contactId}/hidden`, {
      method: 'PUT',
      body: JSON.stringify({ hidden }),
    });
  },
  async setCompanyName({
    companyId,
    ...body
  }: { companyId: string } & SetCompanyNameRequest) {
    return await dssFetch(`/crm/companies/${companyId}/name`, {
      method: 'PUT',
      body: JSON.stringify(body),
    });
  },
  async setCompanyHidden({
    companyId,
    hidden,
  }: {
    companyId: string;
    hidden: boolean;
  }) {
    return await dssFetch(`/crm/companies/${companyId}/hidden`, {
      method: 'PUT',
      body: JSON.stringify({ hidden }),
    });
  },
  async setEmailSync({
    companyId,
    emailSync,
  }: {
    companyId: string;
    emailSync: boolean;
  }) {
    return await dssFetch(`/crm/companies/${companyId}/email-sync`, {
      method: 'PUT',
      body: JSON.stringify({ email_sync: emailSync }),
    });
  },
  async getCrmTeamSettings() {
    return await dssFetch<CrmTeamSettingsResponse>('/crm/settings', {
      method: 'GET',
    });
  },
  async updateCrmTeamSettings(body: UpdateCrmTeamSettingsRequest) {
    return await dssFetch<CrmTeamSettingsResponse>('/crm/settings', {
      method: 'PUT',
      body: JSON.stringify(body),
    });
  },
  async replaceCrmTeamStages(body: ReplaceCrmStagesRequest) {
    return await dssFetch<CrmStagesResponse>('/crm/stages', {
      method: 'PUT',
      body: JSON.stringify(body),
    });
  },
  async resetCrmTeamStages() {
    return await dssFetch('/crm/stages', { method: 'DELETE' });
  },
} satisfies StorageServiceClient &
  typeof enhancements &
  Record<string, unknown>;

const _uploadFileToPresignedUrl = async (
  presignedUrl: URL,
  file: IDocumentStorageServiceFile,
  signal?: AbortSignal
): Promise<void> => {
  const buffer = await file.arrayBuffer();
  const blob = new Blob([buffer], { type: file.type });

  const sha = await file.hash();
  const base64Sha = btoa(
    sha
      .match(/\w{2}/g)!
      .map((a) => String.fromCharCode(parseInt(a, 16)))
      .join('')
  );

  const response = await platformFetch(presignedUrl, {
    method: 'PUT',
    body: blob,
    headers: {
      'Content-Type': file.type,
      'x-amz-checksum-sha256': base64Sha,
    },
    signal,
  });

  if (!response.ok) {
    const text = await response.text();
    throw new Error(`Failed to upload file: ${text}`);
  }
};

registerClient('storage', storageServiceClient);