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.

10.3 KB
Raw Blame
import { match, P } from 'ts-pattern';
import { Sdk as AgentHarnessSdk } from '../../generated/agent-harness/sdk.gen';
import { Sdk as AuthSdk } from '../../generated/auth/sdk.gen';
import { Sdk as CalendarSdk } from '../../generated/calendar/sdk.gen';
import { Sdk as CognitionSdk } from '../../generated/cognition/sdk.gen';
import { Sdk as ContactsSdk } from '../../generated/contacts/sdk.gen';
import { Sdk as EmailSdk } from '../../generated/email/sdk.gen';
import { Sdk as NotificationSdk } from '../../generated/notification/sdk.gen';
import { Sdk as PropertiesSdk } from '../../generated/properties/sdk.gen';
import { Sdk as ScheduledActionSdk } from '../../generated/scheduled-action/sdk.gen';
import { Sdk as SearchSdk } from '../../generated/search/sdk.gen';
import { createClient } from '../../generated/storage/client';
import { Sdk as StorageSdk } from '../../generated/storage/sdk.gen';
import type { Bot } from '../../generated/storage/types.gen';
import { Sdk as UnfurlSdk } from '../../generated/unfurl/sdk.gen';
import {
  type Env,
  HOSTS,
  type MacroAuth,
  type MacroOpts,
  type ServiceName,
  type TokenSource,
  WEB_APP_URLS,
} from '../config';
import { BotsNamespace } from '../entities/bots/namespace';
import { User } from '../entities/users/user';
import { MacroEvents } from '../events/receiver';
import { type LocalPortmap, resolveLocalPortmap } from '../local-portmap';
import { observeSdk } from './activity';

const USER_API_KEY_HEADER = 'x-macro-user-api-key';

const USER_API_KEY_PREFIX = 'mak_';

const BOT_TOKEN_PREFIX = 'mbot_';

type CredentialHeader = readonly [name: string, value: string];

function userCredentialHeader(secret: string): CredentialHeader {
  return match(secret)
    .with(P.string.startsWith(BOT_TOKEN_PREFIX), () => {
      throw new Error(
        "bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.",
      );
    })
    .with(
      P.string.startsWith(USER_API_KEY_PREFIX),
      (key): CredentialHeader => [USER_API_KEY_HEADER, key],
    )
    .otherwise(
      (token): CredentialHeader => ['Authorization', `Bearer ${token}`],
    );
}

async function resolveToken(source: TokenSource): Promise<string> {
  return typeof source === 'function' ? await source() : source;
}

export async function requestAuthHeaders(
  auth: MacroAuth,
  requestedAs?: string,
  existing?: { hasBotScope?: boolean },
): Promise<ReadonlyArray<readonly [string, string]>> {
  return match(auth)
    .with({ type: 'bot' }, async (botAuth) => {
      const tok = await resolveToken(botAuth.token);
      if (!tok.startsWith(BOT_TOKEN_PREFIX)) {
        throw new Error(
          "user API key passed as a bot token. Use auth: { type: 'user', apiKey } or MACRO_API_KEY.",
        );
      }
      const headers: Array<readonly [string, string]> = [
        ['x-macro-bot-token', tok],
      ];
      if (!existing?.hasBotScope) {
        headers.push([
          'x-macro-bot-scope',
          botAuth.scope ?? (requestedAs ? 'user' : 'team'),
        ]);
      }
      if (requestedAs) {
        headers.push(['x-macro-bot-for-macro-user-id', requestedAs]);
      }
      return headers;
    })
    .with({ type: 'user', apiKey: P.string }, ({ apiKey }) => {
      if (apiKey.startsWith(BOT_TOKEN_PREFIX)) {
        throw new Error(
          "bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.",
        );
      }
      return [[USER_API_KEY_HEADER, apiKey] as const];
    })
    .with({ type: 'user' }, async ({ token }) => {
      const pair = userCredentialHeader(await resolveToken(token));
      return [pair];
    })
    .exhaustive();
}

export class MacroClient {
  readonly scheduledAction: ScheduledActionSdk;

  readonly unfurl: UnfurlSdk;

  readonly agentHarness: AgentHarnessSdk;

  readonly auth: AuthSdk;

  readonly calendar: CalendarSdk;

  readonly cognition: CognitionSdk;

  readonly contacts: ContactsSdk;

  readonly email: EmailSdk;

  readonly notification: NotificationSdk;

  readonly properties: PropertiesSdk;

  readonly search: SearchSdk;

  readonly storage: StorageSdk;

  readonly webAppUrl: string;

  readonly wsVerify?: string;

  readonly events: MacroEvents;

  /** Resolved authentication config (distinct from `auth`, the auth-service SDK). */
  readonly authConfig: MacroAuth;

  /** Resolved service base urls: env defaults, then the local-stack portmap,
   * then `opts.hosts` overrides. */
  readonly hosts: Record<ServiceName, string>;

  /** The local stack's generated port map; only set when env is `local`. */
  readonly localPortmap?: LocalPortmap;

  private readonly requestedAs?: string;

  private selfBotRecord?: Promise<Bot>;

  private selfPrincipal?: Promise<string>;

