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.

13.0 KB
Raw Blame
import type {
  ApiContactInfo,
  ApiDraftContactInfo,
  CalendarInvitation,
  GetThreadResponses,
  MailboxOperation,
  UpdateThreadStateRequest,
} from '../../../generated/email/types.gen';
import type { EmailFollowupCommand } from '../../../generated/storage/types.gen';
import { unwrap } from '../../utils';
import type { MacroClient } from '../../utils/client';
import type { Calendar } from '../calendar/calendar';
import { CalendarEvent } from '../calendar/event';
import { PropertiedEntity } from '../entity';
import { Project } from '../projects/project';
import { entitySearch } from '../search/options';
import { EntityAccess } from '../sharing/access';
import {
  type SharePermissionOptions,
  sharePermissionBody,
} from '../sharing/permissions';
import { EmailAttachment } from './attachment';
import type { Label } from './label';
import { Link } from './link';
import { EmailMessage } from './message';

type ThreadDetail = GetThreadResponses[200]['thread'];

/** Options for replying within an email thread. */
export interface ReplyEmailOptions {
  /** Recipients. */
  to: ApiDraftContactInfo[];
  /** Cc recipients. */
  cc?: ApiDraftContactInfo[];
  /** Bcc recipients. */
  bcc?: ApiDraftContactInfo[];
  /** Plain-text body. */
  bodyText: string;
  /** Subject line. Defaults to the subject of the thread's first message. */
  subject?: string;
  /** The message being replied to. */
  replyingTo?: EmailMessage;
}

/** Open tracking for one of the caller's sent messages. */
export interface EmailReadReceipt {
  /** The tracked message. */
  message: EmailMessage;

  /** Counted pixel fetches; repeats within a few seconds count once. */
  openCount: number;

  /** When the first counted fetch happened, if any. */
  firstOpenedAt?: string;

  /** When the latest counted fetch happened, if any. */
  lastOpenedAt?: string;
}

/**
 * An email thread. A free-to-construct handle: the detail record (including
 * up to the first 100 messages) loads lazily on first field access.
 */
export class EmailThread extends PropertiedEntity<ThreadDetail> {
  /** Access requests and direct user grants. */
  readonly access = new EntityAccess(this.client, 'email_thread', this);

  /** Read follow-up state for this thread. */
  async followup() {
    return unwrap(
      await this.client.storage.getEmailFollowup({
        path: { thread_id: this.id },
      }),
    );
  }

  /** Set or remove a follow-up using a persisted operation id and revision. */
  async setFollowup(command: EmailFollowupCommand) {
    return unwrap(
      await this.client.storage.setEmailFollowup({
        path: { thread_id: this.id },
        body: command,
      }),
    );
  }

  /** Calendar invitations resolved from this thread's messages. */
  async calendarInvitations() {
    return unwrap(
      await this.client.email.getThreadCalendarInvitations({
        path: { thread_id: this.id },
      }),
    );
  }

  /** Add a shared event one of this thread's messages carries (a published
   * `.ics`, such as one sent with Forward by email) to one of the
   * requester's Google calendars, and return a handle to the synced
   * snapshot. The event is read from the saved message, never from the
   * caller, and lands the way {@link CalendarEvent.addToCalendar} adds a
   * channel-shared one: the meeting's iCalendar UID and organizer, only the
   * requester as a guest, no join link, nobody notified. Refused with
   * `invalid_input` for an invitation, which is answered from the calendar
   * instead, `already_on_calendar` when the meeting is already on one of
   * their calendars, whichever calendar is named (it cannot be added to
   * another of theirs either), and `copy_refused` when Google will not
   * import it. */
  async addEventToCalendar(
    message: EmailMessage,
    invitation: CalendarInvitation,
    options: { calendar?: Calendar } = {},
  ): Promise<CalendarEvent> {
    const record = unwrap(
      await this.client.email.copyThreadCalendarInvitation({
        path: {
          thread_id: this.id,
          message_id: message.id,
          invitation_id: invitation.id,
        },
        body: { calendarId: options.calendar?.id },
      }),
    );
    return CalendarEvent.fromRecord(this.client, record);
  }

