Skillfarm / website · skillfarm.ai / src / lib / github.ts
| 1 | import type { Env } from '../env'; |
| 2 | import { HttpError, now } from './util'; |
| 3 | import { ownRepo } from './hosts'; |
| 4 | |
| 5 | export const BUNDLE_LIMITS = { files: 30, fileBytes: 200_000, totalBytes: 400_000 }; |
| 6 | |
| 7 | const 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 | ]); |
| 12 | const TEXT_NAMES = new Set(['license', 'licence', 'notice', 'makefile', 'dockerfile', 'readme', 'authors', 'changelog', 'justfile', 'procfile']); |
| 13 | |
| 14 | export 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 | |
| 21 | export 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. |
| 27 | const apiBase = (env: Env) => ((env.DEV_LOGIN && env.GITHUB_API_BASE) || 'https://api.github.com').replace(/\/+$/, ''); |
| 28 | const rawBase = (env: Env) => ((env.DEV_LOGIN && env.GITHUB_RAW_BASE) || 'https://raw.githubusercontent.com').replace(/\/+$/, ''); |
| 29 | |
| 30 | function 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 | return h; |
| 33 | } |
| 34 | |
| 35 | export type RepoRef = { owner: string; repo: string; ref?: string; path?: string }; |
| 36 | |
| 37 | const NAME = /^[A-Za-z0-9_.-]{1,100}$/; |
| 38 | |
| 39 | /** Accepts github.com URLs (repo, tree, blob) and owner/repo[/path] shorthand. */ |
| 40 | export function parseGithubUrl(input: string): RepoRef | null { |
| 41 | let s = input.trim(); |
| 42 | if (!s) return null; |
| 43 | s = s.replace(/^git\+/, '').replace(/\.git$/, ''); |
| 44 | let parts: string[]; |
| 45 | if (/^https?:\/\//i.test(s)) { |
| 46 | let u: URL; |
| 47 | try { |
| 48 | u = new URL(s); |
| 49 | } catch { |
| 50 | return null; |
| 51 | } |
| 52 | if (u.hostname !== 'github.com' && u.hostname !== 'www.github.com') return null; |
| 53 | parts = u.pathname.split('/').filter(Boolean).map(decodeURIComponent); |
| 54 | } else { |
| 55 | parts = s.split('/').filter(Boolean); |
| 56 | } |
| 57 | if (parts.length < 2) return null; |
| 58 | const [owner, repo, kind, ...rest] = parts; |
| 59 | if (!NAME.test(owner) || !NAME.test(repo.replace(/\.git$/, ''))) return null; |
| 60 | const out: RepoRef = { owner, repo: repo.replace(/\.git$/, '') }; |
| 61 | if (kind === 'tree' || kind === 'blob') { |
| 62 | // The ref may contain slashes; assume the common single-segment form. |
| 63 | out.ref = rest[0]; |
| 64 | out.path = rest.slice(1).join('/'); |
| 65 | } else if (kind) { |
| 66 | out.path = [kind, ...rest].join('/'); |
| 67 | } |
| 68 | if (out.path) { |
| 69 | out.path = out.path.replace(/\/?SKILL\.md$/i, '').replace(/\/+$/, ''); |
| 70 | if (out.path && !isSafePath(out.path)) return null; |
| 71 | } |
| 72 | return out; |
| 73 | } |
| 74 | |
| 75 | export type RepoInfo = { |
| 76 | full_name: string; stars: number; forks: number; open_issues: number; pushed_at: string | null; license_spdx: string | null; |
| 77 | archived: boolean; owner_id: string; default_branch: string; private: boolean; |
| 78 | }; |
| 79 | |
| 80 | async function getRepo(env: Env, fullName: string, etag?: string | null): Promise<{ status: number; etag: string | null; info: RepoInfo | null }> { |
| 81 | const res = await fetch(`${apiBase(env)}/repos/${fullName}`, { headers: headers(env, etag ? { 'if-none-match': etag } : {}) }); |
| 82 | if (res.status === 304) return { status: 304, etag: etag ?? null, info: null }; |
| 83 | if (!res.ok) return { status: res.status, etag: null, info: null }; |
| 84 | const j = (await res.json()) as any; |
| 85 | return { |
| 86 | status: 200, |
| 87 | etag: res.headers.get('etag'), |
| 88 | info: { |
| 89 | 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, |
| 90 | 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 ?? ''), |
| 91 | default_branch: j.default_branch ?? 'main', private: !!j.private, |
| 92 | }, |
| 93 | }; |
| 94 | } |
| 95 | |
| 96 | function upsertSignals(env: Env, key: string, info: RepoInfo, etag: string | null): D1PreparedStatement { |
| 97 | return env.DB.prepare( |
| 98 | `INSERT INTO repo_signals (repo_full_name, stars, forks, open_issues, pushed_at, license_spdx, archived, unavailable, owner_id, etag, fetched_at) |
| 99 | VALUES (?,?,?,?,?,?,?,0,?,?,?) |
| 100 | ON CONFLICT(repo_full_name) DO UPDATE SET stars=excluded.stars, forks=excluded.forks, open_issues=excluded.open_issues, pushed_at=excluded.pushed_at, |
| 101 | license_spdx=excluded.license_spdx, archived=excluded.archived, unavailable=0, owner_id=excluded.owner_id, etag=excluded.etag, fetched_at=excluded.fetched_at`, |
| 102 | ).bind(key, info.stars, info.forks, info.open_issues, info.pushed_at, info.license_spdx, info.archived ? 1 : 0, info.owner_id, etag, now()); |
| 103 | } |
| 104 | |
| 105 | /** Refresh the cached star count for one repo. Pages never wait on this. */ |
| 106 | export async function refreshRepoSignals(env: Env, repo: string): Promise<void> { |
| 107 | const existing = await env.DB.prepare('SELECT etag FROM repo_signals WHERE repo_full_name = ?').bind(repo).first<{ etag: string | null }>(); |
| 108 | const r = await getRepo(env, repo, existing?.etag); |
| 109 | if (r.status === 304) { |
| 110 | await env.DB.prepare('UPDATE repo_signals SET fetched_at = ?, unavailable = 0 WHERE repo_full_name = ?').bind(now(), repo).run(); |
| 111 | } else if (r.status === 200 && r.info && !r.info.private) { |
| 112 | await upsertSignals(env, repo, r.info, r.etag).run(); |
| 113 | } else if (r.status === 404 || r.status === 451 || r.status === 410 || (r.info && r.info.private)) { |
| 114 | // Renamed, deleted or made private: keep the last count and mark it. |
| 115 | await env.DB.prepare( |
| 116 | `INSERT INTO repo_signals (repo_full_name, unavailable, fetched_at) VALUES (?, 1, ?) |
| 117 | ON CONFLICT(repo_full_name) DO UPDATE SET unavailable = 1, fetched_at = excluded.fetched_at`, |
| 118 | ).bind(repo, now()).run(); |
| 119 | } |
| 120 | // 403/429 (rate limited) and 5xx: leave the row alone and try again on the next pass. |
| 121 | } |
| 122 | |
| 123 | const STALE_ON_VIEW = 6 * 3600; |
| 124 | |
| 125 | /** Queue background refreshes for repos whose cached row is older than six hours. */ |
| 126 | export function refreshStale(env: Env, ctx: { waitUntil(p: Promise<unknown>): void }, rows: { github_repo: string | null; repo_fetched_at?: number | null }[]): void { |
| 127 | const seen = new Set<string>(); |
| 128 | for (const r of rows) { |
| 129 | if (!r.github_repo || ownRepo(r.github_repo) || seen.has(r.github_repo)) continue; |
| 130 | if ((r.repo_fetched_at ?? 0) > now() - STALE_ON_VIEW) continue; |
| 131 | seen.add(r.github_repo); |
| 132 | if (seen.size > 5) break; |
| 133 | ctx.waitUntil(refreshRepoSignals(env, r.github_repo).catch(() => {})); |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | /** Daily pass: refresh every repo not fetched in the last 24 hours, oldest first. */ |
| 138 | export async function refreshAllStale(env: Env, max = 80): Promise<number> { |
| 139 | const rows = await env.DB.prepare( |
| 140 | `SELECT DISTINCT s.github_repo AS repo FROM skills s LEFT JOIN repo_signals r ON r.repo_full_name = s.github_repo |
| 141 | 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 ?`, |
| 142 | ).bind(now() - 86400, max).all<{ repo: string }>(); |
| 143 | const repos = rows.results.filter((r) => !ownRepo(r.repo)); |
| 144 | for (const r of repos) await refreshRepoSignals(env, r.repo).catch(() => {}); |
| 145 | return repos.length; |
| 146 | } |
| 147 | |
| 148 | export type ImportedFile = { path: string; data: Uint8Array }; |
| 149 | export 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. */ |
| 152 | export 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. */ |
| 154 | export type SkillFolder = { path: string; name: string; files: TreeFile[]; problem?: string }; |
| 155 | export 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. */ |
| 158 | export 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. |
| 161 | const AGENT_DIRS = new Set(['.claude', '.agents', '.codex', '.gemini']); |
| 162 | const 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 | */ |
| 168 | export 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. */ |
| 222 | export 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. */ |
| 238 | export 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 | } |