Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

15.0 KB
Raw Blame
import { parseJson, type JsonValue } from "./schema.ts";
import { isBotPackage, parseBotPackage, parsePackageDocument, upgradeV1, type PackageDocument, type ParsedBotPackage } from "./bot-package.ts";
import { PACKAGE_V1_VERSION } from "../shared/package-format.ts";
import { fetchGithubFolder } from "./share-github.ts";
import { parseTeamManifest, type ParsedTeamManifest } from "./team-manifest.ts";

export const TEAM_LIBRARY_REPOSITORY = "https://github.com/milind-soni/openmausbot-teams";
export const TEAM_LIBRARY_RAW_ROOT = "https://raw.githubusercontent.com/milind-soni/openmausbot-teams/main";
export const TEAM_LIBRARY_CATALOG_URL = `${TEAM_LIBRARY_RAW_ROOT}/catalog.json`;

// Templates published from MausBot are merged into the catalog automatically, so it grows by several a day.
const MAX_CATALOG_BYTES = 2_000_000, MAX_CATALOG_TEAMS = 1000;
const MAX_MANIFEST_BYTES = 1_000_000;

export interface TeamCatalogEntry {
  slug: string;
  name: string;
  summary: string;
  category: string;
  outcome?: string;
  setupMinutes?: number;
  featured?: boolean;
  package?: string;
  manifest: string;
  readme: string;
  /** A template folder (`teams/<slug>`): read whole, with its skills and pictures, instead of the files made from it. */
  folder?: string;
  /** A folder holding one bot (added without a department) or a department. */
  kind?: "bot" | "department";
  /** Each bot's face on the gallery card; `picture` is a path in the repository until the catalog route reads it. */
  avatars?: TeamCatalogAvatar[];
  members: number;
  skills: string[];
  requires: { apps: string[] };
  /** Who published it ("Published by"), as the template's own frontmatter credits them. */
  author?: string;
}

export interface TeamCatalogAvatar {
  key: string;
  name: string;
  color: string;
  mascotBody?: string;
  mascotExpression?: string;
  picture?: string;
}

export interface TeamCatalog {
  format: "openmaus.catalog";
  version: 1;
  repositoryUrl: typeof TEAM_LIBRARY_REPOSITORY;
  teams: TeamCatalogEntry[];
}

type Fetcher = typeof fetch;

const isRecord = (value: unknown): value is Record<string, unknown> =>
  Boolean(value) && typeof value === "object" && !Array.isArray(value);

function text(value: unknown, field: string, max: number): string {
  if (typeof value !== "string" || !value.trim()) throw new Error(`${field} is required`);
  const normalized = value.trim();
  if (normalized.length > max) throw new Error(`${field} is too long`);
  return normalized;
}

function relativeFile(value: unknown, field: string, suffix: string, prefix: string): string {
  const path = text(value, field, 300);
  if (
    path.startsWith("/") ||
    path.includes("\\") ||
    path.split("/").some((part) => !part || part === "." || part === "..") ||
    !path.startsWith(prefix) ||
    !path.endsWith(suffix)
  ) {
    throw new Error(`${field} is not a safe catalog path`);
  }
  return path;
}

function stringList(value: unknown, field: string, maxItems: number): string[] {
  if (!Array.isArray(value) || value.length > maxItems) throw new Error(`${field} is invalid`);
  return value.map((item, index) => text(item, `${field}[${index}]`, 100));
}

/** A catalog entry's credit, as a name or `{ name }`: one line of up to 100 characters, else none. */
function catalogAuthor(value: unknown): string | undefined {
  const name = typeof value === "string" ? value : isRecord(value) && typeof value.name === "string" ? value.name : undefined;
  const line = name?.replace(/[\p{Cc}\p{Cf}]+/gu, " ").replace(/\s+/g, " ").trim();
  return line && line.length <= 100 ? line : undefined;
}

const LOOK = /^[a-z0-9][a-z0-9-]{0,39}$/;
const MAX_FACES = 50;