  constructor(opts: MacroOpts) {
    const env = resolveEnv(opts);
    const localPortmap = env === 'local' ? resolveLocalPortmap() : undefined;
    const hosts = { ...HOSTS[env], ...localPortmap?.hosts, ...opts.hosts };
    this.hosts = hosts;
    this.localPortmap = localPortmap;
    const envWebUrl =
      typeof process !== 'undefined' ? process.env.MACRO_WEB_URL : undefined;
    this.webAppUrl =
      opts.webAppUrl ??
      envWebUrl ??
      localPortmap?.webAppUrl ??
      WEB_APP_URLS[env];
    this.authConfig = resolveAuth(opts);
    this.requestedAs = opts.requestedAs;
    if (this.requestedAs && this.authConfig.type !== 'bot') {
      throw new Error(
        'requestedAs() requires bot auth — a user token always acts as its own user',
      );
    }
    this.wsVerify = opts.wsVerify;

    this.scheduledAction = observeSdk(
      new ScheduledActionSdk({
        client: this.makeClient(hosts['scheduled-action']),
      }),
      'scheduled-action',
      opts.onRequest,
    );
    this.unfurl = observeSdk(
      new UnfurlSdk({ client: this.makeClient(hosts.unfurl) }),
      'unfurl',
      opts.onRequest,
    );
    this.agentHarness = observeSdk(
      new AgentHarnessSdk({
        client: this.makeClient(hosts['agent-harness']),
      }),
      'agent-harness',
      opts.onRequest,
    );
    this.auth = observeSdk(
      new AuthSdk({ client: this.makeClient(hosts.auth) }),
      'auth',
      opts.onRequest,
    );
    this.calendar = observeSdk(
      new CalendarSdk({
        client: this.makeClient(hosts.calendar),
      }),
      'calendar',
      opts.onRequest,
    );
    this.cognition = observeSdk(
      new CognitionSdk({
        client: this.makeClient(hosts.cognition),
      }),
      'cognition',
      opts.onRequest,
    );
    this.contacts = observeSdk(
      new ContactsSdk({
        client: this.makeClient(hosts.contacts),
      }),
      'contacts',
      opts.onRequest,
    );
    this.email = observeSdk(
      new EmailSdk({ client: this.makeClient(hosts.email) }),
      'email',
      opts.onRequest,
    );
    this.notification = observeSdk(
      new NotificationSdk({
        client: this.makeClient(hosts.notification),
      }),
      'notification',
      opts.onRequest,
    );
    this.properties = observeSdk(
      new PropertiesSdk({
        client: this.makeClient(hosts.properties),
      }),
      'properties',
      opts.onRequest,
    );
    this.search = observeSdk(
      new SearchSdk({ client: this.makeClient(hosts.search) }),
      'search',
      opts.onRequest,
    );
    this.storage = observeSdk(
      new StorageSdk({ client: this.makeClient(hosts.storage) }),
      'storage',
      opts.onRequest,
    );

    const envWebhookSecret =
      typeof process !== 'undefined'
        ? process.env.MACRO_WEBHOOK_SECRET
        : undefined;
    const webhookSecret = opts.webhookSecret ?? envWebhookSecret;
    this.events = new MacroEvents(this, webhookSecret);
  }

  /** Whether requests have a user identity accepted by acting-user endpoints. */
  hasActingUser(): boolean {
    return this.authConfig.type === 'user' || this.requestedAs !== undefined;
  }

  /**
   * The authenticated bot's own record, fetched once and cached. Bot auth
   * only. Failed lookups are not cached, so a later call retries.
   */
  selfBot(): Promise<Bot> {
    this.selfBotRecord ??= new BotsNamespace(this).me().catch((error) => {
      this.selfBotRecord = undefined;
      throw error;
    });
    return this.selfBotRecord;
  }

  /**
   * The authenticated caller's mentionable principal — `bot|<uuid>` for bot
   * auth, `macro|<email>` for user auth — fetched once and cached. Failed
   * lookups are not cached, so a later call retries.
   */
  myPrincipalId(): Promise<string> {
    this.selfPrincipal ??= (
      this.authConfig.type === 'bot'
        ? this.selfBot().then((bot) => `bot|${bot.id}`)
        : User.me(this).then((user) => user.id)
    ).catch((error) => {
      this.selfPrincipal = undefined;
      throw error;
    });
    return this.selfPrincipal;
  }

  private makeClient(baseUrl: string) {
    const c = createClient({ baseUrl });
    c.interceptors.request.use(async (request) => {
      const headers = await requestAuthHeaders(
        this.authConfig,
        this.requestedAs,
        { hasBotScope: request.headers.has('x-macro-bot-scope') },
      );
      for (const [name, value] of headers) {
        request.headers.set(name, value);
      }
      return request;
    });
    return c;
  }
}

function resolveEnv(opts: MacroOpts): Env {
  if (opts.env) return opts.env;
  const fromEnv =
    typeof process !== 'undefined' ? process.env.MACRO_ENV : undefined;
  if (!fromEnv) return 'prod';
  if (!(fromEnv in HOSTS)) {
    throw new Error(
      `invalid MACRO_ENV "${fromEnv}" — expected local, dev, or prod`,
    );
  }
  return fromEnv as Env;
}

function resolveAuth(opts: MacroOpts): MacroAuth {
  if (opts.auth) return opts.auth;
  if (opts.token) return { type: 'user', token: opts.token };
  const envApiKey =
    typeof process !== 'undefined' ? process.env.MACRO_API_KEY : undefined;
  const envBotToken =
    typeof process !== 'undefined' ? process.env.MACRO_BOT_TOKEN : undefined;
  if (envApiKey && envBotToken) {
    throw new Error(
      'both MACRO_API_KEY and MACRO_BOT_TOKEN are set — pass auth to new Macro() to pick one',
    );
  }
  if (envBotToken) return { type: 'bot', token: envBotToken };
  return {
    type: 'user',
    token:
      envApiKey ??
      (() => {
        throw new Error(
          'no Macro credential. Set MACRO_API_KEY (API key or bearer token) or MACRO_BOT_TOKEN, or pass token/auth to new Macro().',
        );
      }),
  };
}

export type { ServiceName };