Branchwell

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

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