import type { Env } from '../env'; import { HttpError, now } from './util'; import { ownRepo } from './hosts'; export const BUNDLE_LIMITS = { files: 30, fileBytes: 200_000, totalBytes: 400_000 }; const TEXT_EXT = new Set([ 'md', 'markdown', 'txt', 'json', 'jsonl', 'yaml', 'yml', 'toml', 'ini', 'cfg', 'py', 'js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', 'sh', 'bash', 'zsh', 'fish', 'rb', 'go', 'rs', 'php', 'pl', 'lua', 'r', 'swift', 'kt', 'java', 'c', 'h', 'cpp', 'cs', 'html', 'htm', 'css', 'scss', 'csv', 'tsv', 'xml', 'sql', 'ps1', 'bat', 'tmpl', 'tpl', 'j2', 'mustache', 'hbs', 'gitignore', 'env-example', 'example', 'graphql', 'proto', 'tf', 'dockerfile', 'svg', ]); const TEXT_NAMES = new Set(['license', 'licence', 'notice', 'makefile', 'dockerfile', 'readme', 'authors', 'changelog', 'justfile', 'procfile']); export function isTextPath(path: string): boolean { const name = path.split('/').pop()!.toLowerCase(); if (TEXT_NAMES.has(name)) return true; const ext = name.includes('.') ? name.split('.').pop()! : ''; return TEXT_EXT.has(ext); } export function isSafePath(path: string): boolean { if (!path || path.length > 200 || path.startsWith('/') || path.includes('\\') || path.includes('\0')) return false; return path.split('/').every((seg) => seg !== '' && seg !== '.' && seg !== '..' && seg.length <= 100); } // Local development and the tests point these at a stand-in for GitHub. const apiBase = (env: Env) => ((env.DEV_LOGIN && env.GITHUB_API_BASE) || 'https://api.github.com').replace(/\/+$/, ''); const rawBase = (env: Env) => ((env.DEV_LOGIN && env.GITHUB_RAW_BASE) || 'https://raw.githubusercontent.com').replace(/\/+$/, ''); function headers(env: Env, extra: Record = {}): Record { const h: Record = { 'user-agent': 'skillfarm', accept: 'application/vnd.github+json', 'x-github-api-version': '2022-11-28', ...extra }; // An OAuth app may identify itself with its id and secret for a higher rate limit on public data. if (env.GITHUB_CLIENT_ID && env.GITHUB_CLIENT_SECRET) h.authorization = 'Basic ' + btoa(`${env.GITHUB_CLIENT_ID}:${env.GITHUB_CLIENT_SECRET}`); return h; } export type RepoRef = { owner: string; repo: string; ref?: string; path?: string }; const NAME = /^[A-Za-z0-9_.-]{1,100}$/; /** Accepts github.com URLs (repo, tree, blob) and owner/repo[/path] shorthand. */ export function parseGithubUrl(input: string): RepoRef | null { let s = input.trim(); if (!s) return null; s = s.replace(/^git\+/, '').replace(/\.git$/, ''); let parts: string[]; if (/^https?:\/\//i.test(s)) { let u: URL; try { u = new URL(s); } catch { return null; } if (u.hostname !== 'github.com' && u.hostname !== 'www.github.com') return null; parts = u.pathname.split('/').filter(Boolean).map(decodeURIComponent); } else { parts = s.split('/').filter(Boolean); } if (parts.length < 2) return null; const [owner, repo, kind, ...rest] = parts; if (!NAME.test(owner) || !NAME.test(repo.replace(/\.git$/, ''))) return null; const out: RepoRef = { owner, repo: repo.replace(/\.git$/, '') }; if (kind === 'tree' || kind === 'blob') { // The ref may contain slashes; assume the common single-segment form. out.ref = rest[0]; out.path = rest.slice(1).join('/'); } else if (kind) { out.path = [kind, ...rest].join('/'); } if (out.path) { out.path = out.path.replace(/\/?SKILL\.md$/i, '').replace(/\/+$/, ''); if (out.path && !isSafePath(out.path)) return null; } return out; } export type RepoInfo = { full_name: string; stars: number; forks: number; open_issues: number; pushed_at: string | null; license_spdx: string | null; archived: boolean; owner_id: string; default_branch: string; private: boolean; }; async function getRepo(env: Env, fullName: string, etag?: string | null): Promise<{ status: number; etag: string | null; info: RepoInfo | null }> { const res = await fetch(`${apiBase(env)}/repos/${fullName}`, { headers: headers(env, etag ? { 'if-none-match': etag } : {}) }); if (res.status === 304) return { status: 304, etag: etag ?? null, info: null }; if (!res.ok) return { status: res.status, etag: null, info: null }; const j = (await res.json()) as any; return { status: 200, etag: res.headers.get('etag'), info: { 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, 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 ?? ''), default_branch: j.default_branch ?? 'main', private: !!j.private, }, }; } function upsertSignals(env: Env, key: string, info: RepoInfo, etag: string | null): D1PreparedStatement { return env.DB.prepare( `INSERT INTO repo_signals (repo_full_name, stars, forks, open_issues, pushed_at, license_spdx, archived, unavailable, owner_id, etag, fetched_at) VALUES (?,?,?,?,?,?,?,0,?,?,?) ON CONFLICT(repo_full_name) DO UPDATE SET stars=excluded.stars, forks=excluded.forks, open_issues=excluded.open_issues, pushed_at=excluded.pushed_at, license_spdx=excluded.license_spdx, archived=excluded.archived, unavailable=0, owner_id=excluded.owner_id, etag=excluded.etag, fetched_at=excluded.fetched_at`, ).bind(key, info.stars, info.forks, info.open_issues, info.pushed_at, info.license_spdx, info.archived ? 1 : 0, info.owner_id, etag, now()); } /** Refresh the cached star count for one repo. Pages never wait on this. */ export async function refreshRepoSignals(env: Env, repo: string): Promise { const existing = await env.DB.prepare('SELECT etag FROM repo_signals WHERE repo_full_name = ?').bind(repo).first<{ etag: string | null }>(); const r = await getRepo(env, repo, existing?.etag); if (r.status === 304) { await env.DB.prepare('UPDATE repo_signals SET fetched_at = ?, unavailable = 0 WHERE repo_full_name = ?').bind(now(), repo).run(); } else if (r.status === 200 && r.info && !r.info.private) { await upsertSignals(env, repo, r.info, r.etag).run(); } else if (r.status === 404 || r.status === 451 || r.status === 410 || (r.info && r.info.private)) { // Renamed, deleted or made private: keep the last count and mark it. await env.DB.prepare( `INSERT INTO repo_signals (repo_full_name, unavailable, fetched_at) VALUES (?, 1, ?) ON CONFLICT(repo_full_name) DO UPDATE SET unavailable = 1, fetched_at = excluded.fetched_at`, ).bind(repo, now()).run(); } // 403/429 (rate limited) and 5xx: leave the row alone and try again on the next pass. } const STALE_ON_VIEW = 6 * 3600; /** Queue background refreshes for repos whose cached row is older than six hours. */ export function refreshStale(env: Env, ctx: { waitUntil(p: Promise): void }, rows: { github_repo: string | null; repo_fetched_at?: number | null }[]): void { const seen = new Set(); for (const r of rows) { if (!r.github_repo || ownRepo(r.github_repo) || seen.has(r.github_repo)) continue; if ((r.repo_fetched_at ?? 0) > now() - STALE_ON_VIEW) continue; seen.add(r.github_repo); if (seen.size > 5) break; ctx.waitUntil(refreshRepoSignals(env, r.github_repo).catch(() => {})); } } /** Daily pass: refresh every repo not fetched in the last 24 hours, oldest first. */ export async function refreshAllStale(env: Env, max = 80): Promise { const rows = await env.DB.prepare( `SELECT DISTINCT s.github_repo AS repo FROM skills s LEFT JOIN repo_signals r ON r.repo_full_name = s.github_repo 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 ?`, ).bind(now() - 86400, max).all<{ repo: string }>(); const repos = rows.results.filter((r) => !ownRepo(r.repo)); for (const r of repos) await refreshRepoSignals(env, r.repo).catch(() => {}); return repos.length; } export type ImportedFile = { path: string; data: Uint8Array }; export type Imported = { repo: string; ref: string; path: string; files: ImportedFile[]; info: RepoInfo; etag: string | null }; /** One file of a skill folder as the repo tree lists it: where it sits in the repo, and its path inside the skill. */ export type TreeFile = { path: string; rel: string; size: number }; /** A folder that holds a SKILL.md. `problem` is set when the folder cannot be taken as it is. */ export type SkillFolder = { path: string; name: string; files: TreeFile[]; problem?: string }; export type RepoScan = { repo: string; ref: string; info: RepoInfo; etag: string | null; folders: SkillFolder[]; truncated: boolean; duplicates: string[] }; /** The most skills one repo share can bring in. */ export const REPO_SKILL_LIMIT = 25; // Agent folders are a normal home for skills. Other hidden folders, and installed packages, are not somebody's own skills. const AGENT_DIRS = new Set(['.claude', '.agents', '.codex', '.gemini']); const skipSegment = (seg: string) => seg === 'node_modules' || seg === 'vendor' || (seg.startsWith('.') && !AGENT_DIRS.has(seg)); /** * Read a public repo's file list and find every skill folder in it. Nothing is downloaded yet. * With a path, only skills at or under that folder are returned. */ export async function scanRepo(env: Env, ref: RepoRef): Promise { const r = await getRepo(env, `${ref.owner}/${ref.repo}`); if (r.status === 403 || r.status === 429) throw new HttpError(503, 'GitHub is rate limiting Skillfarm right now. Try again in a few minutes.'); 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.'); const info = r.info; const branch = ref.ref || info.default_branch; const treeRes = await fetch(`${apiBase(env)}/repos/${info.full_name}/git/trees/${encodeURIComponent(branch)}?recursive=1`, { headers: headers(env) }); if (treeRes.status === 403 || treeRes.status === 429) throw new HttpError(503, 'GitHub is rate limiting Skillfarm right now. Try again in a few minutes.'); if (!treeRes.ok) throw new HttpError(400, `Could not read the "${branch}" branch of ${info.full_name}.`); const tree = (await treeRes.json()) as { sha: string; tree: { path: string; type: string; size?: number }[]; truncated?: boolean }; const blobs = tree.tree.filter((t) => t.type === 'blob'); const scope = (ref.path ?? '').replace(/^\/+|\/+$/g, ''); const dirOf = (p: string) => p.replace(/\/?SKILL\.md$/i, ''); let dirs = blobs.filter((b) => /(^|\/)SKILL\.md$/i.test(b.path)).map((b) => dirOf(b.path)); const allDirs = dirs; const exact = dirs.find((d) => d.toLowerCase() === scope.toLowerCase()); if (scope && exact !== undefined) dirs = [exact]; else { if (scope) dirs = dirs.filter((d) => d.toLowerCase().startsWith(scope.toLowerCase() + '/')); dirs = dirs.filter((d) => !d.split('/').some((seg) => seg !== '' && skipSegment(seg))); } // The same skill is often kept twice, once in an agent's folder and once in a public one. Keep the public copy. const byName = new Map(); const duplicates: string[] = []; const rank = (d: string) => (d.startsWith('.') ? 1000 : 0) + d.length; for (const d of [...dirs].sort((a, b) => rank(a) - rank(b) || a.localeCompare(b))) { const key = (d.split('/').pop() || info.full_name.split('/')[1]).toLowerCase(); if (byName.has(key)) duplicates.push(d); else byName.set(key, d); } const folders: SkillFolder[] = []; for (const dir of [...byName.values()].sort((a, b) => a.localeCompare(b))) { const prefix = dir === '' ? '' : dir + '/'; const wanted = blobs.filter((b) => b.path.startsWith(prefix)).map((b) => ({ path: b.path, rel: b.path.slice(prefix.length), size: b.size ?? 0 })); // A skill at the repo root would otherwise drag in the whole repo; nested skills are separate skills. const nested = allDirs.filter((d) => d !== dir && d.startsWith(prefix)).map((d) => d.slice(prefix.length) + '/'); const mine = wanted.filter((b) => !nested.some((n) => b.rel.startsWith(n)) && !b.rel.startsWith('.git') && !/(^|\/)(node_modules|\.github)\//.test(b.rel)); const text = mine.filter((b) => isTextPath(b.rel) && isSafePath(b.rel)); const total = text.reduce((n, b) => n + b.size, 0); const tooBig = text.find((b) => b.size > BUNDLE_LIMITS.fileBytes); let problem: string | undefined; if (text.length > BUNDLE_LIMITS.files) problem = `It has ${text.length} text files. The limit is ${BUNDLE_LIMITS.files}.`; else if (tooBig) problem = `${tooBig.rel} is larger than ${BUNDLE_LIMITS.fileBytes / 1000} KB.`; else if (total > BUNDLE_LIMITS.totalBytes) problem = `It is ${Math.round(total / 1000)} KB. The limit is ${BUNDLE_LIMITS.totalBytes / 1000} KB.`; folders.push({ path: dir, name: dir.split('/').pop() || info.full_name.split('/')[1], files: text, problem }); } await upsertSignals(env, info.full_name, info, r.etag).run(); return { repo: info.full_name, ref: tree.sha, info, etag: r.etag, folders, truncated: !!tree.truncated, duplicates }; } /** Download the files of one skill folder at a fixed commit. */ export async function fetchSkillFiles(env: Env, repo: string, sha: string, files: TreeFile[]): Promise { const out: ImportedFile[] = []; for (const b of files) { if (!isSafePath(b.rel) || !isTextPath(b.rel)) continue; const raw = await fetch(`${rawBase(env)}/${repo}/${sha}/${b.path.split('/').map(encodeURIComponent).join('/')}`, { headers: { 'user-agent': 'skillfarm' } }); if (!raw.ok) throw new HttpError(502, `Could not download ${b.rel} from GitHub.`); const data = new Uint8Array(await raw.arrayBuffer()); if (data.length > BUNDLE_LIMITS.fileBytes) throw new HttpError(400, `${b.rel} is larger than ${BUNDLE_LIMITS.fileBytes / 1000} KB.`); // Normalise the entry file name so every bundle has exactly "SKILL.md". out.push({ path: /^SKILL\.md$/i.test(b.rel) ? 'SKILL.md' : b.rel, data }); } if (!out.some((f) => f.path === 'SKILL.md')) throw new HttpError(400, 'No SKILL.md was found in that folder.'); return out; } /** Pull one skill folder (SKILL.md plus its supporting text files) from a public repo. */ export async function importFromGithub(env: Env, ref: RepoRef): Promise { const scan = await scanRepo(env, ref); const scope = (ref.path ?? '').replace(/^\/+|\/+$/g, ''); let folder = scan.folders.find((f) => f.path.toLowerCase() === scope.toLowerCase()); if (!folder) { if (scan.folders.length === 1) folder = scan.folders[0]; else if (scan.folders.length === 0) throw new HttpError(400, `No SKILL.md was found${scope ? ` under "${scope}"` : ''} in ${scan.repo}.`); else { const list = scan.folders.slice(0, 12).map((f) => f.path || '(repo root)').join(', '); throw new HttpError(400, `${scan.repo} holds ${scan.folders.length} skills. Give the link to one skill folder. Found: ${list}${scan.folders.length > 12 ? ', …' : ''}`); } } if (folder.problem) throw new HttpError(400, `That skill folder cannot be taken as it is. ${folder.problem}`); const files = await fetchSkillFiles(env, scan.repo, scan.ref, folder.files); return { repo: scan.repo, ref: scan.ref, path: folder.path, files, info: scan.info, etag: scan.etag }; }