Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

7.8 KB
Raw Blame
#!/usr/bin/env node

import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { createHash } from "node:crypto";
import { parseDocument } from "yaml";
import process from "node:process";
import { format as formatWithPrettier } from "prettier";

const packageRoot = resolve(new URL("..", import.meta.url).pathname);
const generatedPath = resolve(packageRoot, "src/generated/skills.js");
const mcpGeneratedPath = resolve(packageRoot, "src/generated/mcp-skills.js");
const sourceRef = process.env.LANGFUSE_SKILLS_REF ?? "main";
const isCheckMode = process.argv.includes("--check");

const getGitHubHeaders = () => ({
  Accept: "application/vnd.github+json",
  Authorization: process.env.GITHUB_TOKEN
    ? `Bearer ${process.env.GITHUB_TOKEN}`
    : undefined,
  "User-Agent": "langfuse-sync-skills",
});

const fetchResponse = async (url) => {
  const response = await fetch(url, { headers: getGitHubHeaders() });

  if (!response.ok) {
    throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
  }

  return response;
};

const parseSkill = (fileName, markdown) => {
  const frontmatterMatch = markdown.match(/^---\n([\s\S]*?)\n---\n?/);
  if (!frontmatterMatch) {
    throw new Error(`${fileName} is missing frontmatter`);
  }

  const metadata = {};
  let currentKey;
  for (const line of frontmatterMatch[1].split("\n")) {
    const match = line.match(/^([a-z_]+):\s*(.*)$/);
    if (match) {
      currentKey = match[1];
      metadata[currentKey] = match[2];
    } else if (currentKey === "description" && line.trim()) {
      metadata.description += ` ${line.trim()}`;
    }
  }

  for (const key of ["name", "description"]) {
    if (
      metadata[key]?.startsWith("'") &&
      metadata[key]?.endsWith("'")
    ) {
      metadata[key] = metadata[key].slice(1, -1).replaceAll("''", "'");
    }
  }
  if (
    !metadata ||
    typeof metadata !== "object" ||
    Array.isArray(metadata) ||
    typeof metadata.name !== "string" ||
    typeof metadata.description !== "string"
  ) {
    throw new Error(`${fileName} has invalid skill metadata`);
  }

  const instructions = markdown.slice(frontmatterMatch[0].length).trim();
  if (!instructions) {
    throw new Error(`${fileName} is missing instructions`);
  }

  return {
    name: metadata.name,
    description: metadata.description,
    instructions,
  };
};

const fetchTree = async () => {
  const response = await fetchResponse(
    `https://api.github.com/repos/langfuse/skills/git/trees/${encodeURIComponent(sourceRef)}?recursive=1`,
  );
  const tree = await response.json();
  if (tree.truncated) throw new Error("Incomplete upstream tree");
  return tree;
};

const findSkillRoots = (tree) => {
  const roots = tree.tree
    .filter((entry) => /^skills\/[^/]+\/SKILL\.md$/.test(entry.path))
    .map((entry) => entry.path.slice(0, -9))
    .sort();
  if (roots.length === 0) throw new Error("No upstream skills found");
  return roots;
};

const downloadFile = async (sha, root, entry) => {
  const response = await fetchResponse(
    `https://raw.githubusercontent.com/langfuse/skills/${sha}/${entry.path}`,
  );
  return {
    path: entry.path.slice(root.length + 1),
    bytes: Buffer.from(await response.arrayBuffer()),
  };
};

const downloadBundle = async (tree, root) => {
  const entries = tree.tree
    .filter(
      (entry) => entry.type === "blob" && entry.path.startsWith(root + "/"),
    )
    .sort((a, b) => a.path.localeCompare(b.path));
  const files = await Promise.all(
    entries.map((entry) => downloadFile(tree.sha, root, entry)),
  );
  return { name: root.split("/").at(-1), files };
};

const getExpectedSkills = async () => {
  const tree = await fetchTree();
  const roots = findSkillRoots(tree);
  const bundles = await Promise.all(
    roots.map((root) => downloadBundle(tree, root)),
  );
  return { source: `langfuse/skills@${tree.sha}`, bundles };
};