/** The faces a catalog entry lists. A face that isn't well formed is left out; it never fails the catalog. */
function catalogAvatars(value: unknown, slug: string): TeamCatalogAvatar[] | undefined {
  if (!Array.isArray(value)) return undefined;
  const picture = new RegExp(`^teams/${slug}/avatars/[a-z0-9][a-z0-9_-]{0,63}\\.(?:webp|png|jpg)$`);
  return value.slice(0, MAX_FACES).flatMap((raw): TeamCatalogAvatar[] => {
    if (!isRecord(raw) || typeof raw.key !== "string" || !/^[a-z0-9][a-z0-9_-]{0,63}$/.test(raw.key)) return [];
    if (typeof raw.name !== "string" || !raw.name.trim() || raw.name.trim().length > 100) return [];
    if (typeof raw.color !== "string" || !LOOK.test(raw.color)) return [];
    return [{
      key: raw.key, name: raw.name.trim(), color: raw.color,
      ...(typeof raw.mascotBody === "string" && LOOK.test(raw.mascotBody) ? { mascotBody: raw.mascotBody } : {}),
      ...(typeof raw.mascotExpression === "string" && LOOK.test(raw.mascotExpression) ? { mascotExpression: raw.mascotExpression } : {}),
      ...(typeof raw.picture === "string" && picture.test(raw.picture) ? { picture: raw.picture } : {}),
    }];
  });
}

/** Validate the remotely maintained index before any of it reaches the renderer. */
export function parseTeamCatalog(value: unknown): TeamCatalog {
  if (!isRecord(value) || value.format !== "openmaus.catalog" || value.version !== 1) {
    throw new Error("The team library catalog is not supported");
  }
  if (!Array.isArray(value.teams) || value.teams.length > MAX_CATALOG_TEAMS) {
    throw new Error("The team library catalog is invalid");
  }
  const slugs = new Set<string>();
  const teams = value.teams.map((raw, index): TeamCatalogEntry => {
    const field = `teams[${index}]`;
    if (!isRecord(raw)) throw new Error(`${field} is invalid`);
    const slug = text(raw.slug, `${field}.slug`, 80);
    if (!/^[a-z0-9][a-z0-9-]*$/.test(slug) || slugs.has(slug)) {
      throw new Error(`${field}.slug is invalid`);
    }
    slugs.add(slug);
    const prefix = `teams/${slug}/`;
    const requires = isRecord(raw.requires) ? raw.requires : {};
    const avatars = catalogAvatars(raw.avatars, slug);
    return {
      slug,
      name: text(raw.name, `${field}.name`, 100),
      summary: text(raw.summary, `${field}.summary`, 300),
      category: text(raw.category, `${field}.category`, 80),
      ...(typeof raw.outcome === "string" ? { outcome: text(raw.outcome, `${field}.outcome`, 300) } : {}),
      ...(typeof raw.setupMinutes === "number" && Number.isSafeInteger(raw.setupMinutes) && raw.setupMinutes > 0 && raw.setupMinutes <= 240
        ? { setupMinutes: raw.setupMinutes }
        : {}),
      ...(typeof raw.featured === "boolean" ? { featured: raw.featured } : {}),
      ...(raw.package !== undefined
        ? { package: relativeFile(raw.package, `${field}.package`, ".md", "packages/") }
        : {}),
      manifest: relativeFile(raw.manifest, `${field}.manifest`, ".mausteam.json", prefix),
      ...(raw.folder === `teams/${slug}` ? { folder: `teams/${slug}` } : {}),
      ...(raw.kind === "bot" || raw.kind === "department" ? { kind: raw.kind } : {}),
      ...(avatars ? { avatars } : {}),
      readme: relativeFile(raw.readme, `${field}.readme`, "README.md", prefix),
      members:
        typeof raw.members === "number" && Number.isSafeInteger(raw.members) && raw.members > 0 && raw.members <= 200
          ? raw.members
          : (() => { throw new Error(`${field}.members is invalid`); })(),
      skills: Array.isArray(raw.skills)
        ? raw.skills.map((skill, skillIndex) =>
            relativeFile(skill, `${field}.skills[${skillIndex}]`, "SKILL.md", `${prefix}skills/`),
          )
        : (() => { throw new Error(`${field}.skills is invalid`); })(),
      requires: { apps: stringList(requires.apps ?? [], `${field}.requires.apps`, 30) },
      ...(catalogAuthor(raw.author) ? { author: catalogAuthor(raw.author)! } : {}),
    };
  });
  return {
    format: "openmaus.catalog",
    version: 1,
    repositoryUrl: TEAM_LIBRARY_REPOSITORY,
    teams,
  };
}

