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.

16.4 KB
Raw Blame
import { isAgentContextData } from '../nodes/AgentContextNode';
import { parseDatabaseQueryJson } from '../nodes/DatabaseQueryNode';

type UserMentionData = {
  userId?: string;
  displayName?: string;
  email?: string;
};

function replaceUserMentions(
  text: string,
  toText: (data: UserMentionData) => string
): string {
  return text.replace(/<m-user-mention>(.*?)<\/m-user-mention>/g, (_, json) => {
    try {
      return toText(JSON.parse(json));
    } catch {
      return '';
    }
  });
}

export function parseUserMentions(text: string): string {
  return replaceUserMentions(text, userMentionDisplayText);
}

/**
 * Flattens user mentions to the text the backend indexes for them, so a
 * search query built from mention chips matches indexed messages.
 */
export function parseUserMentionsForSearch(text: string): string {
  return replaceUserMentions(text, userMentionIndexedText);
}

function userMentionDisplayText(data: UserMentionData) {
  if (data.displayName) return data.displayName;
  if (data.email) return data.email.split('@')[0] || data.email;
  return '';
}

/**
 * Mirrors `PlainTextFormatter::format_user` in
 * `crates/mention_utils/src/parse.rs`, which produces the indexed text of a
 * channel message: a Macro user is their email, a bot its display name, and
 * any other principal "Guest". Change both together.
 */
function userMentionIndexedText(data: UserMentionData) {
  const userId = data.userId ?? '';
  if (userId.startsWith('bot|')) {
    return data.displayName || data.email || 'Bot';
  }
  if (userId.startsWith('macro|')) {
    return userId.slice('macro|'.length) || 'Guest';
  }
  return 'Guest';
}

export function parseContactMentions(text: string): string {
  return text.replace(
    /<m-contact-mention>(.*?)<\/m-contact-mention>/g,
    (_, json) => {
      try {
        const data = JSON.parse(json);
        return data.name || data.emailOrDomain || '';
      } catch {
        return '';
      }
    }
  );
}

export function parseDateMentions(text: string): string {
  return text.replace(/<m-date-mention>(.*?)<\/m-date-mention>/g, (_, json) => {
    try {
      const data = JSON.parse(json);
      return data.displayFormat || '';
    } catch {
      return '';
    }
  });
}

export function parseDocumentMentions(text: string): string {
  return text.replace(
    /<m-document-mention>(.*?)<\/m-document-mention>/g,
    (_, json) => {
      try {
        const data = JSON.parse(json);
        return data.documentName || '';
      } catch {
        return '';
      }
    }
  );
}

export function parseAgentSessionMentions(text: string): string {
  return text.replace(
    /<m-agent-session-mention>(.*?)<\/m-agent-session-mention>/g,
    (_, json) => {
      try {
        const data = JSON.parse(json);
        return typeof data.label === 'string'
          ? data.label
          : typeof data.id === 'string'
            ? data.id
            : '';
      } catch {
        return '';
      }
    }
  );
}

export function parsePullRequestMentions(text: string): string {
  return text.replace(/<m-pr-mention>(.*?)<\/m-pr-mention>/g, (_, json) => {
    try {
      const data = JSON.parse(json);
      return (
        data.label ||
        data.id ||
        (typeof data.url === 'string' ? githubPullRequestRef(data.url) : '') ||
        ''
      );
    } catch {
      return '';
    }
  });
}