const renderGeneratedModule = async ({ bundles }) => {
  const references = bundles.find(
    (bundle) => bundle.name === "langfuse",
  )?.files;
  if (!references) throw new Error("No Langfuse reference skills found");
  const skills = references
    .filter((file) => /^references\/[^/]+\.md$/.test(file.path))
    .map((file) => parseSkill(file.path, file.bytes.toString("utf8")));
  return formatWithPrettier(
    `// This file is generated by packages/langfuse-skills/scripts/sync-skills.mjs.
// Do not edit it manually.

exports.LANGFUSE_SKILLS = [
${skills
  .map(
    (skill) =>
      `  ${JSON.stringify(skill)},`,
  )
  .join("\n")}
];
`,
    { parser: "babel" },
  );
};

const parseFrontmatter = ({ name, files }) => {
  const markdown = files
    .find((file) => file.path === "SKILL.md")
    .bytes.toString("utf8");
  const yaml = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(markdown)?.[1];
  if (yaml === undefined) throw new Error(`Missing frontmatter: ${name}`);
  const document = parseDocument(yaml);
  if (document.errors.length > 0)
    throw new Error(`Invalid frontmatter: ${name}`);
  const frontmatter = document.toJS({ maxAliasCount: 0 });
  if (
    frontmatter?.name !== name ||
    !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name) ||
    name.length > 64 ||
    typeof frontmatter.description !== "string"
  ) {
    throw new Error(`Invalid skill metadata: ${name}`);
  }
  return frontmatter;
};

const toResourceEntry = (root, { path, bytes }) => {
  const uri = `${root}/${path.split("/").map(encodeURIComponent).join("/")}`;
  const content = path.endsWith(".md")
    ? { uri, mimeType: "text/markdown", text: bytes.toString("utf8") }
    : {
        uri,
        mimeType: "application/octet-stream",
        blob: bytes.toString("base64"),
      };
  return {
    manifest: {
      uri,
      digest: `sha256:${createHash("sha256").update(bytes).digest("hex")}`,
      size: bytes.length,
    },
    content,
  };
};

const toSkillEntry = (bundle) => {
  const root = `skill://langfuse/${bundle.name}`;
  const frontmatter = parseFrontmatter(bundle);
  const entries = bundle.files.map((file) => toResourceEntry(root, file));
  return {
    skill: {
      uri: `${root}/SKILL.md`,
      frontmatter,
      resources: entries.map((entry) => entry.manifest),
    },
    resources: entries.map((entry) => entry.content),
  };
};

const renderMcpModule = async ({ source, bundles }) => {
  const entries = bundles.map(toSkillEntry);
  const skills = entries.map((entry) => entry.skill);
  const resources = entries.flatMap((entry) => entry.resources);
  return formatWithPrettier(
    `// This file is generated by packages/langfuse-skills/scripts/sync-skills.mjs.
// Do not edit it manually.
// Source: ${source}

exports.LANGFUSE_MCP_SKILLS = ${JSON.stringify(skills)};
exports.LANGFUSE_MCP_RESOURCES = ${JSON.stringify(resources)};
`,
    { parser: "babel" },
  );
};

const main = async () => {
  const expectedSkills = await getExpectedSkills();
  const expectedModule = await renderGeneratedModule(expectedSkills);
  const expectedMcpModule = await renderMcpModule(expectedSkills);

  if (isCheckMode) {
    try {
      if (readFileSync(generatedPath, "utf8") !== expectedModule) {
        throw new Error("Generated skill catalog differs from upstream");
      }
      if (readFileSync(mcpGeneratedPath, "utf8") !== expectedMcpModule) {
        throw new Error("Generated MCP skill catalog differs from upstream");
      }
    } catch (error) {
      if (error.code === "ENOENT") {
        throw new Error("Generated skill catalog is missing");
      }
      throw error;
    }

    console.log("Generated Langfuse skill catalog is in sync.");
    console.log("Generated MCP skill catalog is in sync.");
    return;
  }

  mkdirSync(resolve(packageRoot, "src/generated"), { recursive: true });
  writeFileSync(generatedPath, expectedModule);
  writeFileSync(mcpGeneratedPath, expectedMcpModule);
  console.log("Synced Langfuse and MCP skill catalogs.");
};

main().catch((error) => {
  console.error(error);
  process.exit(1);
});