Branchwell

Skillfarm / website · skillfarm.ai / src / routes / skills.tsx

Raw 58.3 KB on c724bfa127f7a93b48788385cedf1e60cb4e7943
1import { raw } from 'hono/html';
2import type { Hono } from 'hono';
3import type { AppEnv, Ctx, User } from '../env';
4import { importFromGithub, refreshStale, REPO_SKILL_LIMIT } from '../lib/github';
5import { getImport, importItems, processNextItem, startRepoShare, type ImportItemView, type ImportRow } from '../lib/imports';
6import { copySendOptions, installPlan, installSendOptions, multiAgentCopy } from '../lib/install';
7import { parseSkillMd, renderMarkdown } from '../lib/markdown';
8import { ipKey, rateLimit } from '../lib/ratelimit';
9import type { Finding } from '../lib/scan';
10import { setFlash } from '../lib/session';
11import {
12 addComment, addReview, canView, COMMENT_LIMITS, listComments, removeComment, type CommentRow, CATEGORIES, categoryCounts, categoryName, cleanCategory, fileReport, getSkillCard, getSkillCardById, getVersion, latestVersion, likeSkill, listSkills, PLATFORMS, platformName, readVersionFile, readVersionFiles,
13 recordInstall, removeReview, setSkillState, splitPlatforms, submitSkill, unlikeSkill, type ManifestEntry, type SkillCard as SkillCardRow, type VersionRow,
14} from '../lib/skills';
15import { SEEDS, tierFor } from '../lib/tiers';
16import { clampInt, compactNumber, dateLabel, HttpError, plural, safeNext, timeAgo } from '../lib/util';
17import { makeZip } from '../lib/zip';
18import { icon } from '../views/art';
19import { AgentBadge, Avatar, Copy, Empty, LikeButton, Pager, SendToAgent, SkillCard, Stars, stateLabel, TierBadge } from '../views/components';
20import { render } from '../views/layout';
21
22const SORTS = [
23 { key: 'trending', label: 'Trending' },
24 { key: 'top', label: 'Top' },
25 { key: 'new', label: 'New' },
26];
27
28function requireUser(c: Ctx): User {
29 const u = c.get('user');
30 if (!u) throw new HttpError(401, 'Sign in first.');
31 return u;
32}
33
34async function loadSkill(c: Ctx): Promise<SkillCardRow> {
35 const viewer = c.get('user');
36 const skill = await getSkillCard(c.env, c.req.param('handle')!, c.req.param('slug')!, viewer?.id);
37 if (!skill || skill.state === 'removed' || !canView(skill, viewer)) throw new HttpError(404, 'That skill was not found.');
38 return skill;
39}
40
41/** The version a viewer should see: the approved one, or for the owner and admins the newest. */
42async function visibleVersion(c: Ctx, skill: SkillCardRow, preferLatest = false): Promise<VersionRow | null> {
43 const viewer = c.get('user');
44 const privileged = !!viewer && (viewer.id === skill.owner_id || !!viewer.is_admin);
45 if (privileged && (preferLatest || !skill.current_version_id)) return latestVersion(c.env, skill.id);
46 return getVersion(c.env, skill.current_version_id);
47}
48
49const ShareForm = ({ c, replant, error, values }: { c: Ctx; replant?: SkillCardRow | null; error?: string; values?: Record<string, string> }) => {
50 const v = values ?? {};
51 const platformChecks = (
52 <fieldset class="checks">
53 <legend>Works with</legend>
54 {PLATFORMS.map((p) => (
55 <label>
56 <input type="checkbox" name="platforms" value={p.key} checked={v.platforms ? v.platforms.split(',').includes(p.key) : true} />
57 <span>{p.name}</span>
58 </label>
59 ))}
60 </fieldset>
61 );
62 if (replant) {
63 return (
64 <div class="wrap section share-page">
65 <h1>Replant a skill</h1>
66 <p class="lede">{`Start from ${replant.owner_handle}'s "${replant.title}", make it your own, and submit it. The original is credited on your skill page.`}</p>
67 {error ? <div class="notice notice-error" role="alert">{error}</div> : null}
68 <form method="post" action="/share" class="form card pad share-form" data-share-form>
69 <input type="hidden" name="replant" value={replant.id} />
70 <label>
71 <span>SKILL.md</span>
72 <textarea name="skill_md" rows={16} class="mono" spellcheck={false}>{v.skill_md ?? ''}</textarea>
73 </label>
74 {platformChecks}
75 <details class="optional">
76 <summary>Change the listing title or summary</summary>
77 <p class="muted">By default these come from <code>name</code> and <code>description</code> in the SKILL.md header.</p>
78 <label>
79 <span>Title</span>
80 <input name="title" maxlength={80} value={v.title ?? ''} />
81 </label>
82 <label>
83 <span>Summary</span>
84 <input name="summary" maxlength={280} value={v.summary ?? ''} />
85 </label>
86 </details>
87 <label class="confirm">
88 <input type="checkbox" name="rights" value="1" required />
89 <span>The original's license lets me share my version, and it follows the <a href="/guidelines">guidelines</a>.</span>
90 </label>
91 <div class="form-foot">
92 <button class="btn btn-primary btn-lg" type="submit" data-busy-label="Submitting…">Submit for review</button>
93 </div>
94 </form>
95 </div>
96 );
97 }
98 return (
99 <div class="wrap section share-page">
100 <h1>Share your skills</h1>
101 <p class="lede">
102 Give Skillfarm the address of your public GitHub repo. It reads the repo, finds every skill in it, and a person reviews them. The skills that are approved become cards on your profile, and each one earns you {SEEDS.share} Seeds.
103 </p>
104 {error ? <div class="notice notice-error" role="alert">{error}</div> : null}
105 <form method="post" action="/share" class="form card pad share-form" data-share-form>
106 <label>
107 <span>{icon('github', 18)} Your GitHub repo</span>
108 <input name="repo_url" type="text" inputmode="url" required placeholder="https://github.com/you/your-skills" value={v.repo_url ?? ''} autocapitalize="none" spellcheck={false} />
109 <small>
110 The repo has to be public. Every folder with a SKILL.md in it counts as one skill, up to {REPO_SKILL_LIMIT} at a time. Skillfarm copies each SKILL.md and the text files beside it. Stars from the repo show on your skills.
111 </small>
112 </label>
113 {platformChecks}
114 <label class="confirm">
115 <input type="checkbox" name="rights" value="1" required />
116 <span>I wrote these skills or their license lets me share them, and they follow the <a href="/guidelines">guidelines</a>.</span>
117 </label>
118 <div class="form-foot">
119 <button class="btn btn-primary btn-lg" type="submit" data-busy-label="Reading your repo…">Read my repo</button>
120 <span class="muted">Nothing goes public until it is approved.</span>
121 </div>
122 </form>
123 <ol class="steps-list">
124 <li><strong>Skillfarm reads your repo.</strong> You see the list of skills it found within a minute.</li>
125 <li><strong>A person reviews it.</strong> The whole repo can be approved or turned down, or skills can be taken one by one. You get an email with the decision and the reason.</li>
126 <li><strong>Approved skills go on your profile.</strong> People install them straight from your repo, so you keep one place to maintain them.</li>
127 </ol>
128 <p class="muted">No repo yet? <a href="/help">Help</a> has a prompt that sets one up with your agent. While you wait, you can like and comment on other people's skills.</p>
129 </div>
130 );
131};
132
133const ITEM_STATE: Record<string, { label: string; cls: string }> = {
134 queued: { label: 'Waiting to be read', cls: '' },
135 working: { label: 'Reading', cls: 'pill-pending' },
136 submitted: { label: 'In review', cls: 'pill-pending' },
137 updated: { label: 'New version in review', cls: 'pill-pending' },
138 unchanged: { label: 'No change', cls: '' },
139 skipped: { label: 'Left out', cls: 'pill-rejected' },
140 failed: { label: 'Could not be read', cls: 'pill-rejected' },
141};
142
143/** What the member sees for one skill of their shared repo: how reading went, then the reviewer's decision once there is one. */
144function itemState(i: ImportItemView): { label: string; cls: string; note: string | null } {
145 if (i.version_status === 'approved') return { label: 'Approved', cls: 'pill-verified', note: null };
146 if (i.version_status === 'rejected') return { label: 'Not approved', cls: 'pill-rejected', note: i.decision_note ? `Reviewer note: ${i.decision_note}` : null };
147 if (i.version_status === 'superseded') return { label: 'Replaced by a newer version', cls: '', note: null };
148 const st = ITEM_STATE[i.status] ?? { label: i.status, cls: '' };
149 return { ...st, note: i.detail };
150}
151
152const RepoSharePage = ({ c, imp, items, ownerHandle }: { c: Ctx; imp: ImportRow; items: ImportItemView[]; ownerHandle: string }) => {
153 const reading = imp.status === 'reading';
154 const left = items.filter((i) => i.status === 'queued' || i.status === 'working').length;
155 const inReview = items.filter((i) => i.version_status === 'pending').length;
156 const approved = items.filter((i) => i.version_status === 'approved').length;
157 return (
158 <div class="wrap section share-page repo-share" data-repo-share={reading ? `/share/repo/${imp.id}/next` : undefined}>
159 <p class="crumbs"><a href="/share">Share</a> / {imp.repo}</p>
160 <h1>{imp.repo}</h1>
161 <p class="lede" data-repo-share-status>
162 {reading
163 ? `Skillfarm found ${plural(imp.found, 'skill')} and is reading them. ${left} to go. Keep this page open, or close it and the rest are read within a few minutes.`
164 : inReview
165 ? `${plural(inReview, 'skill')} from this repo ${inReview === 1 ? 'is' : 'are'} waiting for review. Nothing is public yet. You will get an email with the decision.`
166 : imp.decision_note
167 ? 'This repo was not approved.'
168 : approved
169 ? `${plural(approved, 'skill')} from this repo ${approved === 1 ? 'is' : 'are'} live on your profile.`
170 : 'Nothing from this repo is waiting for review.'}
171 </p>
172 {imp.decision_note ? <div class="notice notice-error"><strong>Reviewer note:</strong> {imp.decision_note}</div> : null}
173 {reading ? (
174 <form method="post" action={`/share/repo/${imp.id}/next`} class="no-js-only">
175 <button class="btn btn-ghost" type="submit">Read the next skill</button>
176 </form>
177 ) : null}
178 <ul class="queue repo-items">
179 {items.map((i) => {
180 const st = itemState(i);
181 return (
182 <li class="card pad queue-row">
183 <div class="queue-main">
184 <h3>{i.slug ? <a href={`/skills/${ownerHandle}/${i.slug}`}>{i.title}</a> : i.path.split('/').pop() || imp.repo.split('/')[1]}</h3>
185 {i.summary ? <p class="muted">{i.summary}</p> : null}
186 <p class="queue-meta"><span class="mono">{i.path || '(repo root)'}</span>{st.note ? <span>{st.note}</span> : null}</p>
187 </div>
188 <div class="queue-side"><span class={`pill ${st.cls}`}>{st.label}</span></div>
189 </li>
190 );
191 })}
192 </ul>
193 <p class="muted">Read at commit <code>{imp.ref.slice(0, 7)}</code>, {timeAgo(imp.created_at)}. To send changes later, push them to the repo and share it again. Only the skills that changed go back to review.</p>
194 </div>
195 );
196};
197
198/** Comments on a skill: plain text from signed-in members, on shared skills and picks alike. */
199const Comments = ({ c, skill, comments, base }: { c: Ctx; skill: SkillCardRow; comments: CommentRow[]; base: string }) => {
200 const viewer = c.get('user');
201 return (
202 <section class="comments" id="comments">
203 <h2>{icon('comment', 20)} Comments <small>({comments.length})</small></h2>
204 {skill.state !== 'live' ? null : viewer ? (
205 <form method="post" action={`${base}/comments`} class="form card pad comment-form">
206 <label>
207 <span class="sr-only">Your comment</span>
208 <textarea name="body" rows={3} required minlength={COMMENT_LIMITS.min} maxlength={COMMENT_LIMITS.max} placeholder="Tried it? Have a question or a tip? Say it here."></textarea>
209 </label>
210 <div class="form-foot">
211 <button class="btn btn-primary btn-sm" type="submit">Post comment</button>
212 <span class="muted">Posting as @{viewer.handle}. Be kind and stay on the skill.</span>
213 </div>
214 </form>
215 ) : (
216 <p><a href={`/signin?next=${encodeURIComponent(base + '#comments')}`}>Sign in</a> to leave a comment.</p>
217 )}
218 {comments.length ? (
219 <ul class="review-list comment-list">
220 {comments.map((m) => (
221 <li class="card pad" id={`comment-${m.id}`}>
222 <div class="review-head">
223 <a class="by" href={`/u/${m.handle}`}>
224 <Avatar user={{ id: m.user_id, handle: m.handle, avatar_key: m.avatar_key, avatar_fallback: m.avatar_fallback }} size={32} />
225 <span><strong>{m.display_name}</strong> <em>@{m.handle}</em></span>
226 </a>
227 {m.is_agent ? <AgentBadge /> : null}
228 {m.user_id === skill.owner_id && !m.is_agent ? <span class="pill">Author</span> : null}
229 <time>{timeAgo(m.created_at)}</time>
230 </div>
231 <p>{m.body}</p>
232 {viewer ? (
233 <div class="comment-tools">
234 {viewer.id === m.user_id || viewer.is_admin ? (
235 <form method="post" action={`/comments/${m.id}/remove`}>
236 <input type="hidden" name="back" value={`${base}#comments`} />
237 <button class="link-btn" type="submit">Remove</button>
238 </form>
239 ) : (
240 <form method="post" action="/report" data-confirm="Report this comment to the moderators?">
241 <input type="hidden" name="target_type" value="comment" />
242 <input type="hidden" name="target_id" value={m.id} />
243 <input type="hidden" name="reason" value="Reported from the skill page as breaking the guidelines." />
244 <input type="hidden" name="back" value={`${base}#comments`} />
245 <button class="link-btn" type="submit">Report</button>
246 </form>
247 )}
248 </div>
249 ) : null}
250 </li>
251 ))}
252 </ul>
253 ) : (
254 <p class="muted">No comments yet. Be the first.</p>
255 )}
256 </section>
257 );
258};
259
260/** Share a skill's page: the phone's share sheet where there is one, otherwise the link is copied. */
261const ShareButton = ({ c, skill, by }: { c: Ctx; skill: SkillCardRow; by: string }) => {
262 const url = `${c.env.SITE_URL}/skills/${skill.owner_handle}/${skill.slug}`;
263 const text = `${skill.title} by ${by}, an agent skill on Skillfarm`;
264 return (
265 <div class="share-row">
266 <button type="button" class="btn btn-ghost" data-share data-share-url={url} data-share-title={skill.title} data-share-text={text}>{icon('share', 18)} <span>Share</span></button>
267 <a class="btn btn-ghost btn-icon" href={`https://x.com/intent/post?text=${encodeURIComponent(text)}&url=${encodeURIComponent(url)}`} target="_blank" rel="noopener noreferrer" aria-label="Post this skill on X" title="Post on X">{icon('x', 16)}</a>
268 </div>
269 );
270};
271
272const FindingsList = ({ findings }: { findings: Finding[] }) =>
273 findings.length ? (
274 <ul class="findings">
275 {findings.slice(0, 30).map((f) => (
276 <li class={`sev-${f.severity}`}>
277 <strong>{f.rule}</strong>
278 <span>
279 {f.file}
280 {f.line ? `:${f.line}` : ''}
281 </span>
282 {f.excerpt ? <code>{f.excerpt}</code> : null}
283 </li>
284 ))}
285 </ul>
286 ) : (
287 <p class="muted">The pattern scan found nothing.</p>
288 );
289
290export { FindingsList };
291
292/** The page for one of Sprout's picks. There are no files here: it credits the maker and sends people to the maker's repo. */
293async function pickPage(c: Ctx, skill: SkillCardRow) {
294 const viewer = c.get('user');
295 const admin = !!viewer?.is_admin;
296 const repo = skill.github_repo
297 ? await c.env.DB.prepare('SELECT * FROM repo_signals WHERE repo_full_name = ?').bind(skill.github_repo).first<{ stars: number; forks: number; pushed_at: string | null; license_spdx: string | null; archived: number; unavailable: number; fetched_at: number }>()
298 : null;
299 refreshStale(c.env, c.executionCtx, [skill]);
300 const more = skill.category ? (await listSkills(c.env, { category: skill.category, sort: 'top', limit: 4, viewerId: viewer?.id })).filter((s) => s.id !== skill.id).slice(0, 3) : [];
301 const source = skill.source_url ?? `https://github.com/${skill.github_repo}`;
302 const maker = skill.maker ?? skill.github_repo ?? 'its maker';
303 const platforms = splitPlatforms(skill.platforms);
304 const license = skill.license ?? repo?.license_spdx ?? null;
305 const sends = skill.state === 'live' ? installSendOptions(c.env.SITE_URL, skill, installPlan(c.env.SITE_URL, skill)) : [];
306 const copy = skill.state === 'live' ? multiAgentCopy(skill) : null;
307 const comments = await listComments(c.env, skill.id);
308 const pickBase = `/skills/${skill.owner_handle}/${skill.slug}`;
309 return render(
310 c,
311 { title: `${skill.title} by ${maker}`, description: skill.summary, noindex: skill.state !== 'live', active: 'skills' },
312 <div class="wrap section skill-page pick-page">
313 {skill.state !== 'live' ? <div class="notice notice-info"><strong>{stateLabel(skill.state)}.</strong> This pick is not public.</div> : null}
314 <header class="skill-head">
315 <div class="skill-head-main">
316 <p class="eyebrow">Sprout's pick</p>
317 <h1>{skill.title}</h1>
318 <p class="lede">{skill.summary}</p>
319 <div class="skill-by">
320 <a class="by by-maker" href={skill.maker_url ?? source} target="_blank" rel="noopener noreferrer">
321 {icon('github', 26)}
322 <span>
323 Made by <strong>{maker}</strong>
324 </span>
325 </a>
326 </div>
327 <ul class="chips">
328 {categoryName(skill.category) ? <li class="chip-cat"><a href={`/skills?category=${skill.category}`}>{categoryName(skill.category)}</a></li> : null}
329 {platforms.map((p) => <li>{platformName(p)}</li>)}
330 </ul>
331 </div>
332 <aside class="skill-actions card pad">
333 <div class="counts">
334 <LikeButton skill={skill} viewerId={viewer?.id} large />
335 <Stars skill={skill} />
336 </div>
337 <SendToAgent options={sends} block />
338 <a class="btn btn-ghost btn-block" href={source} target="_blank" rel="noopener noreferrer">{icon('github', 18)} Get it on GitHub {icon('external', 15)}</a>
339 {skill.state === 'live' ? <ShareButton c={c} skill={skill} by={maker} /> : null}
340 {admin ? <a class="btn btn-ghost btn-block" href={`/admin?tab=picks&edit=${skill.id}#pick-form`}>Edit this pick</a> : null}
341 <dl class="facts">
342 <dt>Maker</dt>
343 <dd>{maker}</dd>
344 {skill.github_repo ? (
345 <>
346 <dt>Repo</dt>
347 <dd>
348 <a href={`https://github.com/${skill.github_repo}`} target="_blank" rel="noopener noreferrer">{skill.github_repo}</a>
349 {repo?.unavailable ? <span class="pill pill-rejected">Repo unavailable</span> : null}
350 {repo?.archived ? <span class="pill">Archived</span> : null}
351 </dd>
352 </>
353 ) : null}
354 <dt>License</dt>
355 <dd>{license ?? 'Not stated. Check the repo before you reuse it.'}</dd>
356 {repo?.forks ? (<><dt>Forks</dt><dd>{compactNumber(repo.forks)}</dd></>) : null}
357 {repo?.pushed_at ? (<><dt>Last commit</dt><dd>{dateLabel(Math.floor(Date.parse(repo.pushed_at) / 1000))}</dd></>) : null}
358 </dl>
359 </aside>
360 </header>
361
362 <section class="card pad pick-note">
363 <a class="by" href="/u/sprout">
364 <Avatar user={{ id: skill.owner_id, handle: skill.owner_handle, avatar_key: skill.owner_avatar_key, avatar_fallback: skill.owner_avatar_fallback }} size={44} />
365 <span>
366 <strong>{skill.owner_name}</strong> <em>recommends this</em>
367 </span>
368 </a>
369 <AgentBadge />
370 {skill.pick_note ? <p>{skill.pick_note}</p> : null}
371 <p class="fine">
372 Sprout is the Skillfarm agent. This skill belongs to {maker}. {copy ? 'Skillfarm links to the original, and keeps a converted copy for other agents, described below.' : "Skillfarm links to it and hosts no copy, so you always install the maker's current version."} Stars are for the whole repo.
373 </p>
374 </section>
375
376 {copy ? (
377 <section class="card pad install multi-copy" id="multi-agent">
378 <h2>Multi-agent version</h2>
379 <p class="muted">
380 A copy of this skill, converted by Skillfarm so it reads the same in Claude Code, Codex CLI and Gemini CLI. {maker} wrote it and keeps the credit. The author's text is unchanged, and{' '}
381 <a href={copy.notice_url} target="_blank" rel="noopener noreferrer">the notice lists every change</a>.
382 </p>
383 <SendToAgent options={copySendOptions(c.env.SITE_URL, skill, copy)} />
384 <div class="tabset" data-tabset data-agent-tabs>
385 <div class="tabs" role="tablist">
386 {copy.agents.map((a, i) => (
387 <button type="button" role="tab" class={i === 0 ? 'is-active' : ''} aria-selected={i === 0 ? 'true' : 'false'} data-tab={a.agent}>{a.name}</button>
388 ))}
389 </div>
390 {copy.agents.map((a, i) => (
391 <div data-panel={a.agent} hidden={i !== 0}>
392 <p class="where fine">Goes in <code>{a.folder}</code>, for every project on this machine. Run this in your terminal:</p>
393 <Copy text={a.quick!} />
394 <details>
395 <summary>No Node.js? Use git</summary>
396 <Copy text={a.manual.join(' && ')} />
397 </details>
398 <p class="fine">{a.check}</p>
399 </div>
400 ))}
401 </div>
402 <p>
403 <a href={copy.url} target="_blank" rel="noopener noreferrer">Read the converted copy on GitHub</a>
404 </p>
405 </section>
406 ) : null}
407
408 <section class="card pad install">
409 <h2>{copy ? 'Install the original' : 'Install'}</h2>
410 {skill.install_hint ? (
411 <>
412 <p class="muted">
413 From the maker's own instructions. {skill.install_hint.trimStart().startsWith('/') ? 'Type this inside Claude Code.' : skill.install_hint.trimStart().startsWith('$') ? 'Type this inside Codex.' : 'Run this in your terminal.'} Read the skill first, the same way you would read a script before you run it.
414 </p>
415 <Copy text={skill.install_hint} />
416 </>
417 ) : (
418 <p class="muted">Follow the install steps in the maker's README. Read the skill before you install it, the same way you would read a script before you run it.</p>
419 )}
420 <p>
421 <a href={source} target="_blank" rel="noopener noreferrer">Open {skill.github_path ? 'the skill folder' : 'the repo'} on GitHub</a>
422 </p>
423 </section>
424
425 <Comments c={c} skill={skill} comments={comments} base={pickBase} />
426
427 {more.length ? (
428 <section class="section-tight">
429 <div class="section-head">
430 <h2 class="section-title">More in {categoryName(skill.category)}</h2>
431 <a href={`/skills?category=${skill.category}`}>See all</a>
432 </div>
433 <div class="grid grid-3">{more.map((s) => <SkillCard skill={s} viewerId={viewer?.id} />)}</div>
434 </section>
435 ) : null}
436
437 <div class="skill-foot">
438 <p class="muted">Did you make this skill? You can <a href="/share">share it yourself</a> and it will be listed under your name. To have this pick changed or removed, use Report on this page.</p>
439 {viewer ? (
440 <details class="report">
441 <summary>{icon('flag', 15)} Report this pick</summary>
442 <form method="post" action="/report" class="form">
443 <input type="hidden" name="target_type" value="skill" />
444 <input type="hidden" name="target_id" value={skill.id} />
445 <input type="hidden" name="back" value={`/skills/${skill.owner_handle}/${skill.slug}`} />
446 <label>
447 <span>What is wrong?</span>
448 <textarea name="reason" required minlength={10} maxlength={1000} rows={3}></textarea>
449 </label>
450 <button class="btn btn-ghost btn-sm" type="submit">Send report</button>
451 </form>
452 </details>
453 ) : null}
454 </div>
455 </div>,
456 );
457}
458
459export function registerSkills(app: Hono<AppEnv>) {
460 app.get('/skills', async (c) => {
461 const viewer = c.get('user');
462 const q = (c.req.query('q') ?? '').trim().slice(0, 80);
463 const sort = SORTS.some((s) => s.key === c.req.query('sort')) ? c.req.query('sort')! : q ? 'top' : 'trending';
464 const platform = PLATFORMS.some((p) => p.key === c.req.query('platform')) ? c.req.query('platform')! : '';
465 const category = cleanCategory(c.req.query('category')) ?? '';
466 const from = c.req.query('from') === 'sprout' ? 'sprout' : c.req.query('from') === 'growers' ? 'growers' : '';
467 const page = clampInt(c.req.query('page'), 1, 500, 1);
468 const per = 24;
469 const [rows, counts] = await Promise.all([
470 listSkills(c.env, { q, sort, platform, category, kind: from === 'sprout' ? 'link' : from === 'growers' ? 'hosted' : undefined, limit: per + 1, offset: (page - 1) * per, viewerId: viewer?.id }),
471 categoryCounts(c.env),
472 ]);
473 const skills = rows.slice(0, per);
474 refreshStale(c.env, c.executionCtx, skills);
475 const filtered = !!(q || platform || category || from);
476 const qs = (over: Record<string, string>) => {
477 const p = new URLSearchParams();
478 const all = { q, sort, platform, category, from, ...over };
479 for (const [k, val] of Object.entries(all)) if (val) p.set(k, val);
480 return `/skills?${p.toString()}`;
481 };
482 return render(
483 c,
484 {
485 title: q ? `Skills matching "${q}"` : category ? `${categoryName(category)} skills` : from === 'sprout' ? "Sprout's picks" : 'Browse skills',
486 description: 'Browse the curated list of agent skills on Skillfarm: skills shared by growers, each reviewed before it went live, and picks from around the web recommended by Sprout with credit to their makers.',
487 active: 'skills',
488 },
489 <div class="wrap section">
490 <h1>Browse skills</h1>
491 <p class="lede curated-note">A curated list. Every skill a grower shares is reviewed by a person before it goes live, and <a href="/u/sprout">Sprout</a> adds picks from around the web.</p>
492 <form method="get" action="/skills" class="search" role="search">
493 {icon('search', 20)}
494 <input type="search" name="q" value={q} placeholder="Search by name, description, grower or repo" aria-label="Search skills" />
495 {platform ? <input type="hidden" name="platform" value={platform} /> : null}
496 {category ? <input type="hidden" name="category" value={category} /> : null}
497 {from ? <input type="hidden" name="from" value={from} /> : null}
498 <input type="hidden" name="sort" value={sort} />
499 <button class="btn btn-primary" type="submit">Search</button>
500 </form>
501 <div class="filters">
502 <div class="tabs" role="group" aria-label="Sort">
503 {SORTS.map((s) => (
504 <a href={qs({ sort: s.key })} class={sort === s.key ? 'is-active' : ''}>{s.label}</a>
505 ))}
506 </div>
507 <ul class="chips chips-link" aria-label="Who it is from">
508 <li><a href={qs({ from: '' })} class={!from ? 'is-active' : ''}>Everything</a></li>
509 <li><a href={qs({ from: 'growers' })} class={from === 'growers' ? 'is-active' : ''}>From growers</a></li>
510 <li><a href={qs({ from: 'sprout' })} class={from === 'sprout' ? 'is-active' : ''}>Sprout's picks</a></li>
511 </ul>
512 </div>
513 <dl class="filter-rows">
514 <dt>Category</dt>
515 <dd>
516 <ul class="chips chips-link" aria-label="Category">
517 <li><a href={qs({ category: '' })} class={!category ? 'is-active' : ''}>All</a></li>
518 {CATEGORIES.filter((cat) => counts[cat.key] || category === cat.key).map((cat) => (
519 <li><a href={qs({ category: cat.key })} class={category === cat.key ? 'is-active' : ''}>{cat.name} <small>{counts[cat.key] ?? 0}</small></a></li>
520 ))}
521 </ul>
522 </dd>
523 <dt>Works with</dt>
524 <dd>
525 <ul class="chips chips-link" aria-label="Platform">
526 <li><a href={qs({ platform: '' })} class={!platform ? 'is-active' : ''}>Any agent</a></li>
527 {PLATFORMS.map((p) => (
528 <li><a href={qs({ platform: p.key })} class={platform === p.key ? 'is-active' : ''}>{p.name}</a></li>
529 ))}
530 </ul>
531 </dd>
532 </dl>
533 {from === 'sprout' ? (
534 <p class="pick-explainer">
535 <a href="/u/sprout">Sprout</a> is the Skillfarm agent. Its picks are skills made by other people. Each one names its maker and links to their repo, where you install it and get their updates.
536 </p>
537 ) : null}
538 {skills.length ? (
539 <div class="grid grid-3">{skills.map((s) => <SkillCard skill={s} viewerId={viewer?.id} />)}</div>
540 ) : (
541 <Empty title={filtered ? 'Nothing matches that yet' : 'No skills are live yet'} art="empty">
542 <p>{filtered ? 'Try a broader search, or be the one who shares it.' : 'Skillfarm just opened. Yours could be the first.'}</p>
543 <a href="/share" class="btn btn-primary">Share a skill</a>
544 </Empty>
545 )}
546 <Pager page={page} hasMore={rows.length > per} base={qs({})} />
547 </div>,
548 );
549 });
550
551 app.get('/share', async (c) => {
552 const user = c.get('user');
553 if (!user) return c.redirect(`/signin?next=${encodeURIComponent('/share' + new URL(c.req.url).search)}`);
554 let replant: SkillCardRow | null = null;
555 const values: Record<string, string> = {};
556 const rid = c.req.query('replant');
557 if (rid) {
558 replant = await getSkillCardById(c.env, rid);
559 if (!replant || replant.state !== 'live' || replant.kind === 'link') throw new HttpError(404, 'That skill cannot be replanted.');
560 const v = await getVersion(c.env, replant.current_version_id);
561 const md = v ? await readVersionFile(c.env, v, 'SKILL.md') : null;
562 values.skill_md = md ? new TextDecoder().decode(md) : '';
563 values.platforms = replant.platforms;
564 }
565 return render(c, { title: replant ? 'Replant a skill' : 'Share your skills', noindex: true }, <ShareForm c={c} replant={replant} values={values} />);
566 });
567
568 // Members share a repo, never a single file. The one exception is a replant, which starts from someone else's skill.
569 app.post('/share', async (c) => {
570 const user = requireUser(c);
571 const form = await c.req.parseBody({ all: true });
572 const str = (k: string) => (typeof form[k] === 'string' ? (form[k] as string) : '');
573 const platforms = ([] as unknown[]).concat(form.platforms ?? []).filter((x): x is string => typeof x === 'string');
574 const values = { repo_url: str('repo_url') || str('github_url'), skill_md: str('skill_md'), title: str('title'), summary: str('summary'), platforms: platforms.join(',') };
575 let replant: SkillCardRow | null = null;
576 try {
577 if (!str('rights')) throw new HttpError(400, 'Confirm that you have the right to share these skills.');
578 if (!(await rateLimit(c.env, `submit:${user.id}`, 12, 3600))) throw new HttpError(429, 'That is a lot of submissions in one hour. Take a break and try again.');
579 if (str('replant')) {
580 replant = await getSkillCardById(c.env, str('replant'));
581 if (!replant || replant.state !== 'live' || replant.kind === 'link') throw new HttpError(404, 'That skill cannot be replanted.');
582 const md = values.skill_md.replace(/\r\n/g, '\n');
583 if (md.trim().length < 40) throw new HttpError(400, 'Paste the contents of your SKILL.md.');
584 const result = await submitSkill(c.env, c.executionCtx, {
585 user, source: 'web', files: [{ path: 'SKILL.md', data: new TextEncoder().encode(md) }], title: values.title, summary: values.summary, platforms, category: replant.category, replantedFrom: replant,
586 });
587 setFlash(c, 'ok', 'Submitted. It is in the review queue, and you will get an email when it is approved or denied.');
588 return c.redirect(`/skills/${result.ownerHandle}/${result.skill.slug}`);
589 }
590 if (!values.repo_url.trim()) throw new HttpError(400, 'Paste the address of your GitHub repo.');
591 const imp = await startRepoShare(c.env, { user, source: 'web', url: values.repo_url, platforms });
592 return c.redirect(`/share/repo/${imp.id}`);
593 } catch (e) {
594 if (!(e instanceof HttpError)) throw e;
595 if (e.code.startsWith('open:')) {
596 setFlash(c, 'ok', e.message);
597 return c.redirect(`/share/repo/${e.code.slice(5)}`);
598 }
599 return render(c, { title: replant ? 'Replant a skill' : 'Share your skills', noindex: true }, <ShareForm c={c} replant={replant} error={e.message} values={values} />, e.status);
600 }
601 });
602
603 const loadImport = async (c: Ctx): Promise<{ imp: ImportRow; ownerHandle: string }> => {
604 const user = requireUser(c);
605 const imp = await getImport(c.env, c.req.param('id')!);
606 if (!imp || (imp.user_id !== user.id && !user.is_admin)) throw new HttpError(404, 'That shared repo was not found.');
607 const owner = imp.user_id === user.id ? user : await c.env.DB.prepare('SELECT handle FROM users WHERE id = ?').bind(imp.user_id).first<{ handle: string }>();
608 return { imp, ownerHandle: owner?.handle ?? '' };
609 };
610
611 app.get('/share/repo/:id', async (c) => {
612 const { imp, ownerHandle } = await loadImport(c);
613 const items = await importItems(c.env, imp.id);
614 return render(c, { title: `Sharing ${imp.repo}`, noindex: true }, <RepoSharePage c={c} imp={imp} items={items} ownerHandle={ownerHandle} />);
615 });
616
617 // Read the next skill of a shared repo. The page calls this until nothing is left; one skill per call keeps every request small.
618 app.post('/share/repo/:id/next', async (c) => {
619 const { imp } = await loadImport(c);
620 const step = imp.status === 'reading' ? await processNextItem(c.env, c.executionCtx, imp.id) : { left: 0, processed: false };
621 if ((c.req.header('accept') ?? '').includes('application/json')) return c.json({ left: step.left, found: imp.found });
622 return c.redirect(`/share/repo/${imp.id}`);
623 });
624
625 app.get('/skills/:handle/:slug', async (c) => {
626 const viewer = c.get('user');
627 const skill = await loadSkill(c);
628 const own = viewer?.id === skill.owner_id;
629 const admin = !!viewer?.is_admin;
630 if (skill.kind === 'link') return pickPage(c, skill);
631 const version = await visibleVersion(c, skill);
632 const latest = own || admin ? await latestVersion(c.env, skill.id) : null;
633 const tab = ['files', 'reviews'].includes(c.req.query('tab') ?? '') ? c.req.query('tab')! : 'readme';
634 const manifest: ManifestEntry[] = version ? JSON.parse(version.manifest) : [];
635 const [mdBytes, reviews, parent, repo, replants] = await Promise.all([
636 version ? readVersionFile(c.env, version, 'SKILL.md') : Promise.resolve(null),
637 c.env.DB.prepare(
638 `SELECT r.id, r.rating, r.body, r.created_at, r.user_id, u.handle, u.display_name, u.avatar_key, u.avatar_fallback, u.seeds_total
639 FROM reviews r JOIN users u ON u.id = r.user_id WHERE r.skill_id = ? AND r.removed_at IS NULL ORDER BY r.created_at DESC LIMIT 50`,
640 ).bind(skill.id).all<{ id: string; rating: number; body: string; created_at: number; user_id: string; handle: string; display_name: string; avatar_key: string | null; avatar_fallback: string | null; seeds_total: number }>(),
641 skill.replanted_from_skill_id ? getSkillCardById(c.env, skill.replanted_from_skill_id) : Promise.resolve(null),
642 skill.github_repo ? c.env.DB.prepare('SELECT * FROM repo_signals WHERE repo_full_name = ?').bind(skill.github_repo).first<{ stars: number; forks: number; pushed_at: string | null; license_spdx: string | null; archived: number; unavailable: number; fetched_at: number }>() : Promise.resolve(null),
643 c.env.DB.prepare("SELECT COUNT(*) AS n FROM skills WHERE replanted_from_skill_id = ? AND state = 'live'").bind(skill.id).first<{ n: number }>(),
644 ]);
645 const comments = await listComments(c.env, skill.id);
646 refreshStale(c.env, c.executionCtx, [skill]);
647 const md = mdBytes ? new TextDecoder().decode(mdBytes) : '';
648 const body = md ? parseSkillMd(md).body : '';
649 const base = `/skills/${skill.owner_handle}/${skill.slug}`;
650 const site = c.env.SITE_URL;
651 const platforms = splitPlatforms(skill.platforms);
652 const plan = installPlan(site, skill, { fileCount: manifest.length });
653 const sends = skill.state === 'live' ? installSendOptions(site, skill, plan) : [];
654 const myReview = viewer ? reviews.results.find((r) => r.user_id === viewer.id) : null;
655 const rating = skill.reviews_count ? (skill.rating_sum / skill.reviews_count).toFixed(1) : null;
656 const pending = latest && latest.status === 'pending' ? latest : null;
657 const rejected = latest && latest.status === 'rejected' && latest.id !== skill.current_version_id ? latest : null;
658 return render(
659 c,
660 { title: `${skill.title} by ${skill.owner_handle}`, description: skill.summary, noindex: skill.state !== 'live', active: 'skills' },
661 <div class="wrap section skill-page">
662 {skill.state !== 'live' ? (
663 <div class={`notice notice-${skill.state === 'rejected' ? 'error' : 'info'}`}>
664 <strong>{stateLabel(skill.state)}.</strong>{' '}
665 {skill.state === 'pending' ? 'Only you and the moderators can see this page until it is approved.' : skill.state === 'rejected' ? 'This skill is not public. Fix the issue below and submit a new version.' : 'This skill is not public.'}
666 </div>
667 ) : null}
668 {skill.state === 'live' && pending ? <div class="notice notice-info"><strong>Update in review.</strong> Version {pending.version} is waiting for a moderator. The approved version stays live until then.</div> : null}
669 {rejected ? (
670 <div class="notice notice-error">
671 <strong>Version {rejected.version} was not approved.</strong> {rejected.decision_note ? `Reviewer note: ${rejected.decision_note}` : 'No reviewer note was left.'}
672 </div>
673 ) : null}
674 {(own || admin) && latest && latest.status !== 'approved' && JSON.parse(latest.scan_report).length ? (
675 <details class="card pad scan-box">
676 <summary>What the pattern scan flagged in version {latest.version}</summary>
677 <p class="muted">These are automatic matches for a reviewer to check. Some are false alarms.</p>
678 <FindingsList findings={JSON.parse(latest.scan_report)} />
679 </details>
680 ) : null}
681
682 <header class="skill-head">
683 <div class="skill-head-main">
684 <h1>{skill.title}</h1>
685 <p class="lede">{skill.summary}</p>
686 <div class="skill-by">
687 <a class="by" href={`/u/${skill.owner_handle}`}>
688 <Avatar user={{ id: skill.owner_id, handle: skill.owner_handle, avatar_key: skill.owner_avatar_key, avatar_fallback: skill.owner_avatar_fallback }} size={36} />
689 <span>
690 <strong>{skill.owner_name}</strong> <em>@{skill.owner_handle}</em>
691 </span>
692 </a>
693 <TierBadge seeds={skill.owner_seeds} />
694 {skill.verified_owner ? <span class="pill pill-verified" title={`@${skill.owner_handle}'s GitHub account owns ${skill.github_repo}`}>{icon('check', 14)} Verified owner</span> : null}
695 </div>
696 {parent ? (
697 <p class="replant-line">
698 {icon('replant', 17)} Replanted from{' '}
699 {parent.state === 'live' ? <a href={`/skills/${parent.owner_handle}/${parent.slug}`}>{parent.title}</a> : <span>{parent.title}</span>} by <a href={`/u/${parent.owner_handle}`}>@{parent.owner_handle}</a>
700 </p>
701 ) : null}
702 <ul class="chips">
703 {categoryName(skill.category) ? <li class="chip-cat"><a href={`/skills?category=${skill.category}`}>{categoryName(skill.category)}</a></li> : null}
704 {platforms.map((p) => <li>{platformName(p)}</li>)}
705 </ul>
706 </div>
707 <aside class="skill-actions card pad">
708 <div class="counts">
709 <LikeButton skill={skill} viewerId={viewer?.id} large />
710 <Stars skill={skill} />
711 <span class="stat" title="People who installed this skill">{icon('download', 17)} <span>{compactNumber(skill.installs_count)}</span><span class="sr-only">installs</span></span>
712 </div>
713 {skill.state === 'live' ? (
714 <>
715 <SendToAgent options={sends} block />
716 <a class="btn btn-ghost btn-block" href={`${base}/download`} rel="nofollow">{icon('download', 18)} Download {manifest.length > 1 ? `(${manifest.length} files)` : 'SKILL.md'}</a>
717 <a class="btn btn-ghost btn-block" href={`/share?replant=${skill.id}`}>{icon('replant', 18)} Replant</a>
718 <ShareButton c={c} skill={skill} by={`@${skill.owner_handle}`} />
719 </>
720 ) : null}
721 {own ? <a class="btn btn-ghost btn-block" href={`${base}/edit`}>Submit a new version</a> : null}
722 {admin && pending ? <a class="btn btn-sun btn-block" href={`/admin/review/${pending.id}`}>Open in review queue</a> : null}
723 <dl class="facts">
724 {version ? (<><dt>Version</dt><dd>{version.version}, {skill.published_at ? `updated ${timeAgo(version.decided_at ?? version.created_at)}` : 'not yet approved'}</dd></>) : null}
725 {(replants?.n ?? 0) > 0 ? (<><dt>Replants</dt><dd>{replants!.n}</dd></>) : null}
726 {rating ? (<><dt>Rating</dt><dd>{rating} of 5 from {plural(skill.reviews_count, 'review')}</dd></>) : null}
727 {skill.github_repo ? (
728 <>
729 <dt>Repo</dt>
730 <dd>
731 <a href={`https://github.com/${skill.github_repo}${skill.github_path ? `/tree/HEAD/${skill.github_path}` : ''}`} rel="noopener">{skill.github_repo}</a>
732 {repo?.unavailable ? <span class="pill pill-rejected">Repo unavailable</span> : null}
733 {repo?.archived ? <span class="pill">Archived</span> : null}
734 </dd>
735 {repo ? (<><dt>Forks</dt><dd>{compactNumber(repo.forks)}</dd></>) : null}
736 {repo?.pushed_at ? (<><dt>Last commit</dt><dd>{dateLabel(Math.floor(Date.parse(repo.pushed_at) / 1000))}</dd></>) : null}
737 {repo?.license_spdx ? (<><dt>License</dt><dd>{repo.license_spdx}</dd></>) : null}
738 </>
739 ) : null}
740 </dl>
741 </aside>
742 </header>
743
744 {skill.state === 'live' ? (
745 <section class="card pad install" id="install">
746 <h2>Install</h2>
747 <p class="muted">
748 {plan.source === 'github'
749 ? <>This skill installs straight from its public repo, <a href={plan.repo_url!} rel="noopener">{plan.repo}</a>. Read the files first.</>
750 : 'Read the files first. This copies the reviewed files into your agent\'s skills folder.'}
751 </p>
752 <div class="tabset" data-tabset data-agent-tabs>
753 <div class="tabs" role="tablist">
754 {plan.agents.map((a, i) => (
755 <button type="button" role="tab" class={i === 0 ? 'is-active' : ''} aria-selected={i === 0 ? 'true' : 'false'} data-tab={a.agent}>{a.name}</button>
756 ))}
757 </div>
758 {plan.agents.map((a, i) => (
759 <div data-panel={a.agent} hidden={i !== 0}>
760 <p class="where fine">Goes in <code>{a.folder}</code>, for every project on this machine. Run this in your terminal:</p>
761 {a.quick ? <Copy text={a.quick} /> : null}
762 {plan.source === 'github' ? (
763 <>
764 <details>
765 <summary>No Node.js? Use git</summary>
766 <Copy text={a.manual.join(' && ')} />
767 </details>
768 {a.reviewed_copy ? (
769 <details>
770 <summary>Get exactly the reviewed files from Skillfarm</summary>
771 <p class="fine">The repo can change after a review. This fetches the version a person approved{plan.reviewed_commit ? <>, commit <code>{plan.reviewed_commit.slice(0, 7)}</code></> : null}.</p>
772 <Copy text={a.reviewed_copy} />
773 </details>
774 ) : null}
775 </>
776 ) : null}
777 <p class="fine">{a.check}</p>
778 </div>
779 ))}
780 </div>
781 <p class="fine">New to this? <a href="/help">Help</a> has setup prompts and answers.</p>
782 </section>
783 ) : null}
784
785 <div class="tabs page-tabs">
786 <a href={base} class={tab === 'readme' ? 'is-active' : ''}>SKILL.md</a>
787 <a href={`${base}?tab=files`} class={tab === 'files' ? 'is-active' : ''}>Files ({manifest.length})</a>
788 <a href={`${base}?tab=reviews`} class={tab === 'reviews' ? 'is-active' : ''}>Reviews ({skill.reviews_count})</a>
789 </div>
790
791 {tab === 'readme' ? (
792 <article class="card pad markdown">{body ? raw(renderMarkdown(body)) : <p class="muted">This skill has no readable SKILL.md.</p>}</article>
793 ) : null}
794
795 {tab === 'files' ? (
796 <ul class="card file-list">
797 {manifest.map((m) => (
798 <li>
799 {icon('file', 18)}
800 <a href={`${base}/file/${m.path.split('/').map(encodeURIComponent).join('/')}`}>{m.path}</a>
801 <span class="muted">{m.size < 1024 ? `${m.size} B` : `${(m.size / 1024).toFixed(1)} KB`}</span>
802 </li>
803 ))}
804 </ul>
805 ) : null}
806
807 {tab === 'reviews' ? (
808 <section class="reviews">
809 {viewer && !own && !myReview && skill.state === 'live' ? (
810 <form method="post" action={`${base}/reviews`} class="form card pad">
811 <h2>Write a review</h2>
812 <p class="muted">Tried it? Say how it went. A review earns you {SEEDS.review} Seeds.</p>
813 <fieldset class="rating">
814 <legend>Rating</legend>
815 {[1, 2, 3, 4, 5].map((n) => (
816 <label>
817 <input type="radio" name="rating" value={n} required checked={n === 5} />
818 <span>{n}</span>
819 </label>
820 ))}
821 </fieldset>
822 <label>
823 <span>Your review</span>
824 <textarea name="body" rows={4} required minlength={40} maxlength={2000}></textarea>
825 </label>
826 <button class="btn btn-primary" type="submit">Post review</button>
827 </form>
828 ) : null}
829 {!viewer ? <p><a href={`/signin?next=${encodeURIComponent(base + '?tab=reviews')}`}>Sign in</a> to review this skill.</p> : null}
830 {reviews.results.length ? (
831 <ul class="review-list">
832 {reviews.results.map((r) => (
833 <li class="card pad">
834 <div class="review-head">
835 <a class="by" href={`/u/${r.handle}`}>
836 <Avatar user={{ id: r.user_id, handle: r.handle, avatar_key: r.avatar_key, avatar_fallback: r.avatar_fallback }} size={32} />
837 <span><strong>{r.display_name}</strong> <em>@{r.handle}</em></span>
838 </a>
839 <span class="rating-val" aria-label={`${r.rating} out of 5`}>{'●'.repeat(r.rating)}{'○'.repeat(5 - r.rating)}</span>
840 <time>{timeAgo(r.created_at)}</time>
841 </div>
842 <p>{r.body}</p>
843 {viewer && (viewer.id === r.user_id || admin) ? (
844 <form method="post" action={`/reviews/${r.id}/remove`}>
845 <input type="hidden" name="back" value={`${base}?tab=reviews`} />
846 <button class="link-btn" type="submit">Remove review</button>
847 </form>
848 ) : null}
849 </li>
850 ))}
851 </ul>
852 ) : (
853 <Empty title="No reviews yet" art="tend"><p>Be the first to say how this skill worked for you.</p></Empty>
854 )}
855 </section>
856 ) : null}
857
858 <Comments c={c} skill={skill} comments={comments} base={base} />
859
860 <div class="skill-foot">
861 {viewer && !own ? (
862 <details class="report">
863 <summary>{icon('flag', 15)} Report this skill</summary>
864 <form method="post" action="/report" class="form">
865 <input type="hidden" name="target_type" value="skill" />
866 <input type="hidden" name="target_id" value={skill.id} />
867 <input type="hidden" name="back" value={base} />
868 <label>
869 <span>What is wrong?</span>
870 <textarea name="reason" required minlength={10} maxlength={1000} rows={3}></textarea>
871 </label>
872 <button class="btn btn-ghost btn-sm" type="submit">Send report</button>
873 </form>
874 </details>
875 ) : null}
876 {own ? (
877 <details class="report">
878 <summary>Remove this skill</summary>
879 <form method="post" action={`${base}/remove`} class="form">
880 <p class="muted">This takes the skill down and reverses the Seeds it earned. It cannot be undone.</p>
881 <button class="btn btn-danger btn-sm" type="submit">Remove skill</button>
882 </form>
883 </details>
884 ) : null}
885 </div>
886 </div>,
887 );
888 });
889
890 app.get('/skills/:handle/:slug/file/*', async (c) => {
891 const skill = await loadSkill(c);
892 const version = await visibleVersion(c, skill, c.req.query('v') === 'latest');
893 const base = `/skills/${skill.owner_handle}/${skill.slug}`;
894 const path = decodeURIComponent(new URL(c.req.url).pathname.slice(new URL(c.req.url).pathname.indexOf('/file/') + 6));
895 const data = version ? await readVersionFile(c.env, version, path) : null;
896 if (!data) throw new HttpError(404, 'That file was not found.');
897 const text = new TextDecoder().decode(data);
898 return render(
899 c,
900 { title: `${path} in ${skill.title}`, noindex: true, active: 'skills' },
901 <div class="wrap section">
902 <p class="crumbs"><a href={base}>{skill.title}</a> / <a href={`${base}?tab=files`}>Files</a> / {path}</p>
903 <h1 class="file-title">{path}</h1>
904 <pre class="card code-view"><code>{text}</code></pre>
905 </div>,
906 );
907 });
908
909 app.get('/skills/:handle/:slug/download', async (c) => {
910 const viewer = c.get('user');
911 const skill = await loadSkill(c);
912 const version = await getVersion(c.env, skill.current_version_id);
913 if (!version || skill.state !== 'live') throw new HttpError(404, 'This skill is not available to download.');
914 const ip = c.req.header('cf-connecting-ip') ?? 'local';
915 if (!(await rateLimit(c.env, `dl:${await ipKey(c.env, ip)}`, 120, 3600))) throw new HttpError(429, 'Too many downloads from this network. Try again later.');
916 const files = await readVersionFiles(c.env, version);
917 c.executionCtx.waitUntil(recordInstall(c.env, skill, viewer, ip, c.req.header('user-agent') ?? '').catch((e) => console.error('install count failed', e)));
918 const headers: Record<string, string> = { 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' };
919 if (files.length === 1) {
920 return new Response(files[0].data, { headers: { ...headers, 'content-type': 'text/markdown; charset=utf-8', 'content-disposition': 'attachment; filename="SKILL.md"' } });
921 }
922 return new Response(makeZip(files), { headers: { ...headers, 'content-type': 'application/zip', 'content-disposition': `attachment; filename="${skill.slug}.zip"` } });
923 });
924
925 app.get('/skills/:handle/:slug/edit', async (c) => {
926 const user = c.get('user');
927 const skill = await loadSkill(c);
928 if (!user || user.id !== skill.owner_id || skill.kind === 'link') throw new HttpError(403, 'Only the owner can update this skill.');
929 const v = await latestVersion(c.env, skill.id);
930 const md = v ? await readVersionFile(c.env, v, 'SKILL.md') : null;
931 const base = `/skills/${skill.owner_handle}/${skill.slug}`;
932 return render(
933 c,
934 { title: `Update ${skill.title}`, noindex: true },
935 <div class="wrap section share-page">
936 <p class="crumbs"><a href={base}>{skill.title}</a> / New version</p>
937 <h1>Submit a new version</h1>
938 <p class="lede">The new version is reviewed like the first one. The approved version stays live until then. Updates earn no extra Seeds.</p>
939 <form method="post" action={`${base}/edit`} class="form card pad">
940 {skill.github_repo ? (
941 <>
942 <p>This skill is linked to <strong>{skill.github_repo}</strong>{skill.github_path ? ` (${skill.github_path})` : ''}. Push your changes there, then pull them in.</p>
943 <input type="hidden" name="mode" value="github" />
944 </>
945 ) : (
946 <>
947 <input type="hidden" name="mode" value="paste" />
948 <label>
949 <span>SKILL.md</span>
950 <textarea name="skill_md" rows={20} class="mono" spellcheck={false} required>{md ? new TextDecoder().decode(md) : ''}</textarea>
951 </label>
952 </>
953 )}
954 <fieldset class="checks">
955 <legend>Works with</legend>
956 {PLATFORMS.map((p) => (
957 <label>
958 <input type="checkbox" name="platforms" value={p.key} checked={splitPlatforms(skill.platforms).includes(p.key)} />
959 <span>{p.name}</span>
960 </label>
961 ))}
962 </fieldset>
963 <button class="btn btn-primary" type="submit">{skill.github_repo ? 'Pull latest from GitHub and submit' : 'Submit for review'}</button>
964 </form>
965 </div>,
966 );
967 });
968
969 app.post('/skills/:handle/:slug/edit', async (c) => {
970 const user = requireUser(c);
971 const skill = await loadSkill(c);
972 if (user.id !== skill.owner_id) throw new HttpError(403, 'Only the owner can update this skill.');
973 const base = `/skills/${skill.owner_handle}/${skill.slug}`;
974 const form = await c.req.parseBody({ all: true });
975 const platforms = ([] as unknown[]).concat(form.platforms ?? []).filter((x): x is string => typeof x === 'string');
976 try {
977 if (skill.github_repo) {
978 const [owner, repo] = skill.github_repo.split('/');
979 const imp = await importFromGithub(c.env, { owner, repo, path: skill.github_path ?? '' });
980 await submitSkill(c.env, c.executionCtx, { user, source: 'web', files: imp.files, platforms, existing: skill, github: { repo: imp.repo, path: imp.path, ref: imp.ref, ownerId: imp.info.owner_id } });
981 } else {
982 const md = String(form.skill_md ?? '').replace(/\r\n/g, '\n');
983 await submitSkill(c.env, c.executionCtx, { user, source: 'web', files: [{ path: 'SKILL.md', data: new TextEncoder().encode(md) }], platforms, existing: skill });
984 }
985 setFlash(c, 'ok', 'New version submitted for review.');
986 } catch (e) {
987 if (!(e instanceof HttpError)) throw e;
988 setFlash(c, 'error', e.message);
989 return c.redirect(`${base}/edit`);
990 }
991 return c.redirect(base);
992 });
993
994 app.post('/skills/:handle/:slug/remove', async (c) => {
995 const user = requireUser(c);
996 const skill = await loadSkill(c);
997 await setSkillState(c.env, user, skill, 'removed');
998 setFlash(c, 'ok', `"${skill.title}" was removed.`);
999 return c.redirect(`/u/${user.handle}`);
1000 });
1001
1002 app.post('/skills/:handle/:slug/reviews', async (c) => {
1003 const user = requireUser(c);
1004 const skill = await loadSkill(c);
1005 const form = await c.req.parseBody();
1006 const base = `/skills/${skill.owner_handle}/${skill.slug}?tab=reviews`;
1007 try {
1008 await addReview(c.env, user, skill, parseInt(String(form.rating ?? ''), 10), String(form.body ?? ''));
1009 setFlash(c, 'ok', `Review posted. You earned ${SEEDS.review} Seeds.`);
1010 } catch (e) {
1011 if (!(e instanceof HttpError)) throw e;
1012 setFlash(c, 'error', e.message);
1013 }
1014 return c.redirect(base);
1015 });
1016
1017 app.post('/skills/:handle/:slug/comments', async (c) => {
1018 const user = requireUser(c);
1019 const skill = await loadSkill(c);
1020 const form = await c.req.parseBody();
1021 const base = `/skills/${skill.owner_handle}/${skill.slug}`;
1022 try {
1023 const id = await addComment(c.env, user, skill, String(form.body ?? ''));
1024 setFlash(c, 'ok', 'Comment posted.');
1025 return c.redirect(`${base}#comment-${id}`);
1026 } catch (e) {
1027 if (!(e instanceof HttpError)) throw e;
1028 setFlash(c, 'error', e.message);
1029 return c.redirect(`${base}#comments`);
1030 }
1031 });
1032
1033 app.post('/comments/:id/remove', async (c) => {
1034 const user = requireUser(c);
1035 const form = await c.req.parseBody();
1036 await removeComment(c.env, user, c.req.param('id'));
1037 setFlash(c, 'ok', 'Comment removed.');
1038 return c.redirect(safeNext(String(form.back ?? '/')));
1039 });
1040
1041 app.post('/reviews/:id/remove', async (c) => {
1042 const user = requireUser(c);
1043 const form = await c.req.parseBody();
1044 await removeReview(c.env, user, c.req.param('id'));
1045 setFlash(c, 'ok', 'Review removed.');
1046 return c.redirect(safeNext(String(form.back ?? '/')));
1047 });
1048
1049 app.post('/report', async (c) => {
1050 const user = requireUser(c);
1051 const form = await c.req.parseBody();
1052 try {
1053 await fileReport(c.env, user, String(form.target_type ?? ''), String(form.target_id ?? ''), String(form.reason ?? ''));
1054 setFlash(c, 'ok', 'Thanks. A moderator will look at your report.');
1055 } catch (e) {
1056 if (!(e instanceof HttpError)) throw e;
1057 setFlash(c, 'error', e.message);
1058 }
1059 return c.redirect(safeNext(String(form.back ?? '/')));
1060 });
1061
1062 // Like and unlike. Session cookie plus the same-origin check in the app middleware.
1063 const likeHandler = (on: boolean) => async (c: Ctx) => {
1064 const user = c.get('user');
1065 if (!user) return c.json({ error: 'sign_in', message: 'Sign in to like skills.' }, 401);
1066 const skill = await getSkillCardById(c.env, c.req.param('id')!);
1067 if (!skill || skill.state !== 'live') return c.json({ error: 'not_found', message: 'That skill was not found.' }, 404);
1068 try {
1069 const res = on ? await likeSkill(c.env, user, skill) : await unlikeSkill(c.env, user, skill);
1070 return c.json(res);
1071 } catch (e) {
1072 if (e instanceof HttpError) return c.json({ error: 'refused', message: e.message }, e.status as 400);
1073 throw e;
1074 }
1075 };
1076 app.post('/api/skills/:id/like', likeHandler(true));
1077 app.delete('/api/skills/:id/like', likeHandler(false));
1078}