Branchwell

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

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