  /**
   * Opens recorded for messages sent from the caller's own or delegated
   * inboxes with read receipts on, newest message first. Counts are
   * approximate: some mail apps prefetch images and others block them.
   */
  async readReceipts(): Promise<EmailReadReceipt[]> {
    const { receipts } = unwrap(
      await this.client.email.getThreadReadReceipts({
        path: { thread_id: this.id },
      }),
    );
    return receipts.map((receipt) => ({
      message: EmailMessage.byId(this.client, receipt.message_id),
      openCount: receipt.open_count,
      firstOpenedAt: receipt.first_opened_at ?? undefined,
      lastOpenedAt: receipt.last_opened_at ?? undefined,
    }));
  }

  /** Change project membership or share permissions for this thread. */
  async update(options: {
    project?: Project | null;
    sharePermission?: SharePermissionOptions;
  }): Promise<void> {
    await this.mutate((c) =>
      c.storage.editThreadV2({
        path: { thread_id: this.id },
        body: {
          projectId:
            options.project === undefined
              ? undefined
              : (options.project?.id ?? null),
          sharePermission: options.sharePermission
            ? sharePermissionBody(options.sharePermission)
            : undefined,
        },
      }),
    );
  }

  /** Favorites identify email threads as `email_thread`. */
  readonly entityType = 'email_thread';

  /** The properties service identifies email threads as `THREAD`. */
  protected readonly propertyEntityType = 'THREAD';

  protected async fetch(): Promise<ThreadDetail> {
    const { thread } = unwrap(
      await this.client.email.getThread({
        path: { thread_id: this.id },
        query: { limit: 100 },
      }),
    );
    return thread;
  }

  /** The thread's URL in the Macro web app; hand it to users as the link. */
  webUrl(): string {
    return `${this.client.webAppUrl}/app/mail/${this.id}`;
  }

  /** Identity, loaded detail and {@link webUrl}, so serialized handles carry their link. */
  override toJSON() {
    return { ...super.toJSON(), url: this.webUrl() };
  }

  /** A handle to a thread by id. Details load on first access. */
  static byId(client: MacroClient, id: string): EmailThread {
    return new EmailThread(client, id);
  }

  /** When the thread was created. */
  readonly createdAt = this.field('created_at');

  /** When the thread was last updated. */
  readonly updatedAt = this.field('updated_at');

  /** Whether the thread has been read. */
  readonly isRead = this.field('is_read');

  /** Whether the thread is visible in the inbox (i.e. not archived). */
  readonly inboxVisible = this.field('inbox_visible');

  /** The viewer's access level to this thread. */
  readonly accessLevel = this.field('access_level');

  /** The provider-internal thread id (e.g. Gmail/Outlook), if any. */
  readonly providerId = this.field('provider_id');

  /** The inbox (email link) that owns this thread. */
  readonly link = this.mappedField('link_id', (id) =>
    Link.byId(this.client, id),
  );

  /** The project this thread is attached to, if any. */
  readonly project = this.mappedField('project_id', (id) =>
    id ? Project.byId(this.client, id) : undefined,
  );

  /** Timestamp of the latest inbound message, if any. */
  readonly latestInboundAt = this.field('latest_inbound_message_ts');

  /** Timestamp of the latest outbound message, if any. */
  readonly latestOutboundAt = this.field('latest_outbound_message_ts');

  /** Timestamp of the latest non-spam message, if any. */
  readonly latestNonSpamAt = this.field('latest_non_spam_message_ts');

  /** The thread's subject, from its first message with one. */
  async subject(): Promise<string | undefined> {
    const { messages } = await this.detail.get();
    for (const m of messages) if (m.subject) return m.subject;
    return undefined;
  }

  /**
   * Everyone on the thread (senders and recipients), deduped by email.
   * Derived from the thread's first 100 messages.
   */
  async participants(): Promise<ApiContactInfo[]> {
    const { messages } = await this.detail.get();
    const seen = new Map<string, ApiContactInfo>();
    for (const m of messages) {
      for (const c of [m.from, ...m.to, ...m.cc, ...m.bcc]) {
        if (c && !seen.has(c.email)) seen.set(c.email, c);
      }
    }
    return [...seen.values()];
  }

