Skillfarm / website · skillfarm.ai / src / lib / skills.ts
| 1 | import type { Env, User } from '../env'; |
| 2 | import { brandIn } from './brands'; |
| 3 | import { runAiReview } from './ai'; |
| 4 | import { mail } from './email'; |
| 5 | import { BUNDLE_LIMITS, isSafePath, isTextPath, refreshRepoSignals } from './github'; |
| 6 | import { parseSkillMd } from './markdown'; |
| 7 | import { grant, grantStatements, reverseSkillPoints } from './points'; |
| 8 | import { rateLimit } from './ratelimit'; |
| 9 | import { staticScan, type Finding } from './scan'; |
| 10 | import { LIMITS, SEEDS, tierFor } from './tiers'; |
| 11 | import { DAY, HttpError, hmacHex, likeEscape, newId, now, sha256Hex, slugify } from './util'; |
| 12 | |
| 13 | export const PLATFORMS: { key: string; name: string }[] = [ |
| 14 | { key: 'claude-code', name: 'Terminal agent' }, |
| 15 | { key: 'codex', name: 'Desktop agent' }, |
| 16 | { key: 'gemini-cli', name: 'Command-line agent' }, |
| 17 | ]; |
| 18 | const PLATFORM_KEYS = new Set(PLATFORMS.map((p) => p.key)); |
| 19 | export const platformName = (key: string) => PLATFORMS.find((p) => p.key === key)?.name ?? key; |
| 20 | export const splitPlatforms = (csv: string) => csv.split(',').filter((k) => PLATFORM_KEYS.has(k)); |
| 21 | |
| 22 | export const CATEGORIES: { key: string; name: string }[] = [ |
| 23 | { key: 'design', name: 'Design' }, |
| 24 | { key: 'video', name: 'Video' }, |
| 25 | { key: 'coding', name: 'Coding' }, |
| 26 | { key: 'testing', name: 'Testing' }, |
| 27 | { key: 'writing', name: 'Writing and marketing' }, |
| 28 | { key: 'research', name: 'Data and research' }, |
| 29 | { key: 'devops', name: 'Cloud and DevOps' }, |
| 30 | { key: 'productivity', name: 'Productivity' }, |
| 31 | { key: 'security', name: 'Security' }, |
| 32 | { key: 'business', name: 'Commerce and sales' }, |
| 33 | { key: 'finance', name: 'Finance' }, |
| 34 | { key: 'legal', name: 'Legal' }, |
| 35 | { key: 'science', name: 'Science and health' }, |
| 36 | { key: 'education', name: 'Education' }, |
| 37 | ]; |
| 38 | const CATEGORY_KEYS = new Set(CATEGORIES.map((c) => c.key)); |
| 39 | export const categoryName = (key: string | null) => CATEGORIES.find((c) => c.key === key)?.name ?? null; |
| 40 | export const cleanCategory = (key: unknown) => (typeof key === 'string' && CATEGORY_KEYS.has(key) ? key : null); |
| 41 | |
| 42 | /** The account Sprout's picks belong to. Created by migration 0002. */ |
| 43 | export const SPROUT_ID = 'sprout00000agent'; |
| 44 | |
| 45 | export type SkillRow = { |
| 46 | id: string; owner_id: string; slug: string; title: string; summary: string; platforms: string; github_repo: string | null; github_path: string | null; |
| 47 | github_ref: string | null; replanted_from_skill_id: string | null; verified_owner: number; state: string; current_version_id: string | null; |
| 48 | likes_count: number; installs_count: number; reviews_count: number; rating_sum: number; comments_count: number; featured_at: number | null; off_home: number; source: string; |
| 49 | created_at: number; updated_at: number; published_at: number | null; |
| 50 | /** "link" is a pick: a recommendation that points to the maker's repo. Skillfarm holds no files for it. */ |
| 51 | kind: 'hosted' | 'link'; category: string | null; maker: string | null; maker_url: string | null; source_url: string | null; license: string | null; |
| 52 | install_hint: string | null; pick_note: string | null; |
| 53 | /** A converted copy of a pick that reads the same in every supported agent: the public repo and the folder inside it. */ |
| 54 | multi_repo?: string | null; multi_path?: string | null; |
| 55 | }; |
| 56 | export type SkillCard = SkillRow & { |
| 57 | owner_handle: string; owner_name: string; owner_avatar_key: string | null; owner_avatar_fallback: string | null; owner_seeds: number; owner_is_agent: number; |
| 58 | stars: number | null; repo_fetched_at: number | null; repo_unavailable: number | null; repo_license?: string | null; liked?: number | null; |
| 59 | }; |
| 60 | export type VersionRow = { |
| 61 | id: string; skill_id: string; version: number; r2_prefix: string; sha256: string; size: number; manifest: string; title: string; summary: string; platforms: string; |
| 62 | status: string; scan_status: string; scan_report: string; ai_status: string; ai_recommendation: string | null; ai_summary: string | null; ai_report: string | null; |
| 63 | ai_attempts: number; decided_by: string | null; decided_at: number | null; decision_note: string | null; created_at: number; |
| 64 | }; |
| 65 | export type ManifestEntry = { path: string; size: number; sha256: string }; |
| 66 | |
| 67 | 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`; |
| 68 | 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, |
| 69 | 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`; |
| 70 | |
| 71 | export type ListOpts = { |
| 72 | q?: string; platform?: string; category?: string; kind?: 'hosted' | 'link'; sort?: string; limit?: number; offset?: number; ownerId?: string; viewerId?: string | null; |
| 73 | featured?: boolean; states?: string[]; |
| 74 | /** Leave out skills an admin has kept off the home page. */ |
| 75 | home?: boolean; |
| 76 | /** Only skills shared by the member with this handle. */ |
| 77 | ownerHandle?: string; |
| 78 | /** Words to look for in who made it: a pick's maker, the owner of the GitHub repo, or the member who shared it. */ |
| 79 | maker?: string; |
| 80 | /** Only skills from this GitHub repo, as "owner/name". */ |
| 81 | repo?: string; |
| 82 | /** Only skills under this licence, as an SPDX id such as "MIT". */ |
| 83 | license?: string; |
| 84 | }; |
| 85 | |
| 86 | /** Up to six search words. Every word has to match somewhere, so "legal contract" finds a skill that mentions both. */ |
| 87 | function searchTerms(q: string): string[] { |
| 88 | return [...new Set(q.toLowerCase().slice(0, 80).split(/[\s,]+/).filter((t) => t.length > 0))].slice(0, 6); |
| 89 | } |
| 90 | |
| 91 | export async function listSkills(env: Env, o: ListOpts): Promise<SkillCard[]> { |
| 92 | const where: string[] = []; |
| 93 | const args: unknown[] = []; |
| 94 | 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` : ''; |
| 95 | if (o.viewerId) args.push(o.viewerId); |
| 96 | const states = o.states ?? ['live']; |
| 97 | where.push(`s.state IN (${states.map(() => '?').join(',')})`); |
| 98 | args.push(...states); |
| 99 | if (o.ownerId) { where.push('s.owner_id = ?'); args.push(o.ownerId); } |
| 100 | if (o.featured) where.push('s.featured_at IS NOT NULL'); |
| 101 | if (o.home) where.push('s.off_home = 0'); |
| 102 | if (o.category && CATEGORY_KEYS.has(o.category)) { where.push('s.category = ?'); args.push(o.category); } |
| 103 | if (o.kind === 'hosted' || o.kind === 'link') { where.push('s.kind = ?'); args.push(o.kind); } |
| 104 | if (o.platform && PLATFORM_KEYS.has(o.platform)) { where.push(`(',' || s.platforms || ',') LIKE ?`); args.push(`%,${o.platform},%`); } |
| 105 | if (o.ownerHandle) { where.push('u.handle = ?'); args.push(o.ownerHandle.toLowerCase().slice(0, 40)); } |
| 106 | if (o.repo) { where.push('LOWER(s.github_repo) = ?'); args.push(o.repo.toLowerCase().slice(0, 140)); } |
| 107 | if (o.license) { where.push('LOWER(COALESCE(s.license, r.license_spdx)) = ?'); args.push(o.license.toLowerCase().slice(0, 40)); } |
| 108 | if (o.maker) { |
| 109 | const like = `%${likeEscape(o.maker.slice(0, 60))}%`; |
| 110 | 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 '\\')))`); |
| 111 | args.push(like, `${like}/%`, like, like); |
| 112 | } |
| 113 | for (const term of o.q ? searchTerms(o.q) : []) { |
| 114 | const like = `%${likeEscape(term)}%`; |
| 115 | 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)']; |
| 116 | // A word that names a category ("legal", "marketing", "devops") matches everything filed under it. |
| 117 | const cats = CATEGORIES.filter((c) => c.key.includes(term) || c.name.toLowerCase().includes(term)).map((c) => c.key); |
| 118 | where.push(`(${fields.map((f) => `${f} LIKE ? ESCAPE '\\'`).join(' OR ')}${cats.length ? ` OR s.category IN (${cats.map(() => '?').join(',')})` : ''})`); |
| 119 | args.push(...fields.map(() => like), ...cats); |
| 120 | } |
| 121 | // 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 |
| 122 | // from the same repo: one repo with twenty picks then takes one slot per round instead of filling a page. |
| 123 | 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)`; |
| 124 | let order = 's.published_at DESC, COALESCE(r.stars, 0) DESC'; |
| 125 | const ts = now(); |
| 126 | if (o.featured) order = 's.featured_at DESC'; |
| 127 | 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`; |
| 128 | else if (o.sort === 'trending') { |
| 129 | // 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. |
| 130 | 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 |
| 131 | + (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) |
| 132 | / ((${ts} - COALESCE(s.published_at, s.created_at)) / 86400.0 + 2.0) DESC, ${repoRank} ASC, COALESCE(r.stars, 0) DESC, s.published_at DESC`; |
| 133 | } else if (o.sort === 'updated') order = 's.updated_at DESC'; |
| 134 | args.push(Math.min(o.limit ?? 24, 400), o.offset ?? 0); |
| 135 | const res = await env.DB.prepare(`SELECT ${CARD_COLS}${liked} ${CARD_FROM} WHERE ${where.join(' AND ')} ORDER BY ${order} LIMIT ? OFFSET ?`).bind(...args).all<SkillCard>(); |
| 136 | return res.results; |
| 137 | } |
| 138 | |
| 139 | export async function getSkillCard(env: Env, handle: string, slug: string, viewerId?: string | null): Promise<SkillCard | null> { |
| 140 | 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` : ''; |
| 141 | const args: unknown[] = viewerId ? [viewerId, handle, slug] : [handle, slug]; |
| 142 | return env.DB.prepare(`SELECT ${CARD_COLS}${liked} ${CARD_FROM} WHERE u.handle = ? AND s.slug = ?`).bind(...args).first<SkillCard>(); |
| 143 | } |
| 144 | |
| 145 | export async function getSkillCardById(env: Env, id: string): Promise<SkillCard | null> { |
| 146 | return env.DB.prepare(`SELECT ${CARD_COLS} ${CARD_FROM} WHERE s.id = ?`).bind(id).first<SkillCard>(); |
| 147 | } |
| 148 | |
| 149 | /** A spread of Sprout's picks for the home page: one pick per repo, then the most-starred pick in each category first. */ |
| 150 | export async function sproutPicks(env: Env, limit: number, viewerId?: string | null): Promise<SkillCard[]> { |
| 151 | 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` : ''; |
| 152 | const args: unknown[] = viewerId ? [viewerId, limit] : [limit]; |
| 153 | const res = await env.DB.prepare( |
| 154 | `SELECT * FROM ( |
| 155 | SELECT x.*, ROW_NUMBER() OVER (PARTITION BY x.category ORDER BY COALESCE(x.stars, 0) DESC, x.published_at DESC) AS cat_rank |
| 156 | FROM ( |
| 157 | SELECT ${CARD_COLS}${liked}, ROW_NUMBER() OVER (PARTITION BY s.github_repo ORDER BY s.published_at DESC) AS repo_rank |
| 158 | ${CARD_FROM} WHERE s.state = 'live' AND s.kind = 'link' AND s.off_home = 0 |
| 159 | ) x WHERE x.repo_rank = 1 |
| 160 | ) ORDER BY cat_rank ASC, COALESCE(stars, 0) DESC LIMIT ?`, |
| 161 | ).bind(...args).all<SkillCard>(); |
| 162 | return res.results; |
| 163 | } |
| 164 | |
| 165 | /** How many live skills each category holds, for the filter chips. */ |
| 166 | export async function categoryCounts(env: Env): Promise<Record<string, number>> { |
| 167 | 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 }>(); |
| 168 | return Object.fromEntries(res.results.map((r) => [r.category, r.n])); |
| 169 | } |
| 170 | |
| 171 | export function canView(skill: SkillRow, viewer: User | null): boolean { |
| 172 | if (skill.state === 'live') return true; |
| 173 | return !!viewer && (viewer.id === skill.owner_id || !!viewer.is_admin); |
| 174 | } |
| 175 | |
| 176 | export async function getVersion(env: Env, id: string | null): Promise<VersionRow | null> { |
| 177 | if (!id) return null; |
| 178 | return env.DB.prepare('SELECT * FROM skill_versions WHERE id = ?').bind(id).first<VersionRow>(); |
| 179 | } |
| 180 | |
| 181 | export async function latestVersion(env: Env, skillId: string): Promise<VersionRow | null> { |
| 182 | return env.DB.prepare('SELECT * FROM skill_versions WHERE skill_id = ? ORDER BY version DESC LIMIT 1').bind(skillId).first<VersionRow>(); |
| 183 | } |
| 184 | |
| 185 | export async function readVersionFile(env: Env, v: VersionRow, path: string): Promise<Uint8Array | null> { |
| 186 | const manifest = JSON.parse(v.manifest) as ManifestEntry[]; |
| 187 | if (!manifest.some((m) => m.path === path)) return null; |
| 188 | const obj = await env.SKILLS.get(v.r2_prefix + path); |
| 189 | return obj ? new Uint8Array(await obj.arrayBuffer()) : null; |
| 190 | } |
| 191 | |
| 192 | export async function readVersionFiles(env: Env, v: VersionRow): Promise<{ path: string; data: Uint8Array }[]> { |
| 193 | const manifest = JSON.parse(v.manifest) as ManifestEntry[]; |
| 194 | const out: { path: string; data: Uint8Array }[] = []; |
| 195 | for (const m of manifest) { |
| 196 | const obj = await env.SKILLS.get(v.r2_prefix + m.path); |
| 197 | if (obj) out.push({ path: m.path, data: new Uint8Array(await obj.arrayBuffer()) }); |
| 198 | } |
| 199 | return out; |
| 200 | } |
| 201 | |
| 202 | export type SubmitInput = { |
| 203 | user: User; |
| 204 | source: 'web' | 'mcp'; |
| 205 | files: { path: string; data: Uint8Array }[]; |
| 206 | title?: string; |
| 207 | summary?: string; |
| 208 | platforms?: string[]; |
| 209 | category?: string | null; |
| 210 | github?: { repo: string; path: string; ref: string; ownerId: string }; |
| 211 | replantedFrom?: SkillRow | null; |
| 212 | existing?: SkillRow | null; |
| 213 | /** 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. */ |
| 214 | partOfRepoShare?: boolean; |
| 215 | }; |
| 216 | |
| 217 | type Waiter = { waitUntil(p: Promise<unknown>): void }; |
| 218 | |
| 219 | function isBinary(data: Uint8Array): boolean { |
| 220 | const n = Math.min(data.length, 8000); |
| 221 | for (let i = 0; i < n; i++) if (data[i] === 0) return true; |
| 222 | return false; |
| 223 | } |
| 224 | |
| 225 | /** The file list of a bundle and the hash that identifies its exact contents. */ |
| 226 | export async function bundleManifest(files: { path: string; data: Uint8Array }[]): Promise<{ manifest: ManifestEntry[]; sha: string }> { |
| 227 | const manifest: ManifestEntry[] = []; |
| 228 | for (const f of files) manifest.push({ path: f.path, size: f.data.length, sha256: await sha256Hex(f.data) }); |
| 229 | manifest.sort((a, b) => (a.path === 'SKILL.md' ? -1 : b.path === 'SKILL.md' ? 1 : a.path.localeCompare(b.path))); |
| 230 | return { manifest, sha: await sha256Hex(manifest.map((m) => `${m.path}\0${m.sha256}`).join('\n')) }; |
| 231 | } |
| 232 | |
| 233 | /** Validate, scan and store a submission. It always lands in the review queue; nothing goes public here. */ |
| 234 | export async function submitSkill(env: Env, ctx: Waiter, input: SubmitInput): Promise<{ skill: SkillRow; version: VersionRow; ownerHandle: string }> { |
| 235 | const { user } = input; |
| 236 | if (user.status !== 'active') throw new HttpError(403, 'This account cannot share skills.'); |
| 237 | const files = input.files; |
| 238 | if (!files.length || files.length > BUNDLE_LIMITS.files) throw new HttpError(400, `A skill can hold up to ${BUNDLE_LIMITS.files} files.`); |
| 239 | const seen = new Set<string>(); |
| 240 | let total = 0; |
| 241 | for (const f of files) { |
| 242 | if (!isSafePath(f.path) || !isTextPath(f.path)) throw new HttpError(400, `"${f.path}" is not an allowed file. Skills hold text files only.`); |
| 243 | if (seen.has(f.path.toLowerCase())) throw new HttpError(400, `"${f.path}" appears twice.`); |
| 244 | seen.add(f.path.toLowerCase()); |
| 245 | if (f.data.length > BUNDLE_LIMITS.fileBytes) throw new HttpError(400, `"${f.path}" is larger than ${BUNDLE_LIMITS.fileBytes / 1000} KB.`); |
| 246 | if (isBinary(f.data)) throw new HttpError(400, `"${f.path}" looks like a binary file. Skills hold text files only.`); |
| 247 | total += f.data.length; |
| 248 | } |
| 249 | 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.`); |
| 250 | const entry = files.find((f) => f.path === 'SKILL.md'); |
| 251 | if (!entry) throw new HttpError(400, 'A skill needs a SKILL.md file.'); |
| 252 | const dec = new TextDecoder(); |
| 253 | const skillMd = dec.decode(entry.data); |
| 254 | const { meta, body } = parseSkillMd(skillMd); |
| 255 | if (body.trim().length < 40) throw new HttpError(400, 'That SKILL.md is nearly empty. Add the instructions the agent should follow.'); |
| 256 | |
| 257 | const existing = input.existing ?? null; |
| 258 | // An update keeps the title the skill already has unless a new one is given. |
| 259 | const title = (input.title || existing?.title || titleFromName(meta.name ?? '')).trim().replace(/\s+/g, ' ').slice(0, 80); |
| 260 | 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.'); |
| 261 | const summary = clip(input.summary || meta.description || existing?.summary || '', 280); |
| 262 | 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.'); |
| 263 | const platforms = [...new Set((input.platforms ?? (existing ? splitPlatforms(existing.platforms) : [])).filter((p) => PLATFORM_KEYS.has(p)))]; |
| 264 | if (!platforms.length) platforms.push(...PLATFORMS.map((p) => p.key)); |
| 265 | |
| 266 | const category = cleanCategory(input.category) ?? existing?.category ?? null; |
| 267 | |
| 268 | const ts = now(); |
| 269 | if (existing) { |
| 270 | if (existing.kind === 'link') throw new HttpError(400, 'A pick has no versions. It links to its maker.'); |
| 271 | if (existing.owner_id !== user.id) throw new HttpError(403, 'Only the owner can update a skill.'); |
| 272 | if (existing.state === 'removed') throw new HttpError(400, 'This skill was removed.'); |
| 273 | 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.'); |
| 274 | } else if (!user.is_admin && !input.partOfRepoShare) { |
| 275 | const limit = tierFor(user.seeds_total).sharesPerWeek; |
| 276 | 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 }>(); |
| 277 | 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.`); |
| 278 | } |
| 279 | |
| 280 | let slug = existing?.slug ?? slugify(meta.name || title); |
| 281 | if (slug.length < 2) throw new HttpError(400, 'That name does not make a usable link. Use letters or numbers.'); |
| 282 | if (!existing) { |
| 283 | 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 }>(); |
| 284 | if (clash && clash.state !== 'removed') throw new HttpError(409, `You already have a skill called "${slug}". Open it and submit a new version instead.`); |
| 285 | if (clash) slug = `${slug}-${newId(4)}`; |
| 286 | } |
| 287 | |
| 288 | // Scan. |
| 289 | const scan = staticScan(files.filter((f) => !isBinary(f.data)).map((f) => ({ path: f.path, text: dec.decode(f.data) }))); |
| 290 | const { manifest, sha: bundleSha } = await bundleManifest(files); |
| 291 | const findings: Finding[] = scan.findings; |
| 292 | const twin = await env.DB.prepare( |
| 293 | `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 |
| 294 | WHERE v.sha256 = ? AND s.owner_id != ? AND s.state = 'live' LIMIT 1`, |
| 295 | ).bind(bundleSha, user.id).first<{ handle: string; slug: string }>(); |
| 296 | if (twin && !(input.replantedFrom)) { |
| 297 | findings.unshift({ severity: 'medium', rule: `Identical to the live skill ${twin.handle}/${twin.slug} by another member`, file: 'SKILL.md', line: 1, excerpt: '' }); |
| 298 | } |
| 299 | const scanStatus = findings.some((f) => f.severity === 'high') ? 'high' : findings.length ? 'flagged' : 'clean'; |
| 300 | |
| 301 | const skillId = existing?.id ?? newId(); |
| 302 | const versionId = newId(); |
| 303 | const prefix = `skills/${skillId}/${versionId}/`; |
| 304 | for (const f of files) await env.SKILLS.put(prefix + f.path, f.data, { httpMetadata: { contentType: 'text/plain; charset=utf-8' } }); |
| 305 | |
| 306 | let verified = 0; |
| 307 | if (input.github) { |
| 308 | 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 }>(); |
| 309 | verified = gh && gh.provider_user_id === input.github.ownerId ? 1 : 0; |
| 310 | } |
| 311 | 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; |
| 312 | const versionNo = (lastVersion?.v ?? 0) + 1; |
| 313 | const aiStatus = env.ANTHROPIC_API_KEY ? 'queued' : 'unavailable'; |
| 314 | const stmts: D1PreparedStatement[] = []; |
| 315 | if (!existing) { |
| 316 | stmts.push( |
| 317 | env.DB.prepare( |
| 318 | `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) |
| 319 | VALUES (?,?,?,?,?,?,?,?,?,?,?,?,'pending',?,?,?)`, |
| 320 | ).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), |
| 321 | ); |
| 322 | } else { |
| 323 | // A waiting version is replaced by the newer one; the live version stays up until a reviewer approves. |
| 324 | stmts.push(env.DB.prepare("UPDATE skill_versions SET status = 'superseded' WHERE skill_id = ? AND status = 'pending'").bind(skillId)); |
| 325 | if (existing.state === 'rejected') stmts.push(env.DB.prepare("UPDATE skills SET state = 'pending', updated_at = ? WHERE id = ?").bind(ts, skillId)); |
| 326 | if (input.github) stmts.push(env.DB.prepare('UPDATE skills SET github_ref = ? WHERE id = ?').bind(input.github.ref, skillId)); |
| 327 | if (category !== existing.category) stmts.push(env.DB.prepare('UPDATE skills SET category = ? WHERE id = ?').bind(category, skillId)); |
| 328 | } |
| 329 | stmts.push( |
| 330 | env.DB.prepare( |
| 331 | `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) |
| 332 | VALUES (?,?,?,?,?,?,?,?,?,?,'pending',?,?,?,?)`, |
| 333 | ).bind(versionId, skillId, versionNo, prefix, bundleSha, total, JSON.stringify(manifest), title, summary, platforms.join(','), scanStatus, JSON.stringify(findings), aiStatus, ts), |
| 334 | ); |
| 335 | await env.DB.batch(stmts); |
| 336 | |
| 337 | const skill = (await env.DB.prepare('SELECT * FROM skills WHERE id = ?').bind(skillId).first<SkillRow>())!; |
| 338 | const version = (await getVersion(env, versionId))!; |
| 339 | const url = `${env.SITE_URL}/skills/${user.handle}/${skill.slug}`; |
| 340 | ctx.waitUntil( |
| 341 | (async () => { |
| 342 | if (!input.partOfRepoShare) await mail.received(env, user, title, url); |
| 343 | 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.'); |
| 344 | })().catch((e) => console.error('submit notices failed', e)), |
| 345 | ); |
| 346 | return { skill, version, ownerHandle: user.handle }; |
| 347 | } |
| 348 | |
| 349 | const SHOUT = new Set(['mcp', 'api', 'cli', 'pdf', 'ui', 'ux', 'ci', 'sql', 'css', 'html', 'ai', 'seo', 'pr', 'json', 'csv', 'sdk', 'url', 'ssh']); |
| 350 | |
| 351 | /** "agent-council" reads better as "Agent Council" on a card. A name that already has capitals or spaces is left alone. */ |
| 352 | export function titleFromName(name: string): string { |
| 353 | const s = name.trim().replace(/\s+/g, ' '); |
| 354 | if (!/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/.test(s)) return s; |
| 355 | return s.split(/[-_]/).map((w) => (SHOUT.has(w) ? w.toUpperCase() : w[0].toUpperCase() + w.slice(1))).join(' '); |
| 356 | } |
| 357 | |
| 358 | /** Shorten a long description at the end of a sentence, or failing that a word. Never mid-word. */ |
| 359 | export function clip(text: string, max: number): string { |
| 360 | const s = text.trim().replace(/\s+/g, ' '); |
| 361 | if (s.length <= max) return s; |
| 362 | const head = s.slice(0, max); |
| 363 | const stop = Math.max(head.lastIndexOf('. '), head.lastIndexOf('! '), head.lastIndexOf('? ')); |
| 364 | if (stop >= 60) return head.slice(0, stop + 1); |
| 365 | const cut = head.lastIndexOf(' '); |
| 366 | return (cut > 0 ? head.slice(0, cut) : head.slice(0, max - 1)).replace(/[,;:.\s]+$/, '') + '…'; |
| 367 | } |
| 368 | |
| 369 | export type PickInput = { |
| 370 | id?: string; title: string; summary: string; category: string; maker: string; makerUrl: string; sourceUrl: string; repo: string; path?: string; license?: string; |
| 371 | installHint?: string; note?: string; platforms?: string[]; |
| 372 | }; |
| 373 | |
| 374 | /** |
| 375 | * Add or edit one of Sprout's picks. Only a moderator can do this, and doing it is the moderator's decision to publish: |
| 376 | * a pick goes live at once because there is no submitted file to review, only a link the moderator has chosen. |
| 377 | */ |
| 378 | export async function savePick(env: Env, admin: User, input: PickInput): Promise<SkillRow> { |
| 379 | if (!admin.is_admin) throw new HttpError(403, 'Moderators only.'); |
| 380 | const one = (v: string | undefined, max: number) => (v ?? '').trim().replace(/\s+/g, ' ').slice(0, max); |
| 381 | const title = one(input.title, 80); |
| 382 | const summary = one(input.summary, 280); |
| 383 | const maker = one(input.maker, 80); |
| 384 | const category = cleanCategory(input.category); |
| 385 | const repo = one(input.repo, 140); |
| 386 | const https = (v: string | undefined) => { |
| 387 | const t = (v ?? '').trim(); |
| 388 | if (!t) return null; |
| 389 | let u: URL; |
| 390 | try { u = new URL(t); } catch { throw new HttpError(400, `"${t.slice(0, 80)}" is not a web address.`); } |
| 391 | if (u.protocol !== 'https:') throw new HttpError(400, 'Links must start with https://.'); |
| 392 | return u.toString(); |
| 393 | }; |
| 394 | if (title.length < 2) throw new HttpError(400, 'Give the pick a title.'); |
| 395 | if (summary.length < 12) throw new HttpError(400, 'Say what the skill does in a sentence.'); |
| 396 | if (!maker) throw new HttpError(400, 'Say what kind of maker made it, such as "a cloud company" or "an independent developer".'); |
| 397 | if (!category) throw new HttpError(400, 'Pick a category.'); |
| 398 | if (!/^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/.test(repo)) throw new HttpError(400, 'Give the repo as owner/name.'); |
| 399 | const path = (input.path ?? '').trim().replace(/^\/+|\/+$/g, '').slice(0, 200) || null; |
| 400 | const sourceUrl = https(input.sourceUrl) ?? `https://github.com/${repo}${path ? `/tree/HEAD/${path}` : ''}`; |
| 401 | const makerUrl = https(input.makerUrl) ?? `https://github.com/${repo.split('/')[0]}`; |
| 402 | const platforms = [...new Set((input.platforms ?? []).filter((p) => PLATFORM_KEYS.has(p)))]; |
| 403 | if (!platforms.length) platforms.push(...PLATFORMS.map((p) => p.key)); |
| 404 | const license = one(input.license, 60) || null; |
| 405 | const hint = (input.installHint ?? '').trim().slice(0, 400) || null; |
| 406 | const note = one(input.note, 600) || null; |
| 407 | const brand = brandIn(title, summary, maker, note); |
| 408 | if (brand) throw new HttpError(400, `Use plain words on cards: "${brand}" is a company, product or person name. Describe it instead, such as "a cloud company".`); |
| 409 | const sprout = await env.DB.prepare('SELECT id FROM users WHERE id = ? AND is_agent = 1').bind(SPROUT_ID).first(); |
| 410 | if (!sprout) throw new HttpError(503, 'The Sprout account is missing. Apply the database migrations.'); |
| 411 | const ts = now(); |
| 412 | let id = input.id ?? ''; |
| 413 | if (id) { |
| 414 | const cur = await env.DB.prepare('SELECT * FROM skills WHERE id = ?').bind(id).first<SkillRow>(); |
| 415 | if (!cur || cur.kind !== 'link') throw new HttpError(404, 'That pick was not found.'); |
| 416 | await env.DB.batch([ |
| 417 | env.DB.prepare( |
| 418 | `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 = ?`, |
| 419 | ).bind(title, summary, platforms.join(','), category, maker, makerUrl, sourceUrl, repo, path, license, hint, note, ts, id), |
| 420 | 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), |
| 421 | ]); |
| 422 | } else { |
| 423 | id = newId(); |
| 424 | let slug = slugify(title); |
| 425 | if (slug.length < 2) throw new HttpError(400, 'That title does not make a usable link. Use letters or numbers.'); |
| 426 | const clash = await env.DB.prepare('SELECT id FROM skills WHERE owner_id = ? AND slug = ?').bind(SPROUT_ID, slug).first(); |
| 427 | if (clash) slug = `${slug}-${newId(4)}`; |
| 428 | await env.DB.batch([ |
| 429 | env.DB.prepare( |
| 430 | `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) |
| 431 | VALUES (?,?,?,?,?,?,?,'link',?,?,?,?,?,?,?,?,'live','pick',?,?,?)`, |
| 432 | ).bind(id, SPROUT_ID, slug, title, summary, platforms.join(','), category, maker, makerUrl, sourceUrl, repo, path, license, hint, note, ts, ts, ts), |
| 433 | 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), |
| 434 | ]); |
| 435 | } |
| 436 | await refreshRepoSignals(env, repo).catch(() => {}); |
| 437 | return (await env.DB.prepare('SELECT * FROM skills WHERE id = ?').bind(id).first<SkillRow>())!; |
| 438 | } |
| 439 | |
| 440 | /** A moderator's decision on a waiting version. Apart from a moderator's own picks (savePick), this is the only path to "live". */ |
| 441 | export async function decideVersion( |
| 442 | env: Env, admin: User, versionId: string, decision: 'approve' | 'reject', note: string, |
| 443 | opts: { category?: string | null; silent?: boolean } = {}, |
| 444 | ): Promise<SkillRow> { |
| 445 | if (!admin.is_admin) throw new HttpError(403, 'Moderators only.'); |
| 446 | const v = await getVersion(env, versionId); |
| 447 | if (!v) throw new HttpError(404, 'That submission was not found.'); |
| 448 | if (v.status !== 'pending') throw new HttpError(409, 'That submission was already decided.'); |
| 449 | const skill = (await env.DB.prepare('SELECT * FROM skills WHERE id = ?').bind(v.skill_id).first<SkillRow>())!; |
| 450 | const owner = (await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(skill.owner_id).first<User>())!; |
| 451 | const ts = now(); |
| 452 | const url = `${env.SITE_URL}/skills/${owner.handle}/${skill.slug}`; |
| 453 | 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); |
| 454 | |
| 455 | if (decision === 'reject') { |
| 456 | const stmts = [ |
| 457 | 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), |
| 458 | log, |
| 459 | ]; |
| 460 | if (!skill.current_version_id) stmts.push(env.DB.prepare("UPDATE skills SET state = 'rejected', updated_at = ? WHERE id = ?").bind(ts, skill.id)); |
| 461 | await env.DB.batch(stmts); |
| 462 | if (!opts.silent) await mail.denied(env, owner, v.title, url, note); |
| 463 | return { ...skill, state: skill.current_version_id ? skill.state : 'rejected' }; |
| 464 | } |
| 465 | |
| 466 | if (owner.status !== 'active') throw new HttpError(409, 'The owner of this skill is banned.'); |
| 467 | const first = !skill.published_at; |
| 468 | await env.DB.batch([ |
| 469 | env.DB.prepare("UPDATE skill_versions SET status = 'superseded' WHERE skill_id = ? AND status = 'approved'").bind(skill.id), |
| 470 | 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), |
| 471 | env.DB.prepare( |
| 472 | `UPDATE skills SET state = CASE WHEN state IN ('pending','rejected') THEN 'live' ELSE state END, current_version_id = ?, title = ?, summary = ?, platforms = ?, |
| 473 | category = COALESCE(?, category), updated_at = ?, published_at = COALESCE(published_at, ?) WHERE id = ?`, |
| 474 | ).bind(v.id, v.title, v.summary, v.platforms, cleanCategory(opts.category), ts, ts, skill.id), |
| 475 | log, |
| 476 | ]); |
| 477 | if (first) { |
| 478 | // Share Seeds are granted once per skill, only after approval. New versions earn nothing. |
| 479 | await grant(env, { userId: owner.id, kind: 'share', amount: SEEDS.share, sourceType: 'skill', sourceId: skill.id, skillId: skill.id }); |
| 480 | if (skill.replanted_from_skill_id) { |
| 481 | 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 }>(); |
| 482 | if (parent && parent.owner_id !== owner.id) { |
| 483 | await grant(env, { userId: parent.owner_id, kind: 'replant', amount: SEEDS.replant, sourceType: 'skill', sourceId: skill.id, skillId: skill.id }); |
| 484 | } |
| 485 | } |
| 486 | } |
| 487 | if (skill.github_repo) await refreshRepoSignals(env, skill.github_repo).catch(() => {}); |
| 488 | if (!opts.silent) await mail.approved(env, owner, v.title, url, first ? SEEDS.share : 0); |
| 489 | return { ...skill, state: 'live', current_version_id: v.id }; |
| 490 | } |
| 491 | |
| 492 | export async function setSkillState(env: Env, actor: User, skill: SkillRow, state: 'removed' | 'hidden' | 'live', note = ''): Promise<void> { |
| 493 | const isOwner = actor.id === skill.owner_id; |
| 494 | if (!actor.is_admin && !(isOwner && state === 'removed')) throw new HttpError(403, 'Not allowed.'); |
| 495 | if (state === 'live' && !skill.current_version_id && skill.kind !== 'link') throw new HttpError(409, 'This skill has no approved version.'); |
| 496 | const ts = now(); |
| 497 | await env.DB.batch([ |
| 498 | 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), |
| 499 | env.DB.prepare("UPDATE skill_versions SET status = 'superseded' WHERE skill_id = ? AND status = 'pending' AND ? = 'removed'").bind(skill.id, state), |
| 500 | 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), |
| 501 | ]); |
| 502 | if (state === 'removed') { |
| 503 | await reverseSkillPoints(env, skill.id); |
| 504 | if (!isOwner) { |
| 505 | const owner = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(skill.owner_id).first<User>(); |
| 506 | if (owner) await mail.removed(env, owner, skill.title, note); |
| 507 | } |
| 508 | } |
| 509 | } |
| 510 | |
| 511 | function oldEnough(user: User): boolean { |
| 512 | return user.created_at <= now() - LIMITS.minAccountAgeDays * DAY; |
| 513 | } |
| 514 | |
| 515 | export async function likeSkill(env: Env, user: User, skill: SkillRow): Promise<{ liked: boolean; likes: number }> { |
| 516 | if (skill.state !== 'live') throw new HttpError(404, 'That skill is not live.'); |
| 517 | if (skill.owner_id === user.id) throw new HttpError(400, 'You cannot like your own skill.'); |
| 518 | if (!(await rateLimit(env, `like:${user.id}`, LIMITS.likeActionsPerHour, 3600))) throw new HttpError(429, 'Slow down a little. Try again in an hour.'); |
| 519 | const id = newId(); |
| 520 | const ts = now(); |
| 521 | const res = await env.DB.batch([ |
| 522 | env.DB.prepare('INSERT OR IGNORE INTO likes (id, skill_id, user_id, created_at) VALUES (?,?,?,?)').bind(id, skill.id, user.id, ts), |
| 523 | 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), |
| 524 | ]); |
| 525 | const inserted = (res[0].meta.changes ?? 0) > 0; |
| 526 | // Likes on a pick are counted but pay nobody: Sprout earns no Seeds, and the maker is not a member here. |
| 527 | if (inserted && skill.kind !== 'link' && oldEnough(user) && user.email) { |
| 528 | const dayStart = ts - (ts % DAY); |
| 529 | 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 }>(); |
| 530 | if ((today?.n ?? 0) < LIMITS.likeSeedsPerSkillPerDay) { |
| 531 | await grant(env, { userId: skill.owner_id, kind: 'like', amount: SEEDS.like, sourceType: 'like', sourceId: id, skillId: skill.id }); |
| 532 | } |
| 533 | } |
| 534 | const row = await env.DB.prepare('SELECT likes_count FROM skills WHERE id = ?').bind(skill.id).first<{ likes_count: number }>(); |
| 535 | return { liked: true, likes: row?.likes_count ?? 0 }; |
| 536 | } |
| 537 | |
| 538 | export async function unlikeSkill(env: Env, user: User, skill: SkillRow): Promise<{ liked: boolean; likes: number }> { |
| 539 | if (!(await rateLimit(env, `like:${user.id}`, LIMITS.likeActionsPerHour, 3600))) throw new HttpError(429, 'Slow down a little. Try again in an hour.'); |
| 540 | 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 }>(); |
| 541 | if (like) await removeLike(env, like.id, skill.id, skill.owner_id); |
| 542 | const row = await env.DB.prepare('SELECT likes_count FROM skills WHERE id = ?').bind(skill.id).first<{ likes_count: number }>(); |
| 543 | return { liked: false, likes: row?.likes_count ?? 0 }; |
| 544 | } |
| 545 | |
| 546 | async function removeLike(env: Env, likeId: string, skillId: string, ownerId: string): Promise<void> { |
| 547 | const stmts = [ |
| 548 | env.DB.prepare('UPDATE likes SET removed_at = ? WHERE id = ? AND removed_at IS NULL').bind(now(), likeId), |
| 549 | 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), |
| 550 | ]; |
| 551 | const paid = await env.DB.prepare("SELECT 1 AS x FROM point_events WHERE kind = 'like' AND source_id = ?").bind(likeId).first(); |
| 552 | if (paid) stmts.push(...grantStatements(env, { userId: ownerId, kind: 'like_reversal', amount: -SEEDS.like, sourceType: 'like', sourceId: likeId, skillId })); |
| 553 | await env.DB.batch(stmts); |
| 554 | } |
| 555 | |
| 556 | export async function addReview(env: Env, user: User, skill: SkillRow, rating: number, body: string): Promise<void> { |
| 557 | if (skill.state !== 'live') throw new HttpError(404, 'That skill is not live.'); |
| 558 | if (skill.owner_id === user.id) throw new HttpError(400, 'You cannot review your own skill.'); |
| 559 | if (skill.kind === 'link') throw new HttpError(400, 'Picks link to their maker and do not take reviews here.'); |
| 560 | if (!oldEnough(user)) throw new HttpError(403, `Reviews open up once your account is ${LIMITS.minAccountAgeDays} days old.`); |
| 561 | const text = body.trim(); |
| 562 | if (text.length < LIMITS.minReviewLength) throw new HttpError(400, `Write at least ${LIMITS.minReviewLength} characters so the review is useful.`); |
| 563 | if (text.length > 2000) throw new HttpError(400, 'Keep reviews under 2,000 characters.'); |
| 564 | if (!(rating >= 1 && rating <= 5)) throw new HttpError(400, 'Pick a rating from 1 to 5.'); |
| 565 | const prior = await env.DB.prepare('SELECT id FROM reviews WHERE skill_id = ? AND user_id = ?').bind(skill.id, user.id).first(); |
| 566 | if (prior) throw new HttpError(409, 'You already reviewed this skill.'); |
| 567 | 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.'); |
| 568 | const id = newId(); |
| 569 | await env.DB.batch([ |
| 570 | 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()), |
| 571 | env.DB.prepare('UPDATE skills SET reviews_count = reviews_count + 1, rating_sum = rating_sum + ? WHERE id = ?').bind(Math.round(rating), skill.id), |
| 572 | ]); |
| 573 | await grant(env, { userId: user.id, kind: 'review', amount: SEEDS.review, sourceType: 'review', sourceId: id, skillId: null }); |
| 574 | } |
| 575 | |
| 576 | export async function removeReview(env: Env, actor: User, reviewId: string): Promise<void> { |
| 577 | 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 }>(); |
| 578 | if (!r) throw new HttpError(404, 'That review was not found.'); |
| 579 | if (!actor.is_admin && actor.id !== r.user_id) throw new HttpError(403, 'Not allowed.'); |
| 580 | await env.DB.batch([ |
| 581 | env.DB.prepare('UPDATE reviews SET removed_at = ? WHERE id = ?').bind(now(), r.id), |
| 582 | 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), |
| 583 | ...grantStatements(env, { userId: r.user_id, kind: 'review_reversal', amount: -SEEDS.review, sourceType: 'review', sourceId: r.id }), |
| 584 | ]); |
| 585 | } |
| 586 | |
| 587 | /** Count one install per installer per skill. Anonymous installers are a salted hash, never a stored IP. */ |
| 588 | export async function recordInstall(env: Env, skill: SkillRow, viewer: User | null, ip: string, ua: string): Promise<void> { |
| 589 | if (skill.state !== 'live' || skill.kind === 'link') return; |
| 590 | const key = viewer ? `u:${viewer.id}` : `a:${(await hmacHex(env.SESSION_SECRET ?? 'skillfarm', `${ip}|${ua}`)).slice(0, 32)}`; |
| 591 | if (viewer?.id === skill.owner_id) return; |
| 592 | const id = newId(); |
| 593 | const ts = now(); |
| 594 | const res = await env.DB.batch([ |
| 595 | 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), |
| 596 | env.DB.prepare('UPDATE skills SET installs_count = (SELECT COUNT(*) FROM installs WHERE skill_id = ?1) WHERE id = ?1').bind(skill.id), |
| 597 | ]); |
| 598 | if ((res[0].meta.changes ?? 0) === 0) return; |
| 599 | const dayStart = ts - (ts % DAY); |
| 600 | 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 }>(); |
| 601 | if ((today?.n ?? 0) < LIMITS.installSeedsPerSkillPerDay) { |
| 602 | await grant(env, { userId: skill.owner_id, kind: 'install', amount: SEEDS.install, sourceType: 'install', sourceId: id, skillId: skill.id }); |
| 603 | } |
| 604 | } |
| 605 | |
| 606 | export type CommentRow = { |
| 607 | id: string; skill_id: string; user_id: string; body: string; created_at: number; |
| 608 | handle: string; display_name: string; avatar_key: string | null; avatar_fallback: string | null; seeds_total: number; is_agent: number; |
| 609 | }; |
| 610 | |
| 611 | export const COMMENT_LIMITS = { min: 2, max: 1000, perDay: 40, perMinute: 4 }; |
| 612 | |
| 613 | export async function listComments(env: Env, skillId: string, limit = 100): Promise<CommentRow[]> { |
| 614 | const res = await env.DB.prepare( |
| 615 | `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 |
| 616 | 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 ?`, |
| 617 | ).bind(skillId, limit).all<CommentRow>(); |
| 618 | return res.results; |
| 619 | } |
| 620 | |
| 621 | /** 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. */ |
| 622 | export async function addComment(env: Env, user: User, skill: SkillRow, body: string): Promise<string> { |
| 623 | if (user.status !== 'active') throw new HttpError(403, 'This account cannot comment.'); |
| 624 | if (skill.state !== 'live') throw new HttpError(404, 'That skill is not live.'); |
| 625 | const text = body.replace(/\r\n/g, '\n').replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim(); |
| 626 | if (text.length < COMMENT_LIMITS.min) throw new HttpError(400, 'Write a comment first.'); |
| 627 | if (text.length > COMMENT_LIMITS.max) throw new HttpError(400, `Keep comments under ${COMMENT_LIMITS.max.toLocaleString('en-US')} characters.`); |
| 628 | 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.'); |
| 629 | 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.'); |
| 630 | 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(); |
| 631 | if (same) throw new HttpError(409, 'You already posted that comment.'); |
| 632 | const id = newId(); |
| 633 | await env.DB.batch([ |
| 634 | env.DB.prepare('INSERT INTO comments (id, skill_id, user_id, body, created_at) VALUES (?,?,?,?,?)').bind(id, skill.id, user.id, text, now()), |
| 635 | 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), |
| 636 | ]); |
| 637 | return id; |
| 638 | } |
| 639 | |
| 640 | export async function removeComment(env: Env, actor: User, commentId: string): Promise<void> { |
| 641 | 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 }>(); |
| 642 | if (!row) throw new HttpError(404, 'That comment was not found.'); |
| 643 | if (!actor.is_admin && actor.id !== row.user_id) throw new HttpError(403, 'Not allowed.'); |
| 644 | const ts = now(); |
| 645 | const stmts = [ |
| 646 | env.DB.prepare('UPDATE comments SET removed_at = ?, removed_by = ? WHERE id = ?').bind(ts, actor.id, row.id), |
| 647 | 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), |
| 648 | ]; |
| 649 | 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)); |
| 650 | await env.DB.batch(stmts); |
| 651 | } |
| 652 | |
| 653 | export async function fileReport(env: Env, user: User, targetType: string, targetId: string, reason: string): Promise<void> { |
| 654 | if (!['skill', 'review', 'user', 'comment'].includes(targetType)) throw new HttpError(400, 'Unknown report target.'); |
| 655 | const text = reason.trim().slice(0, 1000); |
| 656 | if (text.length < 10) throw new HttpError(400, 'Say what is wrong in a sentence or two.'); |
| 657 | if (!(await rateLimit(env, `report:${user.id}`, LIMITS.reportsPerDay, DAY))) throw new HttpError(429, 'You have filed a lot of reports today.'); |
| 658 | 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(); |
| 659 | } |
| 660 | |
| 661 | /** Ban a member: sign them out everywhere, hide their skills, and reverse the Seeds their likes gave. */ |
| 662 | export async function banUser(env: Env, admin: User, targetId: string, note: string): Promise<void> { |
| 663 | if (!admin.is_admin) throw new HttpError(403, 'Moderators only.'); |
| 664 | const target = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(targetId).first<User>(); |
| 665 | if (!target) throw new HttpError(404, 'Member not found.'); |
| 666 | if (target.is_admin) throw new HttpError(400, 'Admins cannot be banned here.'); |
| 667 | const ts = now(); |
| 668 | await env.DB.batch([ |
| 669 | env.DB.prepare("UPDATE users SET status = 'banned', spotlight_at = NULL WHERE id = ?").bind(targetId), |
| 670 | env.DB.prepare('DELETE FROM sessions WHERE user_id = ?').bind(targetId), |
| 671 | env.DB.prepare('UPDATE api_tokens SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL').bind(ts, targetId), |
| 672 | env.DB.prepare("UPDATE skills SET state = 'hidden', featured_at = NULL WHERE owner_id = ? AND state = 'live'").bind(targetId), |
| 673 | 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), |
| 674 | 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), |
| 675 | ]); |
| 676 | 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 }>(); |
| 677 | for (const l of likes.results) await removeLike(env, l.id, l.skill_id, l.owner_id); |
| 678 | } |
| 679 | |
| 680 | export { runAiReview }; |