/** `owner/repo#123` for a github.com pull request URL. */
function githubPullRequestRef(url: string): string | undefined {
  const match = url.match(
    /github\.com\/([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+)\/pull\/([1-9][0-9]*)/
  );
  return match ? `${match[1]}/${match[2]}#${match[3]}` : undefined;
}

/** Account manager cards read as what they are; their payload is only an id. */
export function parseAccountManagerRequests(text: string): string {
  return text.replace(
    /<m-account-manager-request>.*?<\/m-account-manager-request>/g,
    'Account manager request'
  );
}

/** `<m-connect-app>` chips read as their call to action. */
export function parseConnectApps(text: string): string {
  return text.replace(/<m-connect-app>(.*?)<\/m-connect-app>/g, (_, json) => {
    try {
      const data = JSON.parse(json);
      return typeof data.name === 'string' && data.name
        ? `Connect ${data.name}`
        : '';
    } catch {
      return '';
    }
  });
}

export function parseDatabaseQueries(text: string): string {
  return text.replace(/<m-db-query>(.*?)<\/m-db-query>/g, (_, json) => {
    const data = parseDatabaseQueryJson(json);
    return data?.title || data?.prompt || 'Live database answer';
  });
}

/**
 * An agent's steps are not prose: a preview of its reply quotes what it
 * wrote, not every command it ran.
 */
export function parseAgentActivities(text: string): string {
  return text.replace(
    /<m-agent-activity>.*?<\/m-agent-activity>(?:\r?\n)*/gs,
    ''
  );
}

/** A Cursor `<system_notification …>` block reads as its summary line. */
export function parseCursorSystemNotifications(text: string): string {
  return text.replace(
    /<system_notification\b[^>]*>(.*?)<\/system_notification>/gs,
    (_, body: string) => body.trim()
  );
}

export function parseTagMentions(text: string): string {
  return text.replace(/<m-tag>(.*?)<\/m-tag>/g, (_, json) => {
    try {
      const data = JSON.parse(json);
      return data.name ? `#${data.name}` : '';
    } catch {
      return '';
    }
  });
}

export function parseLinks(text: string): string {
  return text.replace(/<m-link>(.*?)<\/m-link>/g, (_, json) => {
    try {
      const data = JSON.parse(json);
      return data.text || data.url || '';
    } catch {
      return '';
    }
  });
}

export function parseGroupMentions(text: string): string {
  return text.replace(
    /<m-group-mention>(.*?)<\/m-group-mention>/g,
    (_, json) => {
      try {
        const data = JSON.parse(json);
        return `@${data.groupAlias || ''}`;
      } catch {
        return '';
      }
    }
  );
}

export function parseDocumentCards(text: string): string {
  return text.replace(
    /<m-document-card>(.*?)<\/m-document-card>/g,
    (_, json) => {
      try {
        const data = JSON.parse(json);
        return data.documentName || '';
      } catch {
        return '';
      }
    }
  );
}

/** Replace reply-target nodes with their user-visible preview text. */
export function parseReplyTargets(text: string): string {
  return text.replace(
    /<m-reply-target>(.*?)<\/m-reply-target>/gs,
    (_, json) => {
      try {
        const data = JSON.parse(json);
        return data.displayText || '';
      } catch {
        return '';
      }
    }
  );
}

export function parseSnapshots(text: string): string {
  return text.replace(/<m-snapshot>(.*?)<\/m-snapshot>/g, (_, encoded) => {
    try {
      // Decode base64 (may also be raw JSON for backward compat)
      const jsonStr = encoded.startsWith('{')
        ? encoded
        : new TextDecoder().decode(
            Uint8Array.from(atob(encoded), (c) => c.charCodeAt(0))
          );
      const data = JSON.parse(jsonStr);
      return data.documentName || '';
    } catch {
      return '';
    }
  });
}

/** Remove private agent context from user-visible text. */
export function stripAgentContext(text: string): string {
  const match = text.match(
    /^<m-agent-context>(.*?)<\/m-agent-context>(?:\r?\n\r?\n)?/s
  );
  if (!match) return text;
  try {
    const data: unknown = JSON.parse(match[1] ?? '');
    if (
      !isAgentContextData(data) ||
      Object.keys(data as Record<string, unknown>).length !== 2
    ) {
      return text;
    }
    return text.slice(match[0].length);
  } catch {
    return text;
  }
}

/**
 * Converts markdown text with XML mention tags to plain text.
 * Extracts the readable text from mention nodes:
 * - User mentions: displayName (fallback to the email local part)
 * - Contact mentions: name (fallback to emailOrDomain)
 * - Date mentions: displayFormat
 * - Document mentions: documentName
 * - Document cards: documentName
 * - Snapshots: documentName (base64-encoded payload)
 * - Group mentions: @groupAlias (e.g., @here)
 * - Links: text (fallback to url)
 * - Reply targets: displayText
 * - Cursor system notifications: the summary between the tags
 * - Agent activity: nothing; the steps of a reply are not its text
 */
export function markdownToPlainText(markdown: string): string {
  return flattenMarkdown(markdown, parseUserMentions);
}

/**
 * Like `markdownToPlainText`, but user mentions become the text the search
 * index holds for them (see `parseUserMentionsForSearch`). Use it for text
 * that is matched against indexed content, such as a search query.
 */
export function markdownToSearchText(markdown: string): string {
  return flattenMarkdown(markdown, parseUserMentionsForSearch);
}

function flattenMarkdown(
  markdown: string,
  userMentions: (text: string) => string
): string {
  const transforms: Array<(text: string) => string> = [
    parseAgentActivities,
    userMentions,
    parseContactMentions,
    parseDateMentions,
    parseGroupMentions,
    parseDocumentMentions,
    parsePullRequestMentions,
    parseAgentSessionMentions,
    parseTagMentions,
    parseConnectApps,
    parseAccountManagerRequests,
    parseCursorSystemNotifications,
    parseDatabaseQueries,
    parseSnapshots,
    parseDocumentCards,
    parseLinks,
    parseReplyTargets,
    stripAgentContext,
  ];

  return transforms.reduce((text, transform) => transform(text), markdown);
}

/**
 * The payload fields `markdownToEmbeddingText` reads across the internal
 * format's `<m-*>` JSON tags. Each tag uses a small subset of these.
 */
type MentionTagPayload = {
  prompt?: string;
  title?: string;
  documentId?: string;
  documentName?: string;
  blockName?: string;
  blockParams?: { channel_message_id?: string };
  label?: string;
  url?: string;
  text?: string;
  alt?: string;
  id?: string;
  srcType?: string;
  email?: string;
  name?: string;
  emailOrDomain?: string;
  displayFormat?: string;
  groupAlias?: string;
  displayText?: string;
  equation?: string;
};

/**
 * Replaces every `<{tag}>{json}</{tag}>` occurrence with `render(payload)`.
 * Unparseable payloads are dropped rather than left in place.
 */
function replaceJsonTag(
  text: string,
  tag: string,
  render: (data: MentionTagPayload) => string
): string {
  return text.replace(new RegExp(`<${tag}>(.*?)</${tag}>`, 'gs'), (_, json) => {
    try {
      return render(JSON.parse(json));
    } catch {
      return '';
    }
  });
}

function documentRefToEmbeddingText(data: MentionTagPayload): string {
  const name = data.documentName || '';
  if (!data.documentId) return name;
  const blockName = data.blockName || 'document';
  const channelMessageId = data.blockParams?.channel_message_id;
  const suffix = channelMessageId ? `#${channelMessageId}` : '';
  return `[${name}](${blockName}:${data.documentId}${suffix})`;
}

/** Snapshot payloads may be base64-encoded (or raw JSON for backward compat). */
function snapshotToEmbeddingText(encoded: string): string {
  try {
    const json = encoded.startsWith('{')
      ? encoded
      : new TextDecoder().decode(
          Uint8Array.from(atob(encoded), (c) => c.charCodeAt(0))
        );
    return documentRefToEmbeddingText(JSON.parse(json));
  } catch {
    return '';
  }
}

/**
 * Flattens `<m-table>` markup into plain rows: one line per row, cells joined
 * with ` | `. Cell payloads are markdown with newlines escaped as literal
 * `\n`; any tags nested in cells are handled by the leaf passes afterwards.
 */
function flattenTables(text: string): string {
  return text.replace(
    /<m-table(?:\s[^>]*)?>(.*?)<\/m-table>/gs,
    (_, table: string) =>
      [...table.matchAll(/<m-table-row(?:\s[^>]*)?>(.*?)<\/m-table-row>/gs)]
        .map((row) =>
          [
            ...row[1].matchAll(
              /<m-table-cell(?:\s[^>]*)?>(.*?)<\/m-table-cell>/gs
            ),
          ]
            .map((cell) =>
              cell[1].replace(/\\n/g, ' ').replaceAll('<br>', ' ').trim()
            )
            .join(' | ')
        )
        .join('\n')
  );
}

/**
 * Unwraps `<m-email-thread-embed>` blocks: the payload is a JSON metadata
 * object immediately followed by the quoted thread's markdown with newlines
 * escaped as literal `\n`.
 */
function flattenEmailThreadEmbeds(text: string): string {
  return text.replace(
    /<m-email-thread-embed>(.*?)<\/m-email-thread-embed>/gs,
    (_, embed: string) => embed.replace(/^\{.*?\}/, '').replace(/\\n/g, '\n')
  );
}

/**
 * Converts internal markdown to compact, embedding-friendly text for task
 * dedup. Every internal-format `<m-*>` tag is reduced to the identity that
 * distinguishes it, dropping the JSON boilerplate that is the same in every
 * tag:
 * - Document mentions/cards/snapshots: `[documentName](blockName:documentId)`,
 *   with `#channel_message_id` appended when the mention targets a channel
 *   message
 * - Links: `[text](url)`; videos: `[video](url)`; images: `[alt](dss:id|url)`
 * - User mentions: email; contacts: name; dates: display format;
 *   groups: `@alias`; themes: name; equations: the source expression;
 *   awaits: placeholder text
 * - Tables and email-thread embeds are flattened to their inner text
 * - Watermarks and unrecognized `m-*` tags are dropped entirely
 *
 * This is the format the task dedup backend embeds: the task composer sends it
 * directly to the similarity-search endpoint, and lexical-service produces it
 * for stored tasks via the markdown endpoint's `embedding` target. Both sides
 * must agree, so any change here changes what new embeddings look like and
 * may warrant re-running the task embedding backfill.
 */
export function markdownToEmbeddingText(markdown: string): string {
  // Containers first: their payloads nest further tags that the leaf passes
  // below pick up.
  let text = stripAgentContext(markdown).replace(
    /<m-snapshot>(.*?)<\/m-snapshot>/gs,
    (_, encoded) => snapshotToEmbeddingText(encoded)
  );
  text = flattenTables(text);
  text = flattenEmailThreadEmbeds(text);

  // Leaf tags.
  text = replaceJsonTag(text, 'm-agent-session-mention', (data) =>
    data.id
      ? `[${data.label || 'Agent session'}](agent_session:${data.id})`
      : data.label || ''
  );
  text = replaceJsonTag(text, 'm-document-mention', documentRefToEmbeddingText);
  text = replaceJsonTag(text, 'm-document-card', documentRefToEmbeddingText);
  text = replaceJsonTag(text, 'm-pr-mention', (data) => {
    if (data.id) return `[${data.label || 'Pull request'}](pr:${data.id})`;
    if (data.url) {
      return `[${data.label || githubPullRequestRef(data.url) || 'Pull request'}](${data.url})`;
    }
    return data.label || '';
  });
  text = replaceJsonTag(text, 'm-link', (data) =>
    data.url ? `[${data.text || data.url}](${data.url})` : data.text || ''
  );
  text = replaceJsonTag(text, 'm-image', (data) => {
    // dss images get a stable id; urls elsewhere may be transient.
    const target =
      data.srcType === 'dss' && data.id ? `dss:${data.id}` : data.url;
    return target ? `[${data.alt || 'image'}](${target})` : data.alt || '';
  });
  text = replaceJsonTag(text, 'm-video', (data) =>
    data.url ? `[video](${data.url})` : ''
  );
  text = replaceJsonTag(
    text,
    'm-katex-equation',
    (data) => data.equation || ''
  );
  text = replaceJsonTag(text, 'm-user-mention', userMentionDisplayText);
  text = replaceJsonTag(
    text,
    'm-contact-mention',
    (data) => data.name || data.emailOrDomain || ''
  );
  text = replaceJsonTag(
    text,
    'm-date-mention',
    (data) => data.displayFormat || ''
  );
  text = replaceJsonTag(
    text,
    'm-group-mention',
    (data) => `@${data.groupAlias || ''}`
  );
  text = replaceJsonTag(text, 'm-tag', (data) =>
    data.name ? `#${data.name}` : ''
  );
  text = replaceJsonTag(text, 'm-theme-mention', (data) => data.name || '');
  text = replaceJsonTag(text, 'm-connect-app', (data) =>
    data.name ? `Connect ${data.name}` : ''
  );
  text = replaceJsonTag(
    text,
    'm-account-manager-request',
    () => 'Account manager request'
  );
  text = replaceJsonTag(
    text,
    'm-db-query',
    (data) => data.title || data.prompt || 'Live database answer'
  );
  text = replaceJsonTag(text, 'm-await', (data) => data.text || '');
  text = replaceJsonTag(
    text,
    'm-reply-target',
    (data) => data.displayText || ''
  );
  text = replaceJsonTag(text, 'm-watermark', () => '');

  // Anything still tagged is an unrecognized m-* node: drop it entirely so
  // its payload cannot leak boilerplate into the embedding (the string
  // analogue of the UNKNOWN_MENTION fallback transformer).
  return text.replace(
    /<(m-[a-zA-Z0-9_-]+)>(.*?)<\/\1>/gs,
    (tagged, tag: string) => (tag === 'm-agent-context' ? tagged : '')
  );
}