Branchwell

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

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