Restore PROMPT branding, rename waterfall-wiki, and add system tag workflows
waterfall-wiki CI and deployment / verify-and-deploy (push) Has been cancelled
studio CI and deployment / verify-and-deploy (push) Successful in 9m15s

This commit is contained in:
2026-10-27 00:35:59 +08:00
parent 0c1ed2d292
commit ad398db781
178 changed files with 585 additions and 365 deletions
@@ -0,0 +1,46 @@
import Head from 'next/head';
import Link from 'next/link';
import {useEffect,useRef,useState} from 'react';
import {useRouter} from 'next/router';
import {X,ChevronLeft,ChevronRight,Link as LinkIcon,FileText,Pencil} from 'lucide-react';
import type {ExploreEntry} from '@/lib/explore';
import {previewUrl,exploreUrl} from '@/content/page-links';
import {Shell} from './Shell';
import {ExploreFeed} from './ExploreFeed';
import {NoteMarkdown} from './NoteMarkdown';
import {QuickTags} from './QuickTags';
import {NoteEditor} from './NoteEditor';
export function ExploreDetail({entry:initial,background}:{entry:ExploreEntry;background:ExploreEntry[]}){
const [entry,setEntry]=useState(initial),[index,setIndex]=useState(0),[copied,setCopied]=useState(''),[editing,setEditing]=useState(false),[copyError,setCopyError]=useState('');
const router=useRouter();const closeRef=useRef<HTMLButtonElement>(null),detailRef=useRef<HTMLDivElement>(null);const media=entry.media[index];
useEffect(()=>{setEntry(initial);setIndex(0);setCopied('');setEditing(false)},[initial]);
const close=()=>{if(editing){setEditing(false);return;}void router.push('/')};
useEffect(()=>{
const previous=document.activeElement as HTMLElement|null;if(!editing)closeRef.current?.focus();const old=document.body.style.overflow;document.body.style.overflow='hidden';
function key(e:KeyboardEvent){
if(e.key==='Escape'){e.preventDefault();close();return;}
const typing=e.target instanceof HTMLElement&&!!e.target.closest('input,textarea,select,[contenteditable="true"]');
if(!editing&&!typing&&e.key==='ArrowLeft')setIndex(n=>Math.max(0,n-1));
if(!editing&&!typing&&e.key==='ArrowRight')setIndex(n=>Math.max(0,Math.min(entry.media.length-1,n+1)));
if(e.key==='Tab'){const items=Array.from(detailRef.current?.querySelectorAll<HTMLElement>('a[href],button:not(:disabled),input:not(:disabled),textarea:not(:disabled),select:not(:disabled),summary,video,audio')||[]).filter(el=>el.getClientRects().length);if(!items.length)return;const first=items[0],last=items[items.length-1];if(e.shiftKey&&document.activeElement===first){e.preventDefault();last.focus()}else if(!e.shiftKey&&document.activeElement===last){e.preventDefault();first.focus()}}
}
window.addEventListener('keydown',key);return()=>{document.body.style.overflow=old;window.removeEventListener('keydown',key);previous?.focus()};
},[entry.id,editing]);
async function copy(mode:'web'|'agent'){
try{const url=window.location.origin+exploreUrl(entry.id)+(mode==='agent'?'?agent_mode=True':'');
if(navigator.clipboard)await navigator.clipboard.writeText(url);else{const input=document.createElement('textarea');input.value=url;document.body.appendChild(input);input.select();const success=document.execCommand('copy');input.remove();if(!success)throw Error('Copy failed');}
setCopied(mode);setCopyError('');
}catch{setCopied('');setCopyError('复制失败,请重试。')}
}
return <Shell><Head><title>{entry.title} · PROMPT</title><link rel="canonical" href={exploreUrl(entry.id)}/><link rel="alternate" type="text/plain" href={exploreUrl(entry.id)+'?agent_mode=True'}/></Head>
<div aria-hidden="true" inert><ExploreFeed key={entry.revision} initial={background.map(e=>e.id===entry.id?entry:e)}/></div>
<div className="note-overlay" onClick={()=>{if(!editing)close()}}><div className="note-dialog" ref={detailRef} role="dialog" aria-modal="true" aria-labelledby="note-title" onClick={e=>e.stopPropagation()}>
<button className="note-close" ref={closeRef} aria-label={editing?'取消编辑':'关闭详情'} onClick={close}><X/></button>
<section className={'note-stage '+(!media?'note-text-stage':'')}>
{media?.kind==='image'?<img key={media.url} src={previewUrl(media.url,1280)} alt={media.title} decoding="async"/>:media?.kind==='video'?<video controls playsInline preload="metadata" src={media.url} poster={media.poster?previewUrl(media.poster,960):undefined}/>:media?.kind==='audio'?<div className="note-audio"><span>♫</span><audio controls preload="metadata" src={media.url}/></div>:<div className="note-title-cover" style={{background:entry.color}}><small>{entry.namespace}</small><strong>{entry.title}</strong><span>灵感笔记</span></div>}
{entry.media.length>1&&<><button className="note-prev" aria-label="上一张" disabled={index===0} onClick={()=>setIndex(n=>n-1)}><ChevronLeft/></button><button className="note-next" aria-label="下一张" disabled={index===entry.media.length-1} onClick={()=>setIndex(n=>n+1)}><ChevronRight/></button><div className="note-dots">{entry.media.map((_,i)=><button key={i} className={i===index?'selected':''} aria-label={'查看第 '+(i+1)+' 张'} aria-pressed={i===index} onClick={()=>setIndex(i)}/>)}</div><span className="note-count">{index+1} / {entry.media.length}</span></>}
</section><section className="note-info"><div className="note-content">
{editing?<NoteEditor key={entry.id} entry={entry} onCancel={()=>setEditing(false)} onSaved={updated=>{setEntry(updated);setEditing(false);setCopied('')}}/>:<><h1 id="note-title">{entry.title}</h1><p className="note-description">{entry.description}</p><div className="note-tags">{entry.systemTags?.map(t=><Link className="system-tag-pill" key={t.id} href={"/categories?category="+encodeURIComponent(t.name)}>{t.name}</Link>)}{entry.categories.map(c=><Link key={c} href={'/categories?category='+encodeURIComponent(c)}>#{c} </Link>)}<QuickTags entry={entry} onSaved={setEntry}/></div><NoteMarkdown text={entry.markdown.replace(/^# [^\n]*(?:\n|$)\n?/,'')}/><section id="backlinks" className="note-backlinks"><h2>被 {entry.backlinkCount??0} 篇笔记引用</h2>{entry.backlinks?.length?<ul>{entry.backlinks.map(ref=><li key={ref.id}><Link href={exploreUrl(ref.id)}>{ref.title}</Link></li>)}</ul>:<p>还没有笔记引用本文。</p>}</section><div className="note-id">内容 ID · {entry.id}</div></>}
</div>{!editing&&<footer><button onClick={()=>void copy('web')}><LinkIcon size={18}/>{copied==='web'?'网页链接已复制':'复制网页链接'}</button><button onClick={()=>void copy('agent')}><FileText size={18}/>{copied==='agent'?'纯文本链接已复制':'复制纯文本链接'}</button><button onClick={()=>setEditing(true)}><Pencil size={17}/>编辑</button>{copyError&&<span role="status">{copyError}</span>}</footer>}</section>
</div></div></Shell>;
}
@@ -0,0 +1,18 @@
import Link from 'next/link';
import {useState} from 'react';
import {Images,Link2} from 'lucide-react';
import type {ExploreEntry} from '@/lib/explore';
import {QuickTags} from './QuickTags';
import {exploreUrl,previewUrl} from '@/content/page-links';
export function ExploreFeed({initial,cursor:initialCursor=null,q='',category='',total}:{initial:ExploreEntry[];cursor?:string|null;q?:string;category?:string;total?:number}){
const [entries,setEntries]=useState(initial);const [cursor,setCursor]=useState(initialCursor);const [busy,setBusy]=useState(false);const [error,setError]=useState('');
async function more(){setBusy(true);try{const res=await fetch('/api/explore-feed?'+new URLSearchParams({q,category,cursor:cursor||''}));if(!res.ok)throw Error();const data=await res.json();setEntries(old=>[...old,...data.entries.filter((e:ExploreEntry)=>!old.some(o=>o.id===e.id))]);setCursor(data.nextCursor);setError('');}catch{setError('加载失败,点击重试')}finally{setBusy(false)}}
return <>{q&&<div className="search-results-heading" role="status">搜索「{q}」{total!==undefined?` · ${total} 篇`:""}<span>按匹配程度、被引用数排序</span></div>}<div className="discovery-grid">{entries.map((entry,i)=><article key={entry.id} className="discovery-card">
<Link href={exploreUrl(entry.id)} className="discovery-note-link"><div className="discovery-cover" style={{background:entry.color,aspectRatio:'4 / 5'}}>
{entry.media[0]?<img src={previewUrl(entry.media[0].poster||entry.media[0].url,480)} alt={entry.media[0].title} loading={i<4?'eager':'lazy'} decoding="async"/>:<><small>{entry.namespace.toUpperCase()}</small><strong>{entry.title}</strong><span>记录 · 连接 · 灵感</span></>}
{!!entry.systemTags?.length&&<span className="discovery-system-tags">{entry.systemTags.map(t=><span key={t.id}>{t.name}</span>)}</span>}
{entry.imageCount>1&&<span className="discovery-image-count" aria-label={`${entry.imageCount} 张图片`}><Images size={13}/>{entry.imageCount}</span>}
</div><h2>{entry.title}</h2>{q&&entry.searchExcerpt&&<p className="search-excerpt">{entry.searchExcerpt}</p>}</Link>
<div className="discovery-card-meta"><div className="discovery-tags" aria-label="普通标签">{entry.categories.slice(0,2).map(tag=><Link key={tag} href={'/categories?category='+encodeURIComponent(tag)}>#{tag}</Link>)}{entry.categories.length>2&&<span title={entry.categories.map(t=>'#'+t).join(' ')}>+{entry.categories.length-2}</span>}</div><Link className="backlink-count" href={exploreUrl(entry.id)+"#backlinks"} aria-label={`被 ${entry.backlinkCount??0} 篇笔记引用`}><Link2 size={14}/><span>{entry.backlinkCount??0}</span></Link><QuickTags entry={entry} onSaved={updated=>setEntries(old=>old.map(e=>e.id===entry.id?updated:e).filter(e=>!category||e.categories.includes(category)||e.systemTags?.some(t=>t.name===category||t.system_key===category)||e.namespace===category))}/></div>
</article>)}</div>{!entries.length&&<p className="discovery-empty">{q?'没有匹配的内容,试试更短的关键词。':'这个分类还没有内容。'}</p>}{cursor&&<div className="load-more"><button disabled={busy} onClick={more}>{busy?'加载中…':error||'再看一些'}</button></div>}</>;
}
@@ -0,0 +1,42 @@
import {previewUrl} from '@/content/page-links';
import {SkillCard} from "./SkillCard";
import {skillCatalog} from "@/content/skills/catalog";
import Head from "next/head";
import Link from "next/link";
import { useEffect,useRef,useState } from "react";
import { useRouter } from "next/router";
import { Search,Image as ImageIcon,ArrowUpRight,AudioLines,Film,Layers,ArrowDown,Upload } from "lucide-react";
import { Shell } from "./Shell";
import { sections,mediaUrl,type FeedData,type Post } from "@/lib/model";
export function PostCard({post}:{post:Post}){
const image=post.assets.find(a=>a.kind==='image');const video=post.assets.find(a=>a.kind==='video');const cover=post.cover_asset_id||image?.id;
const label=sections.find(s=>s.kind===post.kind)?.name;const count=post.assets.filter(a=>a.kind!=='text').length;
const source=cover?mediaUrl(cover):video?.variants.includes('poster')?mediaUrl(video.id,'poster'):null;
return <Link className="post-card" href={`/explore/${post.id}`}><div className={`post-cover cover-${post.kind}`} style={image?.width&&image?.height?{aspectRatio:`${image.width}/${image.height}`,maxHeight:460}:undefined}>
{source?<img src={previewUrl(source,480)} alt={post.title} loading="lazy"/>:post.kind==='audio'?<div className="waveform">{Array.from({length:36},(_,i)=><i key={i} style={{height:12+((i*31)%65)}}/>)}</div>:<div className="cover-symbol">{post.kind==='video'?<Film size={42}/>:<Layers size={42}/>}<span>{label}</span></div>}
{count>1&&<span className="cover-count"><Layers size={12}/>{count}</span>}{video&&<span className="cover-badge">{video.has_audio?'有声音':'无声音'}</span>}
</div><h3 title={post.title}>{post.title}</h3><div className="post-meta"><span><i className={`type-dot ${post.kind}`}/>{label}</span><time>{new Date(post.created_at).toLocaleDateString('zh-CN',{month:'2-digit',day:'2-digit',timeZone:'Asia/Shanghai'})}</time></div></Link>;
}
function Masonry({posts,includeSkills=false,q=""}:{posts:Post[];includeSkills?:boolean;q?:string}){
const element=useRef<HTMLDivElement>(null);const [width,setWidth]=useState(1100);
useEffect(()=>{if(!element.current)return;const observer=new ResizeObserver(entries=>setWidth(entries[0].contentRect.width));observer.observe(element.current);return ()=>observer.disconnect();},[]);
const count=width>1250?5:width>1000?4:width>720?3:2;
type Item={post?:Post;skill?:typeof skillCatalog[number];date:string};const columns:Item[][]=Array.from({length:count},()=>[]);const items:Item[]=[...posts.map(post=>({post,date:post.created_at})),...(includeSkills?skillCatalog.filter(s=>(s.title+s.description+s.category).toLowerCase().includes(q.toLowerCase())).map(skill=>({skill,date:skill.created_at})):[])].sort((a,b)=>b.date.localeCompare(a.date));const heights=Array(count).fill(0);const cardWidth=(width-(width<=720?14:20)*(count-1))/count;
for(const item of items){const image=item.post?.assets.find(a=>a.kind==='image');const ratio=item.skill?1.25:image?.width&&image.height?image.height/image.width:item.post?.kind==='audio'?1:1.25;const index=heights.indexOf(Math.min(...heights));columns[index].push(item);heights[index]+=Math.min(cardWidth*ratio,item.skill?440:460)+78;}
return <div ref={element} className="masonry" style={{gridTemplateColumns:`repeat(${count}, minmax(0,1fr))`}}>{columns.map((items,i)=><div className="masonry-column" key={i}>{items.map(item=>item.skill?<SkillCard skill={item.skill} key={item.skill.id}/>:<PostCard post={item.post!} key={item.post!.id}/>)}</div>)}</div>;
}
export function Feed({initial,section='',tagPath=''}:{initial:FeedData;section?:string;tagPath?:string}){
const router=useRouter();const [posts,setPosts]=useState(initial.posts);const [cursor,setCursor]=useState(initial.nextCursor);const [busy,setBusy]=useState(false);const [error,setError]=useState('');const generation=useRef(0);
useEffect(()=>{generation.current++;setPosts(initial.posts);setCursor(initial.nextCursor);setError('');setBusy(false);},[initial,router.query.q]);
const current=sections.find(s=>s.path===section);const target=initial.tags.find(t=>t.path===tagPath);const children=initial.tags;
async function load(){const gen=generation.current;setBusy(true);setError('');try{const q=new URLSearchParams({section,path:tagPath,cursor:cursor||'',q:String(router.query.q||'')});const res=await fetch('/api/feed?'+q);const d=await res.json();if(!res.ok)throw new Error(d.error);if(gen===generation.current){setPosts(old=>[...old,...d.posts.filter((p:Post)=>!old.some(a=>a.id===p.id))]);setCursor(d.nextCursor);}}catch{if(gen===generation.current)setError('加载没有完成,点击重试。');}finally{if(gen===generation.current)setBusy(false);}}
return <Shell><Head><title>{target?.name||current?.name||'灵感首页'} · PROMPT</title><meta name="description" content="自己的图文、视频与声音创作空间"/><link rel="alternate" type="text/markdown" href="/index.md" title="Agent 文档入口"/></Head>
{current&&<header className="page-header feed-heading"><div><h1>{target?.name||current.name}</h1><p>{current.hint}</p></div></header>}
{tagPath&&<div className="breadcrumbs"><Link href={`/${section}`}>全部{current?.name}</Link>{tagPath.split('/').map((_,i)=>{const path=tagPath.split('/').slice(0,i+1).join('/');return <span key={path}> / <Link href={`/${section}/${path}`}>{initial.tags.find(t=>t.path===path)?.name}</Link></span>;})}</div>}
<div className="feed-toolbar"><div className="feed-tabs">{!section?<><Link className="selected" href="/">全部</Link>{sections.map(s=><Link key={s.path} href={`/${s.path}`}>{s.name}</Link>)}</>:<><Link className={!tagPath?'selected':''} href={`/${section}`}>全部</Link>{children.map(t=><Link key={t.id} href={`/${section}/${t.path}`}>{t.name}</Link>)}</>}</div><span className="sort-label"><ArrowDown size={13}/>最近收录</span></div>
{initial.unavailable?<div className="empty-state"><Layers/><h2>素材库暂时没有连接上</h2><p>请稍后刷新,已保存的内容不会因此丢失。</p></div>:(posts.length||(!section&&skillCatalog.some(s=>(s.title+s.description+s.category).toLowerCase().includes(String(router.query.q||'').toLowerCase()))))?<Masonry posts={posts} includeSkills={!section} q={String(router.query.q||'')}/>:<div className="empty-state"><div className="empty-art"><span/><ImageIcon size={42} strokeWidth={1.2}/><i><AudioLines size={18}/></i><b><Film size={19}/></b></div><span className="eyebrow">A LITTLE SPACE FOR SOMETHING GOOD</span><h2>{router.query.q?'还没有找到这份灵感':'这里还没有内容'}</h2><p>{router.query.q?'换一个词试试看。':'导入图片、视频或声音,开始整理你的素材。'}</p><Link className="primary-button" href={`/library/import${current&&['image','video','audio'].includes(current.kind)?'?kind='+current.kind:''}`}><Upload size={16}/>导入素材<ArrowUpRight size={16}/></Link><small>图文和动态作品通过代码加入,自由决定每一个像素。</small></div>}
{cursor&&<div className="load-more"><button disabled={busy} onClick={load}>{busy?'正在翻找…':error||'再看一些'}<ArrowDown size={14}/></button></div>}
<footer className="page-footer">PROMPT <span>·</span> PROBABLY RENDERING ONE MORE PIXEL TONIGHT</footer>
</Shell>;
}
@@ -0,0 +1,12 @@
import Head from 'next/head';
import Link from 'next/link';
import {Shell} from './Shell';
import {SkillCard} from './SkillCard';
import {skillCatalog} from '@/content/skills/catalog';
import {guidanceDocuments,humanDocumentUrl} from '@/content/skills/guidance';
export function GuidanceIndex(){return <Shell><Head><title>指导文档 · PROMPT</title><link rel="canonical" href="/skills"/><link rel="alternate" type="text/markdown" href="/skills/index.md" title="指导文档"/></Head>
<header className="page-header"><div><h1>指导文档</h1><p>每篇都有独立地址,网页与 Markdown 一一对应。沿着引用,找到需要的方法。</p></div></header>
<article className="docs-body"><h2>全部文档</h2><p>这些分组只帮助浏览。任何一篇都可以独立进入,也可以引用其他文档。</p><div className="guidance-directory">{guidanceDocuments.map(doc=><div key={doc.path}><Link href={humanDocumentUrl(doc.path)}>{doc.title}</Link><small>{doc.collection}</small><a href={`${humanDocumentUrl(doc.path)}/index.md`}>Markdown ↗</a></div>)}</div></article>
<h2>按创作主题浏览</h2>
<div className="skills-masonry">{skillCatalog.map(skill=><SkillCard key={skill.id} skill={skill}/>)}</div>
</Shell>}
@@ -0,0 +1,20 @@
import {useEffect,useState,type FormEvent} from 'react';
import type {ExploreEntry} from '@/lib/explore';
import type {Tag} from '@/lib/model';
import {TagInput} from './TagInput';
import {NoteMarkdown} from './NoteMarkdown';
export function NoteEditor({entry,onSaved,onCancel}:{entry:ExploreEntry;onSaved:(entry:ExploreEntry)=>void;onCancel:()=>void}){
const [title,setTitle]=useState(entry.title),[description,setDescription]=useState(entry.description),[markdown,setMarkdown]=useState(entry.editableMarkdown||'');
const [allTags,setAllTags]=useState<Tag[]>([]),[selected,setSelected]=useState<string[]>([]),[revision,setRevision]=useState('');
const [loading,setLoading]=useState(true),[busy,setBusy]=useState(false),[tagBusy,setTagBusy]=useState(false),[error,setError]=useState('');
useEffect(()=>{let live=true;void(async()=>{try{const res=await fetch('/api/notes/'+entry.id);const data=await res.json();if(!res.ok)throw Error(data.error||'无法读取笔记');if(live){setTitle(data.entry.title);setDescription(data.entry.description);setMarkdown(data.entry.editableMarkdown);setRevision(data.entry.revision);setAllTags(data.tags);setSelected(data.tags.filter((t:Tag)=>[...data.entry.categories,...(data.entry.systemTags||[]).map((s:Tag)=>s.name)].some((name:string)=>name.toLocaleLowerCase()===t.name.toLocaleLowerCase())).map((t:Tag)=>t.id));}}catch(e){if(live)setError(e instanceof Error?e.message:'读取失败');}finally{if(live)setLoading(false)}})();return()=>{live=false}},[entry.id]);
async function save(e:FormEvent){e.preventDefault();if(busy||loading||tagBusy||!revision)return;setBusy(true);setError('');try{const res=await fetch('/api/notes/'+entry.id,{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({title,description,markdown,tags:selected,revision})});const data=await res.json();if(!res.ok)throw Error(data.error||'保存失败');onSaved(data.entry);}catch(e){setError(e instanceof Error?e.message:'保存失败');}finally{setBusy(false)}}
return <form className="note-editor" onSubmit={save} aria-label="编辑笔记"><h1 id="note-title">编辑笔记</h1>{loading&&<p role="status">正在读取最新内容…</p>}
<fieldset disabled={loading||busy}><div className="form-field"><label htmlFor="note-edit-title">标题</label><input id="note-edit-title" autoFocus required maxLength={200} value={title} onChange={e=>setTitle(e.target.value)}/></div>
<div className="form-field"><label htmlFor="note-edit-description">描述</label><textarea id="note-edit-description" rows={3} maxLength={1000} value={description} onChange={e=>setDescription(e.target.value)}/></div>
{!loading&&<TagInput initial={allTags} selected={selected} onChange={setSelected} disabled={busy} onBusyChange={setTagBusy}/>}
<div className="form-field"><label htmlFor="note-edit-body">正文 <small>支持 Markdown 列表、链接和代码块</small></label><textarea id="note-edit-body" className="note-editor-body" rows={15} maxLength={100000} value={markdown} onChange={e=>setMarkdown(e.target.value)}/></div>
<details><summary>预览正文</summary><NoteMarkdown text={markdown}/></details></fieldset>
{error&&<p role="alert" className="error-message">{error}</p>}
<div className="note-editor-actions"><button type="button" className="secondary-button" disabled={busy||tagBusy} onClick={onCancel}>取消</button><button type="submit" className="primary-button" disabled={loading||busy||tagBusy||!revision}>{busy?'保存中…':'保存修改'}</button></div></form>;
}
@@ -0,0 +1,14 @@
import React from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import {Link as LinkIcon,ArrowUpRight} from 'lucide-react';
export function NoteMarkdown({text}:{text:string}){
return <div className="note-markdown"><ReactMarkdown remarkPlugins={[remarkGfm]} components={{
a:({href,children})=>{
if(!href)return <span>{children}</span>;
const destination=href.replace(/\?agent_mode=True$/i,'');
return <a className="note-inline-link" href={destination}><LinkIcon size={13} aria-hidden="true"/><span>{children}</span>{/^https?:/.test(destination)&&<ArrowUpRight size={12} aria-hidden="true"/>}</a>;
},
img:({src,alt})=>typeof src==='string'?<a className="note-inline-link" href={src}><LinkIcon size={13} aria-hidden="true"/>{alt||'查看图片'}</a>:null,
}}>{text}</ReactMarkdown></div>;
}
@@ -0,0 +1,11 @@
import {useState} from 'react';
import {Tags,X} from 'lucide-react';
import type {ExploreEntry} from '@/lib/explore';
import type {Tag} from '@/lib/model';
import {TagInput} from './TagInput';
export function QuickTags({entry,onSaved}:{entry:ExploreEntry;onSaved:(value:ExploreEntry)=>void}){
const [open,setOpen]=useState(false),[tags,setTags]=useState<Tag[]>([]),[selected,setSelected]=useState<string[]>([]),[revision,setRevision]=useState(''),[loading,setLoading]=useState(false),[busy,setBusy]=useState(false),[tagBusy,setTagBusy]=useState(false),[error,setError]=useState('');
async function show(){setOpen(true);setLoading(true);setError('');setRevision('');try{const r=await fetch('/api/notes/'+entry.id),d=await r.json();if(!r.ok)throw Error(d.error);setTags(d.tags);const names=[...d.entry.categories,...(d.entry.systemTags||[]).map((t:Tag)=>t.name)];setSelected(d.tags.filter((t:Tag)=>names.includes(t.name)).map((t:Tag)=>t.id));setRevision(d.entry.revision);}catch{setError('读取标签失败,请关闭后重试')}finally{setLoading(false)}}
async function save(){setBusy(true);setError('');try{const r=await fetch('/api/notes/'+entry.id,{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify({tags:selected,revision})}),d=await r.json();if(!r.ok)throw Error(d.error);onSaved(d.entry);setOpen(false);}catch(e){setError(e instanceof Error?e.message:'保存失败')}finally{setBusy(false)}}
return <><button type="button" className="quick-tags-trigger" aria-label={'编辑 '+entry.title+' 的标签'} onClick={()=>void show()}><Tags size={14}/></button>{open&&<div className="tag-popover" role="dialog" aria-label={'编辑 '+entry.title+' 的标签'}><header><b>编辑标签</b><button type="button" aria-label="关闭标签编辑" disabled={busy||tagBusy} onClick={()=>setOpen(false)}><X size={17}/></button></header>{loading?<p role="status">读取中…</p>:revision&&<TagInput initial={tags} selected={selected} onChange={setSelected} disabled={busy} onBusyChange={setTagBusy}/>}<p role="alert" className="error-message">{error}</p><button type="button" className="primary-button" disabled={loading||busy||tagBusy||!revision} onClick={()=>void save()}>{busy?'保存中…':'保存标签'}</button></div>}</>;
}
@@ -0,0 +1,15 @@
import Link from "next/link";
import { useRouter } from "next/router";
import { Grid2X2,Image,Film,AudioLines,BookOpen,Clapperboard,Sparkles,ArrowUpRight,Layers,Tags,Upload,Menu,X,Search } from "lucide-react";
import { useEffect,useState,type ReactNode } from "react";
const groups=[{label:'',items:[{href:'/',label:'首页',icon:Grid2X2},{href:'/categories',label:'分类',icon:Tags}]}];
export function Shell({children}:{children:ReactNode}){
const router=useRouter();const [open,setOpen]=useState(false);const [query,setQuery]=useState(String(router.query.q||''));
useEffect(()=>setQuery(String(router.query.q||'')),[router.query.q]);
return <div className="app-shell"><button className="mobile-menu icon-button" aria-label={open?"关闭导航":"展开导航"} aria-expanded={open} onClick={()=>setOpen(!open)}>{open?<X size={22}/>:<Menu size={22}/>}</button>
<aside className={`sidebar ${open?'is-open':''}`}><Link href="/" className="brand" aria-label="PROMPT 首页" onClick={()=>setOpen(false)}><img className="brand-mark" src="/brand-mark.svg" width={40} height={40} alt=""/><strong>PROMPT</strong></Link>
<nav>{groups.map((g,i)=><div className="nav-group" key={i}>{g.label&&<p>{g.label}</p>}{g.items.map(item=>{const active=item.href==='/'?router.asPath.split('?')[0]==='/':router.asPath.split('?')[0].startsWith(item.href);return <Link key={item.href} href={item.href} title={item.label} className={`nav-item ${active?'active':''}`} onClick={()=>setOpen(false)}><item.icon size={24} strokeWidth={active?2.2:1.8}/><span>{item.label}</span></Link>;})}</div>)}</nav>
<button className="auth-logout" onClick={async()=>{const response=await fetch('/api/auth/logout',{method:'POST'});if(response.ok)window.location.assign('/login');}}>退出登录</button></aside><main className="main-content"><div className="global-topbar"><form className="global-search" role="search" onSubmit={e=>{e.preventDefault();const path=router.asPath.split('?')[0];const destination=path==='/categories'?path:'/';void router.push({pathname:destination,query:{...(destination==='/categories'&&router.query.category?{category:router.query.category}:{}),...(query.trim()?{q:query.trim()}:{})}});}}><Search size={24}/><input aria-label="搜索笔记全文" placeholder="搜索知识、灵感和素材" value={query} onChange={e=>setQuery(e.target.value)}/>{query&&<button type="button" aria-label="清空搜索" onClick={()=>{setQuery('');void router.push({pathname:router.pathname==='/categories'?'/categories':'/',query:router.query.category?{category:router.query.category}:{}})}}><X size={20}/></button>}<button type="submit" className="search-submit">搜索</button></form></div>{children}</main>{open&&<button className="nav-scrim" aria-label="关闭导航" onClick={()=>setOpen(false)}/>}
</div>;
}
@@ -0,0 +1,6 @@
import {guidanceUrl} from '@/content/page-links';
import {previewUrl} from '@/content/page-links';
import Link from 'next/link';
import {ArrowUpRight} from 'lucide-react';
import {skillCatalog} from '@/content/skills/catalog';
export function SkillCard({skill}:{skill:typeof skillCatalog[number]}){return <Link href={guidanceUrl(skill.id)} className="post-card skill-pin"><div className="post-cover skill-pin-cover"><img src={previewUrl(skill.image,480)} alt={skill.alt} loading="lazy"/></div><h3 title={skill.title}>{skill.title}</h3><div className="post-meta"><span>{skill.category}</span><ArrowUpRight size={14} aria-hidden="true"/></div></Link>}
@@ -0,0 +1,49 @@
import {previewUrl} from '@/content/page-links';
import Head from 'next/head';
import Link from 'next/link';
import {useState,useEffect,useRef} from 'react';
import {X,PanelRight,Copy,ExternalLink} from 'lucide-react';
import {Shell} from './Shell';
import {getGuidance,guidanceMarkdown,guidanceBacklinks,humanDocumentUrl,markdownDocumentUrl,legacyDocumentPath,type GuidanceResource} from '@/content/skills/guidance';
export function SkillDocs({documentPath,documentId='index',skillId='street-people'}:{documentPath?:string;documentId?:string;skillId?:string}){
const path=documentPath??legacyDocumentPath(skillId,documentId);
const doc=getGuidance(path)!;
const [open,setOpen]=useState(false);
const [selected,setSelected]=useState<GuidanceResource|null>(null);
const [copied,setCopied]=useState(false);
const panel=useRef<HTMLElement>(null);
useEffect(()=>{setOpen(window.innerWidth>760)},[]);
useEffect(()=>{setSelected(null);setCopied(false)},[path]);
useEffect(()=>{if(!open)return;const handler=(e:KeyboardEvent)=>{if(e.key==='Escape')setOpen(false)};window.addEventListener('keydown',handler);return()=>window.removeEventListener('keydown',handler)},[open]);
const resource=(id:string)=>doc.resources.find(r=>r.id===id)!;
const incoming=guidanceBacklinks(path);
async function copy(){
try{
const value=new URL(markdownDocumentUrl(path),location.origin).href;
if(navigator.clipboard)await navigator.clipboard.writeText(value);
else{const input=document.createElement('textarea');input.value=value;document.body.appendChild(input);input.select();const ok=document.execCommand('copy');input.remove();if(!ok)throw Error('Copy unavailable');}
setCopied(true);
}catch{setCopied(false)}
}
return <Shell><Head><title>{doc.title} · 指导文档 · PROMPT</title><link rel="canonical" href={humanDocumentUrl(path)}/><link rel="alternate" type="text/markdown" href={markdownDocumentUrl(path)} title={doc.title}/></Head>
<div className="docs-top"><Link href="/skills">← 全部指导文档</Link><button onClick={()=>setOpen(v=>!v)} aria-expanded={open}><PanelRight size={16}/>文档与来源 · {doc.resources.length}</button></div>
<div className={`docs-layout ${open?'with-sources':''}`}><article className="docs-body">
<div className="docs-eyebrow">{doc.collection} / 指导文档</div><h1>{doc.title}</h1>
<div className="docs-actions"><button onClick={copy}><Copy size={14}/>{copied?'已复制本文 Markdown 地址':'复制本文给 Agent'}</button><a href={markdownDocumentUrl(path)} target="_blank" rel="noreferrer">本文 Markdown ↗</a></div>
<p className="docs-hint">网页与 Markdown 来自同一份文档。每篇都有独立地址,可以直接进入,也可以沿引用继续阅读。</p>
{doc.blocks.map((b,i)=>b.type==='heading'?<h2 key={i}>{b.text}</h2>:b.type==='code'?<pre key={i}>{b.text}</pre>:b.type==='links'?<div className="docs-inline-links" key={i}>{b.refs!.map(id=>{
const r=resource(id);
return r.kind==='document'?<Link href={r.human!} key={id}>文档 · {r.title}<ExternalLink size={12}/></Link>:<a href={r.href} key={id} onClick={e=>{e.preventDefault();setSelected(r);setOpen(true);panel.current?.focus()}}>{r.kind==='image'?'图片':r.method} · {r.title}<ExternalLink size={12}/></a>;
})}</div>:<p key={i}>{b.text}</p>)}
{incoming.length>0&&<><h2>引用本文的文档</h2><div className="docs-inline-links">{incoming.map(d=><Link key={d.path} href={humanDocumentUrl(d.path)}>{d.title}<ExternalLink size={12}/></Link>)}</div></>}
</article>
{open&&<aside className="docs-sources" ref={panel} tabIndex={-1} aria-label="文档与资源"><header><div><b>文档与来源</b><small>本文的文档、参考图与接口</small></div><button aria-label="关闭文档与来源" onClick={()=>setOpen(false)}><X size={18}/></button></header>
{(['document','image','api'] as const).map(kind=><section key={kind}><h3>{kind==='document'?'指导文档':kind==='image'?'参考与示意图':'API 接口'}</h3>{doc.resources.filter(r=>r.kind===kind).map(r=><button key={r.id} className={selected?.id===r.id?'selected':''} onClick={()=>setSelected(r)}><span>{r.method||(r.kind==='image'?'IMG':'MD')}</span><div>{r.title}<small>{r.human||r.href}</small></div></button>)}</section>)}
{selected&&<div className="docs-resource-preview"><h3>{selected.title}</h3>{selected.kind==='image'?<img src={previewUrl(selected.href,1280)} alt={selected.title}/>:selected.kind==='document'?<pre>{guidanceMarkdown(selected.documentPath!)}</pre>:<><code>{selected.method} {selected.href}</code><pre>{JSON.stringify(selected.detail||{method:selected.method,path:selected.href},null,2)}</pre><p>{selected.description}</p></>}
<div className="docs-resource-actions">{selected.human&&<Link href={selected.human}>打开文档网页 ↗</Link>}{selected.method!=='POST'&&!selected.template&&<a href={selected.href} target="_blank" rel="noreferrer">{selected.kind==='document'?'打开 Markdown':'打开资源'} ↗</a>}</div>
</div>}
</aside>}
</div>
</Shell>;
}
@@ -0,0 +1,11 @@
import {useId,useState} from 'react';
import type {Tag} from '@/lib/model';
export function TagInput({initial,selected,onChange,disabled=false,onBusyChange}:{initial:Tag[];selected:string[];onChange:(ids:string[])=>void;disabled?:boolean;onBusyChange?:(busy:boolean)=>void}){
const uid=useId(),[all,setAll]=useState(initial),[input,setInput]=useState(''),[systemQuery,setSystemQuery]=useState(''),[busy,setBusy]=useState(false),[error,setError]=useState('');
const name=input.replace(/^#/,'').trim(),isHash=input.startsWith('#'),ordinary=all.filter(t=>t.kind!=='system'),systems=all.filter(t=>t.kind==='system');
const suggestions=ordinary.filter(t=>!selected.includes(t.id)&&(!name||t.name.toLocaleLowerCase().includes(name.toLocaleLowerCase()))).slice(0,8);
function toggle(id:string){onChange(selected.includes(id)?selected.filter(v=>v!==id):[...selected,id]);}
async function add(){if(!isHash||!name||busy||disabled||selected.length>=50)return;setBusy(true);onBusyChange?.(true);setError('');try{const res=await fetch('/api/tags',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({name:input})});const tag:Tag&{error?:string}=await res.json();if(!res.ok)throw Error(tag.error||'标签创建失败');if(tag.kind==='system')throw Error('请在系统标签列表勾选');setAll(a=>a.some(t=>t.id===tag.id)?a:[...a,tag]);if(!selected.includes(tag.id))onChange([...selected,tag.id]);setInput('');}catch(e){setError(e instanceof Error?e.message:'标签创建失败');}finally{setBusy(false);onBusyChange?.(false);}}
return <div className="tag-manager"><div className="form-field"><label htmlFor={uid+'-normal'}>普通标签 <small>输入 #标签,回车添加或新建</small></label><div className="tag-input-selected">{ordinary.filter(t=>selected.includes(t.id)).map(t=><button key={t.id} type="button" disabled={disabled||busy} aria-label={'移除标签 '+t.name} onClick={()=>toggle(t.id)}>#{t.name}<span aria-hidden="true">×</span></button>)}</div><div className="tag-input-row"><input id={uid+'-normal'} value={input} maxLength={61} disabled={disabled||busy} placeholder="#添加普通标签" onChange={e=>setInput(e.target.value)} onKeyDown={e=>{if(e.key==='Enter'&&!e.nativeEvent.isComposing){e.preventDefault();void add()}}}/><button type="button" className="secondary-button" disabled={!isHash||!name||busy||disabled||selected.length>=50} onClick={()=>void add()}>{busy?'添加中…':'添加'}</button></div><div className="tag-input-suggestions">{suggestions.map(t=><button key={t.id} type="button" disabled={disabled||busy||selected.length>=50} onClick={()=>{toggle(t.id);setInput('')}}>#{t.name}</button>)}</div></div>
<fieldset className="system-tag-picker" disabled={disabled||busy}><legend>系统标签 <small>只能搜索和勾选已有标签</small></legend><input aria-label="搜索系统标签" placeholder="搜索系统标签" value={systemQuery} onKeyDown={e=>{if(e.key==='Enter')e.preventDefault()}} onChange={e=>setSystemQuery(e.target.value)}/><div>{systems.filter(t=>t.name.includes(systemQuery.trim())).map(t=><label key={t.id}><input type="checkbox" checked={selected.includes(t.id)} disabled={!selected.includes(t.id)&&selected.length>=50} onChange={()=>toggle(t.id)}/>{t.name}</label>)}</div>{!systems.some(t=>t.name.includes(systemQuery.trim()))&&<p>没有匹配的系统标签</p>}</fieldset>{error&&<p role="alert" className="error-message">{error}</p>}</div>;
}
@@ -0,0 +1,37 @@
import Link from "next/link";
import { coverSvg } from "./cover";
import { useState, type CSSProperties, type ReactNode } from "react";
import { ArrowUpRight, ChevronLeft, ChevronRight, List, BookOpen, Check, ArrowDown } from "lucide-react";
import { chapters, seriesCover, sourceChecked, type Chapter, type Skill } from "./data";
function Footer({chapter,page}:{chapter:Chapter;page:number}) {
return <footer className="learning-sheet-footer"><span>PROMPT / 学习资料自己做</span><span>第 {chapter.number} 辑 <b>{String(page+1).padStart(2,"0")} / 08</b></span></footer>;
}
function Sheet({chapter,page,children,className=""}:{chapter:Chapter;page:number;children:ReactNode;className?:string}) {
return <section className={`learning-sheet ${className}`} aria-label={`第 ${page+1} 页`}><div className="learning-sheet-top"><span>学习资料自己做 / VOL. {chapter.number}</span><span>THE LEARNING EDIT</span></div>{children}<Footer chapter={chapter} page={page}/></section>;
}
function Sample({skill,index}:{skill:Skill;index:number}) {
return <div className={`learning-sample sample-${index%3}`} aria-label="排版示意,不是工具实测结果"><span className="sample-label">成品形态 · 排版示意</span>{skill.sample.map((line,i)=><div key={line}><span>{String(i+1).padStart(2,"0")}</span><p>{line}</p>{i===0&&<Check size={15}/>}</div>)}</div>;
}
function SkillCard({skill,index}:{skill:Skill;index:number}) {
return <article className="learning-skill"><div className="learning-skill-heading"><span className="learning-number">{String(index+1).padStart(2,"0")}</span><div><span className="learning-category">{skill.category}</span><h3>{skill.title}</h3></div></div><a className="learning-skill-name" href={skill.source} target="_blank" rel="noreferrer">{skill.name}<ArrowUpRight size={13}/></a><div className="learning-io"><p><b>给它</b><span>{skill.input}</span></p><p><b>得到</b><span>{skill.output}</span></p></div><Sample skill={skill} index={index}/><div className="learning-prompt"><span>可以这样问</span><p>“{skill.prompt}”</p></div><p className="learning-caveat">{skill.note}</p></article>;
}
const labels=["系列封面","本篇索引","01—02","03—04","05—06","07—08","09—10","使用路线"];
export function LearningSeries({chapterKey,pageNumber,standalone=false}:{chapterKey:string;pageNumber?:number;standalone?:boolean}) {
const chapter=chapters.find(c=>c.key===chapterKey)!;
const [current,setCurrent]=useState(0);const page=pageNumber??current;const setPage=(value:number|((p:number)=>number))=>{const next=typeof value==='function'?value(page):value;if(standalone)location.href=`/p/${chapter.slug}/pages/${next+1}`;else setCurrent(next);};const [continuous,setContinuous]=useState(false);
const boards:ReactNode[]=[
<div className="learning-cover learning-html-cover" key="cover" dangerouslySetInnerHTML={{__html:coverSvg}}/>,
<Sheet chapter={chapter} page={1} key="index"><div className="learning-intro"><span className="learning-chapter">第 {chapter.number} 辑 · 10 个 Skills</span><h2>{chapter.headline[0]}<br/><mark>{chapter.headline[1]}</mark></h2><p>{chapter.subtitle}</p><span className="learning-audience">{chapter.audience}</span></div><div className="learning-index">{chapter.skills.map((skill,i)=><button key={skill.name} onClick={()=>{setContinuous(false);setPage(2+Math.floor(i/2));}}><span>{String(i+1).padStart(2,"0")}</span><div><strong>{skill.title}</strong><small>{skill.name}</small></div><ArrowUpRight size={18}/></button>)}</div><p className="learning-index-note"><BookOpen size={16}/>按需求挑选,不必一次装完。点击条目查看介绍。</p></Sheet>,
...Array.from({length:5},(_,i)=><Sheet chapter={chapter} page={i+2} key={`skills-${i}`} className="learning-pair"><header className="learning-pair-title"><span>把工具用在具体的事情上</span><h2>{["先整理,再开始。","把资料做成自己的。","让学习多一条路径。","把看过变成理解。","留下一份能复用的资料。"][i]}</h2></header>{chapter.skills.slice(i*2,i*2+2).map((skill,j)=><SkillCard key={skill.name} skill={skill} index={i*2+j}/>)}</Sheet>),
<Sheet chapter={chapter} page={7} key="workflow"><div className="learning-ending"><span className="learning-chapter">收藏之后,试着做一份。</span><h2>先选一个需求,<br/><mark>再串成工作流。</mark></h2><p>不求用遍所有工具,先完成一份自己的资料。</p></div><ol className="learning-workflow">{chapter.workflow.map((line,i)=><li key={line}><b>{i+1}</b><span>{line}</span>{i<2&&<ArrowDown size={19}/>}</li>)}</ol><div className="learning-source-box"><h3>10 个来源,放在这里了。<ArrowUpRight size={20}/></h3><div>{chapter.skills.map((skill,i)=><a key={skill.name} href={skill.source} target="_blank" rel="noreferrer"><span>{String(i+1).padStart(2,"0")}</span>{skill.name}<ArrowUpRight size={12}/></a>)}</div><p>依据 GitHub 项目说明整理 · 核对于 {sourceChecked}<br/>尚未逐项安装实测;文中小样为排版示意。</p></div><div className="learning-series-reminder"><b>同系列还有</b>{chapters.filter(c=>c.key!==chapter.key).map(c=><Link key={c.key} href={`/p/${c.slug}`}>{c.number} / {c.subtitle}<ArrowUpRight size={14}/></Link>)}</div></Sheet>,
];
if(standalone)return <main className="learning-standalone w-[1080px] h-[1440px] overflow-hidden" style={{"--learning-accent":chapter.color} as CSSProperties}><div className="learning-boards" data-render-page>{boards[page]}</div></main>;
return <div className="learning-reader" style={{"--learning-accent":chapter.color} as CSSProperties}>
<div className="learning-reader-bar"><div><span className="learning-reader-badge">系列 {chapter.number} / 03</span><strong>{chapter.subtitle}</strong></div><button onClick={()=>setContinuous(v=>!v)} aria-pressed={continuous}><List size={16}/>{continuous?"分页阅读":"连续阅读"}</button></div>
<div className={`learning-boards ${continuous?"is-continuous":""}`} onKeyDown={e=>{if(e.target!==e.currentTarget||continuous)return;if(e.key==="ArrowRight"){e.preventDefault();setPage(p=>Math.min(7,p+1));}if(e.key==="ArrowLeft"){e.preventDefault();setPage(p=>Math.max(0,p-1));}}} tabIndex={0} aria-label="图文画板,可使用左右方向键翻页">{continuous?boards:boards[page]}</div>
{!continuous&&<nav className="learning-pagination" aria-label="图文翻页"><button aria-label="上一页" disabled={page===0} onClick={()=>setPage(p=>p-1)}><ChevronLeft size={20}/></button><span aria-live="polite">{page+1} / 8 <small>{labels[page]}</small></span><button aria-label="下一页" disabled={page===7} onClick={()=>setPage(p=>p+1)}><ChevronRight size={20}/></button></nav>}
<div className="learning-page-tabs" aria-label="选择图文页">{labels.map((label,i)=><button key={label} className={!continuous&&page===i?"selected":""} aria-current={!continuous&&page===i?"page":undefined} onClick={()=>{setContinuous(false);setPage(i);}}><span>{String(i+1).padStart(2,"0")}</span>{label}</button>)}</div>
<div className="learning-related"><span>学习资料自己做 · 系列三篇</span><div>{chapters.map(c=><Link className={c.key===chapter.key?"selected":""} key={c.key} href={`/p/${c.slug}`}><b>{c.number}</b>{c.key===chapter.key?"正在阅读 · ":""}{c.subtitle}<ArrowUpRight size={15}/></Link>)}</div></div>
</div>;
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,70 @@
export type Skill = {
name: string; title: string; category: string; input: string; output: string;
prompt: string; note: string; source: string; sample: [string, string, string];
};
export type Chapter = {
key: string; slug: string; number: string; title: string; headline: [string,string];
subtitle: string; color: string; audience: string; workflow: [string,string,string]; skills: Skill[];
};
const github = (path: string) => `https://github.com/${path}`;
export const seriesCover = "/learning-skills/cover.png";
export const sourceChecked = "2026-10-23";
export const chapters: Chapter[] = [
{
key: "learning-skills-notes", slug: "learning-skills-notes", number: "01",
title: "课件太厚?这 10 个 Skills 帮你整理复习资料",
headline: ["课件太厚,", "复习有方法。"], subtitle: "10 个整理笔记、网课与记忆卡的 Skills",
color: "#c3dc81", audience: "学生党 / 自学者 / 考前复习",
workflow: ["整理原始课件与网课", "搭框架,再做详细笔记", "用速记页与卡片检查理解"],
skills: [
{name:"study-notes",title:"厚课件,拆成章节笔记",category:"课件整理",input:"PDF、PPT、教材或技术文档",output:"Obsidian 笔记、图解、例题与练习",prompt:"把这章课件整理成复习笔记,保留例题,最后给我一组自测题。",note:"输出以 Markdown 笔记库为主。",source:github("siluy/obsidian-study-notes-skill/blob/main/SKILL.md"),sample:["01 章节知识框架","02 关键概念与例题","03 自测与易错点"]},
{name:"exam-cheatsheet",title:"考前,把重点收成几页",category:"速记清单",input:"备考工作区里的笔记、错题与知识库",output:"可溯源的速记资料;按需生成打印 PDF",prompt:"从已掌握的笔记和错题里,编译两页公式与例题速查表。",note:"依赖原项目的备考工作区,上游资料需先准备。",source:github("ZeKaiNie/universal-examprep-skill/blob/main/full/skills/exam-cheatsheet/SKILL.md"),sample:["必背结论 / 公式","典型例题 / 解题过程","来源锚点 / 方法提醒"]},
{name:"学霸笔记",title:"知识点,也能有笔记感",category:"视觉笔记",input:"需要重新组织的知识与说明文字",output:"手写笔记本风格的单文件 HTML",prompt:"把这些知识点排成横线纸笔记,用高亮标出三个易混概念。",note:"负责内容与视觉编排,不代替知识核对。",source:github("Unclecheng-li/note-skill/blob/main/SKILL.md"),sample:["CHAPTER 01 学习笔记","重点概念 → 高亮标记","我的理解 / 旁注留白"]},
{name:"video2knowledge",title:"一段网课,留下可复习的笔记",category:"视频学习",input:"本地课程视频或录屏",output:"时间戳转写、学习笔记、HTML 与记忆卡",prompt:"整理这段课程视频,给出时间戳笔记,再提炼可复习的知识卡。",note:"需要本地视频处理与识别依赖;云服务可选。",source:github("CacinieP/video2knowledge/blob/main/SKILL.md"),sample:["00:42 本节核心问题","03:18 概念与演示","08:06 总结 / 复习卡"]},
{name:"bili-content-organizer",title:"收藏的系列课,终于整理了",category:"系列课程",input:"B 站链接、分 P、合集或已有字幕",output:"按主题组织的结构化课程笔记",prompt:"按知识模块整理这个系列课,保留各节对应的来源。",note:"需能取得字幕;平台访问与登录按原项目要求。",source:github("Mocooa/bili-content-organizer/blob/main/SKILL.md"),sample:["课程目录 / 知识模块","每节课的核心观点","来源视频 / 对应笔记"]},
{name:"learning-pack",title:"想学一个主题,先有路线",category:"学习路线",input:"想系统学习的主题与当前基础",output:"学习路径、资料、视频清单与学习笔记",prompt:"我想从零学摄影,帮我整理循序渐进的学习路径与资料。",note:"资料检索与部分视觉产物依赖联网及配套能力。",source:github("irenerachel/learning-pack-skill/blob/main/SKILL.md"),sample:["入门 → 理解 → 实践","按阶段选择资料","边学边整理一本笔记"]},
{name:"flashcard-generator",title:"看过的笔记,变成会答的卡片",category:"主动回忆",input:"笔记、文章或一个知识主题",output:"问答卡、挖空卡与 Anki CSV",prompt:"把这章笔记做成 20 张单知识点记忆卡,不要把答案写得太长。",note:"导入 Anki 后的复习排程由 Anki 管理。",source:github("JayRHa/agent-skills/blob/main/flashcard-generator/SKILL.md"),sample:["Q 这个概念的核心是什么?","A 用一句话解释","CLOZE 关键术语填空"]},
{name:"processon-mindmap-generator",title:"零散内容,画出知识骨架",category:"知识脑图",input:"文字、文档、网页或已有提纲",output:"可在 ProcessOn 编辑的结构化脑图",prompt:"把这章内容整理成三层脑图,区分核心概念、例子与易错点。",note:"集成 ProcessOn 在线服务,需按项目配置访问凭据。",source:github("processonai/processon-skills/blob/main/skills/processon-mindmap-generator/SKILL.md"),sample:["章节主题","├ 核心概念 / 关联","└ 例题 / 常见误区"]},
{name:"learn-anything",title:"卡住的概念,拆开再学",category:"概念理解",input:"主题、文档、URL 或不理解的概念",output:"模块化学习内容、概念卡与复习安排",prompt:"我总分不清相关和因果,请拆开讲,再用问题检查我是否理解。",note:"仓库名为 learn-anything,技能声明名称为 learn。",source:github("d-wwei/learn-anything/blob/main/SKILL.md"),sample:["概念是什么 / 为什么","常见误区 / 反例","用自己的话重新解释"]},
{name:"revision-tutor",title:"复习结束,再检查一次盲点",category:"理解检查",input:"讲义、笔记与自己的回答",output:"概念解释、理解检查与复习记录卡",prompt:"围绕这份讲义提问,记录我答不清楚的地方,最后给我复习卡。",note:"原项目面向 Claude;跨会话需携带复习记录。",source:github("yangcodingmaster/Revision-Tutor/blob/main/SKILL.md"),sample:["已经讲清楚的概念","仍然卡住的推导","下一轮需要复习的点"]},
],
},
{
key:"learning-skills-teaching",slug:"learning-skills-teaching",number:"02",
title:"老师家长收藏|10 个出题、组卷与教学资料 Skills",
headline:["从一道错题,","到一套资料。"],subtitle:"10 个出题、排卷与制作课件的 Skills",
color:"#f2b994",audience:"教师 / 家长 / 教学内容创作者",
workflow:["收集题目,找到学习难点","生成练习,整理可打印试卷","检查命题,再准备讲评与课件"],
skills:[
{name:"k12-smart-teacher",title:"一道错题,多练几个角度",category:"错题巩固",input:"作业、错题与学段信息",output:"错因解释和基础、提高、挑战三层练习",prompt:"分析这道错题,先讲清楚错因,再给三档举一反三练习。",note:"Word 输出需要 python-docx;题目与答案需教师复核。",source:github("shellery1988/k12-smart-teacher/blob/main/SKILL.md"),sample:["① 找出错因","② 基础 / 提高 / 挑战","③ 讲解与巩固练习"]},
{name:"exam-paper",title:"从一份资料,整理一套练习",category:"练习生成",input:"教材、文档、图像或知识点材料",output:"试题、复习讲义与 Markdown / PDF",prompt:"围绕这一单元生成练习与讲义,附答案和解析,保持题目可追溯。",note:"排版与 PDF 生成依赖项目配套运行环境。",source:github("haitanghuaweimianTom/exam-paper-skill/blob/main/SKILL.md"),sample:["单元知识要点","基础练习 / 迁移练习","参考答案 / 解题提示"]},
{name:"wps-exam-paper",title:"题目有了,卷面也要清楚",category:"Word 试卷",input:"已有题目、分值与试卷要求",output:"带评分栏、题号、答题空间的 Word 试卷",prompt:"把这些题排成一份单元检测卷,留足答题空间并检查总分。",note:"来自 Bwkyd/wps-skills;运行依赖见原项目。",source:github("Bwkyd/wps-skills/blob/main/skills/wps-exam-paper/SKILL.md"),sample:["单元检测 / 姓名 / 班级","题号 一 二 三","得分 __ __ __"]},
{name:"video-exam-extractor",title:"散落在截图里的题,收成文档",category:"题目提取",input:"视频、题目截图或 PDF",output:"提取并组织好的 Word 题目文档",prompt:"把这些截图中的题目提取到 Word,保留题号并检查公式。",note:"识别结果中的公式、图形和选项需要人工核对。",source:github("delancy827/video-exam-extractor/blob/main/SKILL.md"),sample:["题目截图 / 视频画面","识别题干 / 选项 / 图示","结构化题目文档"]},
{name:"exam-paper-formater",title:"试卷、答案、答题卡,一起排",category:"打印排版",input:"已经准备好的题目与答案",output:"打印 PDF、独立答案卷与答题卡",prompt:"把题目排成 A4 试卷,答案单独成卷,再生成配套答题卡。",note:"仓库原名 formater;不把排版工具当作命题工具。",source:github("flyboat403/exam-paper-formater/blob/main/SKILL.md"),sample:["试卷 / 清楚的题目层级","答案 / 独立保存","答题卡 / 对应题号"]},
{name:"exam-evaluator",title:"印卷之前,先看命题结构",category:"命题评估",input:"试卷与相应教学或考试要求",output:"覆盖、结构和难度等分析的 HTML 报告",prompt:"检查这份试卷的知识覆盖和难度结构,指出需要调整的题目。",note:"分析属于辅助建议,不能代替教师审题。",source:github("flyboat403/exam-evaluator/blob/main/SKILL.md"),sample:["知识点是否覆盖?","题型与难度是否合理?","哪些题目需要调整?"]},
{name:"english-exam-studio",title:"英语试卷,变成讲评课件",category:"互动讲评",input:"英语试卷、答案与听力音频",output:"离线互动讲评页面与听力精听内容",prompt:"根据试卷和答案制作讲评页,把听力材料整理成精听环节。",note:"需准备对应试卷与音频,非通用题库。",source:github("hututu-ai/english-exam-studio/blob/main/SKILL.md"),sample:["阅读题 / 对应解析","听力片段 / 精听练习","课堂讲评 / 离线打开"]},
{name:"scriptorium",title:"一节课,配齐讲义和随堂测",category:"课程讲义",input:"计算机课程主题或课程仓库",output:"讲义、康奈尔学习单、测验与题库",prompt:"为这节 Python 循环课制作学生讲义、随堂测验和教师答案。",note:"主要面向计算机课程,内容需结合教学目标。",source:github("agiacalone/scriptorium/blob/main/SKILL.md"),sample:["课前 / 课程目标","课中 / 笔记与填空","课后 / 随堂测验"]},
{name:"ai-study-hero",title:"把每日学习,做成闯关任务",category:"学习任务卡",input:"小学生的主题、基础与学习安排",output:"学习计划、RPG 任务卡与交互知识库",prompt:"把一周的分数复习做成每日任务卡,每天安排少量练习。",note:"面向小学学习场景;计划需家长或教师调整。",source:github("mangoyc/ai-study-hero/blob/main/skill/SKILL.md"),sample:["今日任务 / 小目标","完成练习 / 检查理解","记录进度 / 下次复习"]},
{name:"wps-courseware",title:"课件也要顺着教学思路走",category:"教学 PPT",input:"学科、课题、年级与教学目标",output:"按教学结构组织的 PPT 课件",prompt:"为这节课准备导入、新授、练习和总结四个环节的课件。",note:"与 wps-exam-paper 同仓库,属于不同技能。",source:github("Bwkyd/wps-skills/blob/main/skills/wps-courseware/SKILL.md"),sample:["导入 → 建立问题","新授 → 解释与互动","练习 → 总结与迁移"]},
],
},
{
key:"learning-skills-english",slug:"learning-skills-english",number:"03",
title:"英语资料自己做|10 个词汇、精读、口语与写作 Skills",
headline:["英语资料,","按自己来。"],subtitle:"10 个词汇、精读、口语与写作 Skills",
color:"#afcbe9",audience:"英语自学 / 四六级 / 雅思备考",
workflow:["从文章或主题收集表达","练阅读、口语与写作输出","根据反馈修改,安排下一轮练习"],
skills:[
{name:"ielts-vocabulary-builder",title:"背单词,也把搭配一起带上",category:"主题词汇",input:"雅思主题、已有表达与练习需求",output:"词汇、搭配、词族与应用练习",prompt:"按教育主题整理常用表达,每个词给出搭配和一条使用练习。",note:"与本篇第 2—6 项同属 jurgendn/agent-skills。",source:github("jurgendn/agent-skills/blob/main/skills/test-prep/ielts-vocabulary-builder/SKILL.md"),sample:["education / lifelong learning","搭配 → 语境 → 自己造句","近义表达 / 语域差别"]},
{name:"ielts-reading-strategies",title:"阅读错了,先看错在哪里",category:"阅读方法",input:"阅读文章、题目与自己的答案",output:"题型分析、解题策略与错因反馈",prompt:"分析这组判断题,解释 False 和 Not Given 的区别并定位依据。",note:"训练方法与反馈,不是当季真题库。",source:github("jurgendn/agent-skills/blob/main/skills/test-prep/ielts-reading-strategies/SKILL.md"),sample:["题干关键词 / 文中定位","True / False / Not Given","证据在哪里?"]},
{name:"ielts-speaking-coach",title:"口语练习,不只背一份答案",category:"口语反馈",input:"Part 1—3 题目与文字或转写回答",output:"模拟练习、示例与预估评分反馈",prompt:"用 Part 2 方式陪我练习,回答后从结构和表达给出具体建议。",note:"文字回答无法充分判断发音;评分仅为练习参考。",source:github("jurgendn/agent-skills/blob/main/skills/test-prep/ielts-speaking-coach/SKILL.md"),sample:["Cue card / 一个话题","先说经历,再补充细节","修改重复与含混表达"]},
{name:"ielts-writing-task1",title:"图表作文,先读懂再落笔",category:"图表写作",input:"学术类 Task 1 图表与作文",output:"图表分析、概述、示例与修改建议",prompt:"先找这张图的主要趋势和对比,再帮我检查概述段。",note:"需提供清晰图表或数据;预估分数非官方评分。",source:github("jurgendn/agent-skills/blob/main/skills/test-prep/ielts-writing-task1/SKILL.md"),sample:["主要趋势 / 显著对比","Overview / 先概括","Details / 再给数据"]},
{name:"ielts-writing-task2",title:"大作文,先把论证搭稳",category:"议论文写作",input:"Task 2 题目、提纲或已有作文",output:"审题、论证结构、范文与修改反馈",prompt:"检查这道题的立场和论证链,指出例子没有支撑观点的地方。",note:"示例用于学习,不能替代自己的练习。",source:github("jurgendn/agent-skills/blob/main/skills/test-prep/ielts-writing-task2/SKILL.md"),sample:["观点 → 为什么成立","例子 → 如何支撑","回应题目 → 收束论证"]},
{name:"ielts-learning-planner",title:"备考计划,从自己的时间出发",category:"学习规划",input:"目前基础、目标与每周可用时间",output:"每周安排、专项练习和阶段检查点",prompt:"我每周能学五小时,请按当前薄弱项制定可调整的四周计划。",note:"计划需要按实际进展更新,不保证提分。",source:github("jurgendn/agent-skills/blob/main/skills/test-prep/ielts-learning-planner/SKILL.md"),sample:["本周重点 / 时间分配","专项练习 / 回顾反馈","检查点 / 下一周调整"]},
{name:"english-intensive-reader",title:"一篇文章,左右对照着精读",category:"双栏精读",input:"英文文章、URL、PDF 或 Word",output:"原文与分析双栏笔记、生词和句型",prompt:"逐句精读这篇文章,解释长难句,把值得复用的表达单独列出。",note:"可按原项目保存词汇与导出 Anki CSV。",source:github("infometa/workbuddyskills/blob/main/skills/english-intensive-reader/SKILL.md"),sample:["Original text │ 句子结构","Key phrases │ 生词与搭配","Summary │ 我的复述"]},
{name:"cet-english-learner",title:"四六级,把读懂变成会用",category:"四六级学习",input:"英文文章或视频字幕",output:"词汇、逐段精读、复述引导与墨墨卡片",prompt:"用这篇文章练四六级,拆解重点句式,最后引导我自己复述。",note:"训练需要主动输出,生成资料不等于掌握。",source:github("moyu12-ae/cet-english-learner/blob/main/SKILL.md"),sample:["读懂段落 / 提取表达","拆解句式 / 联系语境","合上原文 / 自己复述"]},
{name:"shadowing-practice",title:"跟读,从一句话开始",category:"影子跟读",input:"适合自己水平的音频与文本",output:"分段、逐句到脱稿的跟读训练流程",prompt:"根据我的水平安排跟读步骤,先逐句练,再过渡到不看字幕。",note:"提供训练指导,不自带语音识别或自动发音评分。",source:github("nexaforgelab/english-skill/blob/main/shadowing-practice/SKILL.md"),sample:["听一句 → 停顿跟读","延长片段 → 接近同步","去掉字幕 → 记录卡点"]},
{name:"IELTS 写作批改助手",title:"作文改完,还要知道怎么改",category:"作文批改",input:"大小作文题目、图表与自己的作文",output:"分项反馈、修改建议与 Word 批改报告",prompt:"逐条解释这篇作文的问题,给出可执行的改法并生成 Word 报告。",note:"该项目包含两个批改 Skills;评分为辅助预估。",source:github("NiceGuo2000/ielts-writing-assistant"),sample:["原句 / 问题位置","影响 / 具体改法","修改示例 / 下次练习"]},
],
},
];
@@ -0,0 +1,13 @@
// Each key describes one independent note. Tags and links connect notes without ownership.
export const noteDescriptions:Record<string,string>={
'street-people':'生成冬日街头人物的透明剪纸素材:画风、参考图片和交付要求。',
'street-people/style':'松散线条、冬日衣着与奶油色纸边的画风说明及人物生成提示词。',
'street-people/upload':'透明 PNG 图包的上传字段、接口示例、返回结果与文件限制。',
'street-people/checks':'检查人物轮廓、真实透明背景、纸片内部和生成来源的交付清单。',
'shadow-puppet':'把照片主体转译成暖灯宣纸上的皮影形象,制作上下对照海报。',
'shadow-puppet/workflow':'照片转皮影海报的逐张制作步骤,包括原片整理、画板、绘制和验收。',
'shadow-puppet/visual-grammar':'皮影海报的造型、配色、镂空、光影和上下等分构图规则。',
'shadow-puppet/prompt':'照片转皮影海报的可替换提示词与原片、风格参考的使用方式。',
'shadow-puppet/delivery':'皮影海报的尺寸、画面质量、来源记录和文件上传要求。',
'image-delivery':'图像尺寸、格式、透明通道、生成来源与交付协议的通用检查说明。',
};
@@ -0,0 +1,16 @@
{
"guidance:street-people": "4ce3283fd98bb03a8fb39a19",
"guidance:street-people/style": "a1207913bf7a7907488d3e69",
"guidance:street-people/upload": "42c414e58ff3b5f80919c2e2",
"guidance:street-people/checks": "7e80ad25076db9178fd6cff7",
"guidance:shadow-puppet": "3c98946754c33309d73d5284",
"guidance:shadow-puppet/workflow": "00837d41ae6b42abbdb62d58",
"guidance:shadow-puppet/visual-grammar": "d64c533a694331948f09b0a2",
"guidance:shadow-puppet/prompt": "9eb8a684f3356d66c0d9162c",
"guidance:shadow-puppet/delivery": "f64332ee01b13e28062f624c",
"guidance:image-delivery": "c8cf8ffbb1c4d4807ae82258",
"wiki:Main:welcome": "54d12ae51429f66fa7991ef5",
"wiki:Help:namespaces": "1a33340838520492b2e095c0",
"wiki:Template:idea": "40e0e456e2f5943610fef538",
"wiki:Draft:inbox": "a599a5734d13ec81fed1ffd1"
}
@@ -0,0 +1,6 @@
import ids from './page-ids.json';
// IDs are persisted, never derive them from titles or positions. Keep IDs when renaming a page.
export function pageId(key:string):string{return (ids as Record<string,string>)[key]||'';}
export const exploreUrl=(id:string)=>'/explore/'+encodeURIComponent(id);
export const guidanceUrl=(path:string)=>exploreUrl(pageId('guidance:'+path));
export function previewUrl(source:string,width=480){return '/api/preview?'+new URLSearchParams({source,width:String(width)});}
@@ -0,0 +1,44 @@
import {shadowPuppetResources,shadowPuppetDocuments} from "./shadow-puppet";
import {streetPeople} from "@/lib/street-people";
export type Resource={id:string;kind:'document'|'image'|'api';title:string;href:string;human?:string;method?:string;description?:string;detail?:unknown;template?:boolean};
export type Block={type:'paragraph'|'heading'|'code'|'links';text?:string;refs?:string[]};
export type SkillDocument={id:string;title:string;blocks:Block[]};
export const skillResources:Resource[]=[
{id:'index',kind:'document',title:'入口文档 · SKILL.md',href:'/skills/street-people/SKILL.md',human:'/tools/skills/street-people'},
{id:'style',kind:'document',title:'画风与生成提示词',href:'/skills/street-people/style.md',human:'/tools/skills/street-people/style'},
{id:'upload',kind:'document',title:'上传与返回结果',href:'/skills/street-people/upload.md',human:'/tools/skills/street-people/upload'},
{id:'checks',kind:'document',title:'交付检查清单',href:'/skills/street-people/checks.md',human:'/tools/skills/street-people/checks'},
{id:'reference',kind:'image',title:'画风参考图',href:'/skills/street-people/reference.png'},
{id:'sample',kind:'image',title:'透明人物示意图',href:'/skills/street-people/sample.png'},
{id:'spec',kind:'api',title:'机器可读接口规范',href:'/api/skills/street-people',method:'GET'},
{id:'submit',kind:'api',title:'提交透明 PNG 图包',href:'/api/skills/street-people',method:'POST'},
];
export const skillDocuments:SkillDocument[]=[
{id:'index',title:'街头小人',blocks:[
{type:'paragraph',text:'用松散的线条、冬天的衣着与奶油色剪纸边,留住街上的一个瞬间。此文档是交给 coding agent 的入口;先阅读说明,再按链接选择需要的子文档与接口。'},
{type:'heading',text:'从这里开始'},
{type:'paragraph',text:'绘图由 agent 自己的图像工具执行。网站负责提供风格规范、检查透明 PNG,并存储发布素材包;不在网站配置模型密钥。'},
{type:'links',refs:['style','reference','sample']},
{type:'heading',text:'生成与交付'},
{type:'paragraph',text:'每张图只包含一个完整人物及其随身物件。明确启用透明背景,检查外部透明、内部纸张与完整轮廓,再按上传文档提交。多个文件组成一篇素材笔记,同一图片仍可被其他笔记引用。'},
{type:'links',refs:['upload','checks']},
{type:'paragraph',text:'所有文档、图片与 API 的完整索引见下方。入口与子文档均为纯文本 Markdown,图片始终以链接提供。'},
{type:'links',refs:skillResources.map(r=>r.id)},
]},
{id:'style',title:'画风与生成提示词',blocks:[{type:'paragraph',text:'完整单人、成人比例、稀疏五官;不规则毡头笔线条,头发与裤子用涂抹排线。保留纸片内部的奶油色,纸片以外是真实透明通道。'}, {type:'links',refs:['reference','sample']},{type:'heading',text:'生成提示词'},{type:'paragraph',text:'将 {{subject}} 替换成衣着与动作。每张单独生成,使用绘图工具的透明背景选项。'},{type:'code',text:streetPeople.prompt},{type:'links',refs:['checks','upload','index']}]},
{id:'upload',title:'上传与返回结果',blocks:[{type:'paragraph',text:'先由 agent 生成 PNG,再以 multipart/form-data 提交。API 不负责绘图。'}, {type:'links',refs:['submit','spec']},{type:'code',text:`POST /api/skills/street-people\nContent-Type: multipart/form-data\n\n${Object.entries(streetPeople.upload.fields).map(([k,v])=>k+': '+v).join('\n')}\n\n201: { id, slug, url, assets }\n400: 文件或表单不符合规范\n409: slug 已存在\n413: 超出上传限制\n500: 服务器或存储错误`},{type:'heading',text:'调用示例'},{type:'code',text:`curl -X POST "$BASE/api/skills/street-people" \\\n -F 'title=街头小人 · 冬日片段' \\\n -F 'slug=winter-street-people' \\\n -F 'description=人物动作、提示词与生成来源' \\\n -F 'files=@person.png;type=image/png'`},{type:'paragraph',text:'最多 16 张,单文件 250 MB,总计 1 GB,每张最多 4000 万像素。重复 slug 返回 409,不会覆盖已有笔记。使用返回的 url 查看结果。'},{type:'links',refs:['checks','index']}]},
{id:'checks',title:'交付检查清单',blocks:[{type:'paragraph',text:'逐张检查完整人物、纸片边缘、衣着与动作。外部需要真实透明像素 alpha=0,内部需要接近不透明像素 alpha≥250。仅增加 alpha 通道而没有透明背景的 PNG 会被拒绝。'}, {type:'paragraph',text:'检查无截肢、无额外人物、无文字、无背景和外部阴影。记录生成来源与提示词;来源不同的图包分开提交。服务器的像素检查不能代替 agent 对画风和内容的检查。'}, {type:'links',refs:['style','sample','upload','index']}]},
];
export const skillCatalog=[{id:'street-people',title:'街头小人',category:'图片生成 · 透明 PNG',description:'松散的线条,冬天的衣着。把街上的一个瞬间,剪成一张小贴纸。',image:'/skills/street-people/sample.png',alt:'手绘街头小人,透明剪纸素材',href:'/skills/street-people',created_at:'2026-10-22T17:29:47Z'},{id:'shadow-puppet',title:'照片入皮影',category:'照片转译 · 3:4 海报',description:'把照片里的主角请上幕布,让它用一个姿态演完一整出戏。',image:'/skills/shadow-puppet/egret-example.png',alt:'白鹭照片与暖灯宣纸皮影的上下等分海报示例',href:'/skills/shadow-puppet',created_at:'2026-10-23T03:45:00Z'}];
export type SkillDefinition={id:string;title:string;documents:SkillDocument[];resources:Resource[]};
const definitions:Record<string,SkillDefinition>={
'street-people':{id:'street-people',title:'街头小人',documents:skillDocuments,resources:skillResources.map(r=>r.kind==='api'?{...r,detail:r.method==='POST'?streetPeople.upload:streetPeople,description:r.method==='POST'?'上传接口。阅读上传文档后,由 Agent 使用 multipart/form-data 提交文件。此处仅展示说明,不会发送请求。':'返回 JSON 规范。入口文档负责引导流程,JSON 用于查阅接口结构。'}:r)},
'shadow-puppet':{id:'shadow-puppet',title:'照片入皮影',documents:shadowPuppetDocuments,resources:shadowPuppetResources},
};
export function getSkill(id:string):SkillDefinition|undefined{return Object.hasOwn(definitions,id)?definitions[id]:undefined;}
export function skillDocumentMarkdown(skillId:string,id:string,origin='http://8.211.154.134:18131'){
const skill=getSkill(skillId);const doc=skill?.documents.find(d=>d.id===id);if(!skill||!doc)return null;
return `# ${doc.title}\n\n`+doc.blocks.map(b=>b.type==='heading'?`## ${b.text}`:b.type==='code'?`\x60\x60\x60\n${b.text}\n\x60\x60\x60`:b.type==='links'?b.refs!.map(id=>{const r=skill.resources.find(r=>r.id===id)!;return `- [${r.title}](${new URL(r.href,origin).href})${r.method?' — '+r.method:''}`}).join('\n'):b.text).join('\n\n')+'\n';
}
// Preserve the existing street-people document API.
export function documentMarkdown(id:string,origin?:string){return skillDocumentMarkdown('street-people',id,origin);}
@@ -0,0 +1,63 @@
import {guidanceUrl} from '../page-links';
import {getSkill,skillCatalog,type Block,type Resource} from './catalog';
export type GuidanceResource=Resource&{documentPath?:string};
export type GuidanceDocument={path:string;title:string;collection:string;blocks:Block[];resources:GuidanceResource[]};
const origin='http://8.211.154.134:18131';
export const humanDocumentUrl=(path:string)=>guidanceUrl(path);
export const markdownDocumentUrl=(path:string)=>`${humanDocumentUrl(path)}?agent_mode=True`;
export const legacyDocumentPath=(skill:string,doc:string)=>skill+(['index','SKILL'].includes(doc)?'':`/${doc}`);
export const documentResource=(path:string,title:string,id=`doc:${path}`):GuidanceResource=>({id,kind:'document',title,documentPath:path,href:markdownDocumentUrl(path),human:humanDocumentUrl(path)});
const shared=documentResource('image-delivery','图像交付与来源记录');
// A flat document registry. Collection names organize browsing, never restrict references.
export const guidanceDocuments:GuidanceDocument[]=skillCatalog.flatMap(card=>{
const skill=getSkill(card.id)!;
const resources:GuidanceResource[]=skill.resources.map(r=>{
if(r.kind!=='document')return {...r,id:`${card.id}:${r.id}`};
const legacy=r.href.match(/^\/skills\/([^/]+)\/([^/]+)\.md$/);
const path=r.href.startsWith('/skills/')&&r.href.endsWith('/index.md')?r.href.slice(8,-9)
:legacy?legacyDocumentPath(legacy[1],legacy[2])
:r.human?.startsWith('/skills/')?r.human.slice(8):legacyDocumentPath(card.id,r.id);
const title=skill.documents.find(d=>legacyDocumentPath(card.id,d.id)===path)?.title??r.title;
return documentResource(path,title,`${card.id}:${r.id}`);
});
return skill.documents.map(doc=>({
path:legacyDocumentPath(card.id,doc.id),title:doc.title,collection:skill.title,
resources:[...resources,shared],
blocks:[...doc.blocks.map(b=>b.type==='links'?{...b,refs:b.refs!.map(id=>`${card.id}:${id}`)}:{...b}),
...(['checks','delivery'].includes(doc.id)?[{type:'heading' as const,text:'共用指导文档'},{type:'links' as const,refs:[shared.id]}]:[])],
}));
});
guidanceDocuments.push({
path:'image-delivery',title:'图像交付与来源记录',collection:'共用指导',
resources:[documentResource('street-people/checks','透明人物验收'),documentResource('shadow-puppet/delivery','皮影海报验收与上传')],
blocks:[
{type:'paragraph',text:'这是一份可被不同创作方法共同引用的指导文档。每篇文档都有独立网址,引用不会复制或隔离内容。'},
{type:'heading',text:'交付前确认'},
{type:'paragraph',text:'按照具体任务确认尺寸、比例、格式、透明背景与成品数量。保留原始生成文件;透明 PNG 与有背景的海报使用各自的验收规则。'},
{type:'heading',text:'记录来源'},
{type:'paragraph',text:'记录原片或参考图、使用的提示词、生成工具及必要的修改说明。来源不同的作品分开说明,便于复用时追溯。'},
{type:'heading',text:'选择对应的交付协议'},
{type:'paragraph',text:'阅读目标文档的上传说明再提交。不同接口的字段和校验条件可能不同,以被引用文档为准。'},
{type:'links',refs:['doc:street-people/checks','doc:shadow-puppet/delivery']},
],
});
const registry=new Map(guidanceDocuments.map(doc=>[doc.path,doc]));
export function getGuidance(path:string){return registry.get(path);}
export function guidanceBacklinks(path:string){return guidanceDocuments.filter(doc=>doc.path!==path&&doc.blocks.some(b=>b.type==='links'&&b.refs!.some(id=>doc.resources.find(r=>r.id===id)?.documentPath===path)));}
export function guidanceMarkdown(path:string,base=origin){
const doc=getGuidance(path);if(!doc)return null;
const url=(href:string)=>new URL(href,base).href;
const blocks=doc.blocks.map(b=>b.type==='heading'?`## ${b.text}`:b.type==='code'?`\x60\x60\x60\n${b.text}\n\x60\x60\x60`:b.type==='links'?b.refs!.map(id=>{
const r=doc.resources.find(r=>r.id===id)!;return `- [${r.title}](${url(r.href)})${r.method?' — '+r.method:''}`;
}).join('\n'):b.text).join('\n\n');
const incoming=guidanceBacklinks(path);
return `# ${doc.title}\n\n[网页版本](${url(humanDocumentUrl(path))}) · [全部指导文档](${url('/skills/index.md')})\n\n${blocks}\n`+
(incoming.length?`\n## 引用本文的文档\n\n${incoming.map(d=>`- [${d.title}](${url(markdownDocumentUrl(d.path))})`).join('\n')}\n`:'');
}
export function guidanceIndexMarkdown(root=false,base=origin){
const url=(href:string)=>new URL(href,base).href;
return `# ${root?'PROMPT':'指导文档'}\n\n[网页版本](${url(root?'/':'/skills')}) · [指导文档目录](${url('/skills/index.md')})\n\n每篇指导文档都有独立网址,网页地址加 /index.md 即为对应的 Markdown。文档可以相互引用,不要求从某个技能入口逐级进入。\n\n## 全部指导文档\n\n`+
guidanceDocuments.map(d=>`- [${d.title}](${url(markdownDocumentUrl(d.path))}) — ${d.collection}`).join('\n')+'\n';
}
@@ -0,0 +1,516 @@
import type {Resource,SkillDocument} from "./catalog";
export const shadowPuppetResources:Resource[] = [
{
"id": "index",
"kind": "document",
"title": "入口文档 · SKILL.md",
"href": "/skills/shadow-puppet/SKILL.md",
"human": "/tools/skills/shadow-puppet"
},
{
"id": "workflow",
"kind": "document",
"title": "制作流程",
"href": "/skills/shadow-puppet/workflow.md",
"human": "/tools/skills/shadow-puppet/workflow"
},
{
"id": "visual-grammar",
"kind": "document",
"title": "画面与皮影语法",
"href": "/skills/shadow-puppet/visual-grammar.md",
"human": "/tools/skills/shadow-puppet/visual-grammar"
},
{
"id": "prompt",
"kind": "document",
"title": "完整提示词",
"href": "/skills/shadow-puppet/prompt.md",
"human": "/tools/skills/shadow-puppet/prompt"
},
{
"id": "delivery",
"kind": "document",
"title": "验收与上传",
"href": "/skills/shadow-puppet/delivery.md",
"human": "/tools/skills/shadow-puppet/delivery"
},
{
"id": "egret-example",
"kind": "image",
"title": "白鹭成品示例",
"href": "/skills/shadow-puppet/egret-example.png"
},
{
"id": "dancer-example",
"kind": "image",
"title": "舞者成品示例",
"href": "/skills/shadow-puppet/dancer-example.png"
},
{
"id": "upload-api",
"kind": "api",
"title": "上传独立海报",
"href": "/api/upload",
"method": "POST",
"description": "Agent 完成图片生成与视觉验收后,再使用此接口上传;接口本身不绘图。",
"detail": {
"encoding": "multipart/form-data",
"fields": {
"kind": "image",
"title": "必填,海报或系列标题",
"files": "1–16 个独立 PNG/JPG 成品",
"description": "原片与提示词记录(可选)",
"tags": "已有分类 UUID 数组 JSON(可选)",
"slug": "唯一网址标识(可选)"
},
"response": {
"status": 201,
"body": {
"id": "post UUID",
"slug": "稳定标识",
"url": "/p/<slug>",
"assets": [
"asset UUID"
]
}
},
"limits": {
"files": 16,
"bytesPerFile": 262144000,
"totalBytes": 1073741824
},
"validation": "API 检查上传格式;3:4、上下等分与视觉质量由 Agent 检查"
}
},
{
"id": "media-api",
"kind": "api",
"title": "读取成品原图",
"href": "/api/media/{asset-id}",
"method": "GET",
"template": true,
"description": "将 {asset-id} 替换为上传返回的素材 UUID,再请求此地址;模板不是可以直接请求的成品地址。",
"detail": {
"pathParameter": {
"asset-id": "上传返回的素材 UUID"
},
"response": "原始图片字节;保留原图格式",
"supports": [
"GET",
"HEAD",
"Range"
]
}
}
];
export const shadowPuppetDocuments:SkillDocument[] = [
{
"id": "index",
"title": "照片入皮影",
"blocks": [
{
"type": "paragraph",
"text": "把照片里的主角请上幕布,让它用一个姿态演完一整出戏。"
},
{
"type": "paragraph",
"text": "将每张原始照片分别制作成一张 3:4 竖版海报。上半张保留摄影,下半张把同一个主角转译成中国传统皮影戏偶;上下区域严格等高。每张照片独立输出,不将多张照片拼接。"
},
{
"type": "heading",
"text": "何时使用"
},
{
"type": "paragraph",
"text": "用于人物、动物、建筑、植物、器物与风景照片的皮影转译。创作由 coding agent 自带的图像生成/编辑工具执行,网站提供文档、参考图与成品上传 API,不执行服务器端模型推理。"
},
{
"type": "heading",
"text": "输入与参考图"
},
{
"type": "paragraph",
"text": "先区分原始照片与风格参考。只有原始照片决定主角的身份、结构、姿态和叙事关系。"
},
{
"type": "paragraph",
"text": "- 白鹭成品示例:参考弯颈、抬足与皮影关节的对应方式,以及暖灯透光效果。"
},
{
"type": "links",
"refs": [
"egret-example"
]
},
{
"type": "paragraph",
"text": "- 舞者成品示例:参考扬袖姿态如何转译成铆钉连接、镂刻纹样和操纵竹签。"
},
{
"type": "links",
"refs": [
"dancer-example"
]
},
{
"type": "paragraph",
"text": "这两张是完成海报,已经含有上下两个区域;不能当成新的原始照片套入上半区,也不能再把它们整张拼进海报。示例用于理解技法;构图比例、留白与主体占比以文字规范为准。"
},
{
"type": "paragraph",
"text": "如果用户只给了完成示例而没有原始照片,可以整理规范与提示词;需要正式生成时,请用户提供原始照片,不编造照片里的主角。只有明确获准时才从示例中截取上半区作为输入。"
},
{
"type": "heading",
"text": "执行顺序"
},
{
"type": "paragraph",
"text": "1. 阅读制作流程,逐张识别主角、姿态与配色。"
},
{
"type": "links",
"refs": [
"workflow"
]
},
{
"type": "paragraph",
"text": "2. 阅读画面与皮影语法,锁定 3:4、上下 1:1 和一幕一偶。"
},
{
"type": "links",
"refs": [
"visual-grammar"
]
},
{
"type": "paragraph",
"text": "3. 使用完整提示词,为每张照片单独调用图像编辑工具。"
},
{
"type": "links",
"refs": [
"prompt"
]
},
{
"type": "paragraph",
"text": "4. 按验收与上传检查成品,再将独立图片发布到网站。"
},
{
"type": "links",
"refs": [
"delivery"
]
},
{
"type": "paragraph",
"text": "完整资源索引包含本技能的全部子文档、参考图片和 API。参考图片以链接提供,执行时先区分风格参考与原始照片。"
},
{
"type": "heading",
"text": "完整资源索引"
},
{
"type": "links",
"refs": [
"index",
"workflow",
"visual-grammar",
"prompt",
"delivery",
"egret-example",
"dancer-example",
"upload-api",
"media-api"
]
}
]
},
{
"id": "workflow",
"title": "制作流程",
"blocks": [
{
"type": "heading",
"text": "1. 先建立逐张任务"
},
{
"type": "paragraph",
"text": "把每张原始照片分配独立编号。多张原片可以连续处理,但每次图像工具调用只对应一张原片,最终每张输出一个独立海报文件。不生成九宫格、联系表或多照片拼贴。"
},
{
"type": "paragraph",
"text": "记录原片文件名、主体识别点、最具表情的姿态、主叙事关系及 2–3 个配色。将成品示例仅作为风格参考,明确区别 edit target 与 style reference。"
},
{
"type": "heading",
"text": "2. 锁定画板"
},
{
"type": "paragraph",
"text": "选择工具支持的精确 3:4 尺寸,优先 1536 × 2048 或等比规格;中线严格为 H/2。若工具无法保证精确尺寸和等分,必须在验收时标出并修正,不能把“约 3:4”称为合格。"
},
{
"type": "paragraph",
"text": "先确定上半区如何容纳原始照片。仅在必要时自然扩展环境背景,保持主体身份、结构与姿态;避免以放大裁切牺牲脚、翅膀、手臂、建筑尖顶或重要物件。"
},
{
"type": "heading",
"text": "3. 为同一主角设计一具戏偶"
},
{
"type": "paragraph",
"text": "不要机械复制照片纹理。先找最能辨认的轮廓和姿态,再简化成少量活动部件:例如白鹭的弯颈与抬足、舞者的扬袖与重心、建筑的檐线与层叠关系。关节、铆钉、雕纹与竹签都围绕这些特点组织。"
},
{
"type": "heading",
"text": "4. 独立调用图像工具"
},
{
"type": "paragraph",
"text": "使用完整提示词,标明原片与示例的不同角色。选择不透明的完整海报背景;本技能不输出透明贴纸。每张原片独立调用并保存。"
},
{
"type": "links",
"refs": [
"prompt"
]
},
{
"type": "paragraph",
"text": "只对失败点做针对性修改:例如上半区身份偏移、分界偏离中线、戏偶过大、关节不合理、缺少竹签、灯光像聚光舞台或出现多余人物。修改时再次锁定其他正确内容。"
},
{
"type": "heading",
"text": "5. 验收并发布"
},
{
"type": "paragraph",
"text": "按照验收与上传确认尺寸、等分、主体保真与皮影语法。先检查,再上传。记录实际使用的提示词、工具和原片映射,供以后复现与重做。"
},
{
"type": "links",
"refs": [
"delivery"
]
},
{
"type": "links",
"refs": [
"index"
]
}
]
},
{
"id": "visual-grammar",
"title": "画面与皮影语法",
"blocks": [
{
"type": "heading",
"text": "尺寸是硬约束"
},
{
"type": "paragraph",
"text": "完整海报宽高比为 3:4,竖版。上下区域高度严格 1:1,各占全图 50%。例如 1536 × 2048 像素,上半区 y=0–1023,下半区 y=1024–2047;分界线位于 y=1024。不得因为题字、边框或留白改变两区高度。两个区块横向铺满画幅,不在外层额外增加标题栏或页脚。"
},
{
"type": "heading",
"text": "上半区:原始照片"
},
{
"type": "paragraph",
"text": "保留主体身份、结构、姿态、真实材质、自然光影与原有色彩氛围。仅进行轻微高级调色,呈现艺术摄影与东方展览图像质感。适配宽幅半区时,优先自然扩展周围环境,保持主体完整;不得拉伸、扭曲、改脸、改变肢体或裁掉最具识别度的动作。禁止把摄影区也做成皮影、插画或 3D。"
},
{
"type": "heading",
"text": "下半区:被老手艺人重新理解的角色"
},
{
"type": "paragraph",
"text": "从照片提取最具识别性的主体、轮廓、姿态与叙事关系。无论原图是人物、动物、建筑、植物、器物还是风景,都理解为可被操纵的一个角色。"
},
{
"type": "paragraph",
"text": "- 用少量平面关节部件概括,以可见铆钉相连。关节服务于原图动作,不能任意拼接。"
},
{
"type": "paragraph",
"text": "- 侧面化、平面化;使用装饰性镂空、云纹与几何雕刻纹样,以及局部半透明彩染。"
},
{
"type": "paragraph",
"text": "- 一两根细长操纵竹签从下边缘伸入并合理连接。不要额外加入操偶人。"
},
{
"type": "paragraph",
"text": "- 一幕一偶与大量留白。主角约占幕布画面 25%–35%,其余空间保持安静;可偏心或靠黄金分割位置。"
},
{
"type": "paragraph",
"text": "- 对建筑、植物和风景,选择照片最具识别性的整体轮廓及关系,把它概括为一具能够活动的戏偶;不要加入无关的人物或堆满一套风景舞台。"
},
{
"type": "paragraph",
"text": "- 照片里有多个主体时,先确定主叙事;若无法在一偶中保留关键关系,先确认创作取舍,不擅自删掉关系核心。"
},
{
"type": "heading",
"text": "灯、纸与颜色"
},
{
"type": "paragraph",
"text": "下半区是在暖光照亮的半透明宣纸幕布上演出,不是摆在台面上的皮影工艺品。幕布呈米黄或浅琥珀光场,四周自然暗下。后方一盏暖灯照透镂空处,形成温暖光点;皮影边缘具有柔和投影虚边和轻微光晕。允许极轻微双影或动态虚影,像缓慢移动中的一瞬间。"
},
{
"type": "paragraph",
"text": "从原照片提取 2–3 种最具情绪价值的颜色,转译成朱红、靛青、橄榄绿、琥珀黄体系内协调的半透明彩染;不必强行集齐全部颜色。阴影使用深褐与暖墨色,避免冷黑。"
},
{
"type": "heading",
"text": "文字可选"
},
{
"type": "paragraph",
"text": "可在幕布一角用少量安静的竖排小字写戏名或短句,像手写节目单。文字不是必需。用户没有指定文案时,宁可无字,也不生成无意义书法、乱码或大标题。"
},
{
"type": "heading",
"text": "避免"
},
{
"type": "paragraph",
"text": "完整写实的下半区、卡通化、廉价国潮、模板化海报、塑料质感、3D 渲染、满场景堆砌、观众、舞台全景、复杂道具。摄影与皮影都必须来自同一张原始照片,不混入另一张照片的主体。"
},
{
"type": "links",
"refs": [
"index"
]
}
]
},
{
"id": "prompt",
"title": "完整提示词",
"blocks": [
{
"type": "paragraph",
"text": "以下提示词每次只对应一张原始照片。将方括号字段替换为当前照片信息,生成前删除不使用的可选题字。"
},
{
"type": "code",
"text": "任务:将本次提供的这一张原始照片制作成一张独立的高级设计海报,不多图拼接。输出 3:4 竖版,尺寸 [1536×2048 或工具支持的精确等比尺寸]。上下两个区域高度严格 1:1,各占全图 50%;水平分界位于画面高度的 50%。两个区域横向铺满,外层没有额外页眉、页脚或改变等分的边框。\n\n输入角色:\n- 原始照片(编辑目标):[原片文件名或链接]。本海报中的所有主体与叙事来自这一张照片。\n- 风格参考(如提供):[白鹭/舞者成品示例链接]。它们已经是完成的海报,只参考皮影技法和光感,不复制主体,不将示例整图放进上半区。\n\n原片观察:\n- 主体与不可改变的识别点:[身份、结构、轮廓与关键物件]\n- 最有表情的瞬间:[姿态、朝向、重心与动作]\n- 核心叙事关系:[主体之间或主体与环境的关系]\n- 2–3 种情绪色:[从本张照片中提取]\n\n上半部分:保留原始照片,保持主体身份、结构、姿态、真实质感、自然光影与原有色彩氛围。仅轻微高级调色,具有艺术摄影与东方展览图像质感。适配画幅时可自然扩展环境背景,禁止拉伸、扭曲、改脸、增减肢体或改变主体。保持关键动作完整;上半区仍然是照片。\n\n下半部分:提取同一原片最具识别性的主体、轮廓、姿态与叙事关系,重构为一具中国传统皮影戏偶(shadow puppet),正在一面暖光照亮的半透明宣纸幕布上演出。无论原图是人物、动物、建筑、植物、器物还是风景,都将它理解为可被操纵的一个角色。主体拆分为少量合理关节部件,以铆钉相连,姿态取自照片最有表情的瞬间;一两根细长的操纵竹签自画面下方伸入并连接戏偶。\n\n用皮影的造型语法重新概括,而非写实复制或卡通化:侧面化、平面化、装饰性镂空、云纹与几何雕刻纹样、局部半透明彩染。保留原物最具识别度的特征,使人一眼认出,同时像被老手艺人重新理解和雕刻过。\n\n光影:幕布后方一盏暖色灯光,镂空处透出温暖光点。照片中的情绪色转译为半透明的朱红、靛青、橄榄绿或琥珀黄,不必使用全部颜色。边缘带柔和投影虚边与轻微光晕,可有极轻微双影或动态虚影,像缓慢演出中的一瞬间。阴影用深褐与暖墨,不用冷黑。\n\n下半区构图:一幕一偶、大量留白。米黄或浅琥珀色暖光场,四周自然暗下。戏偶主体约占幕布画面的 25%–35%,可偏心或位于黄金分割位置,其余空间安静,如戏开场前的停顿。不出现观众、操偶人、舞台全景或复杂道具。\n\n文字:[可选:在幕布一角竖排少量小字“用户指定戏名或短句”]。未指定文案则无字,不添加主标题、广告文字、乱码或无意义书法。\n\n最终呈现:皮影镂刻、半透明彩染、暖灯幕布、柔和投影与东方留白共同构成光影视觉。核心原则:把照片里的主角请上幕布,让它用一个姿态演完一整出戏。\n\n禁止:多照片拼贴、上下比例偏移、主体身份改变、下半区完整写实、卡通、廉价国潮、塑料质感、3D 渲染、满场景堆砌、模板化海报。每张原始照片单独输出一个完整海报文件,画布背景不透明。"
},
{
"type": "links",
"refs": [
"index"
]
}
]
},
{
"id": "delivery",
"title": "验收与上传",
"blocks": [
{
"type": "heading",
"text": "画面验收"
},
{
"type": "paragraph",
"text": "- 文件为独立 3:4 竖版海报。可检查 width × 4 === height × 3,且 height 为偶数。"
},
{
"type": "paragraph",
"text": "- 摄影与皮影区的分界位于 height / 2。仅有正确文件尺寸不足以证明上下等分,仍需查看画面。"
},
{
"type": "paragraph",
"text": "- 上半区保留同一原片主体身份、结构、姿态、自然质感和配色;没有被重新画成插画。"
},
{
"type": "paragraph",
"text": "- 下半区是同一主角的一具皮影,轮廓与动作可辨,有合理的关节铆钉及一两根从下缘伸入的竹签。"
},
{
"type": "paragraph",
"text": "- 镂空透暖光、彩染半透明、纸幕材质明确、投影柔软,留白充足;没有观众、复杂舞台、3D 或卡通。"
},
{
"type": "paragraph",
"text": "- 每张原片对应一个独立成品,没有多照片拼贴。题字若有,必须可读且符合指定内容。"
},
{
"type": "paragraph",
"text": "本技能的整张海报背景不透明。不要使用「街头小人」的透明 PNG 专用接口;该接口针对另一种交付要求。"
},
{
"type": "heading",
"text": "上传 API"
},
{
"type": "paragraph",
"text": "使用网站通用接口 POST /api/upload,编码为 multipart/form-data。请求字段:"
},
{
"type": "paragraph",
"text": "- kind=image。"
},
{
"type": "paragraph",
"text": "- title:必填,当前海报或系列标题。"
},
{
"type": "paragraph",
"text": "- files:独立海报文件。PNG 或 JPG;一张照片输出一个文件。"
},
{
"type": "paragraph",
"text": "- description:可选,记录原片标识、提示词、生成工具与制作说明。"
},
{
"type": "paragraph",
"text": "- tags:可选,已有分类 UUID 数组的 JSON;没有分类时使用 [] 或不传。"
},
{
"type": "paragraph",
"text": "- slug:可选,唯一的小写英文、数字和连字符标识。"
},
{
"type": "paragraph",
"text": "默认每张照片一份独立海报;如果用户要求组成系列,可以把多个独立海报文件作为同一 post 的多图上传,文件仍必须逐张独立。不要为凑系列把它们拼在同一张图片里。"
},
{
"type": "paragraph",
"text": "单次最多 16 个文件,单个不超过 250 MB,总计不超过 1 GB。上传接口校验文件格式;3:4、上下等分与视觉质量由 Agent 在上传前验收,不宣称接口自动识别构图。"
},
{
"type": "code",
"text": "# BASE 为当前 PROMPT 网站的根地址\ncurl -X POST \"$BASE/api/upload\" \\\n -F 'kind=image' \\\n -F 'title=照片入皮影 · 戏名' \\\n -F 'description=原片:photo-01;每张单独制作;已检查3:4与上下等分。' \\\n -F 'files=@photo-01-shadow-puppet.png;type=image/png'"
},
{
"type": "paragraph",
"text": "成功返回 201,包含 id、slug、url 和 assets。用返回的 url 打开 post;assets 为可复用素材 ID。引用或下载原图使用 GET /api/media/<asset-id>。"
},
{
"type": "paragraph",
"text": "400 表示表单或文件格式不符合要求,409 表示 slug 已存在,413 表示文件数量或大小超限,500 表示服务或存储异常。失败时不重复盲传;先检查错误。给用户回报真实的文件、post 地址与已完成的检查,不把推送成功当成生产上传成功。"
},
{
"type": "links",
"refs": [
"upload-api",
"media-api",
"index"
]
}
]
}
];
+11
View File
@@ -0,0 +1,11 @@
export const namespaces=['Main','File','Category','Template','Draft','Help'] as const;
export type Namespace=typeof namespaces[number];
export type WikiPage={namespace:Namespace;slug:string;title:string;summary:string;body:string;categories:string[];color:string};
export const wikiPages:WikiPage[]=[
{namespace:'Main',slug:'welcome',title:'让灵感有处可寻',summary:'像翻阅笔记一样,发现和连接知识。',body:'这里是 PROMPT Wiki。每个条目都有一个稳定的页面地址,以及对应的 Markdown 正文。\n\n名字空间决定页面的用途,分类把不同用途的内容连接起来。素材可以被多篇条目引用,草稿也可以在成熟后成为正式条目。',categories:['创作方法'],color:'#f5ddd2'},
{namespace:'Help',slug:'namespaces',title:'名字空间,内容的不同房间',summary:'条目、文件、分类、模板与草稿,各有自己的位置。',body:'Main:正式知识条目。\nFile:图片、视频、音频的说明页,现有素材包位于 /wiki/File:slug,同时保留 /p/ 兼容地址。\nCategory:跨名字空间的分类索引。\nTemplate:可复用的内容结构说明。\nDraft:待完善的草稿(当前内容公开,不用于私密信息)。\nHelp:使用指南。\n\n在 src/content/wiki.ts 添加内容,即可生成网页与 AI 正文。现有素材包也提供 /api/wiki-post/slug 的 Markdown。',categories:['使用指南'],color:'#dde8df'},
{namespace:'Template',slug:'idea',title:'一个想法的骨架',summary:'从问题、观察到表达,让创作有迹可循。',body:'## 问题\n你想回答什么?\n\n## 观察\n收集具体场景与可信来源。\n\n## 表达\n把结论写成独立的页面,再交给创作站制作。',categories:['创作方法'],color:'#e6def0'},
{namespace:'Draft',slug:'inbox',title:'还没成形,也值得留下',summary:'给正在生长的想法留一个位置。',body:'草稿用于公开孵化内容。补充来源、结构和分类后,可以迁移到 Main 名字空间。',categories:['创作方法'],color:'#f0e7ca'}];
export function wikiPath(p:Pick<WikiPage,'namespace'|'slug'>){return '/wiki/'+encodeURIComponent(p.namespace+':'+p.slug);}
export function wikiMarkdown(p:WikiPage){return '# '+p.title+'\n\nNamespace: '+p.namespace+'\nCategories: '+p.categories.join(', ')+'\n\n'+p.summary+'\n\n'+p.body+'\n';}
export function findWikiPage(key:string):WikiPage|undefined{if(key.startsWith('Category:')){const name=key.slice(9);const members=wikiPages.filter(p=>p.categories.includes(name));if(!members.length)return;return {namespace:'Category',slug:name,title:name,summary:'分类中的相关页面',body:members.map(p=>'['+p.namespace+':'+p.title+']('+wikiPath(p)+')').join('\n\n'),categories:[],color:'#e6e9ef'};}return wikiPages.find(p=>p.namespace+':'+p.slug===key);}
@@ -0,0 +1,101 @@
import type {NextApiRequest,NextApiResponse} from 'next';
// Read documentation before business validation or storage access. Mutations never enter this branch.
export const apiDocuments:Record<string,readonly string[]>={
"/api/explore-feed": [
"统一内容流",
"GET",
"查询参数:q(可选,最多 200 字符);category(可选,标签名称或命名空间);cursor(可选,上一页 nextCursor)。",
"JSON:entries、total、sort 与 nextCursor;entry.backlinkCount 为不同来源笔记数(重复链接和自引用不计);默认按引用数降序,搜索时先按标题/标签/简介/正文的匹配程度再按引用数排序,最后按新旧排序。q 支持空格分隔的多个关键词(全部匹配)及双引号短语,中英文不区分大小写。分类过滤发生在分页之前。没有更多结果时 nextCursor 为 null。静态文档与数据库笔记统一搜索与分页;已由相同 publicId 的数据库笔记接管时不重复展示。",
"GET /api/explore-feed?q=排版",
"400:游标无效或与搜索条件不符;503:素材库暂时无法连接。"
],
"/api/feed": [
"素材列表",
"GET",
"查询参数:section(images / videos / audio / articles / motion,可选);path(可选,标签 path);q(可选,最多 200 字符);cursor(可选,上一页 nextCursor)。",
"JSON:posts、tags、contributions、nextCursor;每页最多 24 个 post。",
"GET /api/feed?section=images",
"400:未知 section、标签或无效游标。"
],
"/api/notes/{id}": [
"读取与编辑笔记",
"GET, PUT, PATCH",
"PATCH 只更新标签,application/json 必须为 {tags:标签 UUID 数组,revision:GET 返回值};系统标签从 GET /api/tags 中 kind=system 的固定项选择。路径参数:id,笔记稳定 ID(publicId 或存储 UUID)。PUT 使用 application/json,以下字段必填:title(1–200 字符)、description(最多 1000 字符)、markdown(最多 100000 字符)、tags(最多 50 个标签 UUID)、revision(GET 返回的 entry.revision,64 位十六进制)。可选 assets(最多 100 项 {id:媒体 UUID,role:content|caption},替换媒体关联,原二进制不删除);coverAssetId(图片 UUID 或 null,必须为本笔记 content 图片;null 清除显式封面)。静态代码页须先通过创建接口保存为数据库笔记,才可更新媒体。",
"GET 返回 {entry,tags},entry.backlinks 为引用来源 {id,title} 数组,entry.backlinkCount 为其长度;只计算正文中本站 post 的 Markdown 链接(含引用式链接和粘贴的完整网址),排除代码块、图片、外站链接及自引用。entry.assets 为媒体关联、entry.coverAssetId 为显式封面;PUT 返回更新后的 {entry}。先 GET 获取 revision,再 PUT;冲突后重新读取。",
"GET /api/notes/{id}\nPUT /api/notes/{id}\n{\"title\":\"标题\",\"description\":\"简介\",\"markdown\":\"正文\",\"tags\":[],\"revision\":\"<GET 返回的 entry.revision>\"}",
"400:输入错误;404:笔记不存在;409:版本冲突。"
],
"/api/posts": [
"创建笔记或素材包",
"POST",
"application/json:kind(必填,image / video / audio / article / motion)、title(必填,1–200 字符);publicId(可选,唯一的 24 位小写十六进制稳定 ID,用于保留原页面地址);slug(可选,最多 120 字符,以小写字母或数字开头,仅含小写字母、数字、连字符);description(可选,最多 1000 字符);text(可选,最多 100000 字符);tags(可选,最多 50 个 UUID);coverAssetId(可选,图片 UUID);assets(可选,最多 100 项,{id: UUID,role: content | caption},role 默认 content)。媒体类型必须引用至少一个对应类型的 content 素材。",
"201 JSON:{id,slug,url,publicId?},url 为 /explore/<publicId 或 id>。id 仍为存储 UUID。引用已有素材;不会在此接口上传二进制文件。",
"POST /api/posts\n{\"kind\":\"article\",\"title\":\"新笔记\",\"text\":\"正文\",\"tags\":[]}",
"400:输入或素材引用不合法;409:slug 或 publicId 已存在。"
],
"/api/tags": [
"标签列表与创建",
"GET, POST",
"标签 JSON 含 kind=normal|system;系统项另含 system_key。POST 只允许创建/复用普通标签,不能提交 kind 或 system_key,也不能用名称添加系统标签;系统标签只通过已有 UUID 选择。POST 使用 application/json:name(必填,去掉开头 # 并 trim 后 1–60 字符,不含 #、空白、英文或中文逗号);slug(可选,最多 60 字符,以小写字母或数字开头,仅含小写字母、数字、连字符)。",
"GET 返回标签数组;POST 新建返回 201,名称已存在时复用并返回 200。标签含 id、name、slug、path。",
"POST /api/tags\n{\"name\":\"排版\"}",
"400:输入错误;409:slug 冲突。"
],
"/api/upload": [
"上传媒体,可独立保存素材",
"POST",
"multipart/form-data:kind(必填,image / video / audio);title(普通上传必填,1–200 字符;assetOnly=true 时可省略);assetOnly(可选,字符串 true / false,默认 false;true 时只存媒体,不创建 post);slug(可选,小写字母或数字组成的非空段,以连字符分隔,最多 120 字符);description(可选,最多 100000 字符);tags(可选,UUID 数组的 JSON 字符串,最多 50 项);文件字段名任意,至少一个文件。最多 16 个文件,单个不超过 250 MB,总计不超过 1 GB。图片支持 JPG、PNG、WebP、GIF、AVIF;音频必须为独立声音文件。",
"201 JSON:普通上传为 {id,slug,url,assets};assetOnly=true 为 {assets,files:[{id,filename,sha256}]},不创建 post。assets 为素材 UUID 数组,之后可交给 /api/posts 组合;视频素材会自动进入后台加工队列。",
"POST /api/upload\nContent-Type: multipart/form-data\nkind=image\ntitle=示例图片\ntags=[]\nfile=<图片文件>",
"400:输入或媒体不合法;409:slug 冲突;413:上传超过限制。"
],
"/api/media/{id}": [
"读取媒体原件或衍生文件",
"GET, HEAD",
"路径参数:id,素材 UUID。查询参数:variant(可选,poster / silent_video / audio_track,读取以 id 为来源的衍生素材)。支持 Range 请求头。",
"二进制媒体,Content-Type 随文件类型变化;200 为完整文件,206 为范围响应,HEAD 无正文。",
"GET /api/media/{id}?variant=poster",
"404:素材不存在或无效 variant;416:请求范围无效。"
],
"/api/preview": [
"轻量图片预览",
"GET, HEAD",
"查询参数:source(必填,本站静态栅格图片路径,或 /api/media/<UUID>,可带 ?variant=poster;作为查询值时必须 URL 编码);width(可选,240 / 480 / 960 / 1280,默认 480)。不接受任意远程图片地址。支持 If-None-Match。",
"WebP 图片;包含 ETag;缓存命中可返回 304;HEAD 无正文。",
"GET /api/preview?source=%2Fapi%2Fmedia%2F<UUID>&width=480",
"400:参数不合法;404:图片不存在;503:预览暂不可用。"
],
"/api/skills/street-people": [
"透明人物规范与上传",
"GET, POST",
"GET 默认返回 JSON 规范,format=md 返回创作指导 Markdown。POST 使用 multipart/form-data,沿用 /api/upload 字段与大小限制;kind 固定为 image,title 默认“街头小人 · 新生成”。图片必须为带 alpha 的 PNG,含 alpha=0 的透明像素及 alpha≥250 的像素。",
"GET 返回生成规范;POST 返回 201 {id,slug,url,assets}。",
"GET /api/skills/street-people\nPOST /api/skills/street-people\nContent-Type: multipart/form-data\nfile=<透明 PNG>",
"400:图片或字段不合法;413:超过上传限制。"
],
"/api/health": [
"应用健康检查",
"GET, HEAD",
"无业务参数。",
"GET 返回 JSON:status、service、release;HEAD 仅返回状态和响应头。",
"GET /api/health",
"405:不支持的方法。"
],
"/api/ready": [
"依赖就绪检查",
"GET",
"无业务参数。检查 PostgreSQL 和对象存储桶。",
"200 JSON:{\"status\":\"ok\",\"database\":\"ready\",\"objects\":\"ready\"}。",
"GET /api/ready",
"503 JSON:{\"status\":\"unavailable\"}。"
]
};
export function serveApiDocumentation(req:NextApiRequest,res:NextApiResponse,path:string){
if(!['GET','HEAD'].includes(req.method||'')||typeof req.query.agent_mode!=='string'||req.query.agent_mode.toLowerCase()!=='true')return false;
const doc=apiDocuments[path];if(!doc)return false;
const [title,methods,parameters,response,example,errors]=doc;
const text=`# ${title}\n\n地址:${path}\n方法:${methods}\n\n## 参数\n${parameters}\n\n## 响应\n${response}\n\n## 调用示例\n${example}\n\n## 错误\n${errors}\n\n## 读取说明\n使用 GET 或 HEAD,在原地址加 ?agent_mode=True;已有查询参数时加 &agent_mode=True。值不区分大小写。动态路径可使用实际 ID,也可保留占位符读取本接口说明。\n业务调用请移除 agent_mode。POST / PUT 不会被转换为说明请求。写入接口会拒绝 Origin 与 Host 不一致的请求;当前没有 API Key 或登录鉴权。\n\nAPI 目录:/api?agent_mode=True\n`;
res.setHeader('Content-Type','text/plain; charset=utf-8');res.setHeader('Cache-Control','no-store');
res.status(200);if(req.method==='HEAD')res.end();else res.send(text);return true;
}
+28
View File
@@ -0,0 +1,28 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { ZodError } from "zod";
export function sameOrigin(req: NextApiRequest) {
const origin=req.headers.origin;
if (origin && new URL(origin).host !== req.headers.host) throw new Error("Cross-origin request rejected");
}
export function apiError(res: NextApiResponse,error: unknown) {
if(error instanceof ZodError) return res.status(400).json({error:"请检查输入内容",issues:error.issues});
const message=error instanceof Error?error.message:"";
const clientMessages:Record<string,string>={
'Media changes require a stored note':'媒体与封面需先通过创建接口保存为数据库笔记',
'Character PNG must have transparency':'请上传带真实透明背景的 PNG,透明区域 alpha 为 0,人物内部 alpha 至少为 250',
'Referenced asset does not exist':'引用的素材不存在',
'A media post needs matching content':'素材包需要包含对应类型的素材',
'Cover must reference an image':'封面需要引用一张图片',
'Unsupported image format':'支持 JPG、PNG、WebP、GIF 和 AVIF 图片',
'File has no video stream':'文件中没有可用的画面',
'Select an audio file':'请选择独立的声音文件',
'Unsupported media MIME type':'文件类型不受支持',
};
if(clientMessages[message])return res.status(400).json({error:clientMessages[message]});
const code=(error as {code?:string})?.code;
if(code==='23505')return res.status(409).json({error:'这个网址标识已经存在,请换一个'});
if(code==='23503')return res.status(400).json({error:'引用的分类或素材不存在'});
if(["Invalid cursor","Tag not found","Cross-origin request rejected"].includes(message)) return res.status(400).json({error:message});
console.error("API failure",error instanceof Error?error.message:"Unknown error");
return res.status(500).json({error:"操作没有完成,请稍后重试"});
}
@@ -0,0 +1,10 @@
import type {PoolClient} from 'pg';
// Serialize appending links so a worker and a concurrent editor cannot reuse a position.
export async function linkDerivedAssets(client:PoolClient,postId:string){
await client.query('SELECT id FROM posts WHERE id=$1 FOR UPDATE',[postId]);
await client.query(`INSERT INTO post_assets(post_id,asset_id,position,role)
SELECT $1,a.id,COALESCE((SELECT max(position)+1 FROM post_assets WHERE post_id=$1),0)
+row_number() OVER(ORDER BY a.id)::integer-1,a.derivation
FROM assets a WHERE a.source_asset_id IN (SELECT asset_id FROM post_assets WHERE post_id=$1 AND role='content')
AND NOT EXISTS(SELECT 1 FROM post_assets pa WHERE pa.post_id=$1 AND pa.asset_id=a.id)`,[postId]);
}
+19
View File
@@ -0,0 +1,19 @@
import { transaction } from './db';
import { authId, matchingStep, type AuthConfig } from './auth';
// A database row serializes all login attempts across workers and restarts.
export async function consumeCode(config: AuthConfig, code: string): Promise<'ok'|'invalid'|'limited'> {
return transaction(async client => {
const id = authId(config);
await client.query('INSERT INTO auth_login_state(id) VALUES($1) ON CONFLICT DO NOTHING',[id]);
const {rows:[state]} = await client.query('SELECT *, extract(epoch FROM clock_timestamp()) * 1000 AS now_ms FROM auth_login_state WHERE id=$1 FOR UPDATE',[id]);
const now = Number(state.now_ms);
const expired = now - new Date(state.window_start).getTime() >= 300000;
const attempts = expired ? 0 : state.attempts;
if (attempts >= 20) return 'limited';
await client.query('UPDATE auth_login_state SET attempts=$2, window_start=CASE WHEN $3 THEN clock_timestamp() ELSE window_start END WHERE id=$1',[id,attempts+1,expired]);
const step = matchingStep(config.secret,code,now);
if (step === null || step <= Number(state.last_step)) return 'invalid';
await client.query('UPDATE auth_login_state SET last_step=$2 WHERE id=$1',[id,step]);
return 'ok';
});
}
+58
View File
@@ -0,0 +1,58 @@
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
import { readFileSync } from 'node:fs';
export const SESSION_COOKIE = 'prompt_session';
export const SESSION_SECONDS = 7 * 24 * 60 * 60;
export type AuthConfig = { secret: string; jwtKey: string };
export function authConfig(): AuthConfig | null {
const path = process.env.AUTH_CONFIG_FILE;
if (!path) return null;
const value = JSON.parse(readFileSync(path, 'utf8')) as AuthConfig;
if (!/^[A-Z2-7]{32}$/.test(value.secret) || !/^[a-f0-9]{64}$/.test(value.jwtKey)) throw Error('Invalid authentication configuration');
return value;
}
export function base32(bytes: Buffer) {
let bits = 0, value = 0, output = '';
for (const byte of bytes) { value = (value << 8) | byte; bits += 8; while (bits >= 5) { bits -= 5; output += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'[(value >>> bits) & 31]; } }
if (bits) output += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'[(value << (5 - bits)) & 31];
return output;
}
export function newAuthConfig(): AuthConfig { return {secret: base32(randomBytes(20)), jwtKey: randomBytes(32).toString('hex')}; }
export function authId(config: AuthConfig) { return createHash('sha256').update(config.jwtKey).digest('hex'); }
export function totp(secret: string, step: number, digits = 6) {
let bits = 0, value = 0; const bytes: number[] = [];
for (const char of secret) { const index = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'.indexOf(char); if (index < 0) throw Error('Invalid TOTP key'); value = (value << 5) | index; bits += 5; if (bits >= 8) { bits -= 8; bytes.push((value >>> bits) & 255); } }
const counter = Buffer.alloc(8); counter.writeBigUInt64BE(BigInt(step));
const hmac = createHmac('sha1', Buffer.from(bytes)).update(counter).digest();
return String((hmac.readUInt32BE(hmac[19] & 15) & 0x7fffffff) % 10 ** digits).padStart(digits, '0');
}
export function matchingStep(secret: string, code: string, now = Date.now()) {
if (!/^\d{6}$/.test(code)) return null;
const current = Math.floor(now / 30000);
for (const step of [current, current - 1, current + 1]) if (timingSafeEqual(Buffer.from(totp(secret, step)), Buffer.from(code))) return step;
return null;
}
export function signSession(config: AuthConfig, now = Math.floor(Date.now() / 1000), lifetime = SESSION_SECONDS) {
const header = Buffer.from(JSON.stringify({alg:'HS256',typ:'JWT'})).toString('base64url');
const payload = Buffer.from(JSON.stringify({iss:'prompt',aud:'prompt-web',sub:'shared',iat:now,exp:now+lifetime,jti:randomBytes(16).toString('hex')})).toString('base64url');
const content = header + '.' + payload;
return content + '.' + createHmac('sha256', Buffer.from(config.jwtKey,'hex')).update(content).digest('base64url');
}
export function validSession(token: string | undefined, config: AuthConfig, now = Math.floor(Date.now() / 1000)) {
try {
if (!token || token.length > 2048) return false;
const parts = token.split('.'); if (parts.length !== 3) return false;
const [header,payload,signature] = parts;
const h = JSON.parse(Buffer.from(header,'base64url').toString());
if (h.alg !== 'HS256' || h.typ !== 'JWT') return false;
const expected = createHmac('sha256',Buffer.from(config.jwtKey,'hex')).update(header+'.'+payload).digest();
const actual = Buffer.from(signature,'base64url');
if (actual.length !== expected.length || !timingSafeEqual(actual,expected)) return false;
const p = JSON.parse(Buffer.from(payload,'base64url').toString());
return p.iss === 'prompt' && p.aud === 'prompt-web' && p.sub === 'shared' && Number.isInteger(p.exp) && Number.isInteger(p.iat) && p.iat <= now + 30 && p.exp > now && p.exp > p.iat && p.exp - p.iat <= SESSION_SECONDS;
} catch { return false; }
}
export function sessionCookie(token: string, clear = false) {
return `${SESSION_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${clear ? 0 : SESSION_SECONDS}${process.env.AUTH_COOKIE_SECURE === 'false' ? '' : '; Secure'}`;
}
export function safeReturn(value: unknown) { return typeof value === 'string' && value.startsWith('/') && !value.startsWith('//') && !/[\\\r\n]/.test(value) && !value.startsWith('/login') ? value : '/'; }
@@ -0,0 +1,11 @@
import sharp from "sharp";
import {streetPeople} from "./street-people";
export async function validateCharacter(path:string) {
try {
const input=sharp(path,{limitInputPixels:streetPeople.limits.pixels});
const meta=await input.metadata();
if(meta.format!=="png"||!meta.hasAlpha)throw new Error("Character PNG must have transparency");
const stats=await input.stats();const alpha=stats.channels.at(-1)!;
if(alpha.min!==0||alpha.max<250)throw new Error("Character PNG must have transparency");
}catch{throw new Error("Character PNG must have transparency");}
}
+13
View File
@@ -0,0 +1,13 @@
import { Pool, type PoolClient } from "pg";
const globalDb = globalThis as unknown as { promptPool?: Pool };
export function db() {
if (!process.env.DATABASE_URL) throw new Error("DATABASE_URL is required");
return globalDb.promptPool ??= new Pool({ connectionString: process.env.DATABASE_URL, max: 10 });
}
export async function transaction<T>(run: (client: PoolClient) => Promise<T>): Promise<T> {
const client = await db().connect();
try { await client.query("BEGIN"); const result = await run(client); await client.query("COMMIT"); return result; }
catch (error) { await client.query("ROLLBACK"); throw error; }
finally { client.release(); }
}
+43
View File
@@ -0,0 +1,43 @@
import {fromMarkdown} from 'mdast-util-from-markdown';
export type SearchDocument={id:string;aliases?:string[];title:string;description:string;markdown:string;categories:string[];systemTags?:string[];namespace:string;createdAt:string};
export type Backlink={id:string;title:string};
const normalize=(value:string)=>value.normalize('NFKC').toLocaleLowerCase().replace(/\s+/g,' ').trim();
/** Markdown AST excludes images, code examples and unused link definitions. */
export function documentLinks(markdown:string):string[]{
const tree=fromMarkdown(markdown),definitions=new Map<string,string>(),links:string[]=[];
function visit(node:typeof tree|typeof tree.children[number],collect:boolean){
if(node.type==='definition'&&!collect)definitions.set(normalize(node.identifier),node.url);
if(collect&&node.type==='link'){links.push(node.url);return;}
if(collect&&node.type==='linkReference'){const url=definitions.get(normalize(node.identifier));if(url)links.push(url);return;}
if(collect&&node.type==='text')for(const match of node.value.matchAll(/https?:\/\/[^\s<>]+/g))links.push(match[0].replace(/[.,;:!?,。;:!?)\]}'"]+$/g,''));
if('children' in node)for(const child of node.children)visit(child as typeof tree.children[number],collect);
}
visit(tree,false);visit(tree,true);return links;
}
export function backlinksFor(documents:SearchDocument[]){
const targets=new Map(documents.flatMap(d=>[d.id,...(d.aliases||[])].map(id=>[id,d.id] as const))),result=new Map(documents.map(d=>[d.id,[] as Backlink[]]));
for(const source of documents){const seen=new Set<string>();for(const href of documentLinks(source.markdown)){
let url:URL;try{url=new URL(href,'http://8.211.154.134:18131/explore/'+source.id);}catch{continue;}
if(!['http:','https:'].includes(url.protocol)||url.host!=='8.211.154.134:18131')continue;
const match=url.pathname.match(/^\/(?:explore|api\/notes)\/([a-f0-9-]+)\/?$/),id=match&&targets.get(match[1]);
if(id&&id!==source.id&&!seen.has(id)){seen.add(id);result.get(id)!.push({id:source.id,title:source.title});}
}}
for(const refs of result.values())refs.sort((a,b)=>a.title.localeCompare(b.title)||a.id.localeCompare(b.id));return result;
}
export function searchTerms(query:string){return (normalize(query).match(/"[^"]+"|[^\s"]+/g)||[]).map(s=>s.replace(/^"|"$/g,''));}
export function searchScore(doc:SearchDocument,query:string):number{
const fields=[normalize(doc.title),normalize([...doc.categories,...(doc.systemTags||[])].join(' ')),normalize(doc.description),normalize(doc.markdown)],terms=searchTerms(query);
if(!terms.length)return 0;
if(!terms.every(t=>fields.some(f=>f.includes(t))))return -1;
return terms.reduce((score,t)=>score+fields.reduce((n,f,i)=>n+(f.includes(t)?[20,10,5,1][i]:0),0),0)+(fields[0]===normalize(query)?100:0);
}
export function rankDocuments(documents:SearchDocument[],q='',category=''){
const links=backlinksFor(documents);
return documents.map(doc=>({doc,score:searchScore(doc,q),backlinkCount:links.get(doc.id)!.length})).filter(x=>x.score>=0&&(!category||x.doc.categories.includes(category)||x.doc.systemTags?.includes(category)||x.doc.namespace===category)).sort((a,b)=>b.score-a.score||b.backlinkCount-a.backlinkCount||b.doc.createdAt.localeCompare(a.doc.createdAt)||a.doc.id.localeCompare(b.doc.id));
}
export class InvalidDiscoveryCursor extends Error{}
export function discoveryPage<T extends {doc:{id:string}}>(ranked:T[],q:string,category:string,cursor?:string){
let start=0;if(cursor){try{const parsed=JSON.parse(Buffer.from(cursor,'base64url').toString());if(parsed.q!==q||parsed.category!==category||typeof parsed.after!=='string')throw Error();const index=ranked.findIndex(x=>x.doc.id===parsed.after);if(index<0)throw Error();start=index+1;}catch{throw new InvalidDiscoveryCursor('无效的搜索游标,请重新搜索。');}}
const rows=ranked.slice(start,start+24),last=rows.at(-1);
return {rows,nextCursor:start+24<ranked.length&&last?Buffer.from(JSON.stringify({q,category,after:last.doc.id})).toString('base64url'):null,total:ranked.length};
}
+52
View File
@@ -0,0 +1,52 @@
import type {Tag} from './model';
import {systemTags,ordinaryTags,selectedSystemTags} from './system-tags';
import type {PoolClient} from 'pg';
import {noteDescriptions} from '@/content/note-descriptions';
import {guidanceDocuments,guidanceMarkdown} from '@/content/skills/guidance';
import {wikiPages,wikiMarkdown} from '@/content/wiki';
import {skillCatalog} from '@/content/skills/catalog';
import {publicPostId} from './model';
import {pageId,exploreUrl,guidanceUrl} from '@/content/page-links';
import {getPostById,discoveryDocuments,postsByPublicIds} from './library';
import {backlinksFor,rankDocuments,discoveryPage,type SearchDocument,type Backlink} from './discovery';
import {applyStaticEdit,staticEdits,withRevision} from './note-edits';
export type ExploreMedia={kind:'image'|'video'|'audio';url:string;title:string;poster?:string};
export type ExploreEntry={id:string;title:string;description:string;imageCount:number;namespace:string;categories:string[];systemTags?:Tag[];markdown:string;media:ExploreMedia[];color:string;postSlug?:string;editableMarkdown?:string;revision?:string;assets?:{id:string;kind:string;role:string}[];coverAssetId?:string|null;backlinkCount?:number;backlinks?:Backlink[];searchExcerpt?:string};
export const staticEntries:ExploreEntry[]=[...guidanceDocuments.map(doc=>{const card=skillCatalog.find(c=>doc.path===c.id);return {id:pageId('guidance:'+doc.path),title:doc.title,description:noteDescriptions[doc.path]||doc.blocks.find(b=>b.type==='paragraph')?.text||doc.title,imageCount:new Set([...(card?[card.image]:[]),...doc.resources.filter(r=>r.kind==='image').map(r=>r.href)]).size,namespace:'Main',categories:[doc.collection,...(doc.collection==='照片入皮影'?['中国风']:doc.collection==='街头小人'?['贴纸']:[])],systemTags:card?[systemTags[0]]:[],markdown:guidanceMarkdown(doc.path)!,media:Array.from(new Map([...(card?[{kind:'image' as const,url:card.image,title:card.alt}]:[]),...doc.resources.filter(r=>r.kind==='image').map(r=>({kind:'image' as const,url:r.href,title:r.title}))].map(m=>[m.url,m])).values()),color:'#eee5dc'};}),...wikiPages.map(page=>({id:pageId('wiki:'+page.namespace+':'+page.slug),title:page.title,description:page.summary,imageCount:0,namespace:page.namespace,categories:page.categories,markdown:wikiMarkdown(page),media:[],color:page.color}))];
// Canonicalize document references, including absolute links; pictures remain explicit links.
export function canonicalMarkdown(text:string){return text.replace(/\]\((?:http:\/\/8\.211\.154\.134:18131)?\/skills\/([^ )]+)\)/g,(whole,path:string)=>{const clean=path.replace(/\/index\.md$/,'').replace(/\.md$/,'');return pageId('guidance:'+clean)?']('+guidanceUrl(clean)+'?agent_mode=True)':whole;});}
async function readEntry(id:string,client?:PoolClient):Promise<ExploreEntry|null>{
const validId=/^(?:[0-9a-f]{24}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/.test(id);
const post=validId&&(process.env.DATABASE_URL||client||id.length===36)?await getPostById(id,client):null;
if(!post){const page=staticEntries.find(e=>e.id===id);if(!page)return null;const edits=await staticEdits(client);return withRevision(applyStaticEdit({...page,markdown:canonicalMarkdown(page.markdown)},edits.find(e=>e.page_id===id)));}
const orderedAssets=[...post.assets].sort((a,b)=>Number(b.id===post.cover_asset_id)-Number(a.id===post.cover_asset_id));
const media:ExploreMedia[]=orderedAssets.filter(a=>a.kind!=='text'&&a.role==='content').map(a=>({kind:a.kind as ExploreMedia['kind'],url:'/api/media/'+a.id,title:a.filename||post.title,...(a.kind==='video'&&a.variants.includes('poster')?{poster:'/api/media/'+post.assets.find(p=>p.source_asset_id===a.id&&p.derivation==='poster')?.id}:{})}));
const editableMarkdown=post.assets.filter(a=>a.kind==='text').map(a=>a.body||'').join('\n\n');
const body=editableMarkdown+'\n\n'+post.assets.filter(a=>a.derivation).map(a=>'['+({poster:'视频封面',audio_track:'独立音轨',silent_video:'静音视频'}[a.derivation||'']||a.derivation)+'](/api/media/'+a.id+')').join(' · ');
return withRevision({id:publicPostId(post),assets:post.assets.filter(a=>a.kind!=='text').map(a=>({id:a.id,kind:a.kind,role:a.role})),coverAssetId:post.cover_asset_id,title:post.title,editableMarkdown,description:post.description||body.slice(0,180)||post.title,imageCount:media.filter(m=>m.kind==='image').length,namespace:['image','video','audio'].includes(post.kind)?'File':'Main',categories:ordinaryTags(post.tags).map(t=>t.name),systemTags:selectedSystemTags(post.tags),markdown:'# '+post.title+'\n\n'+body,media,color:'#eee5dc',postSlug:post.slug});
}
export async function discoveryCorpus(client?:PoolClient){
const [stored,edits]=await Promise.all([process.env.DATABASE_URL||client?discoveryDocuments(client):Promise.resolve([]),staticEdits(client)]);
const published=new Set(stored.map(p=>p.public_id));
const pages=staticEntries.filter(e=>!published.has(e.id)).map(e=>applyStaticEdit(e,edits.find(edit=>edit.page_id===e.id)));
const documents:SearchDocument[]=[...pages.map(e=>({id:e.id,title:e.title,description:e.description,markdown:canonicalMarkdown(e.markdown),categories:e.categories,systemTags:e.systemTags?.flatMap(t=>[t.name,t.system_key||'']),namespace:e.namespace,createdAt:''})),...stored.map(p=>({id:p.public_id||p.id,aliases:[p.id],title:p.title,description:p.description,markdown:canonicalMarkdown(p.markdown),categories:p.categories,systemTags:(p.system_tags||[]).flatMap((t:Tag)=>[t.name,t.system_key||'']),namespace:['image','video','audio'].includes(p.kind)?'File':'Main',createdAt:new Date(p.created_at).toISOString()}))];
return {documents,pages};
}
export async function getEntry(id:string,client?:PoolClient):Promise<ExploreEntry|null>{
const entry=await readEntry(id,client);if(!entry)return null;
const {documents}=await discoveryCorpus(client),refs=backlinksFor(documents).get(entry.id)||[];
return {...entry,backlinkCount:refs.length,backlinks:refs};
}
export async function exploreFeed(q='',category='',cursor?:string){
const {documents,pages}=await discoveryCorpus(),ranked=rankDocuments(documents,q,category),page=discoveryPage(ranked,q,category,cursor);
const staticIds=new Set(pages.map(e=>e.id)),posts=await postsByPublicIds(page.rows.filter(r=>!staticIds.has(r.doc.id)).map(r=>r.doc.id));
const entries:ExploreEntry[]=page.rows.map(({doc,backlinkCount})=>{
const original=pages.find(e=>e.id===doc.id);const post=posts.find(p=>publicPostId(p)===doc.id);
if(original)return {...original,backlinkCount,...(q?{searchExcerpt:excerpt(doc.markdown,q)}:{})};
if(!post)throw Error('Search result disappeared');
const cover=post.cover_asset_id||post.assets.find(a=>a.kind==='image'&&a.role==='content')?.id,video=post.assets.find(a=>a.kind==='video'),poster=post.assets.find(a=>a.source_asset_id===video?.id&&a.derivation==='poster')?.id;
return {id:doc.id,title:doc.title,description:doc.description||doc.markdown.slice(0,180)||doc.title,imageCount:post.assets.filter(a=>a.kind==='image'&&a.role==='content').length,namespace:doc.namespace,categories:doc.categories,systemTags:selectedSystemTags(post.tags),markdown:'',media:cover?[{kind:'image' as const,url:'/api/media/'+cover,title:doc.title}]:poster?[{kind:'image' as const,url:'/api/media/'+poster,title:doc.title}]:[],color:'#eee5dc',backlinkCount,...(q?{searchExcerpt:excerpt(doc.markdown,q)}:{})};
});return {entries,nextCursor:page.nextCursor,total:page.total,sort:q?'relevance,backlinks,newest':'backlinks,newest'};
}
function excerpt(markdown:string,q:string){const clean=markdown.replace(/[`#*_[\]<>]/g,'').replace(/\s+/g,' '),term=q.trim().replace(/^"|"$/g,'').split(/\s+/)[0]||'',at=clean.toLocaleLowerCase().indexOf(term.toLocaleLowerCase());return (at>50?'…':'')+clean.slice(Math.max(0,at-50),Math.max(0,at-50)+180);}
export function entryText(entry:ExploreEntry){return `${entry.markdown}\n\nDescription: ${entry.description}\nBacklinks: ${entry.backlinkCount??0}\n${(entry.backlinks||[]).map(b=>'引用来源:['+b.title+']('+exploreUrl(b.id)+')').join('\n')}\nSystem tags: ${(entry.systemTags||[]).map(t=>t.name).join(', ')}\nNamespace: ${entry.namespace}\nCategories: ${entry.categories.join(', ')}\n\n`+entry.media.map(m=>`- ${m.kind}: [${m.title}](${m.url})`).join('\n')+'\n\n[网页]('+exploreUrl(entry.id)+')\n';}
+6
View File
@@ -0,0 +1,6 @@
export function healthResponse(method: string | undefined, release = "development") {
if (method !== "GET" && method !== "HEAD") {
return { statusCode: 405, body: { error: "Method not allowed" } };
}
return { statusCode: 200, body: { status: "ok", service: "prompt", release } };
}
+48
View File
@@ -0,0 +1,48 @@
import type {PoolClient} from 'pg';
import { db } from "./db";
import { decodeCursor, encodeCursor, type FeedData, type Post, type PostKind, type Tag } from "./model";
export async function tags(client?:PoolClient): Promise<Tag[]> { return (await (client||db()).query('SELECT *,slug AS path FROM tags ORDER BY name,id')).rows; }
const expand = `SELECT p.*,
COALESCE((SELECT jsonb_agg(ae ORDER BY ae.position) FROM (SELECT a.*,pa.position,pa.role,COALESCE((SELECT jsonb_agg(v.derivation) FROM assets v WHERE v.source_asset_id=a.id),'[]') AS variants FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=p.id) ae),'[]') AS assets,
COALESCE((SELECT jsonb_agg(t) FROM tags t JOIN post_tags pt ON pt.tag_id=t.id WHERE pt.post_id=p.id),'[]') AS tags FROM posts p`;
function serialize(posts: Post[], allTags: Tag[]): Post[] {
return posts.map(p => ({...p, created_at: new Date(p.created_at).toISOString(), updated_at:new Date(p.updated_at).toISOString(), tags:p.tags.map(t=>allTags.find(a=>a.id===t.id)!).filter(Boolean)}));
}
export async function getPost(slug: string): Promise<Post | null> {
const result = await db().query(`${expand} WHERE p.slug=$1`,[slug]);
return serialize(result.rows,await tags())[0] || null;
}
export async function getPostById(id:string,client?:PoolClient):Promise<Post|null>{
const result=await (client||db()).query(`${expand} WHERE ${/^[0-9a-f]{24}$/.test(id)?'p.public_id':'p.id'}=$1`,[id]);
return serialize(result.rows,await tags(client))[0]||null;
}
export async function feed(options: {kind?: PostKind; path?: string; cursor?: string; q?: string} = {}): Promise<FeedData> {
const allTags=await tags(); const target=options.path ? allTags.find(t=>t.path===options.path) : undefined;
if(options.path&&!target) throw new Error("Tag not found");
const cursor=decodeCursor(options.cursor); const values: unknown[]=[];
const where=[`EXISTS(SELECT 1 FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=p.id AND pa.role IN ('content','caption') AND ((a.storage_key IS NOT NULL AND a.byte_size>0) OR (a.kind='text' AND a.body IS NOT NULL)))`];
if(options.kind){values.push(options.kind);where.push(`p.kind=$${values.length}`);}
if(target){values.push([target.id]);where.push(`EXISTS(SELECT 1 FROM post_tags WHERE post_id=p.id AND tag_id=ANY($${values.length}::uuid[]))`);}
if(options.q){values.push(`%${options.q.replace(/[\\%_]/g,"\\$&")}%`);where.push(`p.title ILIKE $${values.length}`);}
if(cursor){values.push(...cursor);where.push(`(p.created_at,p.id)<($${values.length-1}::timestamptz,$${values.length}::uuid)`);}
const rows=(await db().query(`${expand} WHERE ${where.join(' AND ')} ORDER BY p.created_at DESC,p.id DESC LIMIT 25`,values)).rows as Post[];
const hasMore=rows.length>24; const posts=serialize(rows.slice(0,24),allTags); const last=posts.at(-1);
const contributions=(await db().query(`SELECT to_char(occurred_at AT TIME ZONE 'Asia/Shanghai','YYYY-MM-DD') AS day,sum(amount)::integer AS total FROM contribution_events WHERE occurred_at>=now()-interval '366 days' GROUP BY day ORDER BY day`)).rows;
return {posts,tags:allTags,contributions,nextCursor:hasMore&&last?encodeCursor(last.created_at,last.id):null};
}
export async function publishedPublicIds():Promise<string[]>{return (await db().query("SELECT public_id FROM posts WHERE public_id IS NOT NULL")).rows.map(p=>p.public_id);}
/** Lightweight text corpus: no image bodies or media files are loaded. */
export async function discoveryDocuments(client?:PoolClient){
return (await (client||db()).query(`SELECT p.id,p.public_id,p.title,p.description,p.kind,p.created_at,
COALESCE((SELECT string_agg(a.body,E'\n\n' ORDER BY pa.position) FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=p.id AND a.kind='text'),'') AS markdown,
COALESCE((SELECT jsonb_agg(t.name) FROM tags t JOIN post_tags pt ON pt.tag_id=t.id WHERE pt.post_id=p.id AND t.kind='normal'),'[]') AS categories,
COALESCE((SELECT jsonb_agg(t) FROM tags t JOIN post_tags pt ON pt.tag_id=t.id WHERE pt.post_id=p.id AND t.kind='system'),'[]') AS system_tags
FROM posts p WHERE EXISTS(SELECT 1 FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=p.id AND pa.role IN ('content','caption') AND ((a.storage_key IS NOT NULL AND a.byte_size>0) OR (a.kind='text' AND a.body IS NOT NULL)))`)).rows;
}
export async function postsByPublicIds(ids:string[],client?:PoolClient):Promise<Post[]>{
if(!ids.length)return [];const rows=(await (client||db()).query(`${expand} WHERE COALESCE(p.public_id,p.id::text)=ANY($1::text[])`,[ids])).rows;
return serialize(rows,await tags(client));
}
@@ -0,0 +1,9 @@
import type {NextApiRequest,NextApiResponse} from 'next';
export function sendMarkdown(req:NextApiRequest,res:NextApiResponse,text:string|null){
res.setHeader('Allow','GET, HEAD');
if(req.method!=='GET'&&req.method!=='HEAD')return res.status(405).end();
if(text===null)return res.status(404).end();
res.setHeader('Content-Type','text/markdown; charset=utf-8');
res.setHeader('Cache-Control','no-cache');
return req.method==='HEAD'?res.status(200).end():res.status(200).send(text);
}
+24
View File
@@ -0,0 +1,24 @@
export const sections = [
{ path: "images", kind: "image", name: "图片素材", hint: "照片、插画与可以反复使用的画面" },
{ path: "videos", kind: "video", name: "视频素材", hint: "片段与镜头,声音随画面一起收好" },
{ path: "audio", kind: "audio", name: "声音素材", hint: "音乐、环境声与声音片段" },
{ path: "articles", kind: "article", name: "图文作品", hint: "用网页编写,慢慢打磨每一页" },
{ path: "motion", kind: "motion", name: "动态作品", hint: "让网页本身成为时间里的画面" },
] as const;
export type PostKind = typeof sections[number]["kind"];
export type Asset = { id: string; kind: "image" | "video" | "audio" | "text"; filename: string | null; body: string | null; width: number | null; height: number | null; duration: number | null; has_audio: boolean | null; processing_status: string; variants: string[]; role: string; source_asset_id: string | null; derivation: string | null };
export type Tag = { id: string; name: string; slug: string; path: string;kind?:'normal'|'system';system_key?:string|null };
export type Post = { description: string; id: string; public_id?: string | null; slug: string; kind: PostKind; title: string; created_at: string; updated_at: string; cover_asset_id: string | null; assets: Asset[]; tags: Tag[] };
export type FeedData = { posts: Post[]; tags: Tag[]; contributions: { day: string; total: number }[]; nextCursor: string | null; unavailable?: boolean };
export function validSection(path: string) { return sections.find(s => s.path === path); }
export const mediaUrl = (id: string, variant?: string) => `/api/media/${id}${variant ? `?variant=${variant}` : ""}`;
export function encodeCursor(date: string, id: string) { return Buffer.from(JSON.stringify([date,id])).toString("base64url"); }
export function decodeCursor(value?: string) {
if (!value) return null;
try { const [date,id] = JSON.parse(Buffer.from(value,"base64url").toString());
if (!Number.isNaN(Date.parse(date)) && /^[0-9a-f-]{36}$/.test(id)) return [date,id];
} catch { /* invalid pagination cursor */ }
throw new Error("Invalid cursor");
}
export const publicPostId=(post:Pick<Post,'id'|'public_id'>)=>post.public_id||post.id;
+59
View File
@@ -0,0 +1,59 @@
import type {PoolClient} from 'pg';
import {createHash,randomUUID} from 'node:crypto';
import {z} from 'zod';
import {db,transaction} from './db';
import type {ExploreEntry} from './explore';
import {linkDerivedAssets} from './asset-links';
import {postInput} from './write';
export function withoutTitle(markdown:string){return markdown.replace(/^# [^\n]*(?:\n|$)\n?/,'');}
export function withRevision(entry:ExploreEntry):ExploreEntry{
const editableMarkdown=entry.editableMarkdown??withoutTitle(entry.markdown);
const revision=createHash('sha256').update(JSON.stringify([entry.title,entry.description,editableMarkdown,[...entry.categories].sort(),(entry.systemTags||[]).map(t=>t.id).sort(),entry.coverAssetId??null,entry.assets?.map(a=>[a.id,a.role])??[]])).digest('hex');
return {...entry,editableMarkdown,revision};
}
export async function staticEdits(client?:PoolClient){if(!process.env.DATABASE_URL)return [];return (await (client||db()).query(`SELECT e.*,COALESCE((SELECT jsonb_agg(t.name ORDER BY t.name) FROM note_edit_tags et JOIN tags t ON t.id=et.tag_id WHERE et.page_id=e.page_id AND t.kind='normal'),'[]') AS categories,COALESCE((SELECT jsonb_agg(t ORDER BY t.name) FROM note_edit_tags et JOIN tags t ON t.id=et.tag_id WHERE et.page_id=e.page_id AND t.kind='system'),'[]') AS "systemTags" FROM note_edits e`)).rows;}
export function applyStaticEdit(entry:ExploreEntry,edit?:{title:string;description:string;markdown:string;categories:string[];systemTags?:ExploreEntry['systemTags']}):ExploreEntry{
return edit?{...entry,title:edit.title,description:edit.description,editableMarkdown:edit.markdown,markdown:'# '+edit.title+'\n\n'+edit.markdown,categories:edit.categories,systemTags:edit.systemTags||[]}:entry;
}
export const noteEditInput=z.object({title:z.string().trim().min(1).max(200),description:z.string().trim().max(1000),markdown:z.string().max(100000),tags:z.array(z.uuid()).max(50),revision:z.string().regex(/^[0-9a-f]{64}$/),assets:postInput.shape.assets.unwrap().optional(),coverAssetId:z.uuid().nullable().optional()});
export class NoteEditConflict extends Error{}
export async function saveNote(id:string,input:z.infer<typeof noteEditInput>,read:(client:PoolClient)=>Promise<ExploreEntry|null>){
await transaction(async client=>{
await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))',['note-edit:'+id]);
const stored=(await client.query(`SELECT id,kind,cover_asset_id FROM posts WHERE ${/^[0-9a-f]{24}$/.test(id)?'public_id':'id'}=$1 FOR UPDATE`,[id])).rows[0];
const isPost=Boolean(stored),postId=stored?.id;
const current=await read(client);if(!current)throw Error('Note not found');
if(current.revision!==input.revision)throw new NoteEditConflict('这篇笔记已被修改,请重新打开编辑后再保存。');
const tagIds=[...new Set(input.tags)];
if((await client.query('SELECT id FROM tags WHERE id=ANY($1::uuid[])',[tagIds])).rowCount!==tagIds.length)throw Error('Tag not found');
if(isPost){
if(input.assets!==undefined){
const ids=[...new Set(input.assets.map(a=>a.id))];
const assets=ids.length?(await client.query('SELECT id,kind FROM assets WHERE id=ANY($1::uuid[])',[ids])).rows:[];
if(assets.length!==ids.length||assets.some(a=>a.kind==='text'))throw Error('Referenced asset does not exist');
if(['image','video','audio'].includes(stored.kind)&&!input.assets.some(a=>a.role==='content'&&assets.some(r=>r.id===a.id&&r.kind===stored.kind)))throw Error('A media post needs matching content');
await client.query("DELETE FROM post_assets pa USING assets a WHERE pa.post_id=$1 AND pa.asset_id=a.id AND a.kind<>'text'",[postId]);
let position=Number((await client.query('SELECT COALESCE(max(position),-1)+1 AS n FROM post_assets WHERE post_id=$1',[postId])).rows[0].n);
for(const a of input.assets)await client.query('INSERT INTO post_assets(post_id,asset_id,position,role) VALUES($1,$2,$3,$4)',[postId,a.id,position++,a.role]);
}
if(input.assets!==undefined&&input.coverAssetId===undefined&&stored.cover_asset_id&&!input.assets.some(a=>a.id===stored.cover_asset_id&&a.role==='content'))await client.query("UPDATE posts SET cover_asset_id=(SELECT a.id FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=$1 AND pa.role='content' AND a.kind='image' ORDER BY pa.position LIMIT 1) WHERE id=$1",[postId]);
if(input.coverAssetId!==undefined){
if(input.coverAssetId!==null&&!(await client.query("SELECT 1 FROM assets a JOIN post_assets pa ON pa.asset_id=a.id WHERE pa.post_id=$1 AND a.id=$2 AND a.kind='image' AND pa.role='content'",[postId,input.coverAssetId])).rowCount)throw Error('Cover must reference an image');
await client.query('UPDATE posts SET cover_asset_id=$2 WHERE id=$1',[postId,input.coverAssetId]);
}
await client.query('UPDATE posts SET title=$2,description=$3,updated_at=now(),edited_at=now() WHERE id=$1',[postId,input.title,input.description]);
// Replace this note's text link, never modify a text asset shared by other notes.
await client.query("DELETE FROM post_assets pa USING assets a WHERE pa.post_id=$1 AND pa.asset_id=a.id AND a.kind='text'",[postId]);
const assetId=randomUUID();await client.query("INSERT INTO assets(id,kind,body) VALUES($1,'text',$2)",[assetId,input.markdown]);
await client.query("INSERT INTO post_assets(post_id,asset_id,position,role) SELECT $1,$2,COALESCE(max(position)+1,0),'caption' FROM post_assets WHERE post_id=$1",[postId,assetId]);
await client.query('DELETE FROM post_tags WHERE post_id=$1',[postId]);
for(const tagId of tagIds)await client.query('INSERT INTO post_tags(post_id,tag_id) VALUES($1,$2)',[postId,tagId]);
if(input.assets!==undefined)await linkDerivedAssets(client,postId);
}else{
if(input.assets!==undefined||input.coverAssetId!==undefined)throw Error('Media changes require a stored note');
await client.query(`INSERT INTO note_edits(page_id,title,description,markdown) VALUES($1,$2,$3,$4) ON CONFLICT(page_id) DO UPDATE SET title=excluded.title,description=excluded.description,markdown=excluded.markdown,updated_at=now()`,[id,input.title,input.description,input.markdown]);
await client.query('DELETE FROM note_edit_tags WHERE page_id=$1',[id]);
for(const tagId of tagIds)await client.query('INSERT INTO note_edit_tags(page_id,tag_id) VALUES($1,$2)',[id,tagId]);
}
});
}
+14
View File
@@ -0,0 +1,14 @@
import sharp from 'sharp';
import {createHash} from 'node:crypto';
import {mkdir,readFile,writeFile,rename,stat,readdir,unlink,realpath} from 'node:fs/promises';
import {resolve,sep,join} from 'node:path';
import {tmpdir} from 'node:os';
export const previewWidths=[240,480,960,1280];
export function previewWidth(value:unknown){const n=Number(value||480);return previewWidths.includes(n)?n:null;}
export function staticPreviewPath(source:string,root:string){if(!source.startsWith('/')||source.startsWith('//')||source.includes('\\')||!/^\/(?:[^?]+)\.(png|jpe?g|webp)$/i.test(source))throw Error('Invalid source');const file=resolve(root,'.'+source);if(!file.startsWith(resolve(root)+sep))throw Error('Invalid source');return file;}
let active=0;const waiting:(()=>void)[]=[];
async function limited<T>(work:()=>Promise<T>){if(active>=3){if(waiting.length>=24)throw Error('Preview busy');await new Promise<void>(done=>waiting.push(done));}else active++;try{return await work()}finally{const next=waiting.shift();if(next)next();else active--;}}
const pending=new Map<string,Promise<Buffer>>();const cache=join(tmpdir(),'prompt-previews-v1');let writes=0;
export async function compressPreview(input:Buffer,width:number){const max=width<=480?100_000:220_000;let size=width,quality=72;let output:Buffer;do{output=await sharp(input,{limitInputPixels:40_000_000,animated:false}).rotate().resize({width:size,withoutEnlargement:true}).webp({quality,effort:3}).toBuffer();if(output.length<=max)return output;size=Math.max(240,Math.floor(size*.8));quality=Math.max(30,quality-10);}while(size>240||quality>30);return sharp(input,{limitInputPixels:40_000_000}).rotate().resize({width:240,withoutEnlargement:true}).webp({quality:30}).toBuffer();}
export async function cachedPreview(identity:string,width:number,load:()=>Promise<Buffer>){const key=createHash('sha256').update(identity+':'+width+':webp-v1').digest('hex');const file=join(cache,key+'.webp');try{return {bytes:await readFile(file),etag:'"'+key+'"'};}catch{/* cache miss */}let task=pending.get(key);if(!task){task=limited(async()=>{await mkdir(cache,{recursive:true});const bytes=await compressPreview(await load(),width);const temp=file+'.'+process.pid+'.tmp';await writeFile(temp,bytes);await rename(temp,file);if(++writes%32===0){const files=await readdir(cache);if(files.length>1024){const dates=await Promise.all(files.map(async name=>({name,time:(await stat(join(cache,name)).catch(()=>({mtimeMs:0}))).mtimeMs})));await Promise.all(dates.sort((a,b)=>a.time-b.time).slice(0,files.length-1024).map(f=>unlink(join(cache,f.name)).catch(()=>{})));}}return bytes;});pending.set(key,task);}try{return {bytes:await task,etag:'"'+key+'"'};}finally{pending.delete(key);}}
export async function loadStaticPreview(source:string){const root=await realpath(join(process.cwd(),'public'));const file=await realpath(staticPreviewPath(source,root));if(!file.startsWith(root+sep))throw Error('Invalid source');const info=await stat(file);if(info.size>64*1024*1024)throw Error('Image too large');return {identity:file+':'+info.mtimeMs,load:()=>readFile(file)};}
+7
View File
@@ -0,0 +1,7 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
export const run=promisify(execFile);
export async function probe(file:string) {
const {stdout}=await run(process.env.FFPROBE_PATH||'ffprobe',['-v','error','-protocol_whitelist','file,pipe','-show_streams','-show_format','-of','json',file],{timeout:30000,maxBuffer:2*1024*1024});
return JSON.parse(stdout) as {streams:{codec_type:string;width?:number;height?:number}[];format:{duration?:string;format_name?:string}};
}
@@ -0,0 +1,53 @@
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import {guidanceDocuments} from "../content/skills/guidance";
import {wikiPages} from "../content/wiki";
import { chapters } from "../content/learning-skills/data";
import { transaction } from "./db";
import { putFile } from "./storage";
function stableId(name: string) {
const bytes=createHash("sha256").update(`prompt:learning-series:${name}`).digest().subarray(0,16);
bytes[6]=(bytes[6]&15)|80;bytes[8]=(bytes[8]&63)|128;
const hex=bytes.toString("hex");return `${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`;
}
// Explicit editorial publication, never part of the generic storage bootstrap.
// Re-running updates these three authored posts without duplicating posts or media.
export async function publishLearningSeries() {
const path="public/learning-skills/cover.png";
const cover=await readFile(path);const digest=createHash("sha256").update(cover).digest("hex");
const storageKey=`editorial/learning-skills/${digest}.png`;
const coverId=stableId("cover");
await putFile(storageKey,path,"image/png");
return transaction(async client=>{
await client.query("SELECT pg_advisory_xact_lock(18131002)");
await client.query(`INSERT INTO assets(id,kind,filename,storage_key,mime_type,byte_size,sha256,width,height)
VALUES($1,'image','学习资料自己做-系列共用封面.png',$2,'image/png',$3,$4,1080,1440)
ON CONFLICT(id) DO UPDATE SET storage_key=excluded.storage_key,byte_size=excluded.byte_size,sha256=excluded.sha256`,[coverId,storageKey,cover.length,digest]);
const root=(await client.query(`INSERT INTO tags(id,slug,name) VALUES($1,'learning-skills','学习工具')
ON CONFLICT(lower(btrim(name))) DO UPDATE SET name=tags.name RETURNING id`,[stableId("tag-root")])).rows[0].id;
for(const name of new Set([...guidanceDocuments.map(d=>d.collection),...wikiPages.flatMap(p=>p.categories)])){
await client.query(`INSERT INTO tags(id,slug,name) VALUES($1,$2,$3) ON CONFLICT(lower(btrim(name))) DO NOTHING`,[stableId('tag:'+name),'tag-'+stableId('tag:'+name),name]);
}
const published:string[]=[];
for(const chapter of chapters){
const existing=(await client.query('SELECT slug,edited_at FROM posts WHERE id=$1 FOR UPDATE',[stableId(chapter.key)])).rows[0];
if(existing?.edited_at){published.push(existing.slug);continue;}
const child=(await client.query(`INSERT INTO tags(id,slug,name) VALUES($1,$2,$3)
ON CONFLICT(lower(btrim(name))) DO UPDATE SET name=tags.name RETURNING id`,[stableId(`tag-${chapter.key}`),chapter.number==="01"?"notes":chapter.number==="02"?"teaching":"english",chapter.number==="01"?"笔记复习":chapter.number==="02"?"教学资料":"英语学习"])).rows[0].id;
const result=await client.query(`INSERT INTO posts(id,slug,kind,title,cover_asset_id,description) VALUES($1,$2,'article',$3,$4,$5)
ON CONFLICT(slug) DO UPDATE SET title=excluded.title,description=excluded.description,cover_asset_id=COALESCE(posts.cover_asset_id,excluded.cover_asset_id),updated_at=now()
WHERE posts.id=excluded.id AND posts.kind='article' RETURNING id,cover_asset_id`,[stableId(chapter.key),chapter.slug,chapter.title,coverId,chapter.subtitle]);
if(!result.rows[0])throw new Error(`Publication slug is already used by another post: ${chapter.slug}`);
const postId=result.rows[0].id;const captionId=stableId(`caption-${chapter.key}`);
const caption=`学习资料自己做 · 第 ${chapter.number} 辑\n\n${chapter.subtitle}\n\n${chapter.skills.map(skill=>`## ${skill.title}\n\n${skill.note}\n\n输入:${skill.input}\n输出:${skill.output}\n\n${skill.prompt}\n\n[来源](${skill.source})`).join("\n\n")}\n\n根据 GitHub 项目说明整理,尚未逐项安装实测。`;
await client.query("INSERT INTO assets(id,kind,body) VALUES($1,'text',$2) ON CONFLICT(id) DO UPDATE SET body=excluded.body",[captionId,caption]);
await client.query(`INSERT INTO post_assets(post_id,asset_id,position,role) VALUES($1,$2,0,'content'),($1,$3,1,'caption')
ON CONFLICT(post_id,position) DO UPDATE SET asset_id=excluded.asset_id,role=excluded.role`,[postId,result.rows[0].cover_asset_id,captionId]);
await client.query("INSERT INTO post_tags(post_id,tag_id) VALUES($1,$2),($1,$3) ON CONFLICT DO NOTHING",[postId,child,root]);
published.push(chapter.slug);
}
return {published,coverId};
});
}
+26
View File
@@ -0,0 +1,26 @@
import { S3Client, PutObjectCommand, GetObjectCommand, DeleteObjectCommand, HeadBucketCommand, CreateBucketCommand } from "@aws-sdk/client-s3";
import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
let instance: S3Client;
export function storage() {
return instance ??= new S3Client({
endpoint: process.env.S3_ENDPOINT, region: "us-east-1", forcePathStyle: true,
credentials: { accessKeyId: process.env.S3_ACCESS_KEY!, secretAccessKey: process.env.S3_SECRET_KEY! },
requestChecksumCalculation: "WHEN_REQUIRED", responseChecksumValidation: "WHEN_REQUIRED",
});
}
export const bucket = () => process.env.S3_BUCKET || "prompt";
export async function ensureBucket() {
try { await storage().send(new HeadBucketCommand({ Bucket: bucket() })); }
catch (e) {
if ((e as { $metadata?: { httpStatusCode: number } }).$metadata?.httpStatusCode !== 404) throw e;
await storage().send(new CreateBucketCommand({ Bucket: bucket() }));
}
}
export async function putFile(key: string, path: string, mime: string) {
const size = (await stat(path)).size;
await storage().send(new PutObjectCommand({ Bucket: bucket(), Key: key, Body: createReadStream(path), ContentLength: size, ContentType: mime }));
return size;
}
export const getObject = (key: string, range?: string) => storage().send(new GetObjectCommand({ Bucket: bucket(), Key: key, Range: range }));
export const removeObject = (key: string) => storage().send(new DeleteObjectCommand({ Bucket: bucket(), Key: key }));
@@ -0,0 +1,9 @@
export const streetPeople = {
id: "street-people", version: "1.0.0", name: "街头小人", description: "松散笔触、冬日衣着与奶油色剪纸边的街头人物。",
prompt: "Draw ONE original full-body street person: {{subject}}. Naive observational felt-tip pen sketch; loose irregular dark plum, cobalt blue OR coral red lines; sparse facial features; adult proportions; simple winter clothes; scribbled hatching on hair and trousers. Ivory cream paper inside the silhouette and a narrow uneven cut-paper border. Center the entire figure and accessories, with transparent padding. True RGBA transparency outside the cutout. Hard die-cut edge, zero glow, zero feathering. No cast shadow, no background, no text, no other people, no polished vector, no anime.",
workflow: ["从 /skills/street-people/SKILL.md 入口阅读文档与子文档,再读取风格规范,将 {{subject}} 替换为人物动作与衣着。", "使用 agent 自己的图片生成工具,明确启用 transparent background;每张只生成一个人物。", "检查人物完整、画风和 alpha 通道;最多 16 张 PNG 通过同一 POST 请求上传,组成一个素材包。", "使用返回的 url 查看 post,assets 为可复用的素材 ID。"],
generation: { executor: "coding-agent", serverSideModel: false, reference: "/skills/street-people/reference.png", transparentBackground: true },
upload: { method: "POST", endpoint: "/api/skills/street-people", encoding: "multipart/form-data", fields: { files: "1–16 张真实透明 PNG,每张一个完整人物;外部 alpha=0,内部 alpha≥250", title: "素材包标题(可选)", description: "提示词、生成来源和补充说明(可选)", tags: "分类 UUID 数组的 JSON(可选)", slug: "唯一小写英文网址标识(可选)" }, response: { id:"post UUID", slug:"稳定标识", url:"/p/<slug>", assets:["asset UUID"] } },
limits: { files:16, bytesPerFile:262144000, totalBytes:1073741824, pixels:40000000 },
errors: { 400:"PNG 格式、透明通道或表单不符合规范", 409:"slug 已存在,请查看已有 post 或更换 slug", 413:"文件数或体积超过限制", 500:"存储或服务器暂不可用" }
} as const;
@@ -0,0 +1,7 @@
import type {Tag} from './model';
export const systemTags:Tag[]=[
{id:'6f890bd2-9f64-4781-8a21-651467ab7101',name:'文档入口',slug:'document-entry',path:'document-entry',kind:'system',system_key:'document-entry'},
{id:'6f890bd2-9f64-4781-8a21-651467ab7102',name:'参考图',slug:'reference-image',path:'reference-image',kind:'system',system_key:'reference-image'},
];
export const ordinaryTags=(values:Tag[])=>values.filter(t=>t.kind!=='system');
export const selectedSystemTags=(values:Tag[])=>values.filter(t=>t.kind==='system');
+29
View File
@@ -0,0 +1,29 @@
import { randomUUID } from "node:crypto";
import { z } from "zod";
import { transaction } from "./db";
import {linkDerivedAssets} from "./asset-links";
export const postInput=z.object({
publicId:z.string().regex(/^[0-9a-f]{24}$/).optional(),
slug:z.string().regex(/^[a-z0-9][a-z0-9-]{0,119}$/).optional(),
kind:z.enum(["image","video","audio","article","motion"]),title:z.string().trim().min(1).max(200),
assets:z.array(z.object({id:z.uuid(),role:z.enum(["content","caption"]).default("content")})).max(100).default([]),
description:z.string().trim().max(1000).default(""),
text:z.string().trim().max(100000).optional(),tags:z.array(z.uuid()).max(50).default([]),
coverAssetId:z.uuid().optional(),
});
export async function createPost(input:z.infer<typeof postInput>) {
const id=randomUUID(); const slug=input.slug||id;
return transaction(async client=>{
const ids=[...new Set(input.assets.map(a=>a.id))];
const assets=ids.length?(await client.query('SELECT id,kind FROM assets WHERE id=ANY($1::uuid[])',[ids])).rows:[];
if(assets.length!==ids.length) throw new Error("Referenced asset does not exist");
if(["image","video","audio"].includes(input.kind)&&!input.assets.some(link=>link.role==='content'&&assets.some(a=>a.id===link.id&&a.kind===input.kind))) throw new Error("A media post needs matching content");
if(input.coverAssetId && !(await client.query("SELECT 1 FROM assets WHERE id=$1 AND kind='image'",[input.coverAssetId])).rowCount) throw new Error("Cover must reference an image");
await client.query('INSERT INTO posts(id,slug,kind,title,cover_asset_id,description,public_id) VALUES($1,$2,$3,$4,$5,$6,$7)',[id,slug,input.kind,input.title,input.coverAssetId||null,input.description||input.text?.slice(0,200)||input.title,input.publicId||null]);
for(const [position,a] of input.assets.entries()) await client.query('INSERT INTO post_assets(post_id,asset_id,position,role) VALUES($1,$2,$3,$4)',[id,a.id,position,a.role]);
if(input.text){const textId=randomUUID();await client.query("INSERT INTO assets(id,kind,body) VALUES($1,'text',$2)",[textId,input.text]);await client.query("INSERT INTO post_assets(post_id,asset_id,position,role) VALUES($1,$2,$3,'caption')",[id,textId,input.assets.length]);}
for(const tag of new Set(input.tags)) await client.query('INSERT INTO post_tags(post_id,tag_id) VALUES($1,$2)',[id,tag]);
await linkDerivedAssets(client,id);
return {id,slug,...(input.publicId?{publicId:input.publicId}:{}),url:'/explore/'+(input.publicId||id)};
});
}
@@ -0,0 +1,11 @@
import type { GetServerSideProps } from "next";
import { Feed } from "@/components/Feed";
import { feed } from "@/lib/library";
import { validSection } from "@/lib/model";
export default Feed;
export const getServerSideProps:GetServerSideProps=async({params,query})=>{
const section=String(params?.section||'');const item=validSection(section);if(!item)return {notFound:true};
const tagPath=Array.isArray(params?.taxonomy)?params.taxonomy.join('/'):'';
try{return {props:{initial:await feed({kind:item.kind,path:tagPath,q:String(query.q||'').slice(0,200)}),section,tagPath}};}
catch(e){if(e instanceof Error&&e.message==='Tag not found')return {notFound:true};return {props:{initial:{posts:[],tags:[],contributions:[],nextCursor:null,unavailable:true},section,tagPath}};}
};
+8
View File
@@ -0,0 +1,8 @@
import type { AppProps } from "next/app";
import "@/styles/globals.css";
import "@/styles/skill-docs.css";
import "@/styles/learning-series.css";
export default function App({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />;
}
@@ -0,0 +1,4 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {guidanceIndexMarkdown} from '@/content/skills/guidance';
import {sendMarkdown} from '@/lib/markdown-response';
export default function handler(req:NextApiRequest,res:NextApiResponse){return sendMarkdown(req,res,guidanceIndexMarkdown(true));}
@@ -0,0 +1,20 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { authConfig, sessionCookie, signSession } from '@/lib/auth';
import { consumeCode } from '@/lib/auth-store';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
res.setHeader('Cache-Control','no-store');
if (req.method !== 'POST') { res.setHeader('Allow','POST'); return res.status(405).end(); }
try {
const origin = req.headers.origin;
if (!origin || new URL(origin).host !== req.headers.host || req.headers['sec-fetch-site'] === 'cross-site') return res.status(403).json({error:'请求来源不受信任'});
const config = authConfig();
if (!config) return res.status(503).json({error:'尚未配置动态码登录,请联系管理员'});
const code = typeof req.body?.code === 'string' ? req.body.code.trim() : '';
const result = await consumeCode(config,code);
if (result === 'limited') { res.setHeader('Retry-After','300'); return res.status(429).json({error:'尝试次数过多,请五分钟后再试'}); }
if (result !== 'ok') return res.status(401).json({error:'动态码不正确或已使用,请等待下一组动态码'});
res.setHeader('Set-Cookie',sessionCookie(signSession(config)));
return res.status(200).json({ok:true});
} catch { return res.status(503).json({error:'登录服务暂时不可用,请稍后重试'}); }
}
export const config = {api:{bodyParser:{sizeLimit:'1kb'}}};
@@ -0,0 +1,8 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { sessionCookie } from '@/lib/auth';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.setHeader('Cache-Control','no-store');
if (req.method !== 'POST') { res.setHeader('Allow','POST'); return res.status(405).end(); }
try { if (!req.headers.origin || new URL(req.headers.origin).host !== req.headers.host || req.headers['sec-fetch-site'] === 'cross-site') return res.status(403).end(); } catch { return res.status(403).end(); }
res.setHeader('Set-Cookie',sessionCookie('',true)); return res.status(200).json({ok:true});
}
@@ -0,0 +1,6 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import type {NextApiRequest,NextApiResponse} from 'next';
import {InvalidDiscoveryCursor} from '@/lib/discovery';
import {exploreFeed} from '@/lib/explore';
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/api/explore-feed'))return;if(req.method!=='GET')return res.status(405).end();try{return res.json(await exploreFeed(String(req.query.q||'').slice(0,200),String(req.query.category||''),String(req.query.cursor||'')||undefined));}catch(e){if(e instanceof InvalidDiscoveryCursor)return res.status(400).json({error:e.message});return res.status(503).json({error:'素材库暂时无法连接'});}}
+12
View File
@@ -0,0 +1,12 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import type { NextApiRequest,NextApiResponse } from "next";
import { feed } from "@/lib/library";
import { validSection } from "@/lib/model";
import { apiError } from "@/lib/api";
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/api/feed'))return;
if(req.method!=='GET')return res.status(405).end();
try {const section=String(req.query.section||'');if(section&&!validSection(section))return res.status(400).json({error:'未知分类'});
res.setHeader('Cache-Control','no-store');return res.json(await feed({kind:validSection(section)?.kind,path:String(req.query.path||''),cursor:String(req.query.cursor||''),q:String(req.query.q||'').slice(0,200)}));
}catch(e){return apiError(res,e);}
}
@@ -0,0 +1,8 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {guidanceIndexMarkdown,guidanceMarkdown} from '@/content/skills/guidance';
import {sendMarkdown} from '@/lib/markdown-response';
export default function handler(req:NextApiRequest,res:NextApiResponse){
const parts=Array.isArray(req.query.path)?req.query.path:[];
const text=parts.length===0?guidanceIndexMarkdown(true):parts[0]!=='skills'?null:parts.length===1?guidanceIndexMarkdown():guidanceMarkdown(parts.slice(1).join('/'));
return sendMarkdown(req,res,text);
}
@@ -0,0 +1,12 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import type { NextApiRequest, NextApiResponse } from "next";
import { healthResponse } from "@/lib/health";
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if(serveApiDocumentation(req,res,'/api/health'))return;
const { statusCode, body } = healthResponse(req.method, process.env.RELEASE_SHA);
res.setHeader("Cache-Control", "no-store");
if (statusCode === 405) res.setHeader("Allow", "GET, HEAD");
if (req.method === "HEAD") return res.status(statusCode).end();
return res.status(statusCode).json(body);
}
@@ -0,0 +1,14 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {apiDocuments} from '@/lib/api-documentation';
export default function handler(req:NextApiRequest,res:NextApiResponse){
if(!['GET','HEAD'].includes(req.method||'')){res.setHeader('Allow','GET, HEAD');return res.status(405).end();}
const entries=[...Object.entries(apiDocuments).map(([path,doc])=>({path,title:doc[0],methods:doc[1],documentation:path+'?agent_mode=True'})),
{path:'/studio/api/export/{slug}',title:'封面渲染与方案导出',methods:'GET, POST',documentation:'/studio/api/export/{slug}?agent_mode=True'},
{path:'/studio/api/health',title:'创作站健康检查',methods:'GET, HEAD',documentation:'/studio/api/health?agent_mode=True'}];
res.setHeader('Cache-Control','no-store');
const plain=typeof req.query.agent_mode==='string'&&req.query.agent_mode.toLowerCase()==='true';
res.setHeader('Content-Type',plain?'text/plain; charset=utf-8':'application/json; charset=utf-8');
if(req.method==='HEAD')return res.status(200).end();
if(plain)return res.send('# PROMPT 业务 API\n\n各接口使用 GET + agent_mode=True 读取说明;已有参数时用 & 拼接。动态路径允许保留占位符。业务调用请移除该参数。\n\n'+entries.map(e=>`- ${e.title}(${e.methods}):${e.documentation}`).join('\n')+'\n');
return res.json({entries});
}
@@ -0,0 +1,26 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import type { NextApiRequest,NextApiResponse } from "next";
import type { Readable } from "node:stream";
import { db } from "@/lib/db";
import { getObject } from "@/lib/storage";
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/api/media/{id}'))return;
if(!['GET','HEAD'].includes(req.method||''))return res.status(405).end();
if(!/^[0-9a-f-]{36}$/.test(String(req.query.id)))return res.status(404).end();
try{
const variant=String(req.query.variant||'');
if(variant&&!['poster','silent_video','audio_track'].includes(variant))return res.status(404).end();
const result=variant?await db().query('SELECT storage_key,mime_type FROM assets WHERE source_asset_id=$1 AND derivation=$2',[req.query.id,variant]):await db().query('SELECT storage_key,mime_type FROM assets WHERE id=$1',[req.query.id]);
if(!result.rows[0]?.storage_key)return res.status(404).end();
const object=await getObject(result.rows[0].storage_key,req.headers.range);
res.status(object.ContentRange?206:200);
res.setHeader('Content-Type',object.ContentType||'application/octet-stream');res.setHeader('X-Content-Type-Options','nosniff');res.setHeader('Accept-Ranges','bytes');
if(object.ContentLength!==undefined)res.setHeader('Content-Length',object.ContentLength);
if(object.ContentRange)res.setHeader('Content-Range',object.ContentRange);
res.setHeader('Cache-Control','private, no-store');
const stream=object.Body as Readable;
if(req.method==='HEAD'){stream.destroy();return res.end();}
res.on('close',()=>stream.destroy());stream.on('error',()=>res.destroy());return stream.pipe(res);
}catch(e){const code=(e as {$metadata?:{httpStatusCode:number}}).$metadata?.httpStatusCode;return res.status(code===416?416:404).end();}
}
export const config={api:{responseLimit:false}};
@@ -0,0 +1,19 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import {z} from 'zod';
import type {NextApiRequest,NextApiResponse} from 'next';
import {getEntry} from '@/lib/explore';
import {tags} from '@/lib/library';
import {noteEditInput,saveNote,NoteEditConflict} from '@/lib/note-edits';
import {sameOrigin,apiError} from '@/lib/api';
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/api/notes/{id}'))return;
res.setHeader('Cache-Control','no-store');
if(!['GET','PUT','PATCH'].includes(req.method||'')){res.setHeader('Allow','GET, PUT, PATCH');return res.status(405).end();}
try{
const id=String(req.query.id||'');const entry=await getEntry(id);if(!entry)return res.status(404).json({error:'笔记不存在'});
if(req.method==='GET')return res.json({entry,tags:await tags()});
sameOrigin(req);const body=req.method==='PATCH'?{title:entry.title,description:entry.description,markdown:entry.editableMarkdown,...z.object({tags:z.array(z.uuid()).max(50),revision:z.string().regex(/^[0-9a-f]{64}$/)}).strict().parse(req.body)}:req.body;const input=noteEditInput.parse(body);await saveNote(id,input,client=>getEntry(id,client));
return res.json({entry:await getEntry(id)});
}catch(e){if(e instanceof NoteEditConflict)return res.status(409).json({error:e.message});return apiError(res,e);}
}
export const config={api:{bodyParser:{sizeLimit:'1mb'}}};
@@ -0,0 +1,9 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import type { NextApiRequest,NextApiResponse } from "next";
import { createPost,postInput } from "@/lib/write";
import { sameOrigin,apiError } from "@/lib/api";
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/api/posts'))return;
if(req.method!=='POST')return res.status(405).end();
try{sameOrigin(req);return res.status(201).json(await createPost(postInput.parse(req.body)));}catch(e){return apiError(res,e);}
}
@@ -0,0 +1,8 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import type {NextApiRequest,NextApiResponse} from 'next';
import {db} from '@/lib/db';
import {getObject} from '@/lib/storage';
import {previewWidth,cachedPreview,loadStaticPreview} from '@/lib/preview';
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/api/preview'))return;if(!['GET','HEAD'].includes(req.method||''))return res.status(405).end();const width=previewWidth(req.query.width);if(!width||typeof req.query.source!=='string')return res.status(400).end();try{const source=req.query.source;let input:{identity:string;load:()=>Promise<Buffer>};if(source.startsWith('/api/media/')){const match=source.match(/^\/api\/media\/([0-9a-f-]{36})(?:\?variant=(poster))?$/);if(!match)return res.status(400).end();const result=match[2]?await db().query('SELECT storage_key,mime_type FROM assets WHERE source_asset_id=$1 AND derivation=$2',[match[1],match[2]]):await db().query('SELECT storage_key,mime_type FROM assets WHERE id=$1',[match[1]]);const row=result.rows[0];if(!row?.storage_key||!row.mime_type?.startsWith('image/'))return res.status(404).end();input={identity:row.storage_key,load:async()=>{const object=await getObject(row.storage_key);if((object.ContentLength||0)>64*1024*1024)throw Error('Image too large');const chunks:Buffer[]=[];let length=0;for await(const chunk of object.Body as AsyncIterable<Uint8Array>){length+=chunk.length;if(length>64*1024*1024)throw Error('Image too large');chunks.push(Buffer.from(chunk));}return Buffer.concat(chunks);}};}else input=await loadStaticPreview(source);const {bytes,etag}=await cachedPreview(input.identity,width,input.load);res.setHeader('ETag',etag);res.setHeader('Cache-Control','private, no-store');res.setHeader('Content-Type','image/webp');res.setHeader('X-Content-Type-Options','nosniff');if(req.headers['if-none-match']===etag)return res.status(304).end();res.setHeader('Content-Length',bytes.length);return req.method==='HEAD'?res.end():res.send(bytes);}catch(e){const message=(e as Error).message;if(message.includes('Invalid source'))return res.status(400).end();if((e as NodeJS.ErrnoException).code==='ENOENT')return res.status(404).end();res.setHeader('Retry-After','5');return res.status(503).end();}}
export const config={api:{responseLimit:false}};
@@ -0,0 +1,11 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import type { NextApiRequest,NextApiResponse } from 'next';
import { db } from '@/lib/db';
import { storage,bucket } from '@/lib/storage';
import { HeadBucketCommand } from '@aws-sdk/client-s3';
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/api/ready'))return;
if(req.method!=='GET')return res.status(405).end();
res.setHeader('Cache-Control','no-store');
try{await db().query('SELECT 1 FROM schema_migrations LIMIT 1');await storage().send(new HeadBucketCommand({Bucket:bucket()}));return res.json({status:'ok',database:'ready',objects:'ready'});}catch{return res.status(503).json({status:'unavailable'});}
}
@@ -0,0 +1,7 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {guidanceMarkdown,legacyDocumentPath} from '@/content/skills/guidance';
import {sendMarkdown} from '@/lib/markdown-response';
export default function handler(req:NextApiRequest,res:NextApiResponse){
const name=String(req.query.doc).replace(/\.md$/,'');
return sendMarkdown(req,res,guidanceMarkdown(legacyDocumentPath(String(req.query.skill),name)));
}
@@ -0,0 +1,4 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {guidanceMarkdown,legacyDocumentPath} from '@/content/skills/guidance';
import {sendMarkdown} from '@/lib/markdown-response';
export default function handler(req:NextApiRequest,res:NextApiResponse){return sendMarkdown(req,res,guidanceMarkdown(legacyDocumentPath('street-people',String(req.query.doc).replace(/\.md$/,''))));}
@@ -0,0 +1,18 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import type {NextApiRequest,NextApiResponse} from "next";
import {upload} from "../upload";
import {streetPeople} from "@/lib/street-people";
import {guidanceMarkdown} from "@/content/skills/guidance";
import {validateCharacter} from "@/lib/character-image";
export const config={api:{bodyParser:false}};
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/api/skills/street-people'))return;
res.setHeader("Allow","GET, POST");
if(req.method==="GET"){
res.setHeader("Cache-Control","private, no-store");
if(req.query.format==="md")return res.setHeader("Content-Type","text/markdown; charset=utf-8").status(200).send(guidanceMarkdown("street-people"));
return res.status(200).json(streetPeople);
}
if(req.method==="POST")return upload(req,res,{validateImage:validateCharacter,defaultTitle:"街头小人 · 新生成"});
return res.status(405).json({error:"使用 GET 读取规范,POST 上传 PNG 素材包"});
}
+23
View File
@@ -0,0 +1,23 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import type {NextApiRequest,NextApiResponse} from 'next';
import {randomUUID} from 'node:crypto';
import {z} from 'zod';
import {db} from '@/lib/db';
import {tags} from '@/lib/library';
import {sameOrigin,apiError} from '@/lib/api';
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/api/tags'))return;
try{
if(req.method==='GET')return res.json(await tags());
if(req.method!=='POST')return res.status(405).end();
sameOrigin(req);
const data=z.object({name:z.string().trim().transform(v=>v.replace(/^#+/,'').trim()).pipe(z.string().min(1).max(60).regex(/^[^#\s,,]+$/)),slug:z.string().regex(/^[a-z0-9][a-z0-9-]{0,59}$/).optional()}).strict().parse(req.body);
const existing=(await tags()).find(t=>t.name.toLocaleLowerCase()===data.name.toLocaleLowerCase());
if(existing?.kind==='system')return res.status(400).json({error:'系统标签只能从系统标签列表搜索并勾选添加'});
const id=randomUUID();
const result=await db().query(`INSERT INTO tags(id,name,slug) VALUES($1,$2,$3)
ON CONFLICT(lower(btrim(name))) DO UPDATE SET name=tags.name WHERE tags.kind='normal' RETURNING *,slug AS path`,[id,data.name,data.slug||'tag-'+id]);
if(!result.rows.length)return res.status(400).json({error:'不能通过 # 创建或添加系统标签'});
return res.status(result.rows[0].id===id?201:200).json(result.rows[0]);
}catch(e){return apiError(res,e);}
}
@@ -0,0 +1,69 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import type { NextApiRequest,NextApiResponse } from "next";
import formidable,{type File} from "formidable";
import { randomUUID,createHash } from "node:crypto";
import { createReadStream } from "node:fs";
import { rm } from "node:fs/promises";
import sharp from "sharp";
import { z } from "zod";
import { transaction } from "@/lib/db";
import { putFile,removeObject } from "@/lib/storage";
import { probe } from "@/lib/probe";
import { sameOrigin,apiError } from "@/lib/api";
export const config={api:{bodyParser:false}};
export type UploadPolicy = { validateImage?: (path:string) => Promise<void>; defaultTitle?:string };
export async function upload(req:NextApiRequest,res:NextApiResponse,policy:UploadPolicy={}){
if(serveApiDocumentation(req,res,'/api/upload'))return;
if(req.method!=='POST')return res.status(405).end();
const temporary:string[]=[];const uploaded:string[]=[];
try{
sameOrigin(req);
const form=formidable({maxFileSize:250*1024*1024,maxTotalFileSize:1024*1024*1024,maxFiles:16,allowEmptyFiles:false});
form.on('fileBegin',(_name,file)=>temporary.push(file.filepath));
const [fields,files]=await form.parse(req);
const assetOnly=z.enum(['true','false']).default('false').parse(fields.assetOnly?.[0])==='true';
const kind=z.enum(['image','video','audio']).parse(policy.validateImage?'image':fields.kind?.[0]);
const title=z.string().trim().min(1).max(200).parse(fields.title?.[0]||policy.defaultTitle||(assetOnly?'上传素材':undefined));
const slug=z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).max(120).optional().parse(fields.slug?.[0]);
const description=z.string().trim().max(100000).parse(fields.description?.[0]||'');
const tagIds=z.array(z.uuid()).max(50).parse(JSON.parse(fields.tags?.[0]||'[]'));
const items=Object.values(files).flat().filter(Boolean) as File[];
if(!items.length) return res.status(400).json({error:'请选择文件'});
const records:{id:string;key:string;mime:string;width:number|undefined;height:number|undefined;duration:number|undefined;hasAudio:boolean|null;size:number;hash:string;filename:string}[]=[];
for(const file of items){
let mime='';let width:number|undefined,height:number|undefined,duration:number|undefined,hasAudio:boolean|null=null;
if(kind==='image'){
if(policy.validateImage)await policy.validateImage(file.filepath);
const meta=await sharp(file.filepath,{limitInputPixels:100000000}).metadata();
const formats:Record<string,string>={jpeg:'image/jpeg',png:'image/png',webp:'image/webp',gif:'image/gif',avif:'image/avif'};
mime=formats[meta.format||''];if(!mime)throw new Error('Unsupported image format');width=meta.width;height=meta.height;
}else{
const meta=await probe(file.filepath);const video=meta.streams.find(s=>s.codec_type==='video');const audio=meta.streams.some(s=>s.codec_type==='audio');
if(kind==='video'&&!video)throw new Error('File has no video stream');if(kind==='audio'&&(!audio||video))throw new Error('Select an audio file');
if(!file.mimetype?.startsWith(kind+'/'))throw new Error('Unsupported media MIME type');
mime=file.mimetype;width=video?.width;height=video?.height;duration=Number(meta.format.duration)||undefined;hasAudio=kind==='video'?audio:null;
}
const hash=createHash('sha256');for await(const chunk of createReadStream(file.filepath))hash.update(chunk);
const id=randomUUID(),key=`originals/${id}`;await putFile(key,file.filepath,mime);uploaded.push(key);
records.push({id,key,mime,width,height,duration,hasAudio,size:file.size,hash:hash.digest('hex'),filename:file.originalFilename||'未命名素材'});
}
const postId=assetOnly?null:randomUUID();
await transaction(async client=>{
if(postId)await client.query('INSERT INTO posts(id,slug,kind,title,description) VALUES($1,$2,$3,$4,$5)',[postId,slug||postId,kind,title,description.slice(0,1000)||title]);
for(const [position,a] of records.entries()){
await client.query('INSERT INTO assets(id,kind,filename,storage_key,mime_type,byte_size,sha256,width,height,duration,has_audio,processing_status) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)',[a.id,kind,a.filename,a.key,a.mime,a.size,a.hash,a.width,a.height,a.duration,a.hasAudio,kind==='video'?'pending':'ready']);
if(postId)await client.query('INSERT INTO post_assets(post_id,asset_id,position) VALUES($1,$2,$3)',[postId,a.id,position]);
for(const tag of new Set(tagIds))await client.query('INSERT INTO asset_tags(asset_id,tag_id) VALUES($1,$2)',[a.id,tag]);
if(kind==='video')await client.query('INSERT INTO media_jobs(id,asset_id) VALUES($1,$2)',[randomUUID(),a.id]);
}
if(postId&&description){const id=randomUUID();await client.query("INSERT INTO assets(id,kind,body) VALUES($1,'text',$2)",[id,description]);await client.query("INSERT INTO post_assets(post_id,asset_id,position,role) VALUES($1,$2,$3,'caption')",[postId,id,records.length]);}
if(postId)for(const tag of new Set(tagIds))await client.query('INSERT INTO post_tags(post_id,tag_id) VALUES($1,$2)',[postId,tag]);
});
uploaded.length=0;
if(assetOnly)return res.status(201).json({assets:records.map(a=>a.id),files:records.map(a=>({id:a.id,filename:a.filename,sha256:a.hash}))});
return res.status(201).json({id:postId,slug:slug||postId,url:`/p/${slug||postId}`,assets:records.map(a=>a.id)});
}catch(e){if(e instanceof Error && (/maxFileSize|maxTotalFileSize|maxFiles/.test(e.message)))return res.status(413).json({error:'最多 16 个文件,单个不超过 250 MB,总计不超过 1 GB'});return apiError(res,e);}
finally{await Promise.allSettled(temporary.map(p=>rm(p,{force:true})));await Promise.allSettled(uploaded.map(removeObject));}
}
export default upload;
@@ -0,0 +1,6 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {publishedPublicIds} from '@/lib/library';
import {staticEntries} from '@/lib/explore';
import {applyStaticEdit,staticEdits} from '@/lib/note-edits';
import {exploreUrl} from '@/content/page-links';
export default async function handler(_:NextApiRequest,res:NextApiResponse){const [edits,published]=await Promise.all([staticEdits(),process.env.DATABASE_URL?publishedPublicIds():Promise.resolve([])]);const entries=staticEntries.filter(e=>!published.includes(e.id)).map(e=>applyStaticEdit(e,edits.find(edit=>edit.page_id===e.id)));res.setHeader('Content-Type','text/plain; charset=utf-8');res.send('# PROMPT\n\n'+entries.map(e=>`- [${e.title}](${exploreUrl(e.id)}?agent_mode=True)`).join('\n')+'\n\n素材分页索引:/api/explore-feed(使用 nextCursor 翻页)。所有内容均使用 /explore/{id}?agent_mode=True 读取纯文本。\n');}
@@ -0,0 +1,3 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {getPost} from '@/lib/library';
export default async function handler(req:NextApiRequest,res:NextApiResponse){if(req.method!=='GET'&&req.method!=='HEAD')return res.status(405).end();try{const post=await getPost(String(req.query.slug||''));if(!post)return res.status(404).end();res.setHeader('Content-Type','text/markdown; charset=utf-8');res.send('# '+post.title+'\n\nNamespace: '+(['image','video','audio'].includes(post.kind)?'File':'Main')+'\n\n'+post.assets.map(a=>a.kind==='text'?a.body:`- ${a.kind}: [${a.filename||a.id}](/api/media/${a.id})`).join('\n\n')+'\n\nCategories: '+post.tags.map(t=>t.name).join(', '));}catch{res.status(503).send('Storage temporarily unavailable');}}
@@ -0,0 +1,4 @@
import postHandler from '../wiki-post/[slug]';
import type {NextApiRequest,NextApiResponse} from 'next';
import {findWikiPage,wikiMarkdown} from '@/content/wiki';
export default async function handler(req:NextApiRequest,res:NextApiResponse){if(req.method!=='GET'&&req.method!=='HEAD')return res.status(405).end();const page=findWikiPage(String(req.query.key||''));if(!page){const key=String(req.query.key||'');if(!/^(Main|File):/.test(key))return res.status(404).end();req.query.slug=key.slice(key.indexOf(':')+1);return postHandler(req,res);}res.setHeader('Content-Type','text/markdown; charset=utf-8');return res.send(wikiMarkdown(page));}
@@ -0,0 +1,15 @@
import type {GetServerSideProps} from 'next';
import Link from 'next/link';
import Head from 'next/head';
import {Shell} from '@/components/Shell';
import {ExploreFeed} from '@/components/ExploreFeed';
import {exploreFeed,type ExploreEntry} from '@/lib/explore';
import {tags} from '@/lib/library';
import {systemTags} from '@/lib/system-tags';
export default function Categories({categories,category,entries,cursor,q,total,unavailable=false}:{categories:string[];category:string;entries:ExploreEntry[];cursor:string|null;q:string;total?:number;unavailable?:boolean}){
const link=(value:string)=>({pathname:'/categories',query:{...(value?{category:value}:{}),...(q?{q}:{})}});
return <Shell><Head><title>分类 · PROMPT</title></Head><nav className="discovery-tabs" aria-label="系统标签分类"><Link href={link('')} className={!category?'selected':''}>全部</Link>{categories.map(c=><Link className={c===category?'selected':''} href={link(c)} key={c}>{c}</Link>)}</nav>{category&&!categories.includes(category)&&<div className="ordinary-tag-filter">#{category}<Link href={link('')}>清除筛选 ×</Link></div>}{unavailable&&<p role="status">分类暂时无法读取,请稍后重试。</p>}<ExploreFeed key={JSON.stringify([category,q])} initial={entries} cursor={cursor} q={q} category={category} total={total}/></Shell>;
}
export const getServerSideProps:GetServerSideProps=async({query})=>{
const category=String(query.category||'').slice(0,200),q=String(query.q||'').slice(0,200);try{const [all,data]=await Promise.all([tags(),exploreFeed(q,category)]);return {props:{categories:all.filter(t=>t.kind==='system').map(t=>t.name),category,q,entries:data.entries,cursor:data.nextCursor,total:data.total}};}catch{return {props:{categories:systemTags.map(t=>t.name),category,q,entries:[],cursor:null,unavailable:true}}}
};
@@ -0,0 +1,5 @@
import type {GetServerSideProps} from 'next';
import {ExploreDetail} from '@/components/ExploreDetail';
import {getEntry,entryText,exploreFeed} from '@/lib/explore';
export default ExploreDetail;
export const getServerSideProps:GetServerSideProps=async({params,query,res,req})=>{try{const entry=await getEntry(String(params?.id||''));if(!entry)return {notFound:true};if(String(query.agent_mode||'').toLowerCase()==='true'){res.setHeader('Content-Type','text/plain; charset=utf-8');res.setHeader('Cache-Control','no-cache');res.end(req.method==='HEAD'?undefined:entryText(entry));return {props:{}};}return {props:{entry,background:(await exploreFeed()).entries}};}catch{res.statusCode=503;res.setHeader('Retry-After','10');res.end('内容暂时无法读取,请稍后重试');return {props:{}};}};
+7
View File
@@ -0,0 +1,7 @@
import type {GetServerSideProps} from 'next';
import Head from 'next/head';
import {Shell} from '@/components/Shell';
import {ExploreFeed} from '@/components/ExploreFeed';
import {exploreFeed,staticEntries,type ExploreEntry} from '@/lib/explore';
export default function Home({entries,cursor,q,total,unavailable=false}:{entries:ExploreEntry[];cursor:string|null;q:string;total?:number;unavailable?:boolean}){return <Shell><Head><title>PROMPT · 发现</title></Head>{unavailable&&<p role="status">素材库暂时无法连接,先看看这些公开笔记。</p>}<ExploreFeed key={q} initial={entries} cursor={cursor} q={q} total={total}/></Shell>}
export const getServerSideProps:GetServerSideProps=async({query})=>{const q=String(query.q||'').slice(0,200);try{const data=await exploreFeed(q);return {props:{entries:data.entries,cursor:data.nextCursor,total:data.total,q}}}catch{return {props:{entries:staticEntries.filter(e=>!q||(e.title+e.description).includes(q)),cursor:null,q,unavailable:true}}}};
@@ -0,0 +1,26 @@
import type { GetServerSideProps } from "next";
import Head from "next/head";
import { useState,type FormEvent } from "react";
import { useRouter } from "next/router";
import { Upload,Image,Film,AudioLines,ArrowUpRight,X,Check } from "lucide-react";
import {TagInput} from "@/components/TagInput";
import { Shell } from "@/components/Shell";
import { tags } from "@/lib/library";
import type { Tag } from "@/lib/model";
export default function Import({allTags}:{allTags:Tag[]}){
const router=useRouter();const [kind,setKind]=useState(['image','video','audio'].includes(String(router.query.kind))?String(router.query.kind):'image');
const [files,setFiles]=useState<File[]>([]);const [title,setTitle]=useState('');const [description,setDescription]=useState('');const [selected,setSelected]=useState<string[]>([]);const [busy,setBusy]=useState(false);const [error,setError]=useState('');
function choose(list:FileList|null){if(!list)return;const items=Array.from(list);setFiles(items);if(!title&&items[0])setTitle(items[0].name.replace(/\.[^.]+$/,''));}
async function submit(e:FormEvent){e.preventDefault();setError('');setBusy(true);try{const data=new FormData();data.set('kind',kind);data.set('title',title);data.set('description',description);data.set('tags',JSON.stringify(selected));files.forEach(f=>data.append('files',f));const res=await fetch('/api/upload',{method:'POST',body:data});const result=await res.json();if(!res.ok)throw new Error(result.error);await router.push('/explore/'+result.id);}catch(e){setError(e instanceof Error?e.message:'上传失败');}finally{setBusy(false);}}
return <Shell><Head><title>素材入库 · PROMPT</title></Head><header className="page-header"><div><span className="eyebrow">MAKE ROOM FOR INSPIRATION</span><h1>导入素材</h1><p>支持多文件导入。同一组素材收录为一个素材包,每份文件都可以再次引用。</p></div></header><form className="editor-panel" onSubmit={submit}>
<div className="kind-picker">{[{id:'image',name:'图片',Icon:Image},{id:'video',name:'视频',Icon:Film},{id:'audio',name:'声音',Icon:AudioLines}].map(t=><button type="button" key={t.id} disabled={busy} className={kind===t.id?'selected':''} onClick={()=>{setKind(t.id);setFiles([]);}}><t.Icon size={19}/>{t.name}</button>)}</div>
<label className="drop-zone" onDragOver={e=>e.preventDefault()} onDrop={e=>{e.preventDefault();if(!busy)choose(e.dataTransfer.files);}}><input type="file" multiple disabled={busy} accept={kind==='image'?'image/jpeg,image/png,image/webp,image/gif,image/avif':kind+'/*'} onChange={e=>choose(e.target.files)}/><span className="upload-circle"><Upload size={24}/></span><strong>选择文件或拖放到这里</strong><span>最多 16 个文件,单个不超过 250 MB</span></label>
{files.length>0&&<ul className="file-list">{files.map((f,i)=><li key={i}><Check size={15}/><span>{f.name}</span><small>{(f.size/1024/1024).toFixed(1)} MB</small><button type="button" aria-label={`移除 ${f.name}`} disabled={busy} onClick={()=>setFiles(a=>a.filter((_,j)=>i!==j))}><X size={14}/></button></li>)}</ul>}
<div className="form-field"><label htmlFor="title">标题</label><input id="title" required maxLength={200} value={title} onChange={e=>setTitle(e.target.value)} placeholder="添加标题"/></div>
<div className="form-field"><label htmlFor="description">描述 <small>选填</small></label><textarea id="description" maxLength={100000} rows={4} value={description} onChange={e=>setDescription(e.target.value)} placeholder="拍摄场景、灵感、下次想怎么用…"/></div>
<TagInput initial={allTags} selected={selected} onChange={setSelected} disabled={busy}/>
{kind==='video'&&<p className="form-note">视频入库后会自动分离画面和声音。有声、无声都会标记;生成的静音视频、音轨和封面会作为资源链接附在这篇笔记中。</p>}
{error&&<p role="alert" className="error-message">{error}</p>}<div className="form-actions"><span>原文件独立保存,素材包只记录引用。</span><button className="primary-button" disabled={!files.length||busy}>{busy?'正在入库,请稍候…':'导入素材'}<ArrowUpRight size={16}/></button></div>
</form></Shell>;
}
export const getServerSideProps:GetServerSideProps=async()=>({props:{allTags:await tags()}});
+17
View File
@@ -0,0 +1,17 @@
import Head from 'next/head';
import { useRouter } from 'next/router';
import { useState, type FormEvent } from 'react';
// Keep this page independent of server-only authentication modules.
export default function Login() {
const router = useRouter(); const [code,setCode] = useState(''); const [error,setError] = useState(''); const [busy,setBusy] = useState(false);
async function submit(event: FormEvent) {
event.preventDefault(); if (busy) return; setBusy(true); setError('');
try {
const response = await fetch('/api/auth/login',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({code})});
const data = await response.json(); if (!response.ok) { setError(data.error || '登录没有完成'); setCode(''); return; }
const next = router.query.next;
window.location.assign(typeof next === 'string' && next.startsWith('/') && !next.startsWith('//') && !/[\\\r\n]/.test(next) && !next.startsWith('/login') ? next : '/');
} catch { setError('暂时无法连接,请稍后重试'); } finally { setBusy(false); }
}
return <><Head><title>动态码登录 · PROMPT</title><meta name="robots" content="noindex,nofollow"/></Head><main className="auth-page"><form className="auth-card" onSubmit={submit}><div className="auth-mark">W</div><p className="auth-brand">PROMPT</p><h1>输入动态码</h1><p className="auth-description">打开验证器,输入当前的 6 位动态码。</p><label htmlFor="auth-code">动态码</label><input id="auth-code" autoFocus inputMode="numeric" autoComplete="one-time-code" pattern="[0-9]{6}" maxLength={6} required value={code} onChange={e=>setCode(e.target.value.replace(/\D/g,''))} placeholder="000000" aria-describedby="auth-error"/><div id="auth-error" role="alert" className="auth-error">{error}</div><button type="submit" disabled={busy || code.length !== 6}>{busy ? '正在验证…' : '进入知识库'}</button><p className="auth-footnote">尚未绑定验证器?请联系管理员。</p></form></main></>;
}
@@ -0,0 +1,5 @@
import type {GetServerSideProps} from 'next';
import {publicPostId} from '@/lib/model';
import {getPost} from '@/lib/library';
export default function LegacyPost(){return null;}
export const getServerSideProps:GetServerSideProps=async({params,query})=>{const post=await getPost(String(params?.slug||''));return post?{redirect:{destination:'/explore/'+publicPostId(post)+(String(query.agent_mode||'').toLowerCase()==='true'?'?agent_mode=True':''),permanent:true}}:{notFound:true};};
@@ -0,0 +1,5 @@
import type {GetServerSideProps} from 'next';
import {getGuidance} from '@/content/skills/guidance';
import {guidanceUrl} from '@/content/page-links';
export default function Legacy(){return null;}
export const getServerSideProps:GetServerSideProps=async({params,query})=>{const parts=params?.path;if(parts===undefined)return {redirect:{destination:'/categories',permanent:false}};const path=Array.isArray(parts)?parts.join('/'):String(parts);return getGuidance(path)?{redirect:{destination:guidanceUrl(path)+(String(query.agent_mode||'').toLowerCase()==='true'?'?agent_mode=True':''),permanent:true}}:{notFound:true};};
@@ -0,0 +1,20 @@
import Head from "next/head";
import { useState } from "react";
import { Download,Copy,Sparkles } from "lucide-react";
import { Shell } from "@/components/Shell";
const strokes=[
{name:'睡眼',hint:'让石头和面包打一个盹',path:'M22 54 Q38 72 54 54 M74 54 Q90 72 106 54 M39 65 l-3 8 M89 65 l3 8'},
{name:'弯弯箭头',hint:'把目光引向一个小细节',path:'M20 87 Q15 26 92 37 M77 22 L100 37 L80 53'},
{name:'一朵小云',hint:'给天空加一点想象',path:'M30 82 C3 83 10 52 31 55 C26 22 71 20 75 47 C100 33 120 64 101 80 M32 82 L99 82'},
{name:'一点心动',hint:'给喜欢的东西圈个重点',path:'M65 99 C-4 57 35 15 64 45 C92 11 133 57 65 99'},
{name:'闪一下',hint:'把光画成一个小小的惊喜',path:'M64 20 Q61 59 28 64 Q60 67 64 106 Q69 68 102 64 Q69 60 64 20 M103 17 L103 35 M94 26 L112 26'},
{name:'草在长',hint:'沿着画面边缘悄悄长出来',path:'M24 101 Q25 73 10 64 M24 101 Q38 71 39 51 M60 101 Q49 74 48 66 M60 101 Q75 65 72 35 M96 101 Q87 71 86 62 M96 101 Q105 76 116 72'},
{name:'松松的圈',hint:'不必画得很圆',path:'M93 30 C44 8 11 40 21 79 C32 118 110 110 110 61 C109 26 76 18 45 25'},
{name:'波浪下划线',hint:'留给一句想记住的话',path:'M13 67 Q23 48 33 67 T53 67 T73 67 T93 67 T113 67'},
];
export default function Doodle(){
const [selected,setSelected]=useState(0);const [color,setColor]=useState('#fffaf0');const [copied,setCopied]=useState(false);
const svg=()=>`<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128"><path d="${strokes[selected].path}" fill="none" stroke="${color}" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
function download(){const url=URL.createObjectURL(new Blob([svg()],{type:'image/svg+xml'}));const a=document.createElement('a');a.href=url;a.download=`prompt-doodle-${selected+1}.svg`;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}
return <Shell><Head><title>线条灵感 · PROMPT</title></Head><header className="page-header"><div><span className="eyebrow">SMALL LINES, LITTLE STORIES</span><h1>线条工具</h1><p>选择图形、调整颜色,下载后用于照片涂鸦。</p></div><span className="pill"><Sparkles size={14}/>照片涂鸦工具箱</span></header><div className="doodle-layout"><section className="doodle-catalog">{strokes.map((s,i)=><button key={s.name} onClick={()=>{setSelected(i);setCopied(false);}} className={`doodle-card ${i===selected?'selected':''}`}><div><svg viewBox="0 0 128 128"><path d={s.path} fill="none" stroke={color} strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"/></svg></div><strong>{s.name}</strong><small>{s.hint}</small></button>)}</section><aside className="surface doodle-inspector"><span className="eyebrow">A LITTLE MARK</span><div className="doodle-large"><svg viewBox="0 0 128 128"><path d={strokes[selected].path} fill="none" stroke={color} strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"/></svg></div><h2>{strokes[selected].name}</h2><p>{strokes[selected].hint}</p><div className="swatches">{['#fffaf0','#332c28','#ef6954','#ecc75b'].map(c=><button aria-label={`线条颜色 ${c}`} key={c} style={{background:c}} className={c===color?'selected':''} onClick={()=>setColor(c)}/>)}</div><button className="primary-button" onClick={download}><Download size={16}/>下载透明底 SVG</button><button className="secondary-button" onClick={async()=>{await navigator.clipboard.writeText(svg());setCopied(true);}}><Copy size={16}/>{copied?'已复制':'复制线条'}</button><p className="form-note">小图用来挑选造型与记录想法。正式画进照片时,位置、比例与笔触仍需要顺着画面调整。</p></aside></div></Shell>;
}
@@ -0,0 +1,5 @@
import type {GetServerSideProps} from 'next';
import {getGuidance,legacyDocumentPath} from '@/content/skills/guidance';
import {guidanceUrl} from '@/content/page-links';
export default function Legacy(){return null;}
export const getServerSideProps:GetServerSideProps=async({params})=>{const doc=params?.doc;const path=legacyDocumentPath(String(params?.skill),Array.isArray(doc)?doc[0]:'index');return getGuidance(path)?{redirect:{destination:guidanceUrl(path),permanent:true}}:{notFound:true};};
@@ -0,0 +1 @@
export {GuidanceIndex as default} from '@/components/GuidanceIndex';
@@ -0,0 +1,4 @@
export {default} from '../../skills/[[...path]]';
import type {GetServerSideProps} from 'next';
import {guidanceUrl} from '@/content/page-links';
export const getServerSideProps:GetServerSideProps=async()=>({redirect:{destination:guidanceUrl('street-people'),permanent:true}});
@@ -0,0 +1,5 @@
export {default} from '../[skill]/[[...doc]]';
import type {GetServerSideProps} from 'next';
import {getGuidance,legacyDocumentPath} from '@/content/skills/guidance';
import {guidanceUrl} from '@/content/page-links';
export const getServerSideProps:GetServerSideProps=async({params})=>{const path=legacyDocumentPath('street-people',String(params?.doc));return getGuidance(path)?{redirect:{destination:guidanceUrl(path),permanent:true}}:{notFound:true};};
@@ -0,0 +1,6 @@
import type {GetServerSideProps} from 'next';
import {getPost} from '@/lib/library';
import {findWikiPage} from '@/content/wiki';
import {pageId,exploreUrl} from '@/content/page-links';
export default function Legacy(){return null;}
export const getServerSideProps:GetServerSideProps=async({params,query})=>{const key=String(params?.key||'');const page=findWikiPage(key);let destination='';if(page?.namespace==='Category')destination='/categories?category='+encodeURIComponent(page.slug);else if(page)destination=exploreUrl(pageId('wiki:'+key));else{const index=key.indexOf(':');if(!['Main','File'].includes(key.slice(0,index)))return {notFound:true};const post=await getPost(key.slice(index+1));if(post)destination=exploreUrl(post.id);}if(!destination)return {notFound:true};if(String(query.agent_mode||'').toLowerCase()==='true')destination+=(destination.includes('?')?'&':'?')+'agent_mode=True';return {redirect:{destination,permanent:true}};};
+25
View File
@@ -0,0 +1,25 @@
import { NextResponse, type NextRequest } from 'next/server';
import { authConfig, SESSION_COOKIE, validSession } from './lib/auth';
export function proxy(request: NextRequest) {
const path = request.nextUrl.pathname;
const responseHeaders = {'Cache-Control':'private, no-store', 'Referrer-Policy':'same-origin'};
// Only login code assets and minimal health probes are public. Images, documents,
// rewrites and /_next/data are protected along with pages and API endpoints.
if (path === '/login' || path === '/api/auth/login' || path === '/api/auth/logout' || path === '/api/health' || path === '/api/ready' || path.startsWith('/_next/static/')) return NextResponse.next({headers:responseHeaders});
let config;
try { config = authConfig(); } catch { return NextResponse.json({error:'登录服务配置不可用'}, {status:503,headers:responseHeaders}); }
if (!config) return NextResponse.next();
const bearer = request.headers.get('authorization');
const token = bearer?.startsWith('Bearer ') ? bearer.slice(7) : request.cookies.get(SESSION_COOKIE)?.value;
if (validSession(token,config)) {
if (!['GET','HEAD','OPTIONS'].includes(request.method) && !bearer) {
const origin = request.headers.get('origin');
const host = request.headers.get('host');
try { if (!origin || new URL(origin).host !== host || request.headers.get('sec-fetch-site') === 'cross-site') return NextResponse.json({error:'请求来源不受信任'}, {status:403,headers:responseHeaders}); } catch { return NextResponse.json({error:'请求来源不受信任'}, {status:403,headers:responseHeaders}); }
}
return NextResponse.next({headers:responseHeaders});
}
if (path.startsWith('/api/') || path.startsWith('/studio/api/') || !['GET','HEAD'].includes(request.method)) return NextResponse.json({error:'请先使用动态码登录'}, {status:401,headers:responseHeaders});
const login = request.nextUrl.clone(); login.pathname = '/login'; login.search = ''; login.searchParams.set('next',path + request.nextUrl.search);
return NextResponse.redirect(login,{headers:responseHeaders});
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,3 @@
.skills-masonry{columns:4 230px;column-gap:24px}.skill-pin{display:block;break-inside:avoid;margin:0 0 28px}.skill-pin-cover{background:#f1eee8!important;aspect-ratio:4/5;display:grid;place-items:center;max-height:440px}.skill-pin-cover img{width:100%;height:100%;object-fit:contain!important;padding:24px}.docs-top{display:flex;justify-content:space-between;font-size:13px;color:#777;gap:15px;margin-bottom:28px}.docs-top button{display:flex;align-items:center;gap:8px}.docs-layout{max-width:1200px;margin:auto;display:grid;gap:35px;grid-template-columns:minmax(0,800px);justify-content:center}.docs-layout.with-sources{grid-template-columns:minmax(0,1fr) 340px}.docs-body{min-width:0;padding:18px 12px 70px}.docs-eyebrow{font-size:11px;color:#9b968b;letter-spacing:1.5px}.docs-body h1{font-size:38px;font-weight:700;margin:18px 0 24px;letter-spacing:-1px}.docs-body h2{font-size:23px;margin:40px 0 20px;font-weight:650}.docs-body>p{font-size:15px;color:#555;line-height:2;margin:22px 0}.docs-actions{display:flex;gap:12px;align-items:center;flex-wrap:wrap;font-size:12px}.docs-actions button{display:flex;align-items:center;gap:8px;background:#252525;color:white;padding:12px 16px;border-radius:24px}.docs-actions a{color:#888}.docs-body>.docs-hint{font-size:12px;color:#999}.docs-body pre,.docs-resource-preview pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#f5f5f2;padding:22px;border-radius:15px;font-size:12px;line-height:1.9;color:#666}.docs-inline-links{display:flex;flex-wrap:wrap;gap:8px;margin:20px 0}.docs-inline-links a{display:flex;align-items:center;gap:7px;border:1px solid #e4e4df;border-radius:20px;padding:9px 12px;font-size:12px;color:#64705b}.docs-sources{position:sticky;top:105px;align-self:start;max-height:calc(100vh - 125px);overflow:auto;border:1px solid #e6e6e1;border-radius:18px;background:white;box-shadow:0 8px 35px #00000008;padding:20px}.docs-sources>header{display:flex;justify-content:space-between;gap:10px;align-items:flex-start;border-bottom:1px solid #eee;padding-bottom:18px}.docs-sources header b{font-size:16px}.docs-sources header small{display:block;font-size:11px;color:#aaa;margin-top:7px}.docs-sources h3{font-size:12px;color:#999;margin:21px 0 10px}.docs-sources section>button{display:flex;text-align:left;align-items:flex-start;gap:9px;width:100%;padding:12px 8px;border-radius:10px}.docs-sources section>button.selected,.docs-sources section>button:hover{background:#f2f3ed}.docs-sources section>button>span{font-size:9px;border:1px solid #ddd;padding:3px 4px;border-radius:5px;color:#92987f;flex-shrink:0}.docs-sources section>button>div{font-size:12px;color:#555;min-width:0}.docs-sources section small{display:block;font-size:10px;overflow-wrap:anywhere;color:#aaa;margin-top:5px}.docs-resource-preview{border-top:1px solid #ddd;margin-top:20px}.docs-resource-preview img{width:100%;max-height:350px;object-fit:contain;background:repeating-conic-gradient(#eee 0 25%,white 0 50%) 0/16px 16px}.docs-resource-preview pre{font-size:10px;max-height:330px;overflow:auto;padding:12px}.docs-resource-preview p,.docs-resource-preview code{font-size:11px;line-height:1.8;overflow-wrap:anywhere}.docs-resource-actions{display:flex;flex-wrap:wrap;gap:12px;font-size:12px;color:#60724e;margin:18px 0}.docs-body a:focus-visible,.docs-sources button:focus-visible{outline:2px solid #81956d;outline-offset:3px}
@media(max-width:1050px){.docs-layout.with-sources{grid-template-columns:minmax(0,1fr) 285px;gap:18px}}@media(max-width:760px){.docs-layout.with-sources{display:block}.docs-sources{position:fixed;right:12px;left:12px;top:95px;bottom:18px;max-height:none;z-index:45;box-shadow:0 0 0 100vmax #0005}.docs-body h1{font-size:30px}.docs-body{padding:10px 0 40px}.docs-body>p{font-size:14px}.skills-masonry{columns:2;column-gap:15px}.skill-pin-cover img{padding:12px}.snapshot-reader{padding:14px 8px}.snapshot-reader>header{align-items:flex-start;flex-direction:column}.snapshot-reader nav{gap:10px}.snapshot-reader nav a{font-size:11px}}
.guidance-directory{border-top:1px solid #e4e4df;margin-top:24px}.guidance-directory>div{display:grid;grid-template-columns:minmax(0,1fr) auto auto;align-items:center;gap:20px;padding:18px 0;border-bottom:1px solid #e4e4df}.guidance-directory>div>a:first-child{font-size:15px;color:#3e4938}.guidance-directory small,.guidance-directory>div>a:last-child{font-size:12px;color:#888}@media(max-width:760px){.guidance-directory>div{grid-template-columns:minmax(0,1fr) auto;gap:8px}.guidance-directory small{grid-column:1;grid-row:2}.guidance-directory>div>a:last-child{grid-column:2;grid-row:1/3}}
+56
View File
@@ -0,0 +1,56 @@
import { mkdtemp,rm,writeFile } from "node:fs/promises";
import { createWriteStream } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { pipeline } from "node:stream/promises";
import type { Readable } from "node:stream";
import { setTimeout } from "node:timers/promises";
import { db,transaction } from "./lib/db";
import { getObject,putFile } from "./lib/storage";
import { probe,run } from "./lib/probe";
import {randomUUID} from "node:crypto";
import {linkDerivedAssets} from "./lib/asset-links";
let stopping=false;
process.on('SIGTERM',()=>{stopping=true;});process.on('SIGINT',()=>{stopping=true;});
async function processOne(){
const job=await transaction(async client=>(await client.query(`UPDATE media_jobs SET status='processing',attempts=attempts+1,locked_at=now() WHERE id=(SELECT id FROM media_jobs WHERE (status='pending' AND available_at<=now()) OR (status='processing' AND locked_at<now()-interval '15 minutes') ORDER BY available_at FOR UPDATE SKIP LOCKED LIMIT 1) RETURNING *`)).rows[0]);
if(!job)return false;
const dir=await mkdtemp(join(tmpdir(),'prompt-video-'));
try{
await db().query("UPDATE assets SET processing_status='processing',processing_error=NULL WHERE id=$1",[job.asset_id]);
const asset=(await db().query('SELECT * FROM assets WHERE id=$1',[job.asset_id])).rows[0];
const input=join(dir,'input');const object=await getObject(asset.storage_key);
await pipeline(object.Body as Readable,createWriteStream(input));
const metadata=await probe(input);const hasAudio=metadata.streams.some(s=>s.codec_type==='audio');
const variants=[{role:'silent_video',mime:'video/mp4',file:'silent.mp4',args:['-map','0:v:0','-an','-c:v','libx264','-preset','veryfast','-crf','22','-pix_fmt','yuv420p','-vf','scale=trunc(iw/2)*2:trunc(ih/2)*2','-movflags','+faststart']},
{role:'poster',mime:'image/jpeg',file:'poster.jpg',args:['-map','0:v:0','-frames:v','1','-vf','scale=min(1200\\,iw):-2']}];
if(hasAudio)variants.push({role:'audio_track',mime:'audio/mp4',file:'audio.m4a',args:['-map','0:a:0','-vn','-c:a','aac','-b:a','192k']});
const outputs:{role:string;mime:string;file:string;args:string[];key:string;size:number}[]=[];
for(const v of variants){const path=join(dir,v.file);await run(process.env.FFMPEG_PATH||'ffmpeg',['-nostdin','-y','-v','error','-protocol_whitelist','file,pipe','-i',input,...v.args,path],{timeout:10*60*1000,maxBuffer:2*1024*1024});const key=`derived/${asset.id}/${v.file}`;const size=await putFile(key,path,v.mime);outputs.push({...v,key,size});}
await transaction(async client=>{
for(const v of outputs)await client.query(`INSERT INTO assets(id,kind,filename,storage_key,mime_type,byte_size,source_asset_id,derivation)
VALUES($1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT(source_asset_id,derivation) WHERE source_asset_id IS NOT NULL
DO UPDATE SET storage_key=excluded.storage_key,mime_type=excluded.mime_type,byte_size=excluded.byte_size`,
[randomUUID(),v.role==='poster'?'image':v.role==='audio_track'?'audio':'video',v.file,v.key,v.mime,v.size,asset.id,v.role]);
const posts=(await client.query("SELECT DISTINCT post_id FROM post_assets WHERE asset_id=$1 AND role='content' ORDER BY post_id",[asset.id])).rows;
for(const post of posts)await linkDerivedAssets(client,post.post_id);
await client.query("UPDATE assets SET has_audio=$2,processing_status='ready',processing_error=NULL WHERE id=$1",[asset.id,hasAudio]);
await client.query("UPDATE media_jobs SET status='ready',last_error=NULL WHERE id=$1",[job.id]);
});
}catch(error){
const message=(error instanceof Error?error.message:'Processing failed').slice(0,2000);const final=job.attempts>=3;
await transaction(async client=>{
await client.query("UPDATE media_jobs SET status=$2,last_error=$3,available_at=now()+interval '30 seconds' WHERE id=$1",[job.id,final?'failed':'pending',message]);
await client.query('UPDATE assets SET processing_status=$2,processing_error=$3 WHERE id=$1',[job.asset_id,final?'failed':'pending',message]);
});
console.error(`Video processing failed for ${job.asset_id}; retry=${!final}`);
}finally{await rm(dir,{recursive:true,force:true});}
return true;
}
async function main(){
const heartbeat=()=>writeFile('/tmp/prompt-worker-health',String(Date.now())).catch(()=>console.error('Worker heartbeat failed'));
await heartbeat();const timer=setInterval(()=>{void heartbeat();},15000);
try{while(!stopping){try{if(!await processOne())await setTimeout(2000);}catch{console.error('Worker connection error; retrying');await setTimeout(5000);}}}
finally{clearInterval(timer);await db().end();}
}
main().catch(()=>process.exit(1));