Branchwell

Skillfarm / website · skillfarm.ai / src / lib / github.ts

Raw 14.9 KB on 1483ab8a067e2125e25ab4212527521810bbb6af
1import type { Env } from '../env';
2import { HttpError, now } from './util';
3
4export const BUNDLE_LIMITS = { files: 30, fileBytes: 200_000, totalBytes: 400_000 };
5
6const TEXT_EXT = new Set([
7 'md', 'markdown', 'txt', 'json', 'jsonl', 'yaml', 'yml', 'toml', 'ini', 'cfg', 'py', 'js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', 'sh', 'bash', 'zsh', 'fish',
8 'rb', 'go', 'rs', 'php', 'pl', 'lua', 'r', 'swift', 'kt', 'java', 'c', 'h', 'cpp', 'cs', 'html', 'htm', 'css', 'scss', 'csv', 'tsv', 'xml', 'sql', 'ps1',
9 'bat', 'tmpl', 'tpl', 'j2', 'mustache', 'hbs', 'gitignore', 'env-example', 'example', 'graphql', 'proto', 'tf', 'dockerfile', 'svg',
10]);
11const TEXT_NAMES = new Set(['license', 'licence', 'notice', 'makefile', 'dockerfile', 'readme', 'authors', 'changelog', 'justfile', 'procfile']);
12
13export function isTextPath(path: string): boolean {
14 const name = path.split('/').pop()!.toLowerCase();
15 if (TEXT_NAMES.has(name)) return true;
16 const ext = name.includes('.') ? name.split('.').pop()! : '';
17 return TEXT_EXT.has(ext);
18}
19
20export function isSafePath(path: string): boolean {
21 if (!path || path.length > 200 || path.startsWith('/') || path.includes('\\') || path.includes('\0')) return false;
22 return path.split('/').every((seg) => seg !== '' && seg !== '.' && seg !== '..' && seg.length <= 100);
23}
24
25// Local development and the tests point these at a stand-in for GitHub.
26const apiBase = (env: Env) => ((env.DEV_LOGIN && env.GITHUB_API_BASE) || 'https://api.github.com').replace(/\/+$/, '');
27const rawBase = (env: Env) => ((env.DEV_LOGIN && env.GITHUB_RAW_BASE) || 'https://raw.githubusercontent.com').replace(/\/+$/, '');
28
29function headers(env: Env, extra: Record<string, string> = {}): Record<string, string> {
30 const h: Record<string, string> = { 'user-agent': 'skillfarm', accept: 'application/vnd.github+json', 'x-github-api-version': '2022-11-28', ...extra };
31 // An OAuth app may identify itself with its id and secret for a higher rate limit on public data.
32 if (env.GITHUB_CLIENT_ID && env.GITHUB_CLIENT_SECRET) h.authorization = 'Basic ' + btoa(`${env.GITHUB_CLIENT_ID}:${env.GITHUB_CLIENT_SECRET}`);
33 return h;
34}
35
36export type RepoRef = { owner: string; repo: string; ref?: string; path?: string };
37
38const NAME = /^[A-Za-z0-9_.-]{1,100}$/;
39
40/** Accepts github.com URLs (repo, tree, blob) and owner/repo[/path] shorthand. */
41export function parseGithubUrl(input: string): RepoRef | null {
42 let s = input.trim();
43 if (!s) return null;
44 s = s.replace(/^git\+/, '').replace(/\.git$/, '');
45 let parts: string[];
46 if (/^https?:\/\//i.test(s)) {
47 let u: URL;
48 try {
49 u = new URL(s);
50 } catch {
51 return null;
52 }
53 if (u.hostname !== 'github.com' && u.hostname !== 'www.github.com') return null;
54 parts = u.pathname.split('/').filter(Boolean).map(decodeURIComponent);
55 } else {
56 parts = s.split('/').filter(Boolean);
57 }
58 if (parts.length < 2) return null;
59 const [owner, repo, kind, ...rest] = parts;
60 if (!NAME.test(owner) || !NAME.test(repo.replace(/\.git$/, ''))) return null;
61 const out: RepoRef = { owner, repo: repo.replace(/\.git$/, '') };
62 if (kind === 'tree' || kind === 'blob') {
63 // The ref may contain slashes; assume the common single-segment form.
64 out.ref = rest[0];
65 out.path = rest.slice(1).join('/');
66 } else if (kind) {
67 out.path = [kind, ...rest].join('/');
68 }
69 if (out.path) {
70 out.path = out.path.replace(/\/?SKILL\.md$/i, '').replace(/\/+$/, '');
71 if (out.path && !isSafePath(out.path)) return null;
72 }
73 return out;
74}
75
76export type RepoInfo = {
77 full_name: string; stars: number; forks: number; open_issues: number; pushed_at: string | null; license_spdx: string | null;
78 archived: boolean; owner_id: string; default_branch: string; private: boolean;
79};
80
81async function getRepo(env: Env, fullName: string, etag?: string | null): Promise<{ status: number; etag: string | null; info: RepoInfo | null }> {
82 const res = await fetch(`${apiBase(env)}/repos/${fullName}`, { headers: headers(env, etag ? { 'if-none-match': etag } : {}) });
83 if (res.status === 304) return { status: 304, etag: etag ?? null, info: null };
84 if (!res.ok) return { status: res.status, etag: null, info: null };
85 const j = (await res.json()) as any;
86 return {
87 status: 200,
88 etag: res.headers.get('etag'),
89 info: {
90 full_name: j.full_name, stars: j.stargazers_count ?? 0, forks: j.forks_count ?? 0, open_issues: j.open_issues_count ?? 0, pushed_at: j.pushed_at ?? null,
91 license_spdx: j.license?.spdx_id && j.license.spdx_id !== 'NOASSERTION' ? j.license.spdx_id : null, archived: !!j.archived, owner_id: String(j.owner?.id ?? ''),
92 default_branch: j.default_branch ?? 'main', private: !!j.private,
93 },
94 };
95}
96
97function upsertSignals(env: Env, key: string, info: RepoInfo, etag: string | null): D1PreparedStatement {
98 return env.DB.prepare(
99 `INSERT INTO repo_signals (repo_full_name, stars, forks, open_issues, pushed_at, license_spdx, archived, unavailable, owner_id, etag, fetched_at)
100 VALUES (?,?,?,?,?,?,?,0,?,?,?)
101 ON CONFLICT(repo_full_name) DO UPDATE SET stars=excluded.stars, forks=excluded.forks, open_issues=excluded.open_issues, pushed_at=excluded.pushed_at,
102 license_spdx=excluded.license_spdx, archived=excluded.archived, unavailable=0, owner_id=excluded.owner_id, etag=excluded.etag, fetched_at=excluded.fetched_at`,
103 ).bind(key, info.stars, info.forks, info.open_issues, info.pushed_at, info.license_spdx, info.archived ? 1 : 0, info.owner_id, etag, now());
104}
105
106/** Refresh the cached star count for one repo. Pages never wait on this. */
107export async function refreshRepoSignals(env: Env, repo: string): Promise<void> {
108 const existing = await env.DB.prepare('SELECT etag FROM repo_signals WHERE repo_full_name = ?').bind(repo).first<{ etag: string | null }>();
109 const r = await getRepo(env, repo, existing?.etag);
110 if (r.status === 304) {
111 await env.DB.prepare('UPDATE repo_signals SET fetched_at = ?, unavailable = 0 WHERE repo_full_name = ?').bind(now(), repo).run();
112 } else if (r.status === 200 && r.info && !r.info.private) {
113 await upsertSignals(env, repo, r.info, r.etag).run();
114 } else if (r.status === 404 || r.status === 451 || r.status === 410 || (r.info && r.info.private)) {
115 // Renamed, deleted or made private: keep the last count and mark it.
116 await env.DB.prepare(
117 `INSERT INTO repo_signals (repo_full_name, unavailable, fetched_at) VALUES (?, 1, ?)
118 ON CONFLICT(repo_full_name) DO UPDATE SET unavailable = 1, fetched_at = excluded.fetched_at`,
119 ).bind(repo, now()).run();
120 }
121 // 403/429 (rate limited) and 5xx: leave the row alone and try again on the next pass.
122}
123
124const STALE_ON_VIEW = 6 * 3600;
125
126/** Queue background refreshes for repos whose cached row is older than six hours. */
127export function refreshStale(env: Env, ctx: { waitUntil(p: Promise<unknown>): void }, rows: { github_repo: string | null; repo_fetched_at?: number | null }[]): void {
128 const seen = new Set<string>();
129 for (const r of rows) {
130 if (!r.github_repo || seen.has(r.github_repo)) continue;
131 if ((r.repo_fetched_at ?? 0) > now() - STALE_ON_VIEW) continue;
132 seen.add(r.github_repo);
133 if (seen.size > 5) break;
134 ctx.waitUntil(refreshRepoSignals(env, r.github_repo).catch(() => {}));
135 }
136}
137
138/** Daily pass: refresh every repo not fetched in the last 24 hours, oldest first. */
139export async function refreshAllStale(env: Env, max = 80): Promise<number> {
140 const rows = await env.DB.prepare(
141 `SELECT DISTINCT s.github_repo AS repo FROM skills s LEFT JOIN repo_signals r ON r.repo_full_name = s.github_repo
142 WHERE s.github_repo IS NOT NULL AND s.state = 'live' AND COALESCE(r.fetched_at, 0) < ? ORDER BY COALESCE(r.fetched_at, 0) ASC LIMIT ?`,
143 ).bind(now() - 86400, max).all<{ repo: string }>();
144 for (const r of rows.results) await refreshRepoSignals(env, r.repo).catch(() => {});
145 return rows.results.length;
146}
147
148export type ImportedFile = { path: string; data: Uint8Array };
149export type Imported = { repo: string; ref: string; path: string; files: ImportedFile[]; info: RepoInfo; etag: string | null };
150
151/** One file of a skill folder as the repo tree lists it: where it sits in the repo, and its path inside the skill. */
152export type TreeFile = { path: string; rel: string; size: number };
153/** A folder that holds a SKILL.md. `problem` is set when the folder cannot be taken as it is. */
154export type SkillFolder = { path: string; name: string; files: TreeFile[]; problem?: string };
155export type RepoScan = { repo: string; ref: string; info: RepoInfo; etag: string | null; folders: SkillFolder[]; truncated: boolean; duplicates: string[] };
156
157/** The most skills one repo share can bring in. */
158export const REPO_SKILL_LIMIT = 25;
159
160// Agent folders are a normal home for skills. Other hidden folders, and installed packages, are not somebody's own skills.
161const AGENT_DIRS = new Set(['.claude', '.agents', '.codex', '.gemini']);
162const skipSegment = (seg: string) => seg === 'node_modules' || seg === 'vendor' || (seg.startsWith('.') && !AGENT_DIRS.has(seg));
163
164/**
165 * Read a public repo's file list and find every skill folder in it. Nothing is downloaded yet.
166 * With a path, only skills at or under that folder are returned.
167 */
168export async function scanRepo(env: Env, ref: RepoRef): Promise<RepoScan> {
169 const r = await getRepo(env, `${ref.owner}/${ref.repo}`);
170 if (r.status === 403 || r.status === 429) throw new HttpError(503, 'GitHub is rate limiting Skillfarm right now. Try again in a few minutes.');
171 if (!r.info || r.info.private) throw new HttpError(400, 'That repository was not found, or it is private. Skillfarm can only read public repos.');
172 const info = r.info;
173 const branch = ref.ref || info.default_branch;
174 const treeRes = await fetch(`${apiBase(env)}/repos/${info.full_name}/git/trees/${encodeURIComponent(branch)}?recursive=1`, { headers: headers(env) });
175 if (treeRes.status === 403 || treeRes.status === 429) throw new HttpError(503, 'GitHub is rate limiting Skillfarm right now. Try again in a few minutes.');
176 if (!treeRes.ok) throw new HttpError(400, `Could not read the "${branch}" branch of ${info.full_name}.`);
177 const tree = (await treeRes.json()) as { sha: string; tree: { path: string; type: string; size?: number }[]; truncated?: boolean };
178 const blobs = tree.tree.filter((t) => t.type === 'blob');
179
180 const scope = (ref.path ?? '').replace(/^\/+|\/+$/g, '');
181 const dirOf = (p: string) => p.replace(/\/?SKILL\.md$/i, '');
182 let dirs = blobs.filter((b) => /(^|\/)SKILL\.md$/i.test(b.path)).map((b) => dirOf(b.path));
183 const allDirs = dirs;
184 const exact = dirs.find((d) => d.toLowerCase() === scope.toLowerCase());
185 if (scope && exact !== undefined) dirs = [exact];
186 else {
187 if (scope) dirs = dirs.filter((d) => d.toLowerCase().startsWith(scope.toLowerCase() + '/'));
188 dirs = dirs.filter((d) => !d.split('/').some((seg) => seg !== '' && skipSegment(seg)));
189 }
190
191 // The same skill is often kept twice, once in an agent's folder and once in a public one. Keep the public copy.
192 const byName = new Map<string, string>();
193 const duplicates: string[] = [];
194 const rank = (d: string) => (d.startsWith('.') ? 1000 : 0) + d.length;
195 for (const d of [...dirs].sort((a, b) => rank(a) - rank(b) || a.localeCompare(b))) {
196 const key = (d.split('/').pop() || info.full_name.split('/')[1]).toLowerCase();
197 if (byName.has(key)) duplicates.push(d);
198 else byName.set(key, d);
199 }
200
201 const folders: SkillFolder[] = [];
202 for (const dir of [...byName.values()].sort((a, b) => a.localeCompare(b))) {
203 const prefix = dir === '' ? '' : dir + '/';
204 const wanted = blobs.filter((b) => b.path.startsWith(prefix)).map((b) => ({ path: b.path, rel: b.path.slice(prefix.length), size: b.size ?? 0 }));
205 // A skill at the repo root would otherwise drag in the whole repo; nested skills are separate skills.
206 const nested = allDirs.filter((d) => d !== dir && d.startsWith(prefix)).map((d) => d.slice(prefix.length) + '/');
207 const mine = wanted.filter((b) => !nested.some((n) => b.rel.startsWith(n)) && !b.rel.startsWith('.git') && !/(^|\/)(node_modules|\.github)\//.test(b.rel));
208 const text = mine.filter((b) => isTextPath(b.rel) && isSafePath(b.rel));
209 const total = text.reduce((n, b) => n + b.size, 0);
210 const tooBig = text.find((b) => b.size > BUNDLE_LIMITS.fileBytes);
211 let problem: string | undefined;
212 if (text.length > BUNDLE_LIMITS.files) problem = `It has ${text.length} text files. The limit is ${BUNDLE_LIMITS.files}.`;
213 else if (tooBig) problem = `${tooBig.rel} is larger than ${BUNDLE_LIMITS.fileBytes / 1000} KB.`;
214 else if (total > BUNDLE_LIMITS.totalBytes) problem = `It is ${Math.round(total / 1000)} KB. The limit is ${BUNDLE_LIMITS.totalBytes / 1000} KB.`;
215 folders.push({ path: dir, name: dir.split('/').pop() || info.full_name.split('/')[1], files: text, problem });
216 }
217 await upsertSignals(env, info.full_name, info, r.etag).run();
218 return { repo: info.full_name, ref: tree.sha, info, etag: r.etag, folders, truncated: !!tree.truncated, duplicates };
219}
220
221/** Download the files of one skill folder at a fixed commit. */
222export async function fetchSkillFiles(env: Env, repo: string, sha: string, files: TreeFile[]): Promise<ImportedFile[]> {
223 const out: ImportedFile[] = [];
224 for (const b of files) {
225 if (!isSafePath(b.rel) || !isTextPath(b.rel)) continue;
226 const raw = await fetch(`${rawBase(env)}/${repo}/${sha}/${b.path.split('/').map(encodeURIComponent).join('/')}`, { headers: { 'user-agent': 'skillfarm' } });
227 if (!raw.ok) throw new HttpError(502, `Could not download ${b.rel} from GitHub.`);
228 const data = new Uint8Array(await raw.arrayBuffer());
229 if (data.length > BUNDLE_LIMITS.fileBytes) throw new HttpError(400, `${b.rel} is larger than ${BUNDLE_LIMITS.fileBytes / 1000} KB.`);
230 // Normalise the entry file name so every bundle has exactly "SKILL.md".
231 out.push({ path: /^SKILL\.md$/i.test(b.rel) ? 'SKILL.md' : b.rel, data });
232 }
233 if (!out.some((f) => f.path === 'SKILL.md')) throw new HttpError(400, 'No SKILL.md was found in that folder.');
234 return out;
235}
236
237/** Pull one skill folder (SKILL.md plus its supporting text files) from a public repo. */
238export async function importFromGithub(env: Env, ref: RepoRef): Promise<Imported> {
239 const scan = await scanRepo(env, ref);
240 const scope = (ref.path ?? '').replace(/^\/+|\/+$/g, '');
241 let folder = scan.folders.find((f) => f.path.toLowerCase() === scope.toLowerCase());
242 if (!folder) {
243 if (scan.folders.length === 1) folder = scan.folders[0];
244 else if (scan.folders.length === 0) throw new HttpError(400, `No SKILL.md was found${scope ? ` under "${scope}"` : ''} in ${scan.repo}.`);
245 else {
246 const list = scan.folders.slice(0, 12).map((f) => f.path || '(repo root)').join(', ');
247 throw new HttpError(400, `${scan.repo} holds ${scan.folders.length} skills. Give the link to one skill folder. Found: ${list}${scan.folders.length > 12 ? ', …' : ''}`);
248 }
249 }
250 if (folder.problem) throw new HttpError(400, `That skill folder cannot be taken as it is. ${folder.problem}`);
251 const files = await fetchSkillFiles(env, scan.repo, scan.ref, folder.files);
252 return { repo: scan.repo, ref: scan.ref, path: folder.path, files, info: scan.info, etag: scan.etag };
253}