async function fetchJson(url: string, maxBytes: number, fetcher: Fetcher): Promise<JsonValue> {
  const response = await fetcher(url, {
    headers: { accept: "application/json, text/plain;q=0.9" },
    redirect: "error",
    signal: AbortSignal.timeout(10_000),
  });
  if (!response.ok) {
    const error = Object.assign(new Error(`GitHub returned HTTP ${response.status}`), { status: response.status });
    throw error;
  }
  const announced = Number(response.headers.get("content-length") ?? 0);
  if (announced > maxBytes) throw new Error("The remote team file is too large");
  const raw = await response.text();
  if (Buffer.byteLength(raw) > maxBytes) throw new Error("The remote team file is too large");
  try {
    return parseJson(raw);
  } catch {
    throw new Error("GitHub did not return valid JSON");
  }
}

async function fetchText(url: string, maxBytes: number, fetcher: Fetcher): Promise<string> {
  const response = await fetcher(url, {
    headers: { accept: "text/markdown, text/plain;q=0.9" },
    redirect: "error",
    signal: AbortSignal.timeout(10_000),
  });
  if (!response.ok) throw Object.assign(new Error(`GitHub returned HTTP ${response.status}`), { status: response.status });
  const announced = Number(response.headers.get("content-length") ?? 0);
  if (announced > maxBytes) throw new Error("The remote team file is too large");
  const raw = await response.text();
  if (Buffer.byteLength(raw) > maxBytes) throw new Error("The remote team file is too large");
  return raw;
}

export async function fetchTeamCatalog(fetcher: Fetcher = fetch): Promise<TeamCatalog> {
  return parseTeamCatalog(await fetchJson(TEAM_LIBRARY_CATALOG_URL, MAX_CATALOG_BYTES, fetcher));
}

export type ParsedShareableTeam = ParsedTeamManifest | ParsedBotPackage | PackageDocument;

function parseShareable(value: JsonValue | string): ParsedShareableTeam {
  if (typeof value === "string") return parseBotPackage(value);
  if (!isBotPackage(value)) return parseTeamManifest(value);
  // A shared team (v2) is read as a file: it cannot claim a publisher.
  return (value as { version?: unknown }).version === 1 ? parseBotPackage(value) : parsePackageDocument(value, { trust: "file" });
}

async function fetchShareable(url: string, fetcher: Fetcher): Promise<ParsedShareableTeam> {
  return url.endsWith(".md")
    ? parseBotPackage(await fetchText(url, MAX_MANIFEST_BYTES, fetcher))
    : parseShareable(await fetchJson(url, MAX_MANIFEST_BYTES, fetcher));
}

export async function fetchLibraryTeam(slug: string, fetcher: Fetcher = fetch): Promise<ParsedShareableTeam> {
  if (!/^[a-z0-9][a-z0-9-]*$/.test(slug)) throw new Error("That team name is invalid");
  const catalog = await fetchTeamCatalog(fetcher);
  const entry = catalog.teams.find((team) => team.slug === slug);
  if (!entry) throw Object.assign(new Error("That library team was not found"), { status: 404 });
  if (entry.folder) {
    const folder = await fetchGithubFolder(`${TEAM_LIBRARY_RAW_ROOT}/${entry.folder}`, fetcher);
    return folder.kind === "package" ? folder.document : parseTeamManifest(folder.manifest as Parameters<typeof parseTeamManifest>[0]);
  }
  return fetchShareable(`${TEAM_LIBRARY_RAW_ROOT}/${entry.package ?? entry.manifest}`, fetcher);
}

const MAX_CHIEF_TEAMS = 30;
const MAX_ROLE_TEXT = 280;

export interface LibraryRole { name: string; title: string; does?: string; lead?: true }
export interface LibraryTeamRoles { name: string; summary: string; roles: LibraryRole[] }

const oneLine = (text: string, max: number): string => {
  const line = text.replace(/\s+/g, " ").trim();
  return line.length > max ? `${line.slice(0, max - 1).trimEnd()}…` : line;
};

