Skip to content

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

8.3 KB
Raw Blame
import { fromMarkdown } from "mdast-util-from-markdown";

type MarkdownNode = {
  type: string;
  children?: MarkdownNode[];
  position?: { start: { offset?: number }; end: { offset?: number } };
};

function stripEmphasis(text: string): string {
  const pending: MarkdownNode[] = [fromMarkdown(text)];
  const markers: Array<[number, number]> = [];
  while (pending.length) {
    const node = pending.pop()!;
    if (node.children) pending.push(...node.children);
    if (node.type !== "emphasis" && node.type !== "strong") continue;
    const start = node.position?.start.offset;
    const end = node.position?.end.offset;
    if (start === undefined || end === undefined) continue;
    const width = node.type === "strong" ? 2 : 1;
    markers.push([start, start + width], [end - width, end]);
  }
  const parts: string[] = [];
  let cursor = 0;
  for (const [start, end] of markers.sort((a, b) => a[0] - b[0])) {
    parts.push(text.slice(cursor, start));
    cursor = end;
  }
  return parts.join("") + text.slice(cursor);
}

function describeCodeBlock(fence: string): string {
  const lang = fence.trim().split(/\s+/)[0]?.replace(/[^a-z0-9+#]/gi, "") ?? "";
  type SpokenLanguages = Record<string, string>;
  const spoken: SpokenLanguages = {
    ts: "TypeScript",
    tsx: "TypeScript",
    js: "JavaScript",
    jsx: "JavaScript",
    py: "Python",
    sh: "shell",
    bash: "shell",
    zsh: "shell",
    json: "JSON",
    yml: "YAML",
    yaml: "YAML",
    sql: "SQL",
    rs: "Rust",
    go: "Go",
    swift: "Swift",
    diff: "diff",
  };
  const name = spoken[lang.toLowerCase()];
  return name ? `. (a ${name} code block) ` : ". (a code block) ";
}

function shortenPaths(text: string): string {
  return text.replace(/(?:[\w.@-]+\/){1,}([\w.-]+\.\w{1,6})\b/g, "$1");
}

const ENDS_SENTENCE = /[.!?:;]\s*$/;

export function speakable(input: string): string {
  if (!input) return "";
  let text = input;

  // Fenced code first: nothing inside it may meet the rules below.
  text = text.replace(/```([^\n]*)\n[\s\S]*?(?:```|$)/g, (_m, fence: string) => describeCodeBlock(fence));
  text = text.replace(/~~~([^\n]*)\n[\s\S]*?(?:~~~|$)/g, (_m, fence: string) => describeCodeBlock(fence));
  text = stripEmphasis(text);

  // Images before links: the syntax differs by one character.
  text = text.replace(/!\[([^\]]*)\]\([^)]*\)/g, (_m, alt: string) => {
    const description = stripEmphasis(alt);
    return description ? `. (image: ${description}) ` : ". (an image) ";
  });
  text = text.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1");
  text = text.replace(/<https?:\/\/[^>\s]+>/g, " a link ");
  text = text.replace(/\bhttps?:\/\/\S+/g, " a link ");

  text = text.replace(/^\s*\|?[\s:-]*\|[\s|:-]*$/gm, "");
  text = text.replace(/^\s*\|(.+)\|\s*$/gm, (_m, row: string) =>
    row
      .split("|")
      .map((cell) => cell.trim())
      .filter(Boolean)
      .join(", "),
  );

  text = text.replace(/`([^`\n]+)`/g, (_m, code: string) => (code.length <= 40 ? code : " that snippet "));

  text = text.replace(/^\s{0,3}#{1,6}\s+(.*)$/gm, (_m, head: string) =>
    ENDS_SENTENCE.test(head) ? head : `${head.trim()}.`,
  );

  text = text.replace(/^\s*[-*+]\s+/gm, "");
  text = text.replace(/^\s*\d+[.)]\s+/gm, "");
  text = text.replace(/^\s*>\s?/gm, "");
  text = text.replace(/^\s*(?:[-*_]\s*){3,}$/gm, "");

  text = text.replace(/~~(.*?)~~/g, "$1");

  text = text.replace(/\[[ xX]\]\s*/g, "");

  text = shortenPaths(text);

  // A voice either ignores emoji or announces them by name.
  text = text.replace(
    // oxlint-disable-next-line no-misleading-character-class -- variation selectors are stripped on their own, not as part of a grapheme
    /[\u{1F000}-\u{1FAFF}\u{2600}-\u{27BF}\u{FE00}-\u{FE0F}\u{2190}-\u{21FF}\u{2B00}-\u{2BFF}]/gu,
    "",
  );

  text = text.replace(/\n{2,}/g, ". ");
  text = text.replace(/\n/g, ". ");

  text = text.replace(/\s+/g, " ");
  text = text.replace(/\s+([.,!?;:])/g, "$1");
  text = text.replace(/(?:\.\s*){2,}/g, ". ");
  text = text.replace(/,\s*\./g, ".");
  text = text.trim();

  // A synthesizer renders a lone full stop as a click: nothing to say means nothing to send.
  return /[\p{L}\p{N}]/u.test(text) ? text : "";
}

// The first spoken block bounds time-to-first-audio, so the voice path caps it
// tighter than the general maxChars.
export const VOICE_FIRST_BLOCK_MAX_CHARS = 90;

const BOUNDARY = /(?<!\b(?:e\.g|i\.e|etc|vs|Dr|Mr|Mrs|Ms|No|approx))(?<![.\d])([.!?])(["')\]]*)\s+/g;
const WORD_SEGMENTER = new Intl.Segmenter(undefined, { granularity: "word" });
const GRAPHEME_SEGMENTER = new Intl.Segmenter(undefined, { granularity: "grapheme" });

export function toUtterances(
  input: string,
  { minChars = 12, maxChars = 320, firstBlockMaxChars }: {
    minChars?: number;
    maxChars?: number;
    firstBlockMaxChars?: number;
  } = {},
): string[] {
  const text = speakable(input);
  if (!text) return [];

  // A sentinel, not " ": the boundary match consumes the trailing space.
  const MARK = "\u0000";
  const rough = text
    .replace(BOUNDARY, `$1$2${MARK}`)
    .split(MARK)
    .map((s) => s.trim())
    .filter(Boolean);

  const out: string[] = [];
  for (const piece of rough) {
    const parts = piece.length <= maxChars ? [piece] : splitLong(piece, maxChars);
    for (const part of parts) {
      const prev = out[out.length - 1];
      if (prev && prev.length + part.length + 1 <= maxChars && (prev.length < minChars || part.length < minChars)) {
        out[out.length - 1] = `${prev} ${part}`;
      } else {
        out.push(part);
      }
    }
  }
  // The cap goes on the assembled first block: the minChars merge above can
  // glue a later piece onto it, so capping the first rough piece is not enough.
  const first = out[0];
  if (firstBlockMaxChars !== undefined && first !== undefined && first.length > firstBlockMaxChars) {
    out.splice(0, 1, ...splitLong(first, firstBlockMaxChars));
  }
  return out;
}

function splitLong(text: string, maxChars: number): string[] {
  const out: string[] = [];
  let rest = text;
  while (rest.length > maxChars) {
    const window = rest.slice(0, maxChars);
    const at = Math.max(window.lastIndexOf(", "), window.lastIndexOf("; "), window.lastIndexOf(" — "));
    let cut = at > maxChars / 2 ? at + 1 : window.lastIndexOf(" ");
    if (cut <= 0) {
      cut = unspacedCut(rest, maxChars);
    }
    if (cut <= 0) break;
    out.push(rest.slice(0, cut).trim());
    rest = rest.slice(cut).trim();
  }
  if (rest) out.push(rest);
  return out;
}

function unspacedCut(text: string, maxChars: number): number {
  let firstWord: Intl.SegmentData | undefined;
  let cut = -1;
  for (const segment of WORD_SEGMENTER.segment(text)) {
    if (segment.index > maxChars) break;
    if (!segment.isWordLike) continue;
    if (firstWord) cut = segment.index;
    else firstWord = segment;
  }
  if (cut > 0 || !firstWord || !/^[\p{Script_Extensions=Katakana}\p{M}]+$/u.test(firstWord.segment)) return cut;
  for (const { index } of GRAPHEME_SEGMENTER.segment(firstWord.segment)) {
    const boundary = firstWord.index + index;
    if (boundary > maxChars) break;
    if (index > 0) cut = boundary;
  }
  return cut;
}

export function narrateTool(toolName: string): string | null {
  const name = toolName.replace(/^mcp__[^_]+__/, "").trim();
  if (!name) return null;
  if (/^(auto-approved|error):/i.test(name)) return null;

  const bare = name.toLowerCase();
  const verbs: Array<[RegExp, string]> = [
    [/^(bash|shell|terminal|run_command|execute|computer_exec)$/, "running a command"],
    [/^(read|read_file|view)$/, "reading a file"],
    [/^(write|create_file)$/, "writing a file"],
    [/^(edit|apply_patch|str_replace|multiedit)$/, "editing a file"],
    [/^(grep|search|glob|find)$/, "searching"],
    [/^(web_?search|websearch)$/, "searching the web"],
    [/^(web_?fetch|fetch)$/, "reading a page"],
    [/^screenshot$/, "looking at the screen"],
    [/^(click|type_text|press_key|scroll|computer_batch)$/, "using the computer"],
    [/^open_url$/, "opening a page"],
    [/^list_bots$/, "checking who's around"],
    [/^trigger$/, "working on an automation"],
    [/^trigger_info$/, "checking automations"],
    [/^delete_trigger$/, "deleting an automation"],
    [/^ask_bot$/, "asking a teammate"],
  ];
  for (const [pattern, phrase] of verbs) {
    if (pattern.test(bare)) return phrase;
  }
  const short = shortenPaths(name).slice(0, 40);
  return /^[\w .:/-]+$/.test(short) ? `running ${short}` : null;
}