Restructure into Wiki, Studio and Python monorepo with scoped CI
python CI and deployment / verify-and-deploy (push) Successful in 7m23s
studio CI and deployment / verify-and-deploy (push) Failing after 5m28s
wiki CI and deployment / verify-and-deploy (push) Failing after 6m13s

This commit is contained in:
2026-10-25 21:13:43 +08:00
parent c898e41672
commit a2330b22e2
152 changed files with 3525 additions and 3287 deletions
@@ -0,0 +1,13 @@
import Link from "next/link";
import {useEffect,useState} from "react";
import {ChevronLeft,ChevronRight,RefreshCw,ExternalLink} from "lucide-react";
import {mediaUrl} from "@/lib/model";
type State={pages:{page_index:number;asset_id:string;rendered_at:string}[];job:{status:string;error:string|null}|null};
export function ArticleGallery({slug}:{slug:string}){
const [state,setState]=useState<State>({pages:[],job:null});const[index,setIndex]=useState(1);const[error,setError]=useState('');const[requesting,setRequesting]=useState(false);
const pending=state.job?.status==='pending'||state.job?.status==='processing';
useEffect(()=>{let live=true;const load=async()=>{try{const r=await fetch(`/api/posts/${slug}/snapshots`);if(!r.ok)throw Error();const s=await r.json();if(live){setState(s);setError('');}}catch{if(live)setError('截图状态读取失败,请重试。');}};void load();const timer=setInterval(()=>void load(),3000);return()=>{live=false;clearInterval(timer)};},[slug]);
async function refresh(all=false){setRequesting(true);setError('');try{const r=await fetch(`/api/posts/${slug}/snapshots`,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(all?{}:{page:index})});if(!r.ok)throw Error();setState(s=>({...s,job:{status:'pending',error:null}}));}catch{setError('刷新没有完成,请重试。')}finally{setRequesting(false)}}
const selected=state.pages.find(p=>p.page_index===index);const url=`/p/${slug}/pages/${index}`;
return <div className="snapshot-reader"><header><div><b>这篇笔记 · 8 张图</b><p>{pending?'正在从最新网页重新截图…':selected?`截图更新于 ${new Date(selected.rendered_at).toLocaleString('zh-CN',{timeZone:'Asia/Shanghai'})}`:'等待生成截图'}</p></div><button className="secondary-button" disabled={pending||requesting} onClick={()=>void refresh()}><RefreshCw size={15}/>刷新这张截图</button><button className="text-link" disabled={pending||requesting} onClick={()=>void refresh(true)}>更新全部</button></header>{error&&<p role="alert">{error}</p>}{state.job?.status==='failed'&&<p role="alert">截图未完成,保留上次版本。可以重新刷新。</p>}<div className="snapshot-stage">{selected?<a href={url} target="_blank" rel="noreferrer"><img src={mediaUrl(selected.asset_id)} alt={`笔记第 ${index} 张截图`} width={1080} height={1440}/></a>:<div className="snapshot-placeholder">这张图还没有截图。<Link href={url} target="_blank">先打开网页原稿 ↗</Link></div>}</div><nav><button aria-label="上一张" disabled={index===1} onClick={()=>setIndex(i=>i-1)}><ChevronLeft/></button><span>{index} / 8</span><button aria-label="下一张" disabled={index===8} onClick={()=>setIndex(i=>i+1)}><ChevronRight/></button><Link href={url} target="_blank"><ExternalLink size={15}/>打开这张图的网页</Link></nav><div className="snapshot-thumbs">{Array.from({length:8},(_,i)=>{const p=state.pages.find(p=>p.page_index===i+1);return <button aria-label={`查看第 ${i+1} 张截图`} aria-pressed={index===i+1} onClick={()=>setIndex(i+1)} key={i}>{p?<img src={mediaUrl(p.asset_id)} alt=""/>:<span>{i+1}</span>}</button>})}</div></div>;
}
+41
View File
@@ -0,0 +1,41 @@
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={`/p/${post.slug}`}><div className={`post-cover cover-${post.kind}`} style={image?.width&&image?.height?{aspectRatio:`${image.width}/${image.height}`,maxHeight:460}:undefined}>
{source?<img src={source} 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.filter(t=>target?t.parent_id===target.id:!t.parent_id);
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>}
+20
View File
@@ -0,0 +1,20 @@
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}]},
{label:'素材',items:[{href:'/images',label:'图片',icon:Image},{href:'/videos',label:'视频',icon:Film},{href:'/audio',label:'声音',icon:AudioLines}]},
{label:'作品',items:[{href:'/articles',label:'图文',icon:BookOpen},{href:'/motion',label:'动态',icon:Clapperboard}]},
{label:'工具',items:[{href:'/skills',label:'指导文档',icon:BookOpen},{href:'/tools/doodle',label:'线条工具',icon:Sparkles}]},
];
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>
<div className="sidebar-bottom"><Link href="/library/import" className="import-link"><Upload size={22}/><span>导入素材</span><ArrowUpRight size={17}/></Link></div>
</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=/^\/(images|videos|audio|articles|motion)(\/|$)/.test(path)?path:'/';void router.push({pathname:destination,query:query?{q:query}:{}});}}><Search size={24}/><input aria-label="搜索素材包" placeholder="搜索知识、灵感和素材" value={query} onChange={e=>setQuery(e.target.value)}/>{query&&<button type="button" aria-label="清空搜索" onClick={()=>setQuery('')}><X size={20}/></button>}</form></div>{children}</main>{open&&<button className="nav-scrim" aria-label="关闭导航" onClick={()=>setOpen(false)}/>}
</div>;
}
+4
View File
@@ -0,0 +1,4 @@
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={skill.href} className="post-card skill-pin"><div className="post-cover skill-pin-cover"><img src={skill.image} 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>}
+48
View File
@@ -0,0 +1,48 @@
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={selected.href} 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,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:["原句 / 问题位置","影响 / 具体改法","修改示例 / 下次练习"]},
],
},
];
+9
View File
@@ -0,0 +1,9 @@
import type { ComponentType } from "react";
import { LearningSeries } from "./learning-skills/Series";
// Register code-authored pages here, then reference their key in the posts API.
// No page or sample post is inserted into the user's library automatically.
export const works: Record<string, { kind: "article" | "motion"; Component: ComponentType }> = {
"learning-skills-notes": {kind:"article", Component:()=> <LearningSeries chapterKey="learning-skills-notes"/>},
"learning-skills-teaching": {kind:"article", Component:()=> <LearningSeries chapterKey="learning-skills-teaching"/>},
"learning-skills-english": {kind:"article", Component:()=> <LearningSeries chapterKey="learning-skills-english"/>},
};
+44
View File
@@ -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);}
+62
View File
@@ -0,0 +1,62 @@
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)=>`/skills/${path}`;
export const markdownDocumentUrl=(path:string)=>`${humanDocumentUrl(path)}/index.md`;
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);}
+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>={
'Character PNG must have transparency':'请上传带真实透明背景的 PNG,透明区域 alpha 为 0,人物内部 alpha 至少为 250',
'Register the coded page before creating its post':'请先在代码中注册对应的作品页面',
'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:"操作没有完成,请稍后重试"});
}
+11
View File
@@ -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(); }
}
+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 } };
}
+30
View File
@@ -0,0 +1,30 @@
import { db } from "./db";
import { decodeCursor, encodeCursor, type FeedData, type Post, type PostKind, type Tag } from "./model";
import { works } from "../content/registry";
const tagTree = `WITH RECURSIVE tree AS (SELECT *,slug::text AS path FROM tags WHERE parent_id IS NULL UNION ALL SELECT t.*,tree.path||'/'||t.slug FROM tags t JOIN tree ON t.parent_id=tree.id) SELECT * FROM tree`;
export async function tags(): Promise<Tag[]> { return (await db().query(`${tagTree} ORDER BY path`)).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.role) FROM asset_variants v WHERE v.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 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=[`((p.kind IN ('article','motion') AND p.page_key=ANY($1::text[])) OR 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='content' AND a.kind=p.kind AND a.storage_key IS NOT NULL AND a.byte_size>0))`];
values.push(Object.keys(works));
if(options.kind){values.push(options.kind);where.push(`p.kind=$${values.length}`);}
if(target){values.push(allTags.filter(t=>t.path===target.path||t.path.startsWith(target.path+"/")).map(t=>t.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};
}
+9
View File
@@ -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);
}
+22
View File
@@ -0,0 +1,22 @@
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[] };
export type Tag = { id: string; parent_id: string | null; name: string; slug: string; path: string };
export type Post = { id: string; slug: string; kind: PostKind; title: string; created_at: string; updated_at: string; page_key: string | null; 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");
}
+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,46 @@
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
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,parent_id,slug,name) VALUES($1,NULL,'learning-skills','学习工具')
ON CONFLICT(parent_id,slug) DO UPDATE SET name=excluded.name RETURNING id`,[stableId("tag-root")])).rows[0].id;
const published:string[]=[];
for(const chapter of chapters){
const child=(await client.query(`INSERT INTO tags(id,parent_id,slug,name) VALUES($1,$2,$3,$4)
ON CONFLICT(parent_id,slug) DO UPDATE SET name=excluded.name RETURNING id`,[stableId(`tag-${chapter.key}`),root,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,page_key,cover_asset_id) VALUES($1,$2,'article',$3,$4,$5)
ON CONFLICT(slug) DO UPDATE SET title=excluded.title,cover_asset_id=COALESCE((SELECT asset_id FROM page_snapshots WHERE post_id=posts.id AND page_index=1),excluded.cover_asset_id),updated_at=now()
WHERE posts.page_key=excluded.page_key AND posts.kind='article' RETURNING id,cover_asset_id`,[stableId(chapter.key),chapter.slug,chapter.title,chapter.key,coverId]);
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${chapter.subtitle}。三篇共用系列封面,每篇 8 页,介绍 10 项工具。\n\n${chapter.skills.map((skill,i)=>`${String(i+1).padStart(2,"0")} ${skill.name} — ${skill.title}`).join("\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) ON CONFLICT DO NOTHING",[postId,child]);
await client.query(`INSERT INTO render_jobs(post_id,status,revision) VALUES($1,'pending',$2) ON CONFLICT(post_id) DO UPDATE SET status='pending',revision=excluded.revision,attempts=0,target_page=NULL,error=NULL WHERE render_jobs.revision IS DISTINCT FROM excluded.revision`,[postId,process.env.RELEASE_SHA||'development']);
published.push(chapter.slug);
}
return {published,coverId};
});
}
+57
View File
@@ -0,0 +1,57 @@
import {chromium} from "playwright-core";
import {createHash,randomUUID} from "node:crypto";
import {mkdtemp,rm} from "node:fs/promises";
import {tmpdir} from "node:os";
import {join} from "node:path";
import {db,transaction} from "./db";
import {putFile} from "./storage";
import {chapters} from "../content/learning-skills/data";
export async function snapshotState(slug:string){
const post=(await db().query('SELECT id,page_key FROM posts WHERE slug=$1',[slug])).rows[0];
if(!post||!chapters.some(c=>c.key===post.page_key))return null;
const pages=(await db().query('SELECT page_index,asset_id,rendered_at,revision FROM page_snapshots WHERE post_id=$1 ORDER BY page_index',[post.id])).rows;
const job=(await db().query('SELECT status,error,revision,attempts,target_page FROM render_jobs WHERE post_id=$1',[post.id])).rows[0]||null;
return {postId:post.id,pages,job};
}
export async function queueSnapshots(postId:string,pageIndex?:number){
await db().query(`INSERT INTO render_jobs(post_id,status,revision,target_page) VALUES($1,'pending',$2,$3) ON CONFLICT(post_id) DO UPDATE SET status='pending',revision=excluded.revision,target_page=excluded.target_page,attempts=0,error=NULL WHERE render_jobs.status NOT IN ('pending','processing')`,[postId,process.env.RELEASE_SHA||'development',pageIndex??null]);
}
export async function renderOne(){
const job=await transaction(async c=>(await c.query(`UPDATE render_jobs SET status='processing',attempts=attempts+1,locked_at=now() WHERE post_id=(SELECT post_id FROM render_jobs WHERE status='pending' OR (status='processing' AND locked_at<now()-interval '10 minutes') ORDER BY post_id FOR UPDATE SKIP LOCKED LIMIT 1) RETURNING *`)).rows[0]);
if(!job)return false;
const dir=await mkdtemp(join(tmpdir(),'prompt-snapshots-'));let browser;
try{
const post=(await db().query('SELECT slug,page_key FROM posts WHERE id=$1',[job.post_id])).rows[0];
if(!chapters.some(c=>c.key===post.page_key&&c.slug===post.slug))throw Error('Unknown coded page');
browser=await chromium.launch({executablePath:process.env.CHROMIUM_PATH||'/usr/bin/chromium',args:['--no-sandbox','--disable-dev-shm-usage']});
const context=await browser.newContext({viewport:{width:1080,height:1440},deviceScaleFactor:1,locale:'zh-CN',timezoneId:'Asia/Shanghai',reducedMotion:'reduce'});
const origin=new URL(process.env.RENDER_ORIGIN||'http://web:3000').origin;
await context.route('**/*',route=>new URL(route.request().url()).origin===origin?route.continue():route.abort());
const page=await context.newPage();const output:{index:number;id:string}[]=[];
for(let index=job.target_page||1;index<=(job.target_page||8);index++){
console.log('Rendering canvas',post.slug,index);
const response=await page.goto(`${origin}/p/${post.slug}/pages/${index}`,{waitUntil:'networkidle',timeout:45000});
if(!response?.ok())throw Error('Canvas page unavailable');
await page.locator('[data-render-page]').waitFor();await page.evaluate(async()=>{await document.fonts.ready;});
console.log('Canvas loaded',post.slug,index);
const overflow=await page.evaluate(()=>{const sheet=document.querySelector('.learning-sheet');if(!sheet)return false;const footer=sheet.querySelector('footer')!;return Array.from(sheet.children).filter(c=>c!==footer).some(c=>c.getBoundingClientRect().bottom>footer.getBoundingClientRect().top-2)});
if(overflow)throw Error(`Canvas ${index} overlaps its footer`);
const path=join(dir,`${index}.png`);const bytes=await page.locator('[data-render-page]').screenshot({path,animations:'disabled'});
const hash=createHash('sha256').update(bytes).digest('hex');const key=`snapshots/${hash}.png`;const size=await putFile(key,path,'image/png');
const asset=(await db().query(`INSERT INTO assets(id,kind,filename,storage_key,mime_type,byte_size,sha256,width,height) VALUES($1,'image',$2,$3,'image/png',$4,$5,1080,1440) ON CONFLICT(storage_key) DO UPDATE SET storage_key=excluded.storage_key RETURNING id`,[randomUUID(),`图文-${index}.png`,key,size,hash])).rows[0];output.push({index,id:asset.id});console.log('Canvas stored',post.slug,index);
}
await transaction(async c=>{
const current=(await c.query('SELECT revision FROM render_jobs WHERE post_id=$1 FOR UPDATE',[job.post_id])).rows[0];
if(current.revision!==job.revision)return;
for(const result of output){
await c.query(`INSERT INTO page_snapshots(post_id,page_index,asset_id,revision) VALUES($1,$2,$3,$4) ON CONFLICT(post_id,page_index) DO UPDATE SET asset_id=excluded.asset_id,revision=excluded.revision,rendered_at=now()`,[job.post_id,result.index,result.id,job.revision]);
await c.query(`INSERT INTO post_assets(post_id,asset_id,position,role) VALUES($1,$2,$3,'content') ON CONFLICT(post_id,position) DO UPDATE SET asset_id=excluded.asset_id,role='content'`,[job.post_id,result.id,result.index===1?0:result.index+1]);
}
// Position zero remains the shared series cover reference; captions remain at one.
if(output[0].index===1)await c.query('UPDATE posts SET cover_asset_id=$2,updated_at=now() WHERE id=$1',[job.post_id,output[0].id]);
await c.query("UPDATE render_jobs SET status='ready',error=NULL WHERE post_id=$1",[job.post_id]);
});
}catch(e){await db().query("UPDATE render_jobs SET status=$2,error=$3 WHERE post_id=$1 AND revision=$4",[job.post_id,job.attempts<3?'pending':'failed',e instanceof Error?e.message:'Screenshot failed',job.revision]);console.error('Page screenshot job failed',job.post_id,e instanceof Error?e.message:'');await new Promise(r=>setTimeout(r,3000));}
finally{await browser?.close();await rm(dir,{recursive:true,force:true});}
return true;
}
+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 }));
+9
View File
@@ -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;
+27
View File
@@ -0,0 +1,27 @@
import { randomUUID } from "node:crypto";
import { z } from "zod";
import { transaction } from "./db";
import { works } from "../content/registry";
export const postInput=z.object({
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([]),
text:z.string().trim().max(100000).optional(),tags:z.array(z.uuid()).max(50).default([]),
coverAssetId:z.uuid().optional(),pageKey:z.string().max(120).optional(),
});
export async function createPost(input:z.infer<typeof postInput>) {
const id=randomUUID(); const slug=input.slug||id;
if(["article","motion"].includes(input.kind)&&(!input.pageKey||works[input.pageKey]?.kind!==input.kind)) throw new Error("Register the coded page before creating its post");
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,page_key,cover_asset_id) VALUES($1,$2,$3,$4,$5,$6)',[id,slug,input.kind,input.title,input.pageKey||null,input.coverAssetId||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]);
return {id,slug};
});
}
@@ -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} />;
}
+4
View File
@@ -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));}
+10
View File
@@ -0,0 +1,10 @@
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(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);
}
+10
View File
@@ -0,0 +1,10 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { healthResponse } from "@/lib/health";
export default function handler(req: NextApiRequest, res: NextApiResponse) {
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);
}
+24
View File
@@ -0,0 +1,24 @@
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(!['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 asset_variants WHERE asset_id=$1 AND role=$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, max-age=3600');
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,8 @@
import type {NextApiRequest,NextApiResponse} from "next";
import {snapshotState,queueSnapshots} from "@/lib/snapshots";
import {sameOrigin,apiError} from "@/lib/api";
export default async function handler(req:NextApiRequest,res:NextApiResponse){
res.setHeader('Cache-Control','no-store');
if(!['GET','POST'].includes(req.method||''))return res.status(405).end();
try{const state=await snapshotState(String(req.query.slug));if(!state)return res.status(404).end();if(req.method==='POST'){sameOrigin(req);const page=req.body?.page;if(page!==undefined&&(!Number.isInteger(page)||page<1||page>8))return res.status(400).json({error:'页码应为 1—8'});await queueSnapshots(state.postId,page);return res.status(202).json({queued:true});}return res.json(state);}catch(e){return apiError(res,e);}
}
+7
View File
@@ -0,0 +1,7 @@
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(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);}
}
+9
View File
@@ -0,0 +1,9 @@
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(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,16 @@
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){
res.setHeader("Allow","GET, POST");
if(req.method==="GET"){
res.setHeader("Cache-Control","public, max-age=300");
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 素材包"});
}
+15
View File
@@ -0,0 +1,15 @@
import type { NextApiRequest,NextApiResponse } from "next";
import { z } from "zod";
import { randomUUID } from "node:crypto";
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){
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().min(1).max(60),slug:z.string().regex(/^[a-z0-9][a-z0-9-]{0,59}$/),parentId:z.uuid().nullable().default(null)}).parse(req.body);
const id=randomUUID(); await db().query('INSERT INTO tags(id,name,slug,parent_id) VALUES($1,$2,$3,$4)',[id,data.name,data.slug,data.parentId]);return res.status(201).json({id});
}catch(e){return apiError(res,e);}
}
+64
View File
@@ -0,0 +1,64 @@
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(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 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);
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=randomUUID();
await transaction(async client=>{
await client.query('INSERT INTO posts(id,slug,kind,title) VALUES($1,$2,$3,$4)',[postId,slug||postId,kind,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']);
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(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]);}
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;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;
+3
View File
@@ -0,0 +1,3 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {wikiPages,wikiPath} from '@/content/wiki';
export default function handler(_:NextApiRequest,res:NextApiResponse){res.setHeader('Content-Type','text/markdown; charset=utf-8');res.send('# PROMPT Wiki\n\n'+wikiPages.map(p=>`- [${p.namespace}:${p.title}](${wikiPath(p)}) · [Markdown](/api/wiki/${encodeURIComponent(p.namespace+':'+p.slug)})`).join('\n')+'\n\n## 现有资料\n\n[指导文档索引](/agent/index.md)\n\n[素材分页索引](/api/feed)(使用 nextCursor 翻页)\n\n每个素材或作品 /p/{slug} 的 Markdown 位于 /api/wiki-post/{slug}。\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');}}
+4
View File
@@ -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));}
+7
View File
@@ -0,0 +1,7 @@
import type {GetServerSideProps} from 'next';
import Head from 'next/head';
import Link from 'next/link';
import {Shell} from '@/components/Shell';
import {wikiPages,namespaces,wikiPath} from '@/content/wiki';
export default function Home({namespace,q}:{namespace:string;q:string}){const pages=wikiPages.filter(p=>(!namespace||p.namespace===namespace)&&(!q||(p.title+p.summary+p.body).includes(q)));const categories=[...new Set(wikiPages.flatMap(p=>p.categories))];return <Shell><Head><title>PROMPT · 灵感百科</title><link rel="alternate" type="text/markdown" href="/api/wiki-index"/></Head><div className="wiki-tabs"><Link href="/" className={!namespace?'selected':''}>发现</Link>{namespaces.map(n=><Link href={'/?namespace='+n} className={namespace===n?'selected':''} key={n}>{n}</Link>)}</div><div className="wiki-intro"><span>YOUR EVERYDAY KNOWLEDGE</span><h1>收藏灵感,也连接知识。</h1><p>每一篇笔记,都是通往下一个想法的入口。</p></div>{namespace==='File'?<div className="wiki-empty"><h2>你的媒体素材库</h2><Link href="/images">图片 → </Link><Link href="/videos">视频 → </Link><Link href="/audio">声音 →</Link></div>:namespace==='Category'?<div className="wiki-cards">{categories.map(c=><Link className="wiki-card" key={c} href={'/wiki/'+encodeURIComponent('Category:'+c)}><div className="wiki-cover" style={{background:'#e6e9ef'}}>{c}</div><h2>Category:{c}</h2><p>浏览相关条目 →</p></Link>)}</div>:<div className="wiki-cards">{pages.map((p,i)=><Link className="wiki-card" href={wikiPath(p)} key={p.slug}><div className="wiki-cover" style={{background:p.color,minHeight:i%2?280:340}}><small>{p.namespace.toUpperCase()} / 0{i+1}</small><strong>{p.title}</strong><span>知识是一种日常</span></div><h2>{p.title}</h2><p>{p.summary}</p><footer><span className="wiki-avatar">P</span>PROMPT Wiki <span>♡</span></footer></Link>)}</div>}{!pages.length&&!['File','Category'].includes(namespace)&&<p>还没有匹配的条目。</p>}<div className="wiki-bottom"><Link href="/articles">浏览已有图文作品 →</Link><a href="/api/wiki-index">AI 内容索引 ↗</a></div></Shell>}
export const getServerSideProps:GetServerSideProps=async({query})=>({props:{namespace:String(query.namespace||''),q:String(query.q||'').slice(0,200)}});
+25
View File
@@ -0,0 +1,25 @@
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 { 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('/p/'+result.slug);}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>
{allTags.length>0&&<div className="form-field"><label>放进哪些分类 <small>可多选</small></label><div className="tag-picker">{allTags.map(t=><label key={t.id}><input type="checkbox" checked={selected.includes(t.id)} onChange={e=>setSelected(s=>e.target.checked?[...s,t.id]:s.filter(id=>id!==t.id))}/>{allTags.filter(a=>t.path.startsWith(a.path+'/')).map(a=>a.name+' / ')}{t.name}</label>)}</div></div>}
{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()}});
+36
View File
@@ -0,0 +1,36 @@
import type { GetServerSideProps } from "next";
import Head from "next/head";
import Link from "next/link";
import { useEffect,useState } from "react";
import { useRouter } from "next/router";
import { ArrowLeft,ChevronLeft,ChevronRight,Volume2,VolumeX,Download,Copy,Layers } from "lucide-react";
import { ArticleGallery } from "@/components/ArticleGallery";
import { Shell } from "@/components/Shell";
import { getPost } from "@/lib/library";
import { mediaUrl,sections,type Post } from "@/lib/model";
import { works } from "@/content/registry";
export default function PostDetail({post}:{post:Post}){
const [index,setIndex]=useState(0);const [copied,setCopied]=useState(false);const router=useRouter();
const media=post.assets.filter(a=>a.kind!=='text');const selected=media[index];const section=sections.find(s=>s.kind===post.kind)!;
useEffect(()=>{if(post.assets.some(a=>['pending','processing'].includes(a.processing_status))){const timer=setTimeout(()=>{void router.replace(router.asPath,undefined,{scroll:false});},3000);return ()=>clearTimeout(timer);}},[post,router]);
const Work=post.page_key?works[post.page_key]?.Component:undefined;
return <Shell><Head><title>{post.title} · PROMPT</title><link rel="alternate" type="text/markdown" href={`/api/wiki-post/${post.slug}`}/></Head><div className="detail-top"><Link href={`/${section.path}`}><ArrowLeft size={17}/>返回{section.name}</Link><span>{['image','video','audio'].includes(post.kind)?'File':'Main'}:{post.slug}</span></div>
<div className={`detail-layout ${Work?'coded-detail':''}`}><section className="detail-media">
{Work?<ArticleGallery key={post.slug} slug={post.slug}/>:selected?<><div className={`media-stage stage-${selected.kind}`}>
{selected.kind==='image'&&<img src={mediaUrl(selected.id)} alt={selected.filename||post.title}/>}
{selected.kind==='video'&&<video key={selected.id} controls playsInline preload="metadata" poster={selected.variants.includes('poster')?mediaUrl(selected.id,'poster'):undefined} src={mediaUrl(selected.id,selected.variants.includes('silent_video')?'silent_video':undefined)}/>}
{selected.kind==='audio'&&<div className="audio-stage"><div className="vinyl"><span/></div><h3>{selected.filename}</h3><audio key={selected.id} controls preload="metadata" src={mediaUrl(selected.id)}/></div>}
{media.length>1&&<><button className="gallery-prev icon-button" disabled={index===0} aria-label="上一个素材" onClick={()=>setIndex(i=>i-1)}><ChevronLeft/></button><button className="gallery-next icon-button" disabled={index===media.length-1} aria-label="下一个素材" onClick={()=>setIndex(i=>i+1)}><ChevronRight/></button><span className="gallery-position">{index+1} / {media.length}</span></>}
</div>
{selected.kind==='video'&&<div className="video-companion"><div><span className="pill">{selected.has_audio?<><Volume2 size={14}/>原视频有声音</>:<><VolumeX size={14}/>原视频无声音</>}</span><small>{selected.processing_status==='ready'?'画面已分离,可独立预览与复用':selected.processing_status==='failed'?'音画分离未完成,原文件仍可使用':'正在后台拆分画面与声音…'}</small></div>{selected.variants.includes('audio_track')&&<div className="bound-audio"><span><Volume2 size={16}/>这段视频的声音</span><audio controls preload="metadata" src={mediaUrl(selected.id,'audio_track')}/><small>音轨随视频保存,不属于独立声音素材。</small></div>}</div>}
{media.length>1&&<div className="thumbnail-strip">{media.map((a,i)=><button key={a.id} className={i===index?'selected':''} onClick={()=>setIndex(i)} aria-label={`查看第 ${i+1} 个素材`}>{a.kind==='image'?<img src={mediaUrl(a.id)} alt=""/>:a.variants.includes('poster')?<img src={mediaUrl(a.id,'poster')} alt=""/>:<span>{a.kind==='audio'?'声音':'视频'} {i+1}</span>}</button>)}</div>}</>:<div className="empty-state"><Layers/><p>这个素材包还没有可展示的内容。</p></div>}
</section><aside className="detail-info"><span className="eyebrow">A PIECE OF YOUR COLLECTION</span><h1>{post.title}</h1><div className="detail-date">{new Date(post.created_at).toLocaleString('zh-CN',{timeZone:'Asia/Shanghai'})}<span>· {Work?8:media.length} {Work?'张图':'份素材'}</span></div>
<div className="description">{post.assets.filter(a=>a.kind==='text').map(a=><p key={a.id}>{a.body}</p>)}</div>
<div className="tag-list">{post.tags.map(t=><Link key={t.id} href={`/${section.path}/${t.path}`}># {t.name}</Link>)}</div>
{selected&&<div className="asset-facts"><h3>素材信息</h3><dl><dt>原文件</dt><dd>{selected.filename}</dd>{selected.width&&<><dt>尺寸</dt><dd>{selected.width} × {selected.height}</dd></>}{selected.duration&&<><dt>时长</dt><dd>{selected.duration.toFixed(1)} 秒</dd></>}<dt>复用方式</dt><dd>引用同一素材,无需再次上传</dd></dl><button className="secondary-button" onClick={async()=>{await navigator.clipboard.writeText(selected.id);setCopied(true);setTimeout(()=>setCopied(false),2000);}}><Copy size={14}/>{copied?'已复制素材 ID':'复制素材 ID'}</button><a className="text-link" href={mediaUrl(selected.id)} download><Download size={14}/>打开原文件</a></div>}
</aside></div>
</Shell>;
}
export const getServerSideProps:GetServerSideProps=async({params})=>{
const post=await getPost(String(params?.slug||''));return post?{props:{post}}:{notFound:true};
};
@@ -0,0 +1,6 @@
import Head from "next/head";
import type {GetServerSideProps} from "next";
import {chapters} from "@/content/learning-skills/data";
import {LearningSeries} from "@/content/learning-skills/Series";
export default function Canvas({chapterKey,page,title}:{chapterKey:string;page:number;title:string}){return <><Head><title>{`${title} · 第 ${page+1} 张`}</title><meta name="robots" content="noindex"/></Head><LearningSeries key={`${chapterKey}-${page}`} chapterKey={chapterKey} pageNumber={page} standalone/></>}
export const getServerSideProps:GetServerSideProps=async({params})=>{const chapter=chapters.find(c=>c.slug===params?.slug);const n=String(params?.page);if(!chapter||!/^([1-8])$/.test(n))return {notFound:true};return {props:{chapterKey:chapter.key,page:Number(n)-1,title:chapter.title}}};
@@ -0,0 +1,10 @@
import type {GetServerSideProps} from 'next';
import {SkillDocs} from '@/components/SkillDocs';
import {GuidanceIndex} from '@/components/GuidanceIndex';
import {getGuidance} from '@/content/skills/guidance';
export default function GuidancePage({documentPath}:{documentPath:string|null}){return documentPath===null?<GuidanceIndex/>:<SkillDocs documentPath={documentPath}/>;}
export const getServerSideProps:GetServerSideProps=async({params})=>{
const parts=params?.path;if(parts===undefined)return {props:{documentPath:null}};
if(!Array.isArray(parts))return {notFound:true};
const documentPath=parts.join('/');return getGuidance(documentPath)?{props:{documentPath}}:{notFound:true};
};
+20
View File
@@ -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,11 @@
import type {GetServerSideProps} from 'next';
import {SkillDocs} from '@/components/SkillDocs';
import {getSkill} from '@/content/skills/catalog';
export default SkillDocs;
export const getServerSideProps:GetServerSideProps=async({params})=>{
const skillId=String(params?.skill);const parts=params?.doc;
if(parts!==undefined&&(!Array.isArray(parts)||parts.length!==1||parts[0]==='index'))return {notFound:true};
const documentId=Array.isArray(parts)?parts[0]:'index';
const skill=getSkill(skillId);
return skill?.documents.some(d=>d.id===documentId)?{props:{skillId,documentId}}:{notFound:true};
};
@@ -0,0 +1 @@
export {GuidanceIndex as default} from '@/components/GuidanceIndex';
@@ -0,0 +1 @@
export {SkillDocs as default} from '@/components/SkillDocs';
@@ -0,0 +1,5 @@
import type {GetServerSideProps} from 'next';
import {SkillDocs} from '@/components/SkillDocs';
import {skillDocuments} from '@/content/skills/catalog';
export default SkillDocs;
export const getServerSideProps:GetServerSideProps=async({params})=>{const id=String(params?.doc);return id!=='index'&&skillDocuments.some(d=>d.id===id)?{props:{documentId:id}}:{notFound:true}};
+10
View File
@@ -0,0 +1,10 @@
import PostDetail from '../p/[slug]';
import {getPost} from '@/lib/library';
import type {Post} from '@/lib/model';
import type {GetServerSideProps} from 'next';
import Head from 'next/head';
import Link from 'next/link';
import {Shell} from '@/components/Shell';
import {findWikiPage,type WikiPage} from '@/content/wiki';
export default function Wiki({page,post}:{page?:WikiPage;post?:Post}){if(post)return <PostDetail post={post}/>;if(!page)return null;const key=page.namespace+':'+page.slug;return <Shell><Head><title>{page.title} · PROMPT Wiki</title><link rel="alternate" type="text/markdown" href={'/api/wiki/'+encodeURIComponent(key)}/></Head><article className="wiki-article"><span className="wiki-label">{page.namespace} : {page.slug}</span><h1>{page.title}</h1><p className="wiki-summary">{page.summary}</p><div className="wiki-body">{page.namespace==='Category'?page.body.split('\n\n').map((line,i)=>{const m=line.match(/^\[(.*?)\]\((.*?)\)$/);return m?<p key={i}><Link href={m[2]}>{m[1]} →</Link></p>:null}):page.body.split('\n\n').map((text,i)=><p key={i}>{text}</p>)}</div><footer>{page.categories.map(c=><Link key={c} href={'/wiki/'+encodeURIComponent('Category:'+c)}># {c} </Link>)}<a href={'/api/wiki/'+encodeURIComponent(key)}>读取 Markdown ↗</a></footer></article></Shell>}
export const getServerSideProps:GetServerSideProps=async({params})=>{const page=findWikiPage(String(params?.key||''));if(page)return {props:{page}};const key=String(params?.key||'');const split=key.indexOf(':');const ns=key.slice(0,split);if(!['Main','File'].includes(ns))return {notFound:true};const post=await getPost(key.slice(split+1));return post&&(['image','video','audio'].includes(post.kind)?'File':'Main')===ns?{props:{post}}:{notFound:true};};
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+3
View File
@@ -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}}
+50
View File
@@ -0,0 +1,50 @@
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 {renderOne} from "./lib/snapshots";
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 asset_variants(asset_id,role,storage_key,mime_type,byte_size) VALUES($1,$2,$3,$4,$5) ON CONFLICT(asset_id,role) DO UPDATE SET storage_key=excluded.storage_key,mime_type=excluded.mime_type,byte_size=excluded.byte_size',[asset.id,v.role,v.key,v.mime,v.size]);
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 renderOne())await setTimeout(2000);}catch{console.error('Worker connection error; retrying');await setTimeout(5000);}}}
finally{clearInterval(timer);await db().end();}
}
main().catch(()=>process.exit(1));