function libraryRoles(team: ParsedShareableTeam): LibraryRole[] {
  const role = (member: { name: string; title?: string; description?: string }, lead: boolean): LibraryRole => ({
    name: member.name, title: member.title?.trim() || "Specialist",
    ...(member.description?.trim() ? { does: oneLine(member.description, MAX_ROLE_TEXT) } : {}),
    ...(lead ? { lead: true as const } : {}),
  });
  if (!("package" in team)) return team.team.members.map((member) => role(member, false));
  const pkg = team.version === PACKAGE_V1_VERSION ? upgradeV1(team).package : team.package;
  return pkg.agents.map((agent) => role(agent, agent.key === pkg.team?.leader));
}

/** Each ready-made team's name, one line and roles: enough for a Chief to create the team itself, one specialist at a
 * time. A team whose file cannot be read keeps its name and summary with no roles. */
export async function libraryTeamRoles(fetcher: Fetcher = fetch): Promise<LibraryTeamRoles[]> {
  const catalog = await fetchTeamCatalog(fetcher);
  return Promise.all(catalog.teams.slice(0, MAX_CHIEF_TEAMS).map(async (entry) => ({
    name: entry.name,
    summary: entry.summary,
    roles: await fetchShareable(`${TEAM_LIBRARY_RAW_ROOT}/${entry.package ?? entry.manifest}`, fetcher).then(libraryRoles, () => []),
  })));
}

function safeSegment(value: string): boolean {
  return /^[A-Za-z0-9._-]+$/.test(value) && value !== "." && value !== "..";
}

/** Public GitHub Markdown playbooks and legacy JSON team files only; other hosts never reach server fetch. */
export function githubManifestUrls(input: string): string[] {
  let url: URL;
  try {
    url = new URL(input.trim());
  } catch {
    throw new Error("Enter a valid GitHub URL");
  }
  if (url.protocol !== "https:" || url.username || url.password || url.port) {
    throw new Error("Only public HTTPS GitHub links are supported");
  }
  const parts = url.pathname.split("/").filter(Boolean).map((part) => decodeURIComponent(part));
  if (!parts.every(safeSegment)) throw new Error("That GitHub path is not supported");

  if (url.hostname === "github.com" || url.hostname === "www.github.com") {
    if (parts.length === 2) {
      const [owner, repo] = parts;
      return [
        `https://raw.githubusercontent.com/${owner}/${repo}/main/botmrr.md`,
        `https://raw.githubusercontent.com/${owner}/${repo}/main/team.md`,
        `https://raw.githubusercontent.com/${owner}/${repo}/main/team.mausteam.json`,
        `https://raw.githubusercontent.com/${owner}/${repo}/master/botmrr.md`,
        `https://raw.githubusercontent.com/${owner}/${repo}/master/team.md`,
        `https://raw.githubusercontent.com/${owner}/${repo}/master/team.mausteam.json`,
      ];
    }
    if (parts.length >= 5 && (parts[2] === "blob" || parts[2] === "raw")) {
      const [owner, repo, , ref, ...file] = parts;
      if (!file.at(-1)?.match(/\.(?:md|json)$/)) throw new Error("The GitHub link must point to a Markdown playbook or JSON team file");
      return [`https://raw.githubusercontent.com/${owner}/${repo}/${ref}/${file.join("/")}`];
    }
  }

  if (url.hostname === "raw.githubusercontent.com" && parts.length >= 4) {
    if (!parts.at(-1)?.match(/\.(?:md|json)$/)) throw new Error("The GitHub link must point to a Markdown playbook or JSON team file");
    return [`https://raw.githubusercontent.com/${parts.join("/")}`];
  }

  throw new Error("Paste a GitHub repository, Markdown playbook, or legacy JSON team link");
}

export async function fetchGithubTeam(input: string, fetcher: Fetcher = fetch): Promise<ParsedShareableTeam> {
  const urls = githubManifestUrls(input);
  let lastError: unknown;
  for (const url of urls) {
    try {
      return await fetchShareable(url, fetcher);
    } catch (error) {
      lastError = error;
      if ((error as { status?: number }).status !== 404) throw error;
    }
  }
  throw lastError ?? new Error("No botmrr.md, team.md, or legacy team file was found in that repository");
}