import type { Env, User } from '../env'; import { runAiReview } from './ai'; import { mail } from './email'; import { BUNDLE_LIMITS, isSafePath, isTextPath, refreshRepoSignals } from './github'; import { parseSkillMd } from './markdown'; import { grant, grantStatements, reverseSkillPoints } from './points'; import { rateLimit } from './ratelimit'; import { staticScan, type Finding } from './scan'; import { LIMITS, SEEDS, tierFor } from './tiers'; import { DAY, HttpError, hmacHex, likeEscape, newId, now, sha256Hex, slugify } from './util'; export const PLATFORMS: { key: string; name: string }[] = [ { key: 'claude-code', name: 'Claude Code' }, { key: 'codex', name: 'Codex CLI' }, { key: 'gemini-cli', name: 'Gemini CLI' }, ]; const PLATFORM_KEYS = new Set(PLATFORMS.map((p) => p.key)); export const platformName = (key: string) => PLATFORMS.find((p) => p.key === key)?.name ?? key; export const splitPlatforms = (csv: string) => csv.split(',').filter((k) => PLATFORM_KEYS.has(k)); export const CATEGORIES: { key: string; name: string }[] = [ { key: 'design', name: 'Design' }, { key: 'video', name: 'Video' }, { key: 'coding', name: 'Coding' }, { key: 'testing', name: 'Testing' }, { key: 'writing', name: 'Writing and marketing' }, { key: 'research', name: 'Data and research' }, { key: 'devops', name: 'Cloud and DevOps' }, { key: 'productivity', name: 'Productivity' }, { key: 'security', name: 'Security' }, { key: 'business', name: 'Commerce and sales' }, { key: 'finance', name: 'Finance' }, { key: 'legal', name: 'Legal' }, { key: 'science', name: 'Science and health' }, { key: 'education', name: 'Education' }, ]; const CATEGORY_KEYS = new Set(CATEGORIES.map((c) => c.key)); export const categoryName = (key: string | null) => CATEGORIES.find((c) => c.key === key)?.name ?? null; export const cleanCategory = (key: unknown) => (typeof key === 'string' && CATEGORY_KEYS.has(key) ? key : null); /** The account Sprout's picks belong to. Created by migration 0002. */ export const SPROUT_ID = 'sprout00000agent'; export type SkillRow = { id: string; owner_id: string; slug: string; title: string; summary: string; platforms: string; github_repo: string | null; github_path: string | null; github_ref: string | null; replanted_from_skill_id: string | null; verified_owner: number; state: string; current_version_id: string | null; likes_count: number; installs_count: number; reviews_count: number; rating_sum: number; comments_count: number; featured_at: number | null; off_home: number; source: string; created_at: number; updated_at: number; published_at: number | null; /** "link" is a pick: a recommendation that points to the maker's repo. Skillfarm holds no files for it. */ kind: 'hosted' | 'link'; category: string | null; maker: string | null; maker_url: string | null; source_url: string | null; license: string | null; install_hint: string | null; pick_note: string | null; /** A converted copy of a pick that reads the same in every supported agent: the public repo and the folder inside it. */ multi_repo?: string | null; multi_path?: string | null; }; export type SkillCard = SkillRow & { owner_handle: string; owner_name: string; owner_avatar_key: string | null; owner_avatar_fallback: string | null; owner_seeds: number; owner_is_agent: number; stars: number | null; repo_fetched_at: number | null; repo_unavailable: number | null; repo_license?: string | null; liked?: number | null; }; export type VersionRow = { id: string; skill_id: string; version: number; r2_prefix: string; sha256: string; size: number; manifest: string; title: string; summary: string; platforms: string; status: string; scan_status: string; scan_report: string; ai_status: string; ai_recommendation: string | null; ai_summary: string | null; ai_report: string | null; ai_attempts: number; decided_by: string | null; decided_at: number | null; decision_note: string | null; created_at: number; }; export type ManifestEntry = { path: string; size: number; sha256: string }; const CARD_FROM = `FROM skills s JOIN users u ON u.id = s.owner_id LEFT JOIN repo_signals r ON r.repo_full_name = s.github_repo`; const CARD_COLS = `s.*, u.handle AS owner_handle, u.display_name AS owner_name, u.avatar_key AS owner_avatar_key, u.avatar_fallback AS owner_avatar_fallback, u.seeds_total AS owner_seeds, u.is_agent AS owner_is_agent, r.stars AS stars, r.fetched_at AS repo_fetched_at, r.unavailable AS repo_unavailable, r.license_spdx AS repo_license`; export type ListOpts = { q?: string; platform?: string; category?: string; kind?: 'hosted' | 'link'; sort?: string; limit?: number; offset?: number; ownerId?: string; viewerId?: string | null; featured?: boolean; states?: string[]; /** Leave out skills an admin has kept off the home page. */ home?: boolean; /** Only skills shared by the member with this handle. */ ownerHandle?: string; /** Words to look for in who made it: a pick's maker, the owner of the GitHub repo, or the member who shared it. */ maker?: string; /** Only skills from this GitHub repo, as "owner/name". */ repo?: string; /** Only skills under this licence, as an SPDX id such as "MIT". */ license?: string; }; /** Up to six search words. Every word has to match somewhere, so "legal contract" finds a skill that mentions both. */ function searchTerms(q: string): string[] { return [...new Set(q.toLowerCase().slice(0, 80).split(/[\s,]+/).filter((t) => t.length > 0))].slice(0, 6); } export async function listSkills(env: Env, o: ListOpts): Promise { const where: string[] = []; const args: unknown[] = []; const liked = o.viewerId ? `, (SELECT 1 FROM likes l WHERE l.skill_id = s.id AND l.user_id = ? AND l.removed_at IS NULL) AS liked` : ''; if (o.viewerId) args.push(o.viewerId); const states = o.states ?? ['live']; where.push(`s.state IN (${states.map(() => '?').join(',')})`); args.push(...states); if (o.ownerId) { where.push('s.owner_id = ?'); args.push(o.ownerId); } if (o.featured) where.push('s.featured_at IS NOT NULL'); if (o.home) where.push('s.off_home = 0'); if (o.category && CATEGORY_KEYS.has(o.category)) { where.push('s.category = ?'); args.push(o.category); } if (o.kind === 'hosted' || o.kind === 'link') { where.push('s.kind = ?'); args.push(o.kind); } if (o.platform && PLATFORM_KEYS.has(o.platform)) { where.push(`(',' || s.platforms || ',') LIKE ?`); args.push(`%,${o.platform},%`); } if (o.ownerHandle) { where.push('u.handle = ?'); args.push(o.ownerHandle.toLowerCase().slice(0, 40)); } if (o.repo) { where.push('LOWER(s.github_repo) = ?'); args.push(o.repo.toLowerCase().slice(0, 140)); } if (o.license) { where.push('LOWER(COALESCE(s.license, r.license_spdx)) = ?'); args.push(o.license.toLowerCase().slice(0, 40)); } if (o.maker) { const like = `%${likeEscape(o.maker.slice(0, 60))}%`; where.push(`(s.maker LIKE ? ESCAPE '\\' OR s.github_repo LIKE ? ESCAPE '\\' OR (s.kind = 'hosted' AND (u.handle LIKE ? ESCAPE '\\' OR u.display_name LIKE ? ESCAPE '\\')))`); args.push(like, `${like}/%`, like, like); } for (const term of o.q ? searchTerms(o.q) : []) { const like = `%${likeEscape(term)}%`; const fields = ['s.title', 's.summary', 's.slug', 'u.handle', 'u.display_name', 's.github_repo', 's.maker', 's.platforms', 's.pick_note', 'COALESCE(s.license, r.license_spdx)']; // A word that names a category ("legal", "marketing", "devops") matches everything filed under it. const cats = CATEGORIES.filter((c) => c.key.includes(term) || c.name.toLowerCase().includes(term)).map((c) => c.key); where.push(`(${fields.map((f) => `${f} LIKE ? ESCAPE '\\'`).join(' OR ')}${cats.length ? ` OR s.category IN (${cats.map(() => '?').join(',')})` : ''})`); args.push(...fields.map(() => like), ...cats); } // Stars break ties, so a list of picks nobody has liked yet still has a sensible order. Before stars, a pick's place among the picks // from the same repo: one repo with twenty picks then takes one slot per round instead of filling a page. const repoRank = `(SELECT COUNT(*) FROM skills s3 WHERE s3.kind = 'link' AND s3.state = 'live' AND s3.github_repo = s.github_repo AND s3.published_at > s.published_at)`; let order = 's.published_at DESC, COALESCE(r.stars, 0) DESC'; const ts = now(); if (o.featured) order = 's.featured_at DESC'; else if (o.sort === 'top') order = `s.likes_count DESC, s.installs_count DESC, ${repoRank} ASC, COALESCE(r.stars, 0) DESC, s.published_at DESC`; else if (o.sort === 'trending') { // A new skill from a member starts with a small score so it gets seen. A pick starts at zero and rises only on likes. order = `((SELECT COUNT(*) FROM likes l2 WHERE l2.skill_id = s.id AND l2.removed_at IS NULL AND l2.created_at > ${ts - 7 * DAY}) * 3.0 + (SELECT COUNT(*) FROM installs i2 WHERE i2.skill_id = s.id AND i2.created_at > ${ts - 7 * DAY}) + CASE WHEN s.kind = 'link' THEN 0 ELSE 0.5 END) / ((${ts} - COALESCE(s.published_at, s.created_at)) / 86400.0 + 2.0) DESC, ${repoRank} ASC, COALESCE(r.stars, 0) DESC, s.published_at DESC`; } else if (o.sort === 'updated') order = 's.updated_at DESC'; args.push(Math.min(o.limit ?? 24, 400), o.offset ?? 0); const res = await env.DB.prepare(`SELECT ${CARD_COLS}${liked} ${CARD_FROM} WHERE ${where.join(' AND ')} ORDER BY ${order} LIMIT ? OFFSET ?`).bind(...args).all(); return res.results; } export async function getSkillCard(env: Env, handle: string, slug: string, viewerId?: string | null): Promise { const liked = viewerId ? `, (SELECT 1 FROM likes l WHERE l.skill_id = s.id AND l.user_id = ? AND l.removed_at IS NULL) AS liked` : ''; const args: unknown[] = viewerId ? [viewerId, handle, slug] : [handle, slug]; return env.DB.prepare(`SELECT ${CARD_COLS}${liked} ${CARD_FROM} WHERE u.handle = ? AND s.slug = ?`).bind(...args).first(); } export async function getSkillCardById(env: Env, id: string): Promise { return env.DB.prepare(`SELECT ${CARD_COLS} ${CARD_FROM} WHERE s.id = ?`).bind(id).first(); } /** A spread of Sprout's picks for the home page: one pick per repo, then the most-starred pick in each category first. */ export async function sproutPicks(env: Env, limit: number, viewerId?: string | null): Promise { const liked = viewerId ? `, (SELECT 1 FROM likes l WHERE l.skill_id = s.id AND l.user_id = ? AND l.removed_at IS NULL) AS liked` : ''; const args: unknown[] = viewerId ? [viewerId, limit] : [limit]; const res = await env.DB.prepare( `SELECT * FROM ( SELECT x.*, ROW_NUMBER() OVER (PARTITION BY x.category ORDER BY COALESCE(x.stars, 0) DESC, x.published_at DESC) AS cat_rank FROM ( SELECT ${CARD_COLS}${liked}, ROW_NUMBER() OVER (PARTITION BY s.github_repo ORDER BY s.published_at DESC) AS repo_rank ${CARD_FROM} WHERE s.state = 'live' AND s.kind = 'link' AND s.off_home = 0 ) x WHERE x.repo_rank = 1 ) ORDER BY cat_rank ASC, COALESCE(stars, 0) DESC LIMIT ?`, ).bind(...args).all(); return res.results; } /** How many live skills each category holds, for the filter chips. */ export async function categoryCounts(env: Env): Promise> { const res = await env.DB.prepare("SELECT category, COUNT(*) AS n FROM skills WHERE state = 'live' AND category IS NOT NULL GROUP BY category").all<{ category: string; n: number }>(); return Object.fromEntries(res.results.map((r) => [r.category, r.n])); } export function canView(skill: SkillRow, viewer: User | null): boolean { if (skill.state === 'live') return true; return !!viewer && (viewer.id === skill.owner_id || !!viewer.is_admin); } export async function getVersion(env: Env, id: string | null): Promise { if (!id) return null; return env.DB.prepare('SELECT * FROM skill_versions WHERE id = ?').bind(id).first(); } export async function latestVersion(env: Env, skillId: string): Promise { return env.DB.prepare('SELECT * FROM skill_versions WHERE skill_id = ? ORDER BY version DESC LIMIT 1').bind(skillId).first(); } export async function readVersionFile(env: Env, v: VersionRow, path: string): Promise { const manifest = JSON.parse(v.manifest) as ManifestEntry[]; if (!manifest.some((m) => m.path === path)) return null; const obj = await env.SKILLS.get(v.r2_prefix + path); return obj ? new Uint8Array(await obj.arrayBuffer()) : null; } export async function readVersionFiles(env: Env, v: VersionRow): Promise<{ path: string; data: Uint8Array }[]> { const manifest = JSON.parse(v.manifest) as ManifestEntry[]; const out: { path: string; data: Uint8Array }[] = []; for (const m of manifest) { const obj = await env.SKILLS.get(v.r2_prefix + m.path); if (obj) out.push({ path: m.path, data: new Uint8Array(await obj.arrayBuffer()) }); } return out; } export type SubmitInput = { user: User; source: 'web' | 'mcp'; files: { path: string; data: Uint8Array }[]; title?: string; summary?: string; platforms?: string[]; category?: string | null; github?: { repo: string; path: string; ref: string; ownerId: string }; replantedFrom?: SkillRow | null; existing?: SkillRow | null; /** Set when the skill comes in as part of a shared repo: the repo share sends one notice for all of them and has its own limits. */ partOfRepoShare?: boolean; }; type Waiter = { waitUntil(p: Promise): void }; function isBinary(data: Uint8Array): boolean { const n = Math.min(data.length, 8000); for (let i = 0; i < n; i++) if (data[i] === 0) return true; return false; } /** The file list of a bundle and the hash that identifies its exact contents. */ export async function bundleManifest(files: { path: string; data: Uint8Array }[]): Promise<{ manifest: ManifestEntry[]; sha: string }> { const manifest: ManifestEntry[] = []; for (const f of files) manifest.push({ path: f.path, size: f.data.length, sha256: await sha256Hex(f.data) }); manifest.sort((a, b) => (a.path === 'SKILL.md' ? -1 : b.path === 'SKILL.md' ? 1 : a.path.localeCompare(b.path))); return { manifest, sha: await sha256Hex(manifest.map((m) => `${m.path}\0${m.sha256}`).join('\n')) }; } /** Validate, scan and store a submission. It always lands in the review queue; nothing goes public here. */ export async function submitSkill(env: Env, ctx: Waiter, input: SubmitInput): Promise<{ skill: SkillRow; version: VersionRow; ownerHandle: string }> { const { user } = input; if (user.status !== 'active') throw new HttpError(403, 'This account cannot share skills.'); const files = input.files; if (!files.length || files.length > BUNDLE_LIMITS.files) throw new HttpError(400, `A skill can hold up to ${BUNDLE_LIMITS.files} files.`); const seen = new Set(); let total = 0; for (const f of files) { if (!isSafePath(f.path) || !isTextPath(f.path)) throw new HttpError(400, `"${f.path}" is not an allowed file. Skills hold text files only.`); if (seen.has(f.path.toLowerCase())) throw new HttpError(400, `"${f.path}" appears twice.`); seen.add(f.path.toLowerCase()); if (f.data.length > BUNDLE_LIMITS.fileBytes) throw new HttpError(400, `"${f.path}" is larger than ${BUNDLE_LIMITS.fileBytes / 1000} KB.`); if (isBinary(f.data)) throw new HttpError(400, `"${f.path}" looks like a binary file. Skills hold text files only.`); total += f.data.length; } if (total > BUNDLE_LIMITS.totalBytes) throw new HttpError(400, `That skill is ${Math.round(total / 1000)} KB. The limit is ${BUNDLE_LIMITS.totalBytes / 1000} KB.`); const entry = files.find((f) => f.path === 'SKILL.md'); if (!entry) throw new HttpError(400, 'A skill needs a SKILL.md file.'); const dec = new TextDecoder(); const skillMd = dec.decode(entry.data); const { meta, body } = parseSkillMd(skillMd); if (body.trim().length < 40) throw new HttpError(400, 'That SKILL.md is nearly empty. Add the instructions the agent should follow.'); const existing = input.existing ?? null; // An update keeps the title the skill already has unless a new one is given. const title = (input.title || existing?.title || titleFromName(meta.name ?? '')).trim().replace(/\s+/g, ' ').slice(0, 80); if (title.length < 3) throw new HttpError(400, 'Give the skill a name: add `name:` to the SKILL.md header or fill in the title.'); const summary = clip(input.summary || meta.description || existing?.summary || '', 280); if (summary.length < 12) throw new HttpError(400, 'Give the skill a short description: add `description:` to the SKILL.md header or fill in the summary.'); const platforms = [...new Set((input.platforms ?? (existing ? splitPlatforms(existing.platforms) : [])).filter((p) => PLATFORM_KEYS.has(p)))]; if (!platforms.length) platforms.push(...PLATFORMS.map((p) => p.key)); const category = cleanCategory(input.category) ?? existing?.category ?? null; const ts = now(); if (existing) { if (existing.kind === 'link') throw new HttpError(400, 'A pick has no versions. It links to its maker.'); if (existing.owner_id !== user.id) throw new HttpError(403, 'Only the owner can update a skill.'); if (existing.state === 'removed') throw new HttpError(400, 'This skill was removed.'); if (!(await rateLimit(env, `version:${user.id}`, LIMITS.versionsPerDay, DAY))) throw new HttpError(429, 'You have submitted a lot of updates today. Try again tomorrow.'); } else if (!user.is_admin && !input.partOfRepoShare) { const limit = tierFor(user.seeds_total).sharesPerWeek; const recent = await env.DB.prepare("SELECT COUNT(*) AS n FROM skills WHERE owner_id = ? AND created_at > ? AND state != 'removed'").bind(user.id, ts - 7 * DAY).first<{ n: number }>(); if ((recent?.n ?? 0) >= limit) throw new HttpError(429, `${tierFor(user.seeds_total).name}s can share ${limit} skills a week. The limit rises with your tier.`); } let slug = existing?.slug ?? slugify(meta.name || title); if (slug.length < 2) throw new HttpError(400, 'That name does not make a usable link. Use letters or numbers.'); if (!existing) { const clash = await env.DB.prepare('SELECT id, state FROM skills WHERE owner_id = ? AND slug = ?').bind(user.id, slug).first<{ id: string; state: string }>(); if (clash && clash.state !== 'removed') throw new HttpError(409, `You already have a skill called "${slug}". Open it and submit a new version instead.`); if (clash) slug = `${slug}-${newId(4)}`; } // Scan. const scan = staticScan(files.filter((f) => !isBinary(f.data)).map((f) => ({ path: f.path, text: dec.decode(f.data) }))); const { manifest, sha: bundleSha } = await bundleManifest(files); const findings: Finding[] = scan.findings; const twin = await env.DB.prepare( `SELECT u.handle, s.slug FROM skill_versions v JOIN skills s ON s.id = v.skill_id JOIN users u ON u.id = s.owner_id WHERE v.sha256 = ? AND s.owner_id != ? AND s.state = 'live' LIMIT 1`, ).bind(bundleSha, user.id).first<{ handle: string; slug: string }>(); if (twin && !(input.replantedFrom)) { findings.unshift({ severity: 'medium', rule: `Identical to the live skill ${twin.handle}/${twin.slug} by another member`, file: 'SKILL.md', line: 1, excerpt: '' }); } const scanStatus = findings.some((f) => f.severity === 'high') ? 'high' : findings.length ? 'flagged' : 'clean'; const skillId = existing?.id ?? newId(); const versionId = newId(); const prefix = `skills/${skillId}/${versionId}/`; for (const f of files) await env.SKILLS.put(prefix + f.path, f.data, { httpMetadata: { contentType: 'text/plain; charset=utf-8' } }); let verified = 0; if (input.github) { const gh = await env.DB.prepare("SELECT provider_user_id FROM oauth_accounts WHERE user_id = ? AND provider = 'github'").bind(user.id).first<{ provider_user_id: string }>(); verified = gh && gh.provider_user_id === input.github.ownerId ? 1 : 0; } const lastVersion = existing ? await env.DB.prepare('SELECT COALESCE(MAX(version), 0) AS v FROM skill_versions WHERE skill_id = ?').bind(skillId).first<{ v: number }>() : null; const versionNo = (lastVersion?.v ?? 0) + 1; const aiStatus = env.ANTHROPIC_API_KEY ? 'queued' : 'unavailable'; const stmts: D1PreparedStatement[] = []; if (!existing) { stmts.push( env.DB.prepare( `INSERT INTO skills (id, owner_id, slug, title, summary, platforms, category, github_repo, github_path, github_ref, replanted_from_skill_id, verified_owner, state, source, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,'pending',?,?,?)`, ).bind(skillId, user.id, slug, title, summary, platforms.join(','), category, input.github?.repo ?? null, input.github?.path ?? null, input.github?.ref ?? null, input.replantedFrom?.id ?? null, verified, input.source, ts, ts), ); } else { // A waiting version is replaced by the newer one; the live version stays up until a reviewer approves. stmts.push(env.DB.prepare("UPDATE skill_versions SET status = 'superseded' WHERE skill_id = ? AND status = 'pending'").bind(skillId)); if (existing.state === 'rejected') stmts.push(env.DB.prepare("UPDATE skills SET state = 'pending', updated_at = ? WHERE id = ?").bind(ts, skillId)); if (input.github) stmts.push(env.DB.prepare('UPDATE skills SET github_ref = ? WHERE id = ?').bind(input.github.ref, skillId)); if (category !== existing.category) stmts.push(env.DB.prepare('UPDATE skills SET category = ? WHERE id = ?').bind(category, skillId)); } stmts.push( env.DB.prepare( `INSERT INTO skill_versions (id, skill_id, version, r2_prefix, sha256, size, manifest, title, summary, platforms, status, scan_status, scan_report, ai_status, created_at) VALUES (?,?,?,?,?,?,?,?,?,?,'pending',?,?,?,?)`, ).bind(versionId, skillId, versionNo, prefix, bundleSha, total, JSON.stringify(manifest), title, summary, platforms.join(','), scanStatus, JSON.stringify(findings), aiStatus, ts), ); await env.DB.batch(stmts); const skill = (await env.DB.prepare('SELECT * FROM skills WHERE id = ?').bind(skillId).first())!; const version = (await getVersion(env, versionId))!; const url = `${env.SITE_URL}/skills/${user.handle}/${skill.slug}`; ctx.waitUntil( (async () => { if (!input.partOfRepoShare) await mail.received(env, user, title, url); if (aiStatus === 'unavailable' && !input.partOfRepoShare) await mail.adminReview(env, title, user.handle, 'unavailable', 'AI review is not configured, so this one needs a manual read.'); })().catch((e) => console.error('submit notices failed', e)), ); return { skill, version, ownerHandle: user.handle }; } const SHOUT = new Set(['mcp', 'api', 'cli', 'pdf', 'ui', 'ux', 'ci', 'sql', 'css', 'html', 'ai', 'seo', 'pr', 'json', 'csv', 'sdk', 'url', 'ssh']); /** "agent-council" reads better as "Agent Council" on a card. A name that already has capitals or spaces is left alone. */ export function titleFromName(name: string): string { const s = name.trim().replace(/\s+/g, ' '); if (!/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/.test(s)) return s; return s.split(/[-_]/).map((w) => (SHOUT.has(w) ? w.toUpperCase() : w[0].toUpperCase() + w.slice(1))).join(' '); } /** Shorten a long description at the end of a sentence, or failing that a word. Never mid-word. */ export function clip(text: string, max: number): string { const s = text.trim().replace(/\s+/g, ' '); if (s.length <= max) return s; const head = s.slice(0, max); const stop = Math.max(head.lastIndexOf('. '), head.lastIndexOf('! '), head.lastIndexOf('? ')); if (stop >= 60) return head.slice(0, stop + 1); const cut = head.lastIndexOf(' '); return (cut > 0 ? head.slice(0, cut) : head.slice(0, max - 1)).replace(/[,;:.\s]+$/, '') + '…'; } export type PickInput = { id?: string; title: string; summary: string; category: string; maker: string; makerUrl: string; sourceUrl: string; repo: string; path?: string; license?: string; installHint?: string; note?: string; platforms?: string[]; }; /** * Add or edit one of Sprout's picks. Only a moderator can do this, and doing it is the moderator's decision to publish: * a pick goes live at once because there is no submitted file to review, only a link the moderator has chosen. */ export async function savePick(env: Env, admin: User, input: PickInput): Promise { if (!admin.is_admin) throw new HttpError(403, 'Moderators only.'); const one = (v: string | undefined, max: number) => (v ?? '').trim().replace(/\s+/g, ' ').slice(0, max); const title = one(input.title, 80); const summary = one(input.summary, 280); const maker = one(input.maker, 80); const category = cleanCategory(input.category); const repo = one(input.repo, 140); const https = (v: string | undefined) => { const t = (v ?? '').trim(); if (!t) return null; let u: URL; try { u = new URL(t); } catch { throw new HttpError(400, `"${t.slice(0, 80)}" is not a web address.`); } if (u.protocol !== 'https:') throw new HttpError(400, 'Links must start with https://.'); return u.toString(); }; if (title.length < 2) throw new HttpError(400, 'Give the pick a title.'); if (summary.length < 12) throw new HttpError(400, 'Say what the skill does in a sentence.'); if (!maker) throw new HttpError(400, 'Name the maker. Picks always credit who made the skill.'); if (!category) throw new HttpError(400, 'Pick a category.'); if (!/^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/.test(repo)) throw new HttpError(400, 'Give the GitHub repo as owner/name.'); const path = (input.path ?? '').trim().replace(/^\/+|\/+$/g, '').slice(0, 200) || null; const sourceUrl = https(input.sourceUrl) ?? `https://github.com/${repo}${path ? `/tree/HEAD/${path}` : ''}`; const makerUrl = https(input.makerUrl) ?? `https://github.com/${repo.split('/')[0]}`; const platforms = [...new Set((input.platforms ?? []).filter((p) => PLATFORM_KEYS.has(p)))]; if (!platforms.length) platforms.push(...PLATFORMS.map((p) => p.key)); const license = one(input.license, 60) || null; const hint = (input.installHint ?? '').trim().slice(0, 400) || null; const note = one(input.note, 600) || null; const sprout = await env.DB.prepare('SELECT id FROM users WHERE id = ? AND is_agent = 1').bind(SPROUT_ID).first(); if (!sprout) throw new HttpError(503, 'The Sprout account is missing. Apply the database migrations.'); const ts = now(); let id = input.id ?? ''; if (id) { const cur = await env.DB.prepare('SELECT * FROM skills WHERE id = ?').bind(id).first(); if (!cur || cur.kind !== 'link') throw new HttpError(404, 'That pick was not found.'); await env.DB.batch([ env.DB.prepare( `UPDATE skills SET title = ?, summary = ?, platforms = ?, category = ?, maker = ?, maker_url = ?, source_url = ?, github_repo = ?, github_path = ?, license = ?, install_hint = ?, pick_note = ?, updated_at = ? WHERE id = ?`, ).bind(title, summary, platforms.join(','), category, maker, makerUrl, sourceUrl, repo, path, license, hint, note, ts, id), env.DB.prepare('INSERT INTO moderation_actions (id, admin_id, action, target_type, target_id, note, created_at) VALUES (?,?,?,?,?,?,?)').bind(newId(), admin.id, 'pick_edit', 'skill', id, null, ts), ]); } else { id = newId(); let slug = slugify(title); if (slug.length < 2) throw new HttpError(400, 'That title does not make a usable link. Use letters or numbers.'); const clash = await env.DB.prepare('SELECT id FROM skills WHERE owner_id = ? AND slug = ?').bind(SPROUT_ID, slug).first(); if (clash) slug = `${slug}-${newId(4)}`; await env.DB.batch([ env.DB.prepare( `INSERT INTO skills (id, owner_id, slug, title, summary, platforms, category, kind, maker, maker_url, source_url, github_repo, github_path, license, install_hint, pick_note, state, source, created_at, updated_at, published_at) VALUES (?,?,?,?,?,?,?,'link',?,?,?,?,?,?,?,?,'live','pick',?,?,?)`, ).bind(id, SPROUT_ID, slug, title, summary, platforms.join(','), category, maker, makerUrl, sourceUrl, repo, path, license, hint, note, ts, ts, ts), env.DB.prepare('INSERT INTO moderation_actions (id, admin_id, action, target_type, target_id, note, created_at) VALUES (?,?,?,?,?,?,?)').bind(newId(), admin.id, 'pick', 'skill', id, null, ts), ]); } await refreshRepoSignals(env, repo).catch(() => {}); return (await env.DB.prepare('SELECT * FROM skills WHERE id = ?').bind(id).first())!; } /** A moderator's decision on a waiting version. Apart from a moderator's own picks (savePick), this is the only path to "live". */ export async function decideVersion( env: Env, admin: User, versionId: string, decision: 'approve' | 'reject', note: string, opts: { category?: string | null; silent?: boolean } = {}, ): Promise { if (!admin.is_admin) throw new HttpError(403, 'Moderators only.'); const v = await getVersion(env, versionId); if (!v) throw new HttpError(404, 'That submission was not found.'); if (v.status !== 'pending') throw new HttpError(409, 'That submission was already decided.'); const skill = (await env.DB.prepare('SELECT * FROM skills WHERE id = ?').bind(v.skill_id).first())!; const owner = (await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(skill.owner_id).first())!; const ts = now(); const url = `${env.SITE_URL}/skills/${owner.handle}/${skill.slug}`; const log = env.DB.prepare('INSERT INTO moderation_actions (id, admin_id, action, target_type, target_id, note, created_at) VALUES (?,?,?,?,?,?,?)').bind(newId(), admin.id, decision, 'version', v.id, note || null, ts); if (decision === 'reject') { const stmts = [ env.DB.prepare("UPDATE skill_versions SET status = 'rejected', decided_by = ?, decided_at = ?, decision_note = ? WHERE id = ?").bind(admin.id, ts, note || null, v.id), log, ]; if (!skill.current_version_id) stmts.push(env.DB.prepare("UPDATE skills SET state = 'rejected', updated_at = ? WHERE id = ?").bind(ts, skill.id)); await env.DB.batch(stmts); if (!opts.silent) await mail.denied(env, owner, v.title, url, note); return { ...skill, state: skill.current_version_id ? skill.state : 'rejected' }; } if (owner.status !== 'active') throw new HttpError(409, 'The owner of this skill is banned.'); const first = !skill.published_at; await env.DB.batch([ env.DB.prepare("UPDATE skill_versions SET status = 'superseded' WHERE skill_id = ? AND status = 'approved'").bind(skill.id), env.DB.prepare("UPDATE skill_versions SET status = 'approved', decided_by = ?, decided_at = ?, decision_note = ? WHERE id = ?").bind(admin.id, ts, note || null, v.id), env.DB.prepare( `UPDATE skills SET state = CASE WHEN state IN ('pending','rejected') THEN 'live' ELSE state END, current_version_id = ?, title = ?, summary = ?, platforms = ?, category = COALESCE(?, category), updated_at = ?, published_at = COALESCE(published_at, ?) WHERE id = ?`, ).bind(v.id, v.title, v.summary, v.platforms, cleanCategory(opts.category), ts, ts, skill.id), log, ]); if (first) { // Share Seeds are granted once per skill, only after approval. New versions earn nothing. await grant(env, { userId: owner.id, kind: 'share', amount: SEEDS.share, sourceType: 'skill', sourceId: skill.id, skillId: skill.id }); if (skill.replanted_from_skill_id) { const parent = await env.DB.prepare('SELECT owner_id, state FROM skills WHERE id = ?').bind(skill.replanted_from_skill_id).first<{ owner_id: string; state: string }>(); if (parent && parent.owner_id !== owner.id) { await grant(env, { userId: parent.owner_id, kind: 'replant', amount: SEEDS.replant, sourceType: 'skill', sourceId: skill.id, skillId: skill.id }); } } } if (skill.github_repo) await refreshRepoSignals(env, skill.github_repo).catch(() => {}); if (!opts.silent) await mail.approved(env, owner, v.title, url, first ? SEEDS.share : 0); return { ...skill, state: 'live', current_version_id: v.id }; } export async function setSkillState(env: Env, actor: User, skill: SkillRow, state: 'removed' | 'hidden' | 'live', note = ''): Promise { const isOwner = actor.id === skill.owner_id; if (!actor.is_admin && !(isOwner && state === 'removed')) throw new HttpError(403, 'Not allowed.'); if (state === 'live' && !skill.current_version_id && skill.kind !== 'link') throw new HttpError(409, 'This skill has no approved version.'); const ts = now(); await env.DB.batch([ env.DB.prepare('UPDATE skills SET state = ?, featured_at = CASE WHEN ? = \'live\' THEN featured_at ELSE NULL END, updated_at = ? WHERE id = ?').bind(state, state, ts, skill.id), env.DB.prepare("UPDATE skill_versions SET status = 'superseded' WHERE skill_id = ? AND status = 'pending' AND ? = 'removed'").bind(skill.id, state), env.DB.prepare('INSERT INTO moderation_actions (id, admin_id, action, target_type, target_id, note, created_at) VALUES (?,?,?,?,?,?,?)').bind(newId(), actor.id, state === 'live' ? 'restore' : state, 'skill', skill.id, note || null, ts), ]); if (state === 'removed') { await reverseSkillPoints(env, skill.id); if (!isOwner) { const owner = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(skill.owner_id).first(); if (owner) await mail.removed(env, owner, skill.title, note); } } } function oldEnough(user: User): boolean { return user.created_at <= now() - LIMITS.minAccountAgeDays * DAY; } export async function likeSkill(env: Env, user: User, skill: SkillRow): Promise<{ liked: boolean; likes: number }> { if (skill.state !== 'live') throw new HttpError(404, 'That skill is not live.'); if (skill.owner_id === user.id) throw new HttpError(400, 'You cannot like your own skill.'); if (!(await rateLimit(env, `like:${user.id}`, LIMITS.likeActionsPerHour, 3600))) throw new HttpError(429, 'Slow down a little. Try again in an hour.'); const id = newId(); const ts = now(); const res = await env.DB.batch([ env.DB.prepare('INSERT OR IGNORE INTO likes (id, skill_id, user_id, created_at) VALUES (?,?,?,?)').bind(id, skill.id, user.id, ts), env.DB.prepare('UPDATE skills SET likes_count = (SELECT COUNT(*) FROM likes WHERE skill_id = ?1 AND removed_at IS NULL) WHERE id = ?1').bind(skill.id), ]); const inserted = (res[0].meta.changes ?? 0) > 0; // Likes on a pick are counted but pay nobody: Sprout earns no Seeds, and the maker is not a member here. if (inserted && skill.kind !== 'link' && oldEnough(user) && user.email) { const dayStart = ts - (ts % DAY); const today = await env.DB.prepare("SELECT COUNT(*) AS n FROM point_events WHERE skill_id = ? AND kind = 'like' AND created_at >= ?").bind(skill.id, dayStart).first<{ n: number }>(); if ((today?.n ?? 0) < LIMITS.likeSeedsPerSkillPerDay) { await grant(env, { userId: skill.owner_id, kind: 'like', amount: SEEDS.like, sourceType: 'like', sourceId: id, skillId: skill.id }); } } const row = await env.DB.prepare('SELECT likes_count FROM skills WHERE id = ?').bind(skill.id).first<{ likes_count: number }>(); return { liked: true, likes: row?.likes_count ?? 0 }; } export async function unlikeSkill(env: Env, user: User, skill: SkillRow): Promise<{ liked: boolean; likes: number }> { if (!(await rateLimit(env, `like:${user.id}`, LIMITS.likeActionsPerHour, 3600))) throw new HttpError(429, 'Slow down a little. Try again in an hour.'); const like = await env.DB.prepare('SELECT id FROM likes WHERE skill_id = ? AND user_id = ? AND removed_at IS NULL').bind(skill.id, user.id).first<{ id: string }>(); if (like) await removeLike(env, like.id, skill.id, skill.owner_id); const row = await env.DB.prepare('SELECT likes_count FROM skills WHERE id = ?').bind(skill.id).first<{ likes_count: number }>(); return { liked: false, likes: row?.likes_count ?? 0 }; } async function removeLike(env: Env, likeId: string, skillId: string, ownerId: string): Promise { const stmts = [ env.DB.prepare('UPDATE likes SET removed_at = ? WHERE id = ? AND removed_at IS NULL').bind(now(), likeId), env.DB.prepare('UPDATE skills SET likes_count = (SELECT COUNT(*) FROM likes WHERE skill_id = ?1 AND removed_at IS NULL) WHERE id = ?1').bind(skillId), ]; const paid = await env.DB.prepare("SELECT 1 AS x FROM point_events WHERE kind = 'like' AND source_id = ?").bind(likeId).first(); if (paid) stmts.push(...grantStatements(env, { userId: ownerId, kind: 'like_reversal', amount: -SEEDS.like, sourceType: 'like', sourceId: likeId, skillId })); await env.DB.batch(stmts); } export async function addReview(env: Env, user: User, skill: SkillRow, rating: number, body: string): Promise { if (skill.state !== 'live') throw new HttpError(404, 'That skill is not live.'); if (skill.owner_id === user.id) throw new HttpError(400, 'You cannot review your own skill.'); if (skill.kind === 'link') throw new HttpError(400, 'Picks link to their maker and do not take reviews here.'); if (!oldEnough(user)) throw new HttpError(403, `Reviews open up once your account is ${LIMITS.minAccountAgeDays} days old.`); const text = body.trim(); if (text.length < LIMITS.minReviewLength) throw new HttpError(400, `Write at least ${LIMITS.minReviewLength} characters so the review is useful.`); if (text.length > 2000) throw new HttpError(400, 'Keep reviews under 2,000 characters.'); if (!(rating >= 1 && rating <= 5)) throw new HttpError(400, 'Pick a rating from 1 to 5.'); const prior = await env.DB.prepare('SELECT id FROM reviews WHERE skill_id = ? AND user_id = ?').bind(skill.id, user.id).first(); if (prior) throw new HttpError(409, 'You already reviewed this skill.'); if (!(await rateLimit(env, `review:${user.id}`, LIMITS.reviewsPerDay, DAY))) throw new HttpError(429, 'That is a lot of reviews for one day. Try again tomorrow.'); const id = newId(); await env.DB.batch([ env.DB.prepare('INSERT INTO reviews (id, skill_id, user_id, rating, body, created_at) VALUES (?,?,?,?,?,?)').bind(id, skill.id, user.id, Math.round(rating), text, now()), env.DB.prepare('UPDATE skills SET reviews_count = reviews_count + 1, rating_sum = rating_sum + ? WHERE id = ?').bind(Math.round(rating), skill.id), ]); await grant(env, { userId: user.id, kind: 'review', amount: SEEDS.review, sourceType: 'review', sourceId: id, skillId: null }); } export async function removeReview(env: Env, actor: User, reviewId: string): Promise { const r = await env.DB.prepare('SELECT * FROM reviews WHERE id = ? AND removed_at IS NULL').bind(reviewId).first<{ id: string; skill_id: string; user_id: string; rating: number }>(); if (!r) throw new HttpError(404, 'That review was not found.'); if (!actor.is_admin && actor.id !== r.user_id) throw new HttpError(403, 'Not allowed.'); await env.DB.batch([ env.DB.prepare('UPDATE reviews SET removed_at = ? WHERE id = ?').bind(now(), r.id), env.DB.prepare('UPDATE skills SET reviews_count = MAX(0, reviews_count - 1), rating_sum = MAX(0, rating_sum - ?) WHERE id = ?').bind(r.rating, r.skill_id), ...grantStatements(env, { userId: r.user_id, kind: 'review_reversal', amount: -SEEDS.review, sourceType: 'review', sourceId: r.id }), ]); } /** Count one install per installer per skill. Anonymous installers are a salted hash, never a stored IP. */ export async function recordInstall(env: Env, skill: SkillRow, viewer: User | null, ip: string, ua: string): Promise { if (skill.state !== 'live' || skill.kind === 'link') return; const key = viewer ? `u:${viewer.id}` : `a:${(await hmacHex(env.SESSION_SECRET ?? 'skillfarm', `${ip}|${ua}`)).slice(0, 32)}`; if (viewer?.id === skill.owner_id) return; const id = newId(); const ts = now(); const res = await env.DB.batch([ env.DB.prepare('INSERT OR IGNORE INTO installs (id, skill_id, installer_key, user_id, created_at) VALUES (?,?,?,?,?)').bind(id, skill.id, key, viewer?.id ?? null, ts), env.DB.prepare('UPDATE skills SET installs_count = (SELECT COUNT(*) FROM installs WHERE skill_id = ?1) WHERE id = ?1').bind(skill.id), ]); if ((res[0].meta.changes ?? 0) === 0) return; const dayStart = ts - (ts % DAY); const today = await env.DB.prepare("SELECT COUNT(*) AS n FROM point_events WHERE skill_id = ? AND kind = 'install' AND created_at >= ?").bind(skill.id, dayStart).first<{ n: number }>(); if ((today?.n ?? 0) < LIMITS.installSeedsPerSkillPerDay) { await grant(env, { userId: skill.owner_id, kind: 'install', amount: SEEDS.install, sourceType: 'install', sourceId: id, skillId: skill.id }); } } export type CommentRow = { id: string; skill_id: string; user_id: string; body: string; created_at: number; handle: string; display_name: string; avatar_key: string | null; avatar_fallback: string | null; seeds_total: number; is_agent: number; }; export const COMMENT_LIMITS = { min: 2, max: 1000, perDay: 40, perMinute: 4 }; export async function listComments(env: Env, skillId: string, limit = 100): Promise { const res = await env.DB.prepare( `SELECT c.id, c.skill_id, c.user_id, c.body, c.created_at, u.handle, u.display_name, u.avatar_key, u.avatar_fallback, u.seeds_total, u.is_agent FROM comments c JOIN users u ON u.id = c.user_id WHERE c.skill_id = ? AND c.removed_at IS NULL AND u.status = 'active' ORDER BY c.created_at ASC LIMIT ?`, ).bind(skillId, limit).all(); return res.results; } /** A comment is plain text from a signed-in member on a live skill. It shows at once; the author or a moderator can remove it. */ export async function addComment(env: Env, user: User, skill: SkillRow, body: string): Promise { if (user.status !== 'active') throw new HttpError(403, 'This account cannot comment.'); if (skill.state !== 'live') throw new HttpError(404, 'That skill is not live.'); const text = body.replace(/\r\n/g, '\n').replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim(); if (text.length < COMMENT_LIMITS.min) throw new HttpError(400, 'Write a comment first.'); if (text.length > COMMENT_LIMITS.max) throw new HttpError(400, `Keep comments under ${COMMENT_LIMITS.max.toLocaleString('en-US')} characters.`); if (!(await rateLimit(env, `comment-fast:${user.id}`, COMMENT_LIMITS.perMinute, 60))) throw new HttpError(429, 'Slow down a little. Try again in a minute.'); if (!(await rateLimit(env, `comment:${user.id}`, COMMENT_LIMITS.perDay, DAY))) throw new HttpError(429, 'That is a lot of comments for one day. Try again tomorrow.'); const same = await env.DB.prepare('SELECT 1 AS x FROM comments WHERE skill_id = ? AND user_id = ? AND body = ? AND removed_at IS NULL').bind(skill.id, user.id, text).first(); if (same) throw new HttpError(409, 'You already posted that comment.'); const id = newId(); await env.DB.batch([ env.DB.prepare('INSERT INTO comments (id, skill_id, user_id, body, created_at) VALUES (?,?,?,?,?)').bind(id, skill.id, user.id, text, now()), env.DB.prepare('UPDATE skills SET comments_count = (SELECT COUNT(*) FROM comments WHERE skill_id = ?1 AND removed_at IS NULL) WHERE id = ?1').bind(skill.id), ]); return id; } export async function removeComment(env: Env, actor: User, commentId: string): Promise { const row = await env.DB.prepare('SELECT id, skill_id, user_id FROM comments WHERE id = ? AND removed_at IS NULL').bind(commentId).first<{ id: string; skill_id: string; user_id: string }>(); if (!row) throw new HttpError(404, 'That comment was not found.'); if (!actor.is_admin && actor.id !== row.user_id) throw new HttpError(403, 'Not allowed.'); const ts = now(); const stmts = [ env.DB.prepare('UPDATE comments SET removed_at = ?, removed_by = ? WHERE id = ?').bind(ts, actor.id, row.id), env.DB.prepare('UPDATE skills SET comments_count = (SELECT COUNT(*) FROM comments WHERE skill_id = ?1 AND removed_at IS NULL) WHERE id = ?1').bind(row.skill_id), ]; if (actor.id !== row.user_id) stmts.push(env.DB.prepare('INSERT INTO moderation_actions (id, admin_id, action, target_type, target_id, note, created_at) VALUES (?,?,?,?,?,?,?)').bind(newId(), actor.id, 'comment_remove', 'comment', row.id, null, ts)); await env.DB.batch(stmts); } export async function fileReport(env: Env, user: User, targetType: string, targetId: string, reason: string): Promise { if (!['skill', 'review', 'user', 'comment'].includes(targetType)) throw new HttpError(400, 'Unknown report target.'); const text = reason.trim().slice(0, 1000); if (text.length < 10) throw new HttpError(400, 'Say what is wrong in a sentence or two.'); if (!(await rateLimit(env, `report:${user.id}`, LIMITS.reportsPerDay, DAY))) throw new HttpError(429, 'You have filed a lot of reports today.'); await env.DB.prepare('INSERT INTO reports (id, reporter_id, target_type, target_id, reason, created_at) VALUES (?,?,?,?,?,?)').bind(newId(), user.id, targetType, targetId, text, now()).run(); } /** Ban a member: sign them out everywhere, hide their skills, and reverse the Seeds their likes gave. */ export async function banUser(env: Env, admin: User, targetId: string, note: string): Promise { if (!admin.is_admin) throw new HttpError(403, 'Moderators only.'); const target = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(targetId).first(); if (!target) throw new HttpError(404, 'Member not found.'); if (target.is_admin) throw new HttpError(400, 'Admins cannot be banned here.'); const ts = now(); await env.DB.batch([ env.DB.prepare("UPDATE users SET status = 'banned', spotlight_at = NULL WHERE id = ?").bind(targetId), env.DB.prepare('DELETE FROM sessions WHERE user_id = ?').bind(targetId), env.DB.prepare('UPDATE api_tokens SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL').bind(ts, targetId), env.DB.prepare("UPDATE skills SET state = 'hidden', featured_at = NULL WHERE owner_id = ? AND state = 'live'").bind(targetId), env.DB.prepare("UPDATE skill_versions SET status = 'rejected', decided_by = ?, decided_at = ?, decision_note = 'Account banned' WHERE status = 'pending' AND skill_id IN (SELECT id FROM skills WHERE owner_id = ?)").bind(admin.id, ts, targetId), env.DB.prepare('INSERT INTO moderation_actions (id, admin_id, action, target_type, target_id, note, created_at) VALUES (?,?,?,?,?,?,?)').bind(newId(), admin.id, 'ban', 'user', targetId, note || null, ts), ]); const likes = await env.DB.prepare('SELECT l.id, l.skill_id, s.owner_id FROM likes l JOIN skills s ON s.id = l.skill_id WHERE l.user_id = ? AND l.removed_at IS NULL LIMIT 500').bind(targetId).all<{ id: string; skill_id: string; owner_id: string }>(); for (const l of likes.results) await removeLike(env, l.id, l.skill_id, l.owner_id); } export { runAiReview };