  /** The messages in this thread, pre-seeded from the list endpoint. */
  async messages(opts?: {
    since?: string;
    limit?: number;
  }): Promise<EmailMessage[]> {
    const records = unwrap(
      await this.client.email.getThreadMessagesHandler({
        path: { id: this.id },
        query: {
          ...(opts?.since ? { since: opts.since } : {}),
          ...(opts?.limit ? { limit: opts.limit } : {}),
        },
      }),
    );
    return records.map((r) => EmailMessage.from(this.client, r));
  }

  /** The attachments across this thread's first 100 messages, pre-seeded from the thread detail. */
  async attachments(): Promise<EmailAttachment[]> {
    const { messages } = await this.detail.get();
    return messages.flatMap((m) =>
      m.attachments.map((a) => EmailAttachment.from(this.client, a)),
    );
  }

  /**
   * Send a plain-text reply in this thread; an agent's program is refused
   * (403) and replies through a review or `email.sendConfirmed` with
   * `replyingTo` instead. Returns a handle when the API reports the created
   * message's id.
   */
  async reply(opts: ReplyEmailOptions): Promise<EmailMessage | undefined> {
    const subject = opts.subject ?? (await this.subject()) ?? '';
    const { message } = await this.mutate((c) =>
      c.email.sendMessage({
        body: {
          message: {
            thread_db_id: this.id,
            replying_to_id: opts.replyingTo?.id ?? null,
            to: opts.to,
            cc: opts.cc ?? null,
            bcc: opts.bcc ?? null,
            subject,
            body_text: opts.bodyText,
          },
        },
      }),
    );
    return message.db_id
      ? EmailMessage.byId(this.client, message.db_id)
      : undefined;
  }

  /** Archive the thread (or unarchive with `false`). */
  async archive(archived = true): Promise<void> {
    await this.mutate((c) =>
      c.email.archiveThread({
        path: { id: this.id },
        body: { value: archived },
      }),
    );
  }

  /**
   * Archive many threads (or unarchive with `false`), sending one request per
   * 100 threads. Resolves to the threads whose state could not change.
   */
  static async archiveMany(
    client: MacroClient,
    threads: EmailThread[],
    archived = true,
  ): Promise<EmailThread[]> {
    const unchanged: EmailThread[] = [];
    for (let start = 0; start < threads.length; start += 100) {
      const batch = threads.slice(start, start + 100);
      const result = unwrap(
        await client.email.archiveThreads({
          body: {
            thread_ids: batch.map((thread) => thread.id),
            value: archived,
          },
        }),
      );
      const failed = new Set(result.failed_thread_ids);
      for (const thread of batch) {
        thread.detail.clear();
        if (failed.has(thread.id)) unchanged.push(thread);
      }
    }
    return unchanged;
  }

  /** Update provider-neutral read, trash, spam, or star state. */
  async updateState(request: UpdateThreadStateRequest): Promise<void> {
    await this.mutate((c) =>
      c.email.updateThreadState({ path: { id: this.id }, body: request }),
    );
  }

  /** Read pending or failed mailbox changes without initiating a retry. */
  async operations(): Promise<MailboxOperation[]> {
    return unwrap(
      await this.client.email.threadOperations({ path: { id: this.id } }),
    );
  }

  /** Mark the thread as seen. */
  async markSeen(): Promise<void> {
    await this.mutate((c) => c.email.threadSeen({ path: { id: this.id } }));
  }

  /** Add a label to every message in the thread. */
  async addLabel(label: Label): Promise<void> {
    await this.mutate((c) =>
      c.email.addRemoveThreadLabel({
        path: { id: this.id },
        body: { label_id: label.id, value: true },
      }),
    );
  }

  /** Remove a label from every message in the thread. */
  async removeLabel(label: Label): Promise<void> {
    await this.mutate((c) =>
      c.email.addRemoveThreadLabel({
        path: { id: this.id },
        body: { label_id: label.id, value: false },
      }),
    );
  }

  /** Attach the thread to a project, or clear the project with `null`. */
  async moveToProject(project: Project | null): Promise<void> {
    await this.mutate((c) =>
      c.email.updateThreadProject({
        path: { thread_id: this.id },
        body: { projectId: project?.id ?? null },
      }),
    );
  }

  /** Search email threads by subject and content, most relevant first, auto-paginated. */
  static search = entitySearch({
    filters: { email_filters: {} },
    type: 'email',
    make: (client, hit) => new EmailThread(client, hit.thread_id),
  });
}