Branchwell

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

Raw 58.5 KB on 443f4fb7f176dfa237ca639945f31e22fbe94e8c
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, isOurs, 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 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('fork', 18)} Your public repo</span>
109 <input name="repo_url" type="text" inputmode="url" required placeholder="Your public repo's address" 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 </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 && !ownRepo(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 own = ownRepo(skill.github_repo);
302 const source = skill.source_url ?? repoWebUrl(skill.github_repo ?? '', skill.github_path);
303 const host = hostName(source);
304 const maker = skill.maker ?? (skill.github_repo ? repoLabel(skill.github_repo) : null) ?? 'its maker';
305 const platforms = splitPlatforms(skill.platforms);
306 const license = skill.license ?? repo?.license_spdx ?? null;
307 const sends = skill.state === 'live' ? installSendOptions(c.env.SITE_URL, skill, installPlan(c.env.SITE_URL, skill)) : [];
308 const copy = skill.state === 'live' ? multiAgentCopy(skill) : null;
309 const comments = await listComments(c.env, skill.id);
310 const pickBase = `/skills/${skill.owner_handle}/${skill.slug}`;
311 return render(
312 c,
313 { title: `${skill.title} by ${maker}`, description: skill.summary, noindex: skill.state !== 'live', active: 'skills' },
314 <div class="wrap section skill-page pick-page">
315 {skill.state !== 'live' ? <div class="notice notice-info"><strong>{stateLabel(skill.state)}.</strong> This pick is not public.</div> : null}
316 <header class="skill-head">
317 <div class="skill-head-main">
318 <p class="eyebrow">Sprout's pick</p>
319 <h1>{skill.title}</h1>
320 <p class="lede">{skill.summary}</p>
321 <div class="skill-by">
322 {isOurs(skill.maker_url ?? source) ? (
323 <a class="by by-maker" href={skill.maker_url ?? source} rel="noopener">
324 {icon('fork', 26)}
325 <span>
326 Made by <strong>{maker}</strong>
327 </span>
328 </a>
329 ) : (
330 <span class="by by-maker">
331 {icon('fork', 26)}
332 <span>
333 Made by <strong>{maker}</strong>
334 </span>
335 </span>
336 )}
337 </div>
338 <ul class="chips">
339 {categoryName(skill.category) ? <li class="chip-cat"><a href={`/skills?category=${skill.category}`}>{categoryName(skill.category)}</a></li> : null}
340 {platforms.map((p) => <li>{platformName(p)}</li>)}
341 </ul>
342 </div>
343 <aside class="skill-actions card pad">
344 <div class="counts">
345 <LikeButton skill={skill} viewerId={viewer?.id} large />
346 <Stars skill={skill} />
347 </div>
348 <SendToAgent options={sends} block />
349 {isOurs(source) ? <a class="btn btn-ghost btn-block" href={source} rel="noopener">{icon('fork', 18)} Get it on {host}</a> : null}
350 {skill.state === 'live' ? <ShareButton c={c} skill={skill} by={maker} /> : null}
351 {admin ? <a class="btn btn-ghost btn-block" href={`/admin?tab=picks&edit=${skill.id}#pick-form`}>Edit this pick</a> : null}
352 <dl class="facts">
353 <dt>Maker</dt>
354 <dd>{maker}</dd>
355 {own ? (
356 <>
357 <dt>Repo</dt>
358 <dd><a href={repoWebUrl(skill.github_repo!)} rel="noopener">{repoLabel(skill.github_repo!)}</a></dd>
359 </>
360 ) : repo?.unavailable || repo?.archived ? (
361 <>
362 <dt>Repo</dt>
363 <dd>
364 {repo?.unavailable ? <span class="pill pill-rejected">Repo unavailable</span> : null}
365 {repo?.archived ? <span class="pill">Archived</span> : null}
366 </dd>
367 </>
368 ) : null}
369 <dt>License</dt>
370 <dd>{license ?? 'Not stated. Check the repo before you reuse it.'}</dd>
371 {repo?.forks ? (<><dt>Forks</dt><dd>{compactNumber(repo.forks)}</dd></>) : null}
372 {repo?.pushed_at ? (<><dt>Last commit</dt><dd>{dateLabel(Math.floor(Date.parse(repo.pushed_at) / 1000))}</dd></>) : null}
373 </dl>
374 </aside>
375 </header>
376
377 <section class="card pad pick-note">
378 <a class="by" href="/u/sprout">
379 <Avatar user={{ id: skill.owner_id, handle: skill.owner_handle, avatar_key: skill.owner_avatar_key, avatar_fallback: skill.owner_avatar_fallback }} size={44} />
380 <span>
381 <strong>{skill.owner_name}</strong> <em>recommends this</em>
382 </span>
383 </a>
384 <AgentBadge />
385 {skill.pick_note ? <p>{skill.pick_note}</p> : null}
386 <p class="fine">
387 Sprout is the Skillfarm agent. This skill belongs to its maker. {copy ? 'Skillfarm keeps a converted copy for other agents, described below.' : "Skillfarm hosts no copy, so you always install the maker's current version."}{own ? '' : ' Stars are for the whole repo.'}
388 </p>
389 </section>
390
391 {copy ? (
392 <section class="card pad install multi-copy" id="multi-agent">
393 <h2>Multi-agent version</h2>
394 <p class="muted">A copy of this skill, converted by Skillfarm so it reads the same in every major coding agent. The author's text is unchanged.</p>
395 <SendToAgent options={copySendOptions(c.env.SITE_URL, skill, copy)} />
396 <div class="tabset" data-tabset data-agent-tabs>
397 <div class="tabs" role="tablist">
398 {copy.agents.map((a, i) => (
399 <button type="button" role="tab" class={i === 0 ? 'is-active' : ''} aria-selected={i === 0 ? 'true' : 'false'} data-tab={a.agent}>{a.name}</button>
400 ))}
401 </div>
402 {copy.agents.map((a, i) => (
403 <div data-panel={a.agent} hidden={i !== 0}>
404 <p class="where fine">Goes in <code>{a.folder}</code>, for every project on this machine. Run this in your terminal:</p>
405 <Copy text={a.quick!} />
406 <details>
407 <summary>No Node.js? Use git</summary>
408 <Copy text={a.manual.join(' && ')} />
409 </details>
410 <p class="fine">{a.check}</p>
411 </div>
412 ))}
413 </div>
414 <p>
415 {isOurs(copy.url) ? <a href={copy.url} rel="noopener">Read the converted copy</a> : null}
416 </p>
417 </section>
418 ) : null}
419
420 <section class="card pad install">
421 <h2>{copy ? 'Install the original' : 'Install'}</h2>
422 {skill.install_hint ? (
423 <>
424 <p class="muted">
425 From the maker's own instructions. {skill.install_hint.trimStart().startsWith('/') ? 'Type this inside your terminal agent.' : skill.install_hint.trimStart().startsWith('$') ? 'Type this inside your desktop agent.' : 'Run this in your terminal.'} Read the skill first, the same way you would read a script before you run it.
426 </p>
427 <Copy text={skill.install_hint} />
428 </>
429 ) : (
430 <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>
431 )}
432 {isOurs(source) ? (
433 <p>
434 <a href={source} rel="noopener">Open {skill.github_path ? 'the skill folder' : 'the repo'} on {host}</a>
435 </p>
436 ) : null}
437 </section>
438
439 <Comments c={c} skill={skill} comments={comments} base={pickBase} />
440
441 {more.length ? (
442 <section class="section-tight">
443 <div class="section-head">
444 <h2 class="section-title">More in {categoryName(skill.category)}</h2>
445 <a href={`/skills?category=${skill.category}`}>See all</a>
446 </div>
447 <div class="grid grid-3">{more.map((s) => <SkillCard skill={s} viewerId={viewer?.id} />)}</div>
448 </section>
449 ) : null}
450
451 <div class="skill-foot">
452 <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>
453 {viewer ? (
454 <details class="report">
455 <summary>{icon('flag', 15)} Report this pick</summary>
456 <form method="post" action="/report" class="form">
457 <input type="hidden" name="target_type" value="skill" />
458 <input type="hidden" name="target_id" value={skill.id} />
459 <input type="hidden" name="back" value={`/skills/${skill.owner_handle}/${skill.slug}`} />
460 <label>
461 <span>What is wrong?</span>
462 <textarea name="reason" required minlength={10} maxlength={1000} rows={3}></textarea>
463 </label>
464 <button class="btn btn-ghost btn-sm" type="submit">Send report</button>
465 </form>
466 </details>
467 ) : null}
468 </div>
469 </div>,
470 );
471}
472
473export function registerSkills(app: Hono<AppEnv>) {
474 app.get('/skills', async (c) => {
475 const viewer = c.get('user');
476 const q = (c.req.query('q') ?? '').trim().slice(0, 80);
477 const sort = SORTS.some((s) => s.key === c.req.query('sort')) ? c.req.query('sort')! : q ? 'top' : 'trending';
478 const platform = PLATFORMS.some((p) => p.key === c.req.query('platform')) ? c.req.query('platform')! : '';
479 const category = cleanCategory(c.req.query('category')) ?? '';
480 const from = c.req.query('from') === 'sprout' ? 'sprout' : c.req.query('from') === 'growers' ? 'growers' : '';
481 const page = clampInt(c.req.query('page'), 1, 500, 1);
482 const per = 24;
483 const [rows, counts] = await Promise.all([
484 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 }),
485 categoryCounts(c.env),
486 ]);
487 const skills = rows.slice(0, per);
488 refreshStale(c.env, c.executionCtx, skills);
489 const filtered = !!(q || platform || category || from);
490 const qs = (over: Record<string, string>) => {
491 const p = new URLSearchParams();
492 const all = { q, sort, platform, category, from, ...over };
493 for (const [k, val] of Object.entries(all)) if (val) p.set(k, val);
494 return `/skills?${p.toString()}`;
495 };
496 return render(
497 c,
498 {
499 title: q ? `Skills matching "${q}"` : category ? `${categoryName(category)} skills` : from === 'sprout' ? "Sprout's picks" : 'Browse skills',
500 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.',
501 active: 'skills',
502 },
503 <div class="wrap section">
504 <h1>Browse skills</h1>
505 <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>
506 <form method="get" action="/skills" class="search" role="search">
507 {icon('search', 20)}
508 <input type="search" name="q" value={q} placeholder="Search by name, description, grower or repo" aria-label="Search skills" />
509 {platform ? <input type="hidden" name="platform" value={platform} /> : null}
510 {category ? <input type="hidden" name="category" value={category} /> : null}
511 {from ? <input type="hidden" name="from" value={from} /> : null}
512 <input type="hidden" name="sort" value={sort} />
513 <button class="btn btn-primary" type="submit">Search</button>
514 </form>
515 <div class="filters">
516 <div class="tabs" role="group" aria-label="Sort">
517 {SORTS.map((s) => (
518 <a href={qs({ sort: s.key })} class={sort === s.key ? 'is-active' : ''}>{s.label}</a>
519 ))}
520 </div>
521 <ul class="chips chips-link" aria-label="Who it is from">
522 <li><a href={qs({ from: '' })} class={!from ? 'is-active' : ''}>Everything</a></li>
523 <li><a href={qs({ from: 'growers' })} class={from === 'growers' ? 'is-active' : ''}>From growers</a></li>
524 <li><a href={qs({ from: 'sprout' })} class={from === 'sprout' ? 'is-active' : ''}>Sprout's picks</a></li>
525 </ul>
526 </div>
527 <dl class="filter-rows">
528 <dt>Category</dt>
529 <dd>
530 <ul class="chips chips-link" aria-label="Category">
531 <li><a href={qs({ category: '' })} class={!category ? 'is-active' : ''}>All</a></li>
532 {CATEGORIES.filter((cat) => counts[cat.key] || category === cat.key).map((cat) => (
533 <li><a href={qs({ category: cat.key })} class={category === cat.key ? 'is-active' : ''}>{cat.name} <small>{counts[cat.key] ?? 0}</small></a></li>
534 ))}
535 </ul>
536 </dd>
537 <dt>Works with</dt>
538 <dd>
539 <ul class="chips chips-link" aria-label="Platform">
540 <li><a href={qs({ platform: '' })} class={!platform ? 'is-active' : ''}>Any agent</a></li>
541 {PLATFORMS.map((p) => (
542 <li><a href={qs({ platform: p.key })} class={platform === p.key ? 'is-active' : ''}>{p.name}</a></li>
543 ))}
544 </ul>
545 </dd>
546 </dl>
547 {from === 'sprout' ? (
548 <p class="pick-explainer">
549 <a href="/u/sprout">Sprout</a> is the Skillfarm agent. Its picks are skills made by other people. Each one names its maker and their repo, where you install it and get their updates.
550 </p>
551 ) : null}
552 {skills.length ? (
553 <div class="grid grid-3">{skills.map((s) => <SkillCard skill={s} viewerId={viewer?.id} />)}</div>
554 ) : (
555 <Empty title={filtered ? 'Nothing matches that yet' : 'No skills are live yet'} art="empty">
556 <p>{filtered ? 'Try a broader search, or be the one who shares it.' : 'Skillfarm just opened. Yours could be the first.'}</p>
557 <a href="/share" class="btn btn-primary">Share a skill</a>
558 </Empty>
559 )}
560 <Pager page={page} hasMore={rows.length > per} base={qs({})} />
561 </div>,
562 );
563 });
564
565 app.get('/share', async (c) => {
566 const user = c.get('user');
567 if (!user) return c.redirect(`/signin?next=${encodeURIComponent('/share' + new URL(c.req.url).search)}`);
568 let replant: SkillCardRow | null = null;
569 const values: Record<string, string> = {};
570 const rid = c.req.query('replant');
571 if (rid) {
572 replant = await getSkillCardById(c.env, rid);
573 if (!replant || replant.state !== 'live' || replant.kind === 'link') throw new HttpError(404, 'That skill cannot be replanted.');
574 const v = await getVersion(c.env, replant.current_version_id);
575 const md = v ? await readVersionFile(c.env, v, 'SKILL.md') : null;
576 values.skill_md = md ? new TextDecoder().decode(md) : '';
577 values.platforms = replant.platforms;
578 }
579 return render(c, { title: replant ? 'Replant a skill' : 'Share your skills', noindex: true }, <ShareForm c={c} replant={replant} values={values} />);
580 });
581
582 // Members share a repo, never a single file. The one exception is a replant, which starts from someone else's skill.
583 app.post('/share', async (c) => {
584 const user = requireUser(c);
585 const form = await c.req.parseBody({ all: true });
586 const str = (k: string) => (typeof form[k] === 'string' ? (form[k] as string) : '');
587 const platforms = ([] as unknown[]).concat(form.platforms ?? []).filter((x): x is string => typeof x === 'string');
588 const values = { repo_url: str('repo_url') || str('github_url'), skill_md: str('skill_md'), title: str('title'), summary: str('summary'), platforms: platforms.join(',') };
589 let replant: SkillCardRow | null = null;
590 try {
591 if (!str('rights')) throw new HttpError(400, 'Confirm that you have the right to share these skills.');
592 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.');
593 if (str('replant')) {
594 replant = await getSkillCardById(c.env, str('replant'));
595 if (!replant || replant.state !== 'live' || replant.kind === 'link') throw new HttpError(404, 'That skill cannot be replanted.');
596 const md = values.skill_md.replace(/\r\n/g, '\n');
597 if (md.trim().length < 40) throw new HttpError(400, 'Paste the contents of your SKILL.md.');
598 const result = await submitSkill(c.env, c.executionCtx, {
599 user, source: 'web', files: [{ path: 'SKILL.md', data: new TextEncoder().encode(md) }], title: values.title, summary: values.summary, platforms, category: replant.category, replantedFrom: replant,
600 });
601 setFlash(c, 'ok', 'Submitted. It is in the review queue, and you will get an email when it is approved or denied.');
602 return c.redirect(`/skills/${result.ownerHandle}/${result.skill.slug}`);
603 }
604 if (!values.repo_url.trim()) throw new HttpError(400, 'Paste the address of your repo.');
605 const imp = await startRepoShare(c.env, { user, source: 'web', url: values.repo_url, platforms });
606 return c.redirect(`/share/repo/${imp.id}`);
607 } catch (e) {
608 if (!(e instanceof HttpError)) throw e;
609 if (e.code.startsWith('open:')) {
610 setFlash(c, 'ok', e.message);
611 return c.redirect(`/share/repo/${e.code.slice(5)}`);
612 }
613 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);
614 }
615 });
616
617 const loadImport = async (c: Ctx): Promise<{ imp: ImportRow; ownerHandle: string }> => {
618 const user = requireUser(c);
619 const imp = await getImport(c.env, c.req.param('id')!);
620 if (!imp || (imp.user_id !== user.id && !user.is_admin)) throw new HttpError(404, 'That shared repo was not found.');
621 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 }>();
622 return { imp, ownerHandle: owner?.handle ?? '' };
623 };
624
625 app.get('/share/repo/:id', async (c) => {
626 const { imp, ownerHandle } = await loadImport(c);
627 const items = await importItems(c.env, imp.id);
628 return render(c, { title: `Sharing ${imp.repo}`, noindex: true }, <RepoSharePage c={c} imp={imp} items={items} ownerHandle={ownerHandle} />);
629 });
630
631 // Read the next skill of a shared repo. The page calls this until nothing is left; one skill per call keeps every request small.
632 app.post('/share/repo/:id/next', async (c) => {
633 const { imp } = await loadImport(c);
634 const step = imp.status === 'reading' ? await processNextItem(c.env, c.executionCtx, imp.id) : { left: 0, processed: false };
635 if ((c.req.header('accept') ?? '').includes('application/json')) return c.json({ left: step.left, found: imp.found });
636 return c.redirect(`/share/repo/${imp.id}`);
637 });
638
639 app.get('/skills/:handle/:slug', async (c) => {
640 const viewer = c.get('user');
641 const skill = await loadSkill(c);
642 const own = viewer?.id === skill.owner_id;
643 const admin = !!viewer?.is_admin;
644 if (skill.kind === 'link') return pickPage(c, skill);
645 const version = await visibleVersion(c, skill);
646 const latest = own || admin ? await latestVersion(c.env, skill.id) : null;
647 const tab = ['files', 'reviews'].includes(c.req.query('tab') ?? '') ? c.req.query('tab')! : 'readme';
648 const manifest: ManifestEntry[] = version ? JSON.parse(version.manifest) : [];
649 const [mdBytes, reviews, parent, repo, replants] = await Promise.all([
650 version ? readVersionFile(c.env, version, 'SKILL.md') : Promise.resolve(null),
651 c.env.DB.prepare(
652 `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
653 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`,
654 ).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 }>(),
655 skill.replanted_from_skill_id ? getSkillCardById(c.env, skill.replanted_from_skill_id) : Promise.resolve(null),
656 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),
657 c.env.DB.prepare("SELECT COUNT(*) AS n FROM skills WHERE replanted_from_skill_id = ? AND state = 'live'").bind(skill.id).first<{ n: number }>(),
658 ]);
659 const comments = await listComments(c.env, skill.id);
660 refreshStale(c.env, c.executionCtx, [skill]);
661 const md = mdBytes ? new TextDecoder().decode(mdBytes) : '';
662 const body = md ? parseSkillMd(md).body : '';
663 const base = `/skills/${skill.owner_handle}/${skill.slug}`;
664 const site = c.env.SITE_URL;
665 const platforms = splitPlatforms(skill.platforms);
666 const plan = installPlan(site, skill, { fileCount: manifest.length });
667 const sends = skill.state === 'live' ? installSendOptions(site, skill, plan) : [];
668 const myReview = viewer ? reviews.results.find((r) => r.user_id === viewer.id) : null;
669 const rating = skill.reviews_count ? (skill.rating_sum / skill.reviews_count).toFixed(1) : null;
670 const pending = latest && latest.status === 'pending' ? latest : null;
671 const rejected = latest && latest.status === 'rejected' && latest.id !== skill.current_version_id ? latest : null;
672 return render(
673 c,
674 { title: `${skill.title} by ${skill.owner_handle}`, description: skill.summary, noindex: skill.state !== 'live', active: 'skills' },
675 <div class="wrap section skill-page">
676 {skill.state !== 'live' ? (
677 <div class={`notice notice-${skill.state === 'rejected' ? 'error' : 'info'}`}>
678 <strong>{stateLabel(skill.state)}.</strong>{' '}
679 {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.'}
680 </div>
681 ) : null}
682 {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}
683 {rejected ? (
684 <div class="notice notice-error">
685 <strong>Version {rejected.version} was not approved.</strong> {rejected.decision_note ? `Reviewer note: ${rejected.decision_note}` : 'No reviewer note was left.'}
686 </div>
687 ) : null}
688 {(own || admin) && latest && latest.status !== 'approved' && JSON.parse(latest.scan_report).length ? (
689 <details class="card pad scan-box">
690 <summary>What the pattern scan flagged in version {latest.version}</summary>
691 <p class="muted">These are automatic matches for a reviewer to check. Some are false alarms.</p>
692 <FindingsList findings={JSON.parse(latest.scan_report)} />
693 </details>
694 ) : null}
695
696 <header class="skill-head">
697 <div class="skill-head-main">
698 <h1>{skill.title}</h1>
699 <p class="lede">{skill.summary}</p>
700 <div class="skill-by">
701 <a class="by" href={`/u/${skill.owner_handle}`}>
702 <Avatar user={{ id: skill.owner_id, handle: skill.owner_handle, avatar_key: skill.owner_avatar_key, avatar_fallback: skill.owner_avatar_fallback }} size={36} />
703 <span>
704 <strong>{skill.owner_name}</strong> <em>@{skill.owner_handle}</em>
705 </span>
706 </a>
707 <TierBadge seeds={skill.owner_seeds} />
708 {skill.verified_owner ? <span class="pill pill-verified" title={`@${skill.owner_handle}'s account owns ${skill.github_repo}`}>{icon('check', 14)} Verified owner</span> : null}
709 </div>
710 {parent ? (
711 <p class="replant-line">
712 {icon('replant', 17)} Replanted from{' '}
713 {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>
714 </p>
715 ) : null}
716 <ul class="chips">
717 {categoryName(skill.category) ? <li class="chip-cat"><a href={`/skills?category=${skill.category}`}>{categoryName(skill.category)}</a></li> : null}
718 {platforms.map((p) => <li>{platformName(p)}</li>)}
719 </ul>
720 </div>
721 <aside class="skill-actions card pad">
722 <div class="counts">
723 <LikeButton skill={skill} viewerId={viewer?.id} large />
724 <Stars skill={skill} />
725 <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>
726 </div>
727 {skill.state === 'live' ? (
728 <>
729 <SendToAgent options={sends} block />
730 <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>
731 <a class="btn btn-ghost btn-block" href={`/share?replant=${skill.id}`}>{icon('replant', 18)} Replant</a>
732 <ShareButton c={c} skill={skill} by={`@${skill.owner_handle}`} />
733 </>
734 ) : null}
735 {own ? <a class="btn btn-ghost btn-block" href={`${base}/edit`}>Submit a new version</a> : null}
736 {admin && pending ? <a class="btn btn-sun btn-block" href={`/admin/review/${pending.id}`}>Open in review queue</a> : null}
737 <dl class="facts">
738 {version ? (<><dt>Version</dt><dd>{version.version}, {skill.published_at ? `updated ${timeAgo(version.decided_at ?? version.created_at)}` : 'not yet approved'}</dd></>) : null}
739 {(replants?.n ?? 0) > 0 ? (<><dt>Replants</dt><dd>{replants!.n}</dd></>) : null}
740 {rating ? (<><dt>Rating</dt><dd>{rating} of 5 from {plural(skill.reviews_count, 'review')}</dd></>) : null}
741 {skill.github_repo ? (
742 <>
743 <dt>Repo</dt>
744 <dd>
745 {ownRepo(skill.github_repo) ? <a href={repoWebUrl(skill.github_repo, skill.github_path)} rel="noopener">{repoLabel(skill.github_repo)}</a> : <span>{repoLabel(skill.github_repo)}</span>}
746 {repo?.unavailable ? <span class="pill pill-rejected">Repo unavailable</span> : null}
747 {repo?.archived ? <span class="pill">Archived</span> : null}
748 </dd>
749 {repo ? (<><dt>Forks</dt><dd>{compactNumber(repo.forks)}</dd></>) : null}
750 {repo?.pushed_at ? (<><dt>Last commit</dt><dd>{dateLabel(Math.floor(Date.parse(repo.pushed_at) / 1000))}</dd></>) : null}
751 {repo?.license_spdx ? (<><dt>License</dt><dd>{repo.license_spdx}</dd></>) : null}
752 </>
753 ) : null}
754 </dl>
755 </aside>
756 </header>
757
758 {skill.state === 'live' ? (
759 <section class="card pad install" id="install">
760 <h2>Install</h2>
761 <p class="muted">
762 {plan.source === 'github'
763 ? <>This skill installs straight from its public repo, {isOurs(plan.repo_url) ? <a href={plan.repo_url!} rel="noopener">{plan.repo}</a> : plan.repo}. Read the files first.</>
764 : 'Read the files first. This copies the reviewed files into your agent\'s skills folder.'}
765 </p>
766 <div class="tabset" data-tabset data-agent-tabs>
767 <div class="tabs" role="tablist">
768 {plan.agents.map((a, i) => (
769 <button type="button" role="tab" class={i === 0 ? 'is-active' : ''} aria-selected={i === 0 ? 'true' : 'false'} data-tab={a.agent}>{a.name}</button>
770 ))}
771 </div>
772 {plan.agents.map((a, i) => (
773 <div data-panel={a.agent} hidden={i !== 0}>
774 <p class="where fine">Goes in <code>{a.folder}</code>, for every project on this machine. Run this in your terminal:</p>
775 {a.quick ? <Copy text={a.quick} /> : null}
776 {plan.source === 'github' ? (
777 <>
778 <details>
779 <summary>No Node.js? Use git</summary>
780 <Copy text={a.manual.join(' && ')} />
781 </details>
782 {a.reviewed_copy ? (
783 <details>
784 <summary>Get exactly the reviewed files from Skillfarm</summary>
785 <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>
786 <Copy text={a.reviewed_copy} />
787 </details>
788 ) : null}
789 </>
790 ) : null}
791 <p class="fine">{a.check}</p>
792 </div>
793 ))}
794 </div>
795 <p class="fine">New to this? <a href="/help">Help</a> has setup prompts and answers.</p>
796 </section>
797 ) : null}
798
799 <div class="tabs page-tabs">
800 <a href={base} class={tab === 'readme' ? 'is-active' : ''}>SKILL.md</a>
801 <a href={`${base}?tab=files`} class={tab === 'files' ? 'is-active' : ''}>Files ({manifest.length})</a>
802 <a href={`${base}?tab=reviews`} class={tab === 'reviews' ? 'is-active' : ''}>Reviews ({skill.reviews_count})</a>
803 </div>
804
805 {tab === 'readme' ? (
806 <article class="card pad markdown">{body ? raw(renderMarkdown(body)) : <p class="muted">This skill has no readable SKILL.md.</p>}</article>
807 ) : null}
808
809 {tab === 'files' ? (
810 <ul class="card file-list">
811 {manifest.map((m) => (
812 <li>
813 {icon('file', 18)}
814 <a href={`${base}/file/${m.path.split('/').map(encodeURIComponent).join('/')}`}>{m.path}</a>
815 <span class="muted">{m.size < 1024 ? `${m.size} B` : `${(m.size / 1024).toFixed(1)} KB`}</span>
816 </li>
817 ))}
818 </ul>
819 ) : null}
820
821 {tab === 'reviews' ? (
822 <section class="reviews">
823 {viewer && !own && !myReview && skill.state === 'live' ? (
824 <form method="post" action={`${base}/reviews`} class="form card pad">
825 <h2>Write a review</h2>
826 <p class="muted">Tried it? Say how it went. A review earns you {SEEDS.review} Seeds.</p>
827 <fieldset class="rating">
828 <legend>Rating</legend>
829 {[1, 2, 3, 4, 5].map((n) => (
830 <label>
831 <input type="radio" name="rating" value={n} required checked={n === 5} />
832 <span>{n}</span>
833 </label>
834 ))}
835 </fieldset>
836 <label>
837 <span>Your review</span>
838 <textarea name="body" rows={4} required minlength={40} maxlength={2000}></textarea>
839 </label>
840 <button class="btn btn-primary" type="submit">Post review</button>
841 </form>
842 ) : null}
843 {!viewer ? <p><a href={`/signin?next=${encodeURIComponent(base + '?tab=reviews')}`}>Sign in</a> to review this skill.</p> : null}
844 {reviews.results.length ? (
845 <ul class="review-list">
846 {reviews.results.map((r) => (
847 <li class="card pad">
848 <div class="review-head">
849 <a class="by" href={`/u/${r.handle}`}>
850 <Avatar user={{ id: r.user_id, handle: r.handle, avatar_key: r.avatar_key, avatar_fallback: r.avatar_fallback }} size={32} />
851 <span><strong>{r.display_name}</strong> <em>@{r.handle}</em></span>
852 </a>
853 <span class="rating-val" aria-label={`${r.rating} out of 5`}>{'●'.repeat(r.rating)}{'○'.repeat(5 - r.rating)}</span>
854 <time>{timeAgo(r.created_at)}</time>
855 </div>
856 <p>{r.body}</p>
857 {viewer && (viewer.id === r.user_id || admin) ? (
858 <form method="post" action={`/reviews/${r.id}/remove`}>
859 <input type="hidden" name="back" value={`${base}?tab=reviews`} />
860 <button class="link-btn" type="submit">Remove review</button>
861 </form>
862 ) : null}
863 </li>
864 ))}
865 </ul>
866 ) : (
867 <Empty title="No reviews yet" art="tend"><p>Be the first to say how this skill worked for you.</p></Empty>
868 )}
869 </section>
870 ) : null}
871
872 <Comments c={c} skill={skill} comments={comments} base={base} />
873
874 <div class="skill-foot">
875 {viewer && !own ? (
876 <details class="report">
877 <summary>{icon('flag', 15)} Report this skill</summary>
878 <form method="post" action="/report" class="form">
879 <input type="hidden" name="target_type" value="skill" />
880 <input type="hidden" name="target_id" value={skill.id} />
881 <input type="hidden" name="back" value={base} />
882 <label>
883 <span>What is wrong?</span>
884 <textarea name="reason" required minlength={10} maxlength={1000} rows={3}></textarea>
885 </label>
886 <button class="btn btn-ghost btn-sm" type="submit">Send report</button>
887 </form>
888 </details>
889 ) : null}
890 {own ? (
891 <details class="report">
892 <summary>Remove this skill</summary>
893 <form method="post" action={`${base}/remove`} class="form">
894 <p class="muted">This takes the skill down and reverses the Seeds it earned. It cannot be undone.</p>
895 <button class="btn btn-danger btn-sm" type="submit">Remove skill</button>
896 </form>
897 </details>
898 ) : null}
899 </div>
900 </div>,
901 );
902 });
903
904 app.get('/skills/:handle/:slug/file/*', async (c) => {
905 const skill = await loadSkill(c);
906 const version = await visibleVersion(c, skill, c.req.query('v') === 'latest');
907 const base = `/skills/${skill.owner_handle}/${skill.slug}`;
908 const path = decodeURIComponent(new URL(c.req.url).pathname.slice(new URL(c.req.url).pathname.indexOf('/file/') + 6));
909 const data = version ? await readVersionFile(c.env, version, path) : null;
910 if (!data) throw new HttpError(404, 'That file was not found.');
911 const text = new TextDecoder().decode(data);
912 return render(
913 c,
914 { title: `${path} in ${skill.title}`, noindex: true, active: 'skills' },
915 <div class="wrap section">
916 <p class="crumbs"><a href={base}>{skill.title}</a> / <a href={`${base}?tab=files`}>Files</a> / {path}</p>
917 <h1 class="file-title">{path}</h1>
918 <pre class="card code-view"><code>{text}</code></pre>
919 </div>,
920 );
921 });
922
923 app.get('/skills/:handle/:slug/download', async (c) => {
924 const viewer = c.get('user');
925 const skill = await loadSkill(c);
926 const version = await getVersion(c.env, skill.current_version_id);
927 if (!version || skill.state !== 'live') throw new HttpError(404, 'This skill is not available to download.');
928 const ip = c.req.header('cf-connecting-ip') ?? 'local';
929 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.');
930 const files = await readVersionFiles(c.env, version);
931 c.executionCtx.waitUntil(recordInstall(c.env, skill, viewer, ip, c.req.header('user-agent') ?? '').catch((e) => console.error('install count failed', e)));
932 const headers: Record<string, string> = { 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' };
933 if (files.length === 1) {
934 return new Response(files[0].data, { headers: { ...headers, 'content-type': 'text/markdown; charset=utf-8', 'content-disposition': 'attachment; filename="SKILL.md"' } });
935 }
936 return new Response(makeZip(files), { headers: { ...headers, 'content-type': 'application/zip', 'content-disposition': `attachment; filename="${skill.slug}.zip"` } });
937 });
938
939 app.get('/skills/:handle/:slug/edit', async (c) => {
940 const user = c.get('user');
941 const skill = await loadSkill(c);
942 if (!user || user.id !== skill.owner_id || skill.kind === 'link') throw new HttpError(403, 'Only the owner can update this skill.');
943 const v = await latestVersion(c.env, skill.id);
944 const md = v ? await readVersionFile(c.env, v, 'SKILL.md') : null;
945 const base = `/skills/${skill.owner_handle}/${skill.slug}`;
946 return render(
947 c,
948 { title: `Update ${skill.title}`, noindex: true },
949 <div class="wrap section share-page">
950 <p class="crumbs"><a href={base}>{skill.title}</a> / New version</p>
951 <h1>Submit a new version</h1>
952 <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>
953 <form method="post" action={`${base}/edit`} class="form card pad">
954 {skill.github_repo ? (
955 <>
956 <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>
957 <input type="hidden" name="mode" value="github" />
958 </>
959 ) : (
960 <>
961 <input type="hidden" name="mode" value="paste" />
962 <label>
963 <span>SKILL.md</span>
964 <textarea name="skill_md" rows={20} class="mono" spellcheck={false} required>{md ? new TextDecoder().decode(md) : ''}</textarea>
965 </label>
966 </>
967 )}
968 <fieldset class="checks">
969 <legend>Works with</legend>
970 {PLATFORMS.map((p) => (
971 <label>
972 <input type="checkbox" name="platforms" value={p.key} checked={splitPlatforms(skill.platforms).includes(p.key)} />
973 <span>{p.name}</span>
974 </label>
975 ))}
976 </fieldset>
977 <button class="btn btn-primary" type="submit">{skill.github_repo ? 'Pull the latest from the repo and submit' : 'Submit for review'}</button>
978 </form>
979 </div>,
980 );
981 });
982
983 app.post('/skills/:handle/:slug/edit', async (c) => {
984 const user = requireUser(c);
985 const skill = await loadSkill(c);
986 if (user.id !== skill.owner_id) throw new HttpError(403, 'Only the owner can update this skill.');
987 const base = `/skills/${skill.owner_handle}/${skill.slug}`;
988 const form = await c.req.parseBody({ all: true });
989 const platforms = ([] as unknown[]).concat(form.platforms ?? []).filter((x): x is string => typeof x === 'string');
990 try {
991 if (skill.github_repo) {
992 const [owner, repo] = skill.github_repo.split('/');
993 const imp = await importFromGithub(c.env, { owner, repo, path: skill.github_path ?? '' });
994 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 } });
995 } else {
996 const md = String(form.skill_md ?? '').replace(/\r\n/g, '\n');
997 await submitSkill(c.env, c.executionCtx, { user, source: 'web', files: [{ path: 'SKILL.md', data: new TextEncoder().encode(md) }], platforms, existing: skill });
998 }
999 setFlash(c, 'ok', 'New version submitted for review.');
1000 } catch (e) {
1001 if (!(e instanceof HttpError)) throw e;
1002 setFlash(c, 'error', e.message);
1003 return c.redirect(`${base}/edit`);
1004 }
1005 return c.redirect(base);
1006 });
1007
1008 app.post('/skills/:handle/:slug/remove', async (c) => {
1009 const user = requireUser(c);
1010 const skill = await loadSkill(c);
1011 await setSkillState(c.env, user, skill, 'removed');
1012 setFlash(c, 'ok', `"${skill.title}" was removed.`);
1013 return c.redirect(`/u/${user.handle}`);
1014 });
1015
1016 app.post('/skills/:handle/:slug/reviews', async (c) => {
1017 const user = requireUser(c);
1018 const skill = await loadSkill(c);
1019 const form = await c.req.parseBody();
1020 const base = `/skills/${skill.owner_handle}/${skill.slug}?tab=reviews`;
1021 try {
1022 await addReview(c.env, user, skill, parseInt(String(form.rating ?? ''), 10), String(form.body ?? ''));
1023 setFlash(c, 'ok', `Review posted. You earned ${SEEDS.review} Seeds.`);
1024 } catch (e) {
1025 if (!(e instanceof HttpError)) throw e;
1026 setFlash(c, 'error', e.message);
1027 }
1028 return c.redirect(base);
1029 });
1030
1031 app.post('/skills/:handle/:slug/comments', async (c) => {
1032 const user = requireUser(c);
1033 const skill = await loadSkill(c);
1034 const form = await c.req.parseBody();
1035 const base = `/skills/${skill.owner_handle}/${skill.slug}`;
1036 try {
1037 const id = await addComment(c.env, user, skill, String(form.body ?? ''));
1038 setFlash(c, 'ok', 'Comment posted.');
1039 return c.redirect(`${base}#comment-${id}`);
1040 } catch (e) {
1041 if (!(e instanceof HttpError)) throw e;
1042 setFlash(c, 'error', e.message);
1043 return c.redirect(`${base}#comments`);
1044 }
1045 });
1046
1047 app.post('/comments/:id/remove', async (c) => {
1048 const user = requireUser(c);
1049 const form = await c.req.parseBody();
1050 await removeComment(c.env, user, c.req.param('id'));
1051 setFlash(c, 'ok', 'Comment removed.');
1052 return c.redirect(safeNext(String(form.back ?? '/')));
1053 });
1054
1055 app.post('/reviews/:id/remove', async (c) => {
1056 const user = requireUser(c);
1057 const form = await c.req.parseBody();
1058 await removeReview(c.env, user, c.req.param('id'));
1059 setFlash(c, 'ok', 'Review removed.');
1060 return c.redirect(safeNext(String(form.back ?? '/')));
1061 });
1062
1063 app.post('/report', async (c) => {
1064 const user = requireUser(c);
1065 const form = await c.req.parseBody();
1066 try {
1067 await fileReport(c.env, user, String(form.target_type ?? ''), String(form.target_id ?? ''), String(form.reason ?? ''));
1068 setFlash(c, 'ok', 'Thanks. A moderator will look at your report.');
1069 } catch (e) {
1070 if (!(e instanceof HttpError)) throw e;
1071 setFlash(c, 'error', e.message);
1072 }
1073 return c.redirect(safeNext(String(form.back ?? '/')));
1074 });
1075
1076 // Like and unlike. Session cookie plus the same-origin check in the app middleware.
1077 const likeHandler = (on: boolean) => async (c: Ctx) => {
1078 const user = c.get('user');
1079 if (!user) return c.json({ error: 'sign_in', message: 'Sign in to like skills.' }, 401);
1080 const skill = await getSkillCardById(c.env, c.req.param('id')!);
1081 if (!skill || skill.state !== 'live') return c.json({ error: 'not_found', message: 'That skill was not found.' }, 404);
1082 try {
1083 const res = on ? await likeSkill(c.env, user, skill) : await unlikeSkill(c.env, user, skill);
1084 return c.json(res);
1085 } catch (e) {
1086 if (e instanceof HttpError) return c.json({ error: 'refused', message: e.message }, e.status as 400);
1087 throw e;
1088 }
1089 };
1090 app.post('/api/skills/:id/like', likeHandler(true));
1091 app.delete('/api/skills/:id/like', likeHandler(false));
1092}