import { defineTool, Type } from "@toolpal/tool"; async function github(path: string): Promise | null> { const headers: Record = { accept: "application/vnd.github+json", "user-agent": "toolpal-github-repo", "x-github-api-version": "2022-11-28", }; if (process.env.GITHUB_TOKEN) headers.authorization = `Bearer ${process.env.GITHUB_TOKEN}`; const res = await fetch(`https://api.github.com${path}`, { headers, signal: AbortSignal.timeout(12_000), }); if (res.status === 404) return null; if ( (res.status === 403 || res.status === 429) && res.headers.get("x-ratelimit-remaining") === "0" ) { throw new Error( "GitHub's rate limit was reached. Set GITHUB_TOKEN for this tool to raise it to 5,000 requests an hour.", ); } if (!res.ok) throw new Error(`GitHub returned HTTP ${res.status} for ${path}`); return (await res.json()) as Record; } function parseRepo(input: string): string { const path = input.trim().replace(/^(https?:\/\/)?(www\.)?github\.com\//i, ""); const m = path.match(/^([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+?)(\.git)?(\/|$)/); if (!m || m[2] === "." || m[2] === ".." || m[2].includes("..")) { throw new Error(`Expected "owner/name" or a github.com URL, got "${input}".`); } return `${m[1]}/${m[2]}`; } export default defineTool({ description: "Looks up live facts about a public GitHub repository: stars, forks, watchers, open issues, language breakdown, license, topics, latest release, and when it was created and last pushed to. Works without an API key; set GITHUB_TOKEN for higher rate limits.", input: Type.Object({ repo: Type.String({ maxLength: 300, description: 'Repository as "owner/name" (e.g. facebook/react) or a github.com URL', }), }), output: Type.Object({ fullName: Type.String(), url: Type.String(), description: Type.Optional(Type.String()), homepage: Type.Optional(Type.String()), stars: Type.Integer(), forks: Type.Integer(), watchers: Type.Integer(), openIssuesAndPullRequests: Type.Integer(), languages: Type.Array(Type.Object({ name: Type.String(), percent: Type.Number() }), { description: "Share of code by bytes, largest first", }), license: Type.Optional(Type.String()), topics: Type.Array(Type.String()), defaultBranch: Type.String(), archived: Type.Boolean(), createdAt: Type.String(), lastPushAt: Type.String(), latestRelease: Type.Optional( Type.Object({ tag: Type.String(), name: Type.Optional(Type.String()), publishedAt: Type.String(), url: Type.String(), }), ), }), handler: async ({ repo }, ctx) => { const name = parseRepo(repo); const [info, release, languages] = await Promise.all([ github(`/repos/${name}`), github(`/repos/${name}/releases/latest`), github(`/repos/${name}/languages`), ]); if (!info) throw new Error(`No public repository named ${name} was found.`); const fullName = String(info.full_name); if (fullName.toLowerCase() !== name.toLowerCase()) { ctx.log("info", `${name} redirects to ${fullName}`); } const bytes = Object.entries((languages ?? {}) as Record) .filter(([, n]) => typeof n === "number" && n > 0) .sort((a, b) => b[1] - a[1]); const totalBytes = bytes.reduce((acc, [, n]) => acc + n, 0); const license = info.license as { spdx_id?: string } | null | undefined; const relPublished = release ? String(release.published_at ?? release.created_at ?? "") : ""; return { fullName, url: String(info.html_url), ...(info.description ? { description: String(info.description) } : {}), ...(info.homepage ? { homepage: String(info.homepage) } : {}), stars: Number(info.stargazers_count ?? 0), forks: Number(info.forks_count ?? 0), watchers: Number(info.subscribers_count ?? 0), openIssuesAndPullRequests: Number(info.open_issues_count ?? 0), languages: totalBytes > 0 ? bytes .slice(0, 8) .map(([lang, n]) => ({ name: lang, percent: Math.round((n / totalBytes) * 1000) / 10 })) : [], ...(license?.spdx_id && license.spdx_id !== "NOASSERTION" ? { license: license.spdx_id } : {}), topics: Array.isArray(info.topics) ? info.topics.map(String) : [], defaultBranch: String(info.default_branch ?? "main"), archived: Boolean(info.archived), createdAt: String(info.created_at ?? ""), lastPushAt: String(info.pushed_at ?? ""), ...(release && release.tag_name && release.html_url ? { latestRelease: { tag: String(release.tag_name), ...(release.name ? { name: String(release.name) } : {}), publishedAt: relPublished, url: String(release.html_url), }, } : {}), }; }, });