Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Assist: skills, projects and memory — storage, built-in SKILL.md playbooks and API

Claude4715d112503c
diff --git a/skills/README.md b/skills/README.md
new file mode 100644
index 00000000..a4f5a9e8
--- /dev/null
+++ b/skills/README.md
@@ -0,0 +1,29 @@
+# Built-in Assist skills
+
+Each folder holds one skill: a `SKILL.md` with YAML frontmatter and Markdown instructions, the
+same format as Anthropic's Agent Skills and Higgsfield Supercomputer's skills. Assist lists them
+under **Assist → Skills → Built-in**, the agent loads one with its `load_skill` tool when a request
+matches, and typing `/name` at the start of a message loads it for that chat.
+
+```markdown
+---
+name: product-photoshoot # required: lowercase letters, numbers, hyphens (≤ 64)
+title: Product Photographer # shown in the app
+description: What it does … # required (≤ 1024 characters)
+when_to_use: When the agent should load it …
+icon: package # a lucide icon name the Skills page knows
+studio: /apps/app-packshot # the Fuobe page that does the job by hand
+tags: [product, ecommerce]
+offline: # hints for the offline planner (no LLM connected)
+ kind: image # image | video | audio | text
+ aspect: "1:1"
+ outputs: 4
+ style: "words appended to the prompt"
+---
+
+# Instructions the agent follows …
+```
+
+Files are read from disk at run time (`src/server/skills.ts`), so editing one here changes Assist
+on the next request. People add their own skills on the Skills page or by uploading a `.zip`,
+`.skill` or `SKILL.md` file; those live in the database, not here.
diff --git a/skills/ad-multiplier/SKILL.md b/skills/ad-multiplier/SKILL.md
new file mode 100644
index 00000000..7fe0ffbd
--- /dev/null
+++ b/skills/ad-multiplier/SKILL.md
@@ -0,0 +1,40 @@
+---
+name: ad-multiplier
+title: Ad Multiplier
+description: Turn one winning video ad into many variants — new hooks, new CTAs, new settings, new subjects or products — keeping what works in the original (timing, structure, audio), for testing on paid social.
+when_to_use: The user has an existing video ad (4–30 s) and wants variations, A/B versions, "new hooks for this ad", "the same ad with our other product" or "localised versions". Needs the reference video.
+icon: copy
+studio: /video-edit
+tags: [ads, variants, video, testing]
+offline:
+ kind: video
+ aspect: "9:16"
+---
+
+# Ad Multiplier
+
+## Pick what varies (one axis per batch, so results are testable)
+| Variant | How |
+|---|---|
+| **Prompt** (scene, style, subject) | video edit of the whole ad |
+| **Hook** (first 2–4 s) | a new opening clip from the first frame, joined before the rest |
+| **CTA** (last 2–4 s) | a new closing clip from the last frame, joined after |
+Prompt is exclusive with Hook/CTA; Hook and CTA can be combined.
+
+## Whole-ad variants (Prompt)
+Op `v2v` with the ad in `video` and the change described precisely ("same shots and timing; the
+creator is now in a sunny kitchen; the product is the green bottle from the image"), product or
+subject photos in `images`. Cloud `seedance-2-5` (video edit with references), `kling-o3`,
+`gemini-omni-flash`; open `oss-mixed-media` or `oss-wan22-vace-restyle`. Resolution 1080p by
+default (480p for quick tests). 3–5 variants per batch, each one `generate` job.
+
+## Hook / CTA variants
+1. Get the first (or last) frame: op `frame` on the ad, or ask the user for a screenshot.
+2. Make a 2–4 s clip from it (op `i2v`) with the new hook action or CTA moment, and the line in
+ quotes if spoken.
+3. Join: op `concat` with [new hook, original ad] or [original ad, new CTA]. Keep the original
+ audio for the body; the new clip carries its own (`generate_audio`).
+
+## Hand-off
+Name each variant by what changed ("Hook B — the spill") so the user can track them in their ad
+manager. Offer captions (`add_captions`) and 1:1 / 4:5 crops (video-repurposer).
diff --git a/skills/amazon-listing-images/SKILL.md b/skills/amazon-listing-images/SKILL.md
new file mode 100644
index 00000000..bcadf643
--- /dev/null
+++ b/skills/amazon-listing-images/SKILL.md
@@ -0,0 +1,47 @@
+---
+name: amazon-listing-images
+title: Amazon Listing Designer
+description: A compliant marketplace listing image set from the user's product photo — the main image on pure white, secondary images (lifestyle, features, dimensions, in-the-box) and A+ content modules.
+when_to_use: The user sells on Amazon, Etsy, eBay, Shopify or another marketplace and wants listing images, a "main image", "secondary images", "A+ content" or "product cards that sell".
+icon: shopping-bag
+studio: /apps/app-packshot
+tags: [amazon, marketplace, listing, ecommerce]
+offline:
+ kind: image
+ aspect: "1:1"
+ outputs: 2
+ style: "e-commerce main image: the product alone on a pure white background (RGB 255,255,255), filling about 85% of the frame, soft natural shadow, accurate colours, sharp, no text, no props, no logos other than the product's own"
+---
+
+# Amazon Listing Designer
+
+## Main image rules (suppressed listings come from breaking these)
+- Pure white background (RGB 255, 255, 255), the product fills ~85% of a square frame.
+- Only the product that's sold: no props, no added text, badges, watermarks or borders.
+- The real product, photographed look, accurate colour; no illustration.
+- At least 1600 px on the long side (upscale with op `upscale-image` if needed).
+
+## The set (7 images, one `generate` call)
+1. **Main** — rules above. Op `bg-remove` (`birefnet-cloud` / `oss-rmbg`) first if the photo has a
+ background, then op `edit` onto pure white with a soft contact shadow (`after` the cut-out).
+2. **Lifestyle** — the product in use by its target customer, 1:1.
+3. **Key benefits** — the product with 3 short callouts and simple icons ("Leak-proof", "BPA-free",
+ "Keeps cold 24 h"); quote each callout exactly.
+4. **Dimensions** — the product with clean dimension lines and the real measurements (ask for them
+ if unknown — never invent numbers).
+5. **In the box** — everything included, laid out flat-lay style, labelled.
+6. **Detail / material** — a macro of the texture or the mechanism.
+7. **Comparison or social proof** — "Ours vs. ordinary" or a rating card (only claims the user gave).
+
+## Models
+`nano-banana-pro` for every step (product fidelity + text), `ideogram-4-5` for text-heavy
+infographics. Open source: `oss-qwen-edit`; `oss-qwen-image` for text layouts. Product photo
+always in `images`.
+
+## A+ modules (if asked)
+Banner 970×600 (≈ 16:10) with brand story, a 4-up feature row (1:1 tiles), and a comparison chart
+image. Same palette and type across modules.
+
+## QC
+`check_generations` with `look: true` on every image: white background really white, no invented
+claims, text spelled right, product not altered. State any rule a result breaks and redo it.
diff --git a/skills/audio-generation/SKILL.md b/skills/audio-generation/SKILL.md
new file mode 100644
index 00000000..2243efd7
--- /dev/null
+++ b/skills/audio-generation/SKILL.md
@@ -0,0 +1,38 @@
+---
+name: audio-generation
+title: Audio Generation
+description: Guides audio jobs — voice-overs, dialogue between voices, music tracks and beds, sound effects, sound for a silent video, voice changing and voice cloning — picking the right model and writing prompts that each kind of model understands.
+when_to_use: The user wants any audio — "a voice-over", "a jingle", "background music", "a whoosh sound", "add sound to this video", "make this sound like me", "a conversation between two characters".
+icon: audio-lines
+studio: /audio
+tags: [audio, music, sfx, voice]
+offline:
+ kind: audio
+---
+
+# Audio Generation
+
+| Want | Op | Cloud | Open source |
+|---|---|---|---|
+| Speech | `tts` | `elevenlabs-v4`, `minimax-speech-2-8`, `inworld-tts` | `oss-chatterbox`, `oss-indextts2` |
+| Two+ speakers | `dialogue` | `elevenlabs-dialogue` | `oss-chatterbox-dialogue` |
+| Music | `music` | `sonilo-music`, `lyria-3-pro`, `minimax-music-2-5` (songs with lyrics), `elevenlabs-music` | `oss-ace-step` |
+| Sound effects | `sfx` | `mirelo-sfx-2`, `stable-audio-3-sfx`, `elevenlabs-sfx` | `oss-stable-audio-3`, `oss-mmaudio-sfx` |
+| Sound for a video | `v2a` | `mirelo-sfx-2-video`, `mmaudio-cloud` | `oss-mmaudio` |
+| Change a voice | `voice-change` | `elevenlabs-voice-changer` | `oss-chatterbox-vc` |
+| Split voice/music | `separate-audio` | `demucs` | `oss-voice-separate` |
+Check `search_models` with kind `audio` when the user names a model or a voice.
+
+## Prompting each kind
+- **Speech**: the exact words only; emotion via punctuation and short sentences. Pass `voice`
+ (a voice id from search_models) or `voice_audio` (a recording to clone).
+- **Music**: genre, tempo in BPM, mood, instruments, structure, length, and "instrumental" when no
+ vocals: "lo-fi hip hop, 80 bpm, warm Rhodes, vinyl crackle, mellow, 60 seconds, instrumental".
+ For songs, put lyrics in the prompt with [verse]/[chorus] tags on models that take lyrics.
+- **SFX**: one sound, physical words, duration: "heavy wooden door slowly creaking open, then a
+ dull thud, 3 seconds, dry room".
+- **Video to audio**: the video in `video`; describe what should be heard, not what's seen.
+
+## Delivery
+Durations: set `duration` when the model lists them. Offer 2 takes for music. To put audio on a
+video use op `mux` (and `background_audio` to keep the original sound under it).
diff --git a/skills/brand-asset-creation/SKILL.md b/skills/brand-asset-creation/SKILL.md
new file mode 100644
index 00000000..81a48976
--- /dev/null
+++ b/skills/brand-asset-creation/SKILL.md
@@ -0,0 +1,42 @@
+---
+name: brand-asset-creation
+title: Brand Asset Creation
+description: Logos and a brand kit from scratch or from the user's existing assets — logo concepts, palette, typography direction, a one-page brand board, and branded applications such as mockups, merchandise, packaging and signage.
+when_to_use: The user wants a new brand identity, a logo, a palette, a brand board or brandbook, or branded mockups (merch, packaging, signage, social templates) — starting empty or from an uploaded logo and materials.
+icon: palette
+studio: /image
+tags: [brand, logo, identity]
+offline:
+ kind: image
+ aspect: "1:1"
+ outputs: 4
+ style: "clean vector logo mark on a plain white background, flat colours, simple geometric shapes, strong silhouette, no mockup, no extra text"
+---
+
+# Brand Asset Creation
+
+## 1. Brief (one compact question if needed)
+Name, what the business does, audience, 3 personality words (e.g. calm, premium, playful),
+colours to use or avoid, and where the logo lives (app icon, signage, packaging). If the user has
+a logo already, start from it — never redraw an existing logo unless asked.
+
+## 2. Logo concepts
+- 4 directions in one `generate` call, one job each: a wordmark, a lettermark/monogram, a symbol
+ + wordmark lockup, and an emblem/badge. Square, plain white background, flat colours, the brand
+ name spelled exactly (quote it in the prompt).
+- Models: `recraft-4-1` (cloud; designed for logos and vector style), `ideogram-4-5` (exact
+ lettering), `nano-banana-pro`. Open: `oss-qwen-image` (renders text well).
+- Turn the chosen logo into a vector with op `vectorize` (cloud `recraft-vectorize`, `image2svg`).
+
+## 3. The kit
+After the user picks a logo:
+- **Palette**: 1 primary, 1 secondary, 2 neutrals, 1 accent — give HEX codes and where each is used.
+- **Typography**: a heading and a body typeface direction (free Google Fonts names when possible).
+- **Brand board**: one 16:9 image with the logo, palette swatches with HEX labels, type samples and
+ 2 example applications (op `edit` with the logo in `images`).
+- Offer to save the palette and name with `remember` (Convention) so later jobs stay on brand.
+
+## 4. Applications
+Mockups with the logo in `images` (op `edit`): business card, tote bag, storefront sign, app icon,
+packaging, Instagram post template. "Place the logo from the image exactly as it is, undistorted."
+Check every result with `look: true` for misspelled names or warped logos.
diff --git a/skills/character-sheet/SKILL.md b/skills/character-sheet/SKILL.md
new file mode 100644
index 00000000..28bc0d50
--- /dev/null
+++ b/skills/character-sheet/SKILL.md
@@ -0,0 +1,44 @@
+---
+name: character-sheet
+title: Character Sheet
+description: Cast a character, lock the wardrobe, and get a verified multi-view reference sheet (front, back, side, portrait) to reuse for recurring characters across images and videos.
+when_to_use: The user needs a consistent character for a series, a film, an ad campaign or a mascot; asks for a "character sheet", "turnaround", "model sheet" or "reference sheet"; or a story needs the same person in many shots.
+icon: user-square
+studio: /elements
+tags: [character, consistency, reference]
+offline:
+ kind: image
+ aspect: "16:9"
+ outputs: 2
+ style: "character reference sheet on a plain light-grey background: full-body front view, back view, side view and a head-and-shoulders portrait, identical face, hair and outfit in every view, even studio lighting, clean labels"
+---
+
+# Character Sheet
+
+## 1. Casting
+- From a photo (the user's or an `@element`): the sheet must keep that face — op `edit` with the
+ photo in `images`.
+- From a brief: write the character in one paragraph — age, build, face (shape, eyes, skin, hair),
+ wardrobe (each garment with colour and material), one signature detail (a scar, a red scarf).
+ If the user wants to choose the face, make 3 portrait candidates first (op `t2i`, `outputs: 3`)
+ and let them pick.
+
+## 2. The sheet
+One image, 16:9, plain light-grey background, four views side by side: full-body front, full-body
+back, full-body side profile, and a head-and-shoulders portrait. Same lighting in every view.
+- Cloud: `nano-banana-pro` (best consistency across views) or `seedream-5-pro`; Higgsfield's
+ `ai-influencer` for photoreal influencers. Open source: `oss-qwen-edit` from a portrait, or
+ `oss-qwen-image` from text.
+- Prompt: "Character reference sheet of <description>. Four views on one sheet: front, back,
+ side, close portrait. Identical face, hairstyle and outfit in every view. Neutral pose, arms
+ slightly away from the body. Plain light-grey background, even studio light, no text."
+
+## 3. Verify
+`check_generations` with `look: true`: the face, hair, outfit colours and the signature detail
+must match in all four views, and nothing may be cut off. Redo with a stronger "identical in every
+view" instruction if not.
+
+## 4. Reuse
+Tell the user to save it as a character (the "Save as character" action on the result, or the
+Elements page) so it gets an `@handle` — every later prompt can then write `@handle`. Offer to
+`remember` the character's description too.
diff --git a/skills/faceless-video/SKILL.md b/skills/faceless-video/SKILL.md
new file mode 100644
index 00000000..2abdee28
--- /dev/null
+++ b/skills/faceless-video/SKILL.md
@@ -0,0 +1,44 @@
+---
+name: faceless-video
+title: Faceless Studio
+description: Finished narrated, illustrated videos — explainers, channel episodes, history and documentary pieces, stories, narrated picture stories and kids songs — with a narrator over stylised scenes, one-off or recurring.
+when_to_use: The user asks for a faceless video, a YouTube/TikTok episode with narration over illustrations, an explainer, a documentary-style piece, a narrated story or a kids video. Not for script-only requests (use youtube-script) or a photo presenter on screen (use narration).
+icon: book-open
+studio: /storyboard
+tags: [faceless, explainer, narration, youtube]
+offline:
+ kind: video
+ aspect: "9:16"
+ style: "consistent illustrated style, clean shapes, soft cinematic lighting, gentle camera motion"
+---
+
+# Faceless Studio
+
+A faceless video = a script read by a narrator over a sequence of scenes in one visual style.
+
+## 1. Brief (ask at most one question)
+Topic, length (default 60 s), format (9:16 for Shorts/TikTok/Reels, 16:9 for YouTube), style
+(e.g. "flat 2D illustration", "watercolour storybook", "3D clay", "dark documentary photo
+collage", "anime"), narrator voice (calm, energetic, warm), audience (adults / kids).
+
+## 2. Script and scenes
+Write the narration first (~150 words per minute), then split it into scenes of roughly 8–10
+seconds: each scene = its narration lines + one visual description in the chosen style. Keep a
+recurring character or mascot identical across scenes (describe it the same way every time, or
+use an `@element`). Show the scene list before generating.
+
+## 3. Produce
+- Prefer the **`faceless_episode` tool**: pass the scenes, style, aspect and voice; it plans the
+ stills, the animated clips, the narration and the final join in one approval.
+- Without it, build the chain with `generate`: one still per scene (op `t2i`), one clip per
+ still (op `i2v`, `after` the still, a slow push-in or pan), the narration (op `tts`), then join
+ the clips (op `concat`) and mux the narration over them (op `mux`).
+- Models: stills cloud `nano-banana-pro` / `seedream-5-pro`, open `oss-z-image-turbo`; clips
+ cloud `gemini-omni-flash` or `seedance-2-5` (5 s), open `oss-wan22-14b-fast`; voice
+ `elevenlabs-v4` / `oss-chatterbox`.
+- "Frame by frame" (cheaper): skip the clips and ask for a slow Ken Burns move on each still.
+
+## 4. Finish
+Offer captions (`add_captions`), a music bed (op `music`, low under the voice), and a thumbnail
+(load thumbnail-generation). For a recurring series, suggest saving the style and voice with
+`remember` so the next episode matches.
diff --git a/skills/image-repurposer/SKILL.md b/skills/image-repurposer/SKILL.md
new file mode 100644
index 00000000..23536a42
--- /dev/null
+++ b/skills/image-repurposer/SKILL.md
@@ -0,0 +1,52 @@
+---
+name: image-repurposer
+title: Image Repurposer
+description: One creative in, a ready pack for every platform out — resize or expand an existing image to new aspect ratios, build platform packs, swap text or offers inside the image, localise in-image text, and make subject-swap variants of a master template.
+when_to_use: Fires only when the user supplies an existing image and wants it adapted ("make this work for Stories", "a version for every platform", "translate the text in this ad", "same ad with our new product"). Not for new images from scratch.
+icon: layout-grid
+studio: /edit
+tags: [resize, platforms, localisation]
+offline:
+ kind: image
+ outputs: 1
+ style: "keep the original design, subject, typography and colours exactly; extend the background naturally to fill the new frame"
+---
+
+# Image Repurposer
+
+The original is the source of truth: keep the subject, layout logic, brand colours and type style.
+Only the frame, the language or the swapped element changes.
+
+## Platform sizes (aspect ratios)
+| Platform | Ratios |
+|---|---|
+| Instagram feed | 4:5, 1:1 |
+| Instagram / Facebook Stories, Reels, TikTok, YouTube Shorts | 9:16 |
+| YouTube thumbnail, X post, LinkedIn post | 16:9 |
+| Pinterest | 2:3 |
+| Facebook / LinkedIn feed | 1:1, 4:5 |
+For "a pack for every platform" make 9:16, 4:5, 1:1 and 16:9 (four jobs in one `generate` call).
+
+## Resizing without cropping the subject
+- Use op `edit` with the image in `images` and the new `aspect_ratio`, prompt: "Extend this exact
+ image to <ratio>: keep everything that's already there unchanged and in place; continue the
+ background naturally; move nothing; keep all text exactly as written." Cloud `nano-banana-pro`
+ (takes many ratios), open `oss-qwen-edit`; for pure canvas extension on open source,
+ `oss-flux-fill` with op `outpaint`.
+- When going much taller (16:9 → 9:16), the headline may need to move: say "re-arrange the text
+ block to sit in the top third, same font and colours" instead of "move nothing".
+
+## Text swaps and localisation
+- Quote the old and the new text exactly: "Replace the headline “Summer Sale” with “Soldes d'été”,
+ same font, size, colour and position; change nothing else". One job per language.
+- Translate the copy yourself (or with a `translate` job) before editing; keep brand names untranslated.
+- Text-heavy creatives render best on `ideogram-4-5` (op `edit`) or `nano-banana-pro`.
+
+## Subject swaps (master template)
+Pass the template first and the new product or person second in `images`: "Replace the product in
+the first image with the product from the second image, matching the lighting and perspective;
+keep the layout, text and background."
+
+## Check
+`check_generations` with `look: true`; reject takes where text changed, got misspelled or the
+subject was cropped. Name each file's platform in your reply.
diff --git a/skills/katana/SKILL.md b/skills/katana/SKILL.md
new file mode 100644
index 00000000..13175fe5
--- /dev/null
+++ b/skills/katana/SKILL.md
@@ -0,0 +1,41 @@
+---
+name: katana
+title: Katana
+description: Remix a reference edit for your subject — recreate a short video's cuts, motion and soundtrack with the user's own person or product — or edit the user's own footage into a finished video.
+when_to_use: The user supplies a reference video and photos of a subject and says "make this edit with me", "do this trend with my product", or invokes /katana with a reference and subject (no further brief needed). Also for "edit my footage like this".
+icon: scissors
+studio: /video-edit
+tags: [remix, trend, edit, video]
+offline:
+ kind: video
+ aspect: "9:16"
+---
+
+# Katana
+
+Katana keeps the reference's timing, camera motion and soundtrack, and puts the user's subject in it.
+
+## Inputs
+- A reference video (1–30 s): an attachment, or an earlier result via `list_recent`.
+- 1–5 photos of the subject (person or product), or a saved `@element`.
+- With `/katana` plus a reference and photos, no text brief is needed: make the remix.
+
+## With the katana tool (preferred)
+If a `katana` tool is listed, call it with the reference and the photos — it detects the cuts,
+swaps the subject into each segment's first frame, regenerates every segment with the reference's
+motion, joins them at the original cut times and keeps the original soundtrack. One approval.
+
+## Without it (build the chain)
+1. Ask for or estimate the cut points (or treat a short reference as one segment).
+2. Per segment: op `trim` (`start_time`, `end_time`) → the segment's first frame with the subject
+ swapped in (op `edit` with the frame and the subject photo; cloud `nano-banana-pro`, open
+ `oss-qwen-edit`) → regenerate the segment following the original motion (op `motion-transfer`
+ or `v2v`: cloud `kling-o3` video edit or `kling-motion-control`, open `oss-wan22-animate`).
+3. Join the segments in order (op `concat`) and put the reference's audio back (op `mux`).
+
+## Own footage
+Edit the user's clip by the brief: restyle with the `restyle_footage` tool, trim and join with
+video-montage steps, captions with `add_captions`.
+
+Say up front that each segment is regenerated, so faces and products can drift slightly between
+cuts; offer to redo a weak segment.
diff --git a/skills/localization/SKILL.md b/skills/localization/SKILL.md
new file mode 100644
index 00000000..168ef8f9
--- /dev/null
+++ b/skills/localization/SKILL.md
@@ -0,0 +1,39 @@
+---
+name: localization
+title: Translate & Dub
+description: Localise videos, voice-overs, captions and scripts into other languages — dub a video in the speaker's own voice with lip sync, translate subtitles with their timing, or translate ad copy and in-image text.
+when_to_use: The user wants a video dubbed, "the same video in Spanish", translated subtitles, a voice-over in another language, or copy translated for another market.
+icon: languages
+studio: /audio
+tags: [dub, translate, localization, captions]
+offline:
+ kind: text
+---
+
+# Translate & Dub
+
+## Dub a video (speech in, speech out)
+Prefer the **`dub_video` tool**: pass the video and the target language(s). It separates the
+voice from the background, transcribes, translates with timing, re-voices in the speaker's own
+voice, optionally lip-syncs, and mixes the new voice over the original background.
+Without it, chain `generate` steps with `after`:
+1. op `separate-audio` (`demucs` / `oss-voice-separate`) → voice and background stems
+2. op `transcribe` on the voice (`scribe-v2` / `oss-qwen3-asr`)
+3. op `translate` (`text-llm` / `oss-text-llm`) with `target_language` — cues keep their timing
+4. op `tts` cloning the voice stem (`chatterbox-cloud` / `oss-chatterbox`)
+5. op `lipsync` (`sync-lipsync-3` / `oss-infinitetalk-v2v`) — skip for voice-over-only footage
+6. op `mux` with the new voice and `background_audio` = the background stem (open source).
+Cloud one-shot alternative: `heygen-translate` (op `dub`).
+
+## Subtitles only
+op `transcribe` → op `translate` (cues keep their timing) → the `add_captions` tool, or deliver the
+.srt (text output) for the user's own editor.
+
+## Copy and in-image text
+Translate yourself (or op `translate`) — adapt idioms, keep brand names, units and prices local
+("$" → "€" only if the user says so). For text inside images, load image-repurposer.
+
+## Quality
+Name the languages up front; one job per language. Flag lines that ran long after translation
+(German and French run ~20% longer) — the dub may speed up there. Offer a native-speaker review
+note when the content is legal or medical.
diff --git a/skills/marketing-studio-cards/SKILL.md b/skills/marketing-studio-cards/SKILL.md
new file mode 100644
index 00000000..049b263f
--- /dev/null
+++ b/skills/marketing-studio-cards/SKILL.md
@@ -0,0 +1,45 @@
+---
+name: marketing-studio-cards
+title: Marketing Studio Cards
+description: Posters, Meta and Instagram ad creatives and marketplace listing cards built around the user's own product photo, with a designed layout, a headline, short copy and a call to action.
+when_to_use: The user wants a designed advertising still around their product — "make a poster", "an Instagram ad", "a sale banner", "a promo card", "an ad with our tagline". The product photo is required. For plain product photos use product-photoshoot; for many ads at once use the create_ads tool.
+icon: megaphone
+studio: /apps/app-ad-creative
+tags: [ads, poster, marketing, social]
+offline:
+ kind: image
+ aspect: "4:5"
+ outputs: 2
+ style: "modern advertising layout around the product photo, bold headline at the top, short supporting line, call-to-action button at the bottom, brand colours, generous whitespace, crisp typography"
+---
+
+# Marketing Studio Cards
+
+## 1. Copy first
+From the brief (and memory: brand colours, tone), write:
+- a headline of 2–6 words (benefit or offer: "Sleep like it's Sunday", "30% off this week"),
+- one supporting line (≤ 12 words),
+- a CTA of 1–3 words ("Shop now", "Try it free").
+Keep brand and product names exact. If a project source has a brand guide, read it with `read_source`.
+
+## 2. Layout families (pick one per card, vary across a set)
+| Layout | Good for |
+|---|---|
+| Hero centre — product big in the middle, headline above, CTA below | launches |
+| Split — product one side, copy the other | feature callouts |
+| Offer burst — big % or price badge | sales |
+| Lifestyle + overlay — product in scene, copy on a band | social feed |
+| Listing card — white background, 3 benefit icons with labels | marketplaces |
+| Testimonial — a short quote with stars | trust |
+
+## 3. Generate
+- One job per card (op `edit` with the product photo in `images`, so the product stays exact).
+ Quote every text element exactly and say "no other text".
+- Models: `nano-banana-pro` (best product fidelity + text), `ideogram-4-5` (best typography),
+ Higgsfield's `marketing-studio-image` when connected. Open source: `oss-qwen-edit`.
+- Ratios: 4:5 feed, 9:16 Stories, 1:1 marketplaces, 16:9 banners. For "the full set", 4:5 + 9:16 + 1:1.
+
+## 4. QC
+`check_generations` with `look: true`: spelling, the CTA present, the product undistorted, text
+not over the product. Redo failures. Offer more variants with the `create_ads` tool, or
+animated versions (op `i2v`, subtle motion, 5 s).
diff --git a/skills/narration/SKILL.md b/skills/narration/SKILL.md
new file mode 100644
index 00000000..2691b113
--- /dev/null
+++ b/skills/narration/SKILL.md
@@ -0,0 +1,39 @@
+---
+name: narration
+title: Narration
+description: Speech narration in two modes, picked by the input — text plus a chosen voice becomes finished narration takes with one consistent voice; a video plus a photo becomes the same video with that person as its on-screen narrator.
+when_to_use: The user wants a voice-over, a narrated read of a script, audiobook-style reading, or a presenter added to a video. The deliverable is speech — not music, sound effects or singing (use audio-generation for those).
+icon: mic
+studio: /audio
+tags: [voice, tts, narration]
+offline:
+ kind: audio
+---
+
+# Narration
+
+## Mode A — text + voice → narration takes
+1. **Script.** Use the user's text verbatim. If they gave a topic instead, write the script first
+ (`generate` with op `write`) and show it. Fix only obvious typos. Spell out numbers, symbols and
+ abbreviations the way they should be spoken ("$4.99" → "four ninety-nine").
+2. **Length.** If the user needs a fixed length (a 30-second spot), estimate ~150 words per minute
+ at a normal pace and trim or extend the script to fit before generating. Say the estimate.
+3. **Voice.** Ask which voice only if the user cares (gender, age, accent, energy). Otherwise:
+ cloud `elevenlabs-v4` (natural, many voices — pass `voice`), `minimax-speech-2-8` for
+ emotion/speed control; open `oss-chatterbox` or `oss-indextts2`. To clone the user's voice,
+ pass their recording as `voice_audio` (models that list voiceClone).
+4. **Blocks.** For long scripts (>1 minute), split at paragraph breaks into blocks of ~20–40 s
+ and make one `tts` job per block in a single `generate` call — same model, same voice, same
+ settings — so a bad take can be redone alone. For one continuous read, a single job.
+5. Offer 2 takes of the opening line when the read's tone matters.
+
+## Mode B — video + photo → on-screen narrator
+1. Voice the narration as in Mode A (or use the video's own speech: op `transcribe`, then `tts`).
+2. Make the presenter talk: op `avatar` with the photo in `images` and the narration as `audio`
+ (cloud `kling-avatar-2` / `omnihuman-2`, open `oss-infinitetalk`).
+3. Tell the user the presenter clip is ready to place over or beside their video in an editor;
+ Fuobe joins clips end to end (op `concat`) but doesn't composite picture-in-picture.
+
+## Checks
+Listen-for list in the follow-up: pronunciation of names, pacing at commas, the last word not
+cut off. Offer a slower or more energetic take.
diff --git a/skills/product-photoshoot/SKILL.md b/skills/product-photoshoot/SKILL.md
new file mode 100644
index 00000000..cf44c68f
--- /dev/null
+++ b/skills/product-photoshoot/SKILL.md
@@ -0,0 +1,59 @@
+---
+name: product-photoshoot
+title: Product Photographer
+description: Studio product photos without a studio — packshots on clean backgrounds, lifestyle scenes, banners, model try-ons, CGI and restyles, from the user's own product photo.
+when_to_use: The user wants product photos, a packshot, e-commerce or catalog images, lifestyle shots of a product, or "make my product look premium". Not for ads with headlines (use marketing-studio-cards) or marketplace listing sets (use amazon-listing-images).
+icon: package
+studio: /apps/app-packshot
+tags: [product, ecommerce, photo]
+offline:
+ kind: image
+ aspect: "1:1"
+ outputs: 4
+ style: "professional studio product photograph, the product as the hero, seamless backdrop, soft key light with a gentle rim light, crisp reflections, accurate colours and label, sharp focus, 100mm macro lens"
+---
+
+# Product Photographer
+
+Turn one product photo into a set of studio-quality images. The product must stay exactly the
+same — shape, colours, label text, logo — only the scene changes.
+
+## 1. Get the product
+- Use the product photo the user attached. If there's none, check `list_elements` for a saved
+ product (write its `@handle` in prompts) or `list_recent` for an earlier upload. If there is
+ still nothing, ask for one clear photo (front-facing, even light, no hands).
+- If the photo has a busy background and the user wants pure packshots, start with a cut-out:
+ a `generate` job with op `bg-remove` (cloud `birefnet-cloud`, open `oss-rmbg`), then chain the
+ scene edits on it with `after`.
+
+## 2. Plan the set
+Unless the user says otherwise, make 4 shots in one `generate` call (one job per shot, so each
+gets its own prompt):
+1. **Hero packshot** — seamless white or light-grey sweep, soft shadow under the product, 1:1.
+2. **Brand-colour backdrop** — a solid or gradient backdrop in a colour that suits the product,
+ hard light and a defined shadow, 4:5.
+3. **Lifestyle** — the product in use in a believable setting (kitchen counter, bathroom shelf,
+ desk, outdoors), shallow depth of field, 4:5.
+4. **Detail / macro** — a close-up of the texture, cap, nozzle or label, 1:1.
+Ask one short question only if the use is unclear (web shop vs. social vs. print).
+
+## 3. Models
+- Cloud: `nano-banana-pro` (best at keeping labels intact), `seedream-5-pro` for photoreal
+ lifestyle scenes, `bria-product-shot` when the user wants a scene from a reference image.
+- Open source: `oss-qwen-edit` (Qwen-Image-Edit 2511).
+- Always pass the product photo in `images` (op `edit`). Run `search_models` once if the user
+ names another model or asks for the cheapest option.
+
+## 4. Prompting
+Write each prompt as: what stays ("Keep the product exactly as in the photo: same shape,
+colours, label and logo, undistorted") → the set (surface, backdrop, props, colour palette) →
+the light (key, fill, rim, softness, direction) → the camera (lens, angle, depth of field) →
+the finish ("commercial product photography, high detail, no extra text").
+Never invent text on the product. Don't add hands or people unless asked.
+
+## 5. Check and offer next steps
+After the jobs finish, `check_generations` with `look: true`. If a label is garbled or the
+shape drifted, redo that shot with a stronger "keep the label exactly" instruction. Offer:
+upscale the favourite (op `upscale-image`), more angles, a 5-second turntable video
+(`generate` with op `i2v`, a slow orbit around the product), or ad versions with
+marketing-studio-cards.
diff --git a/skills/seedance-cinematic-prompter/SKILL.md b/skills/seedance-cinematic-prompter/SKILL.md
new file mode 100644
index 00000000..a6f0f6ca
--- /dev/null
+++ b/skills/seedance-cinematic-prompter/SKILL.md
@@ -0,0 +1,43 @@
+---
+name: seedance-cinematic-prompter
+title: Seedance Cinematic Prompter
+description: Decide the scene, then write a production-safe Seedance 2.5 prompt — subject, action in time order, camera, lens, light, mood, sound — and pick duration, resolution and references so the clip comes out right the first time.
+when_to_use: The user wants a single cinematic video clip on Seedance (or names Seedance), asks for help writing a video prompt, or a previous Seedance take came out wrong.
+icon: camera
+studio: /video
+tags: [seedance, video, prompting]
+offline:
+ kind: video
+ aspect: "16:9"
+ style: "cinematic, 35mm anamorphic, shallow depth of field, motivated practical lighting, subtle film grain, smooth deliberate camera move"
+---
+
+# Seedance Cinematic Prompter (CINEDANCE)
+
+Seedance 2.5 (`seedance-2-5`) follows time-ordered direction well, renders native audio, takes up
+to 10 reference images/videos (op `ref2v`), and runs 4–12 s (30 s in some tiers).
+
+## CINEDANCE — the order of a good prompt
+1. **C**haracter — who, wearing what, one distinctive detail (or `@handle`).
+2. **I**ntention — what they want in this moment.
+3. **N**arrative action — what happens, in order: "first…, then…, finally…". One clear action per 3–4 s.
+4. **E**nvironment — place, time of day, weather, props.
+5. **D**irection — camera move and framing over time: "starts wide, slow dolly-in to a close-up".
+6. **A**tmosphere — light (key direction, colour temperature, practicals), palette, mood.
+7. **N**oise — the sound: ambience, effects, a short line of dialogue in quotes.
+8. **C**raft — lens and film look: "40mm anamorphic, shallow depth of field, light grain".
+9. **E**xclusions — via `negative_prompt`: "no text, no watermark, no extra people".
+
+## Settings
+- Duration: 5 s for one action, 8–10 s for two beats; don't pack 3+ actions into 5 s.
+- `aspect_ratio` 16:9 cinematic, 9:16 social, 21:9 for scope.
+- Start frame: if the user has a still, op `i2v` with it in `images` — the most reliable way to
+ lock the look. With several references, op `ref2v`.
+- `generate_audio: true` when sound matters.
+- For multiple angles of one scene in one clip, `shots` (2–6).
+
+## Production safety
+Avoid real public figures, brand logos you don't own, and graphic violence — rephrase to the
+intent. Name the most likely failure (fast hands, crowd faces, text on signs) and simplify it.
+
+Show the final prompt in a short block, then call `generate`.
diff --git a/skills/short-film/SKILL.md b/skills/short-film/SKILL.md
new file mode 100644
index 00000000..5baef361
--- /dev/null
+++ b/skills/short-film/SKILL.md
@@ -0,0 +1,51 @@
+---
+name: short-film
+title: Cinematic Director
+description: A photoreal multi-clip short film or scripted scene driven by story, character, dialogue and mood — consistent characters across shots, a shot list, then the clips joined into one film.
+when_to_use: The result is 2+ clips, several scenes, or a single video over 15 seconds with recurring characters — even when the user already wrote a shot list, and for "stitch them into one" briefs. Not for social creator formats (ugc-video) or motion graphics (visual-studio).
+icon: clapperboard
+studio: /cinema
+tags: [film, story, video, cinematic]
+offline:
+ kind: video
+ aspect: "16:9"
+ style: "cinematic, anamorphic 35mm film look, motivated lighting, shallow depth of field, film grain"
+---
+
+# Cinematic Director
+
+Think like a director: story first, then coverage, then the look. Keep characters and wardrobe
+identical in every shot.
+
+## 1. Development (in the chat, before any generation)
+- Logline in one sentence. Ask at most one question if the genre or ending is unclear.
+- A shot list of 3–8 shots: for each, the shot size (wide / medium / close-up / insert), the
+ action, the camera move (push-in, dolly, crane, handheld, static), and any spoken line.
+- The look: era, palette (2–3 colours), light (golden hour, neon night, overcast), lens (anamorphic
+ 40mm, 85mm portrait), grain.
+Show the shot list compactly, then go — the approval card is the user's checkpoint.
+
+## 2. Consistency
+- Characters: if the user has saved characters, use their `@handle` (`list_elements`). Otherwise
+ make a character sheet first (load the character-sheet skill) or one hero still per character.
+- Make the first frame of every shot as a still that reuses the character still as a reference
+ (`images`), then animate it. `create_storyboard` does exactly this for up to 8 frames — use it
+ for the stills, then animate each frame.
+
+## 3. Shots
+- Cloud: `seedance-2-5` (default; 5–12 s, native audio, multi-shot), `kling-3` for strong motion,
+ `veo-3-1` for dialogue with lip sync, `cinema-studio-4` for Higgsfield's camera controls.
+- Open source: `oss-wan22-14b-fast` (i2v), `oss-wan22-14b` for quality.
+- One `generate` job per shot with op `i2v`, `after` pointing at that shot's still. Write the
+ prompt as action in time order, then camera, then light: "She turns from the window as the
+ rain starts; slow push-in from medium to close-up; cold blue moonlight, warm practical lamp".
+- For one continuous clip with cuts, a model with multi-shot can take `shots` instead.
+
+## 4. Assembly and sound
+Join the clips in order (op `concat`: cloud `join-clips`, open `oss-join-clips`, `after` each
+clip). Add a score (op `music`: `sonilo-music` / `oss-ace-step`) and mux it (op `mux`). Offer a
+dialogue pass with lipsync for lines that need it.
+
+## 5. Review
+`check_generations` with `look: true` on the stills before animating when the brief is
+demanding. Name the weakest shot and offer to redo it.
diff --git a/skills/thumbnail-generation/SKILL.md b/skills/thumbnail-generation/SKILL.md
new file mode 100644
index 00000000..948b4fe6
--- /dev/null
+++ b/skills/thumbnail-generation/SKILL.md
@@ -0,0 +1,46 @@
+---
+name: thumbnail-generation
+title: Thumbnail Generator
+description: Cinematic, click-worthy YouTube and Instagram thumbnails and video covers, from concept to a final high-resolution frame with short bold text.
+when_to_use: The user asks for a thumbnail, a video cover, a "video preview" image, a YouTube cover or a Reels cover.
+icon: youtube
+studio: /image
+tags: [youtube, thumbnail, cover]
+offline:
+ kind: image
+ aspect: "16:9"
+ outputs: 3
+ style: "high-contrast cinematic YouTube thumbnail, one clear focal subject, expressive face, dramatic rim light, bold readable headline text, uncluttered background, vivid colour grading"
+---
+
+# Thumbnail Generator
+
+A thumbnail has one job: make someone stop scrolling. One subject, one emotion, one idea, at
+most 4 words of text.
+
+## 1. Concept (decide before generating)
+- Ask for the video's title or topic if it isn't in the message. If the user has a photo of
+ themselves (attachment or `@character`), the face goes in the thumbnail.
+- Write 3 distinct concepts, one line each: the subject, the emotion, the visual hook (contrast,
+ before/after, a huge object, a question), and the 2–4 word text. Pick all three to render unless
+ the user wants one.
+
+## 2. Composition rules
+- 16:9 for YouTube (1280×720 minimum; ask the model for 2K when listed), 9:16 for Reels/Shorts
+ covers, 4:5 for Instagram feed.
+- Subject on the left or right third, face large (40–60% of the height), eyes toward the text or
+ the hook. Text on the opposite side, big, 1–2 lines, high contrast with a stroke or shadow.
+- Strong separation: rim light, a darker or blurred background, saturated accent colour.
+- Nothing important in the bottom-right corner (YouTube puts the duration there).
+
+## 3. Models
+- Text in the image: cloud `ideogram-4-5` or `nano-banana-pro` (both render short headlines
+ well), `gpt-image-2-5` for complex scenes. Open: `oss-qwen-image` (best open text rendering).
+- With the user's face: op `edit` with their photo in `images` ("use the person from the photo,
+ same face") on `nano-banana-pro` / `oss-qwen-edit`.
+- Put the exact headline in quotes in the prompt and say "the only text in the image".
+
+## 4. Finish
+`check_generations` with `look: true`: reject any take with misspelled text or a cut-off face and
+redo it. Offer an upscale (op `upscale-image`) of the winner and an A/B pair with a different
+headline.
diff --git a/skills/ugc-video/SKILL.md b/skills/ugc-video/SKILL.md
new file mode 100644
index 00000000..7805979c
--- /dev/null
+++ b/skills/ugc-video/SKILL.md
@@ -0,0 +1,55 @@
+---
+name: ugc-video
+title: UGC Studio
+description: Finished UGC-style videos in six creator formats — creator review, product-only voiceover, unboxing, wearable try-on, step-by-step tutorial and website tour — from a product (and optionally a creator photo).
+when_to_use: The user asks for a UGC video, a creator-style review, a TikTok/Reels ad with a person talking about the product, an unboxing, a try-on or a tutorial video. Not for scripts alone (use youtube-script) or cinematic commercials (use short-film).
+icon: smartphone
+studio: /lipsync
+tags: [ugc, ads, video, social]
+offline:
+ kind: video
+ aspect: "9:16"
+ style: "handheld smartphone footage, natural window light, authentic creator style, vertical framing"
+---
+
+# UGC Studio
+
+UGC works because it looks real: a phone camera, natural light, a person talking to camera,
+quick cuts. Pick **one** format from the brief:
+
+| Format | When | Shape |
+|---|---|---|
+| Creator review | "review", "testimonial", "talking about" | creator holds the product, talks to camera |
+| Product-only voiceover | no person wanted | close product shots + voice-over |
+| Unboxing | "unboxing", new arrival | hands open the box, reveal |
+| Try-on | clothing, shoes, jewellery, glasses | creator wears it, mirror or full body |
+| Tutorial | "how to", steps | 3–5 short steps with the product |
+| Website tour | an app or a site | screen recording style + creator reaction |
+
+A product link alone doesn't mean "website tour".
+
+## 1. Inputs
+Product photo (attachment, `@element` or `list_recent`), and a creator photo if the user has one.
+Without a creator photo, generate one: a `generate` job with op `t2i` ("a relatable 25-year-old
+creator, natural makeup, casual hoodie, bedroom with soft window light, phone selfie framing").
+Save time: if the user has a saved character, use its `@handle`.
+
+## 2. Script (always write it first)
+Write a 15–30 second script in the chat or with a `write` job (`text-llm` / `oss-text-llm`):
+a hook in the first 2 seconds ("I didn't expect this to work…"), 2–3 concrete benefits, a call to
+action. Keep sentences short and spoken. Show the script and the plan in one message.
+
+## 3. Production chain (one `generate` call with `after`)
+1. **Key frame** — op `edit` with the creator photo and the product photo in `images`:
+ "the creator holds the product at chest height, smartphone selfie framing, 9:16".
+ Cloud `nano-banana-pro`, open `oss-qwen-edit`.
+2. **Voice** — op `tts`: the script. Cloud `elevenlabs-v4` (pick a natural voice), open `oss-chatterbox`.
+3. **Talking video** — op `avatar` with the key frame (`after` step 1) and the voice as `audio`
+ (or chain the voice with a second `after`, see generate's description). Cloud `kling-avatar-2`
+ or `omnihuman-2`, open `oss-infinitetalk`.
+For product-only voiceover: replace step 3 with 2–3 `i2v` product clips (5 s each, handheld
+push-ins) and join them, then put the voice on with op `mux`.
+
+## 4. Finish
+Offer captions (the `add_captions` tool), a second hook variant, or a 1:1 cut. Check results with
+`check_generations` and say which take is strongest.
diff --git a/skills/video-montage/SKILL.md b/skills/video-montage/SKILL.md
new file mode 100644
index 00000000..525a14af
--- /dev/null
+++ b/skills/video-montage/SKILL.md
@@ -0,0 +1,34 @@
+---
+name: video-montage
+title: Video Montage
+description: Assembly and post-processing for existing video files — concatenate, stitch or merge clips into one file, lay music under them, attach or burn subtitles, trim — returning one finished rendered file.
+when_to_use: The user has clips (uploaded or made earlier) and wants them joined, cut, given music or captions; "stitch these", "make a montage", "put music on this", "burn in subtitles". Also the final step other skills hand off to.
+icon: film
+studio: /video-tools/join
+tags: [edit, join, music, captions]
+offline:
+ kind: video
+---
+
+# Video Montage
+
+## 1. Collect the clips
+Use the attachments in the order the user gave them; earlier results via `list_recent` (kind
+video). Confirm the order in one line if it isn't obvious ("I'll join them in the order you
+uploaded: beach, sunset, fire").
+
+## 2. Steps (one `generate` call, each later step `after` the previous)
+1. **Trim** each clip if asked: op `trim` with `start_time` / `end_time` (cloud `trim-video`,
+ open `oss-trim`).
+2. **Join**: op `concat` with the clips in `video`/order (cloud `join-clips` takes many clips;
+ open `oss-join-clips` joins up to 4 per step — join in groups, then join the groups). The
+ result plays at the first clip's frame rate; mention it if the clips differ.
+3. **Music**: make a bed with op `music` (cloud `sonilo-music`, open `oss-ace-step`; describe
+ genre, tempo, mood, "instrumental, no vocals", and the length of the montage), or use the
+ user's track. Put it on with op `mux` (cloud `merge-audio-video`, open `oss-mux`); to keep the
+ clips' own sound under the music on open source, pass it as `background_audio`.
+4. **Subtitles**: the `add_captions` tool on the final file.
+
+## 3. Deliver
+`check_generations` until the last step finishes; reply with the length and what was applied.
+Offer a vertical cut (load video-repurposer) or a different track.
diff --git a/skills/video-repurposer/SKILL.md b/skills/video-repurposer/SKILL.md
new file mode 100644
index 00000000..15cb0f03
--- /dev/null
+++ b/skills/video-repurposer/SKILL.md
@@ -0,0 +1,40 @@
+---
+name: video-repurposer
+title: Video Repurposer
+description: One video in, platform-ready cuts out — reframe to new aspect ratios for TikTok, Reels, Shorts, YouTube, LinkedIn or X; cut a long video into short moments; burn in captions; translate or dub; and check each result before delivery.
+when_to_use: The user supplies an existing video and wants it adapted ("make this vertical", "cut this into shorts", "add captions", "a version in Spanish"). Not for new footage (use short-film or ugc-video).
+icon: monitor-smartphone
+studio: /reframe
+tags: [reframe, captions, shorts, repurpose]
+offline:
+ kind: video
+ aspect: "9:16"
+---
+
+# Video Repurposer
+
+Deliver finished files, one per platform, each checked.
+
+## Targets
+| Platform | Ratio | Length |
+|---|---|---|
+| TikTok, Reels, Shorts | 9:16 | ≤ 60 s (best 15–30 s) |
+| Instagram feed | 4:5 or 1:1 | ≤ 60 s |
+| YouTube | 16:9 | any |
+| LinkedIn, X | 1:1 or 16:9 | ≤ 2 min |
+
+## Steps (chain them in one `generate` call with `after`)
+1. **Cut** (when the source is long or the user wants highlights): ask for or propose the moments
+ by time, or `transcribe` first (op `transcribe`: `scribe-v2` / `oss-qwen3-asr`) and pick the
+ strongest 15–30 s from the transcript. Then op `trim` with `start_time` / `end_time`
+ (cloud `trim-video`, open `oss-trim`).
+2. **Reframe**: op `reframe` with the target `aspect_ratio` (cloud `luma-ray-3-2`, `ltx-reframe`,
+ `wan-vace-reframe`; open `oss-wan22-vace-reframe`). The model re-composes, keeping the subject in frame.
+3. **Captions**: the `add_captions` tool (or op `captions`: cloud `auto-subtitle`, open
+ `oss-captions-burnin` after a transcript). Big, centred lower-third, max ~6 words per line.
+4. **Translate / dub** (if asked): the `dub_video` tool.
+
+## QC before you say it's done
+`check_generations` for every output: status succeeded, the right ratio, no cut-off subject, and
+for captions the words match the speech. If something fails, redo only that step. List the
+deliverables with their platform and length in the reply.
diff --git a/skills/visual-studio/SKILL.md b/skills/visual-studio/SKILL.md
new file mode 100644
index 00000000..a0b58875
--- /dev/null
+++ b/skills/visual-studio/SKILL.md
@@ -0,0 +1,40 @@
+---
+name: visual-studio
+title: Visual Studio
+description: Finished motion-design reels with MiniMax H3 in five modes — classic abstract motion, high-energy kinetic graphics, animated typography, infographics, and product-only commercials — from a brief, a style reference, product assets or a storyboard.
+when_to_use: The user wants a motion-graphics style video, a kinetic typography clip, an animated infographic, an abstract loop, or a product-only commercial without people. Not for still images, live-action stories (short-film) or editing existing footage.
+icon: sparkles
+studio: /video
+tags: [motion design, typography, infographic, video]
+offline:
+ kind: video
+ aspect: "9:16"
+ style: "premium motion design, bold geometric shapes, smooth easing, kinetic typography, clean gradients, seamless transitions"
+---
+
+# Visual Studio
+
+MiniMax H3 (`minimax-h3`, or `minimax-h3-max` for higher quality and extend) is strong at
+graphic motion, readable animated text and smooth transitions. Open source: `oss-ltx25` or
+`oss-wan22-14b` (less reliable with text — keep words short).
+
+## Pick one mode
+| Mode | Prompt shape |
+|---|---|
+| Classic | abstract shapes, gradients, loops; "seamless loop" |
+| High motion | fast cuts, whip transitions, beat-driven; name the tempo |
+| Typography | the exact words in quotes, one phrase per beat, the type style |
+| Infographic | the numbers and labels in quotes, chart type, build-up order |
+| Product reel | the product photo as reference, macro moves, light sweeps, no people |
+
+## Build
+1. Write the beats (3–6), each with its on-screen text (≤ 4 words), the motion and the transition.
+2. For a product reel or a style reference, pass the image(s) in `images` (op `i2v` for a start
+ frame, `ref2v` for references). Otherwise op `t2v`.
+3. Short reels: one job with `shots` (multi-shot) or one prompt with the beats in order. Longer:
+ one job per beat, joined with op `concat`.
+4. Music: op `music` with the tempo (e.g. "128 bpm electronic, punchy"), muxed on (op `mux`).
+
+## Check
+`check_generations` with `look: true` isn't available for video frames — ask the user to confirm
+the text reads correctly, and offer to redo a beat with fewer words if not.
diff --git a/skills/youtube-script/SKILL.md b/skills/youtube-script/SKILL.md
new file mode 100644
index 00000000..7a5bd58e
--- /dev/null
+++ b/skills/youtube-script/SKILL.md
@@ -0,0 +1,38 @@
+---
+name: youtube-script
+title: YouTube Script
+description: A complete YouTube script with a full spoken body in one of six genres — business and finance, tech review, commentary or video essay, storytelling or documentary, true crime, or explainer and education — plus hook options, timestamps, production cues and a retention map.
+when_to_use: The user asks for a YouTube script, a video script, an outline with hooks, or "write the script for my video". The deliverable is text; offer to produce the video afterwards with faceless-video or narration.
+icon: file-text
+studio: /assist
+tags: [youtube, script, writing]
+offline:
+ kind: text
+---
+
+# YouTube Script
+
+## Genre playbooks
+| Genre | Hook style | Structure |
+|---|---|---|
+| Business / finance | a surprising number or a costly mistake | problem → 3 lessons → takeaway |
+| Tech review | the verdict up front, then "but…" | verdict → design → performance → who it's for |
+| Commentary / video essay | a provocative claim | claim → evidence → counterpoint → conclusion |
+| Storytelling / documentary | drop into the most dramatic moment | cold open → background → escalation → resolution |
+| True crime | the unanswered question | the case → timeline → theories → what we know |
+| Explainer / education | "by the end you'll know…" | why it matters → 3–5 steps → recap |
+
+## Deliverable (one message, in this order)
+1. **Three hook options** (first 15 seconds, spoken), labelled by angle.
+2. **The script**: full spoken text, not bullet points. Timestamps every section `[00:00]`,
+ production cues in brackets `[B-roll: server racks]`, `[On-screen text: 72%]`, `[Cut to …]`.
+ ~150 spoken words per minute; hit the requested length (default 8 minutes).
+3. **Retention map**: where attention dips and the pattern interrupt planned there (a question, a
+ visual change, a story beat) every 60–90 seconds, plus the open loop that carries to the end.
+4. **Title and thumbnail ideas**: 3 titles under 60 characters, 2 thumbnail concepts.
+
+## How
+Write it yourself in the chat for normal lengths. For very long scripts or when the user wants a
+file, use `generate` with op `write` (`text-llm` / `oss-text-llm`) and put the genre, length and
+structure in `system`. Ask one question at most (the genre or the audience) when the topic leaves
+it open. Offer next steps: narrate it (narration), produce it (faceless-video), or a thumbnail.
diff --git a/src/app/api/assist/memory/[memoryId]/route.ts b/src/app/api/assist/memory/[memoryId]/route.ts
new file mode 100644
index 00000000..502a138e
--- /dev/null
+++ b/src/app/api/assist/memory/[memoryId]/route.ts
@@ -0,0 +1,19 @@
+import { z } from "zod";
+import { deleteMemory, MemoryError, updateMemory } from "@/server/assist/memory";
+import { MemoryCategorySchema } from "@/server/assist/schemas";
+
+const Patch = z.object({ text: z.string().trim().min(1).max(500).optional(), category: MemoryCategorySchema.optional() });
+
+export async function PATCH(request: Request, ctx: RouteContext<"/api/assist/memory/[memoryId]">) {
+ const parsed = Patch.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Invalid change" }, { status: 400 });
+ try {
+ return Response.json(updateMemory((await ctx.params).memoryId, parsed.data));
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: e instanceof MemoryError ? e.status : 500 });
+ }
+}
+
+export async function DELETE(_req: Request, ctx: RouteContext<"/api/assist/memory/[memoryId]">) {
+ return deleteMemory((await ctx.params).memoryId) ? new Response(null, { status: 204 }) : Response.json({ error: "That memory doesn't exist anymore" }, { status: 404 });
+}
diff --git a/src/app/api/assist/memory/import/route.ts b/src/app/api/assist/memory/import/route.ts
new file mode 100644
index 00000000..078e209a
--- /dev/null
+++ b/src/app/api/assist/memory/import/route.ts
@@ -0,0 +1,26 @@
+import { z } from "zod";
+import { parseMemoryImport } from "@/lib/assist";
+import { importMemories, MemoryError } from "@/server/assist/memory";
+import { MemoryCategorySchema } from "@/server/assist/schemas";
+
+const Body = z.object({
+ /** Pasted text (parsed here) … */
+ text: z.string().max(100_000).optional(),
+ /** … or the items the preview showed, as the user adjusted them. */
+ items: z.array(z.object({ text: z.string().trim().min(1).max(500), category: MemoryCategorySchema })).max(200).optional(),
+ scope: z.enum(["personal", "project"]).default("personal"),
+ projectId: z.string().max(40).nullish(),
+});
+
+/** Import memories pasted from another assistant (Claude, ChatGPT, Codex…). */
+export async function POST(request: Request) {
+ const parsed = Body.safeParse(await request.json().catch(() => null));
+ if (!parsed.success || (!parsed.data.text && !parsed.data.items)) return Response.json({ error: "Paste the memories to import" }, { status: 400 });
+ const items = parsed.data.items ?? parseMemoryImport(parsed.data.text ?? "");
+ if (!items.length) return Response.json({ error: "Nothing to import — paste one memory per line or bullet" }, { status: 422 });
+ try {
+ return Response.json(importMemories(items, parsed.data.scope, parsed.data.scope === "project" ? (parsed.data.projectId ?? null) : null));
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: e instanceof MemoryError ? e.status : 500 });
+ }
+}
diff --git a/src/app/api/assist/memory/route.ts b/src/app/api/assist/memory/route.ts
new file mode 100644
index 00000000..3055b204
--- /dev/null
+++ b/src/app/api/assist/memory/route.ts
@@ -0,0 +1,32 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { addMemory, listMemories, MemoryError } from "@/server/assist/memory";
+import { MemoryCategorySchema } from "@/server/assist/schemas";
+
+const Add = z.object({
+ text: z.string().trim().min(1).max(500),
+ category: MemoryCategorySchema,
+ scope: z.enum(["personal", "project"]).optional(),
+ projectId: z.string().max(40).nullish(),
+});
+
+/** Memories: `?scope=personal|project|all` and `?project=<id>`. */
+export async function GET(request: Request) {
+ await connection();
+ const sp = new URL(request.url).searchParams;
+ const scope = sp.get("scope");
+ return Response.json({
+ items: listMemories({ scope: scope === "personal" || scope === "project" ? scope : "all", projectId: sp.get("project") }),
+ });
+}
+
+/** "Remember that: …" */
+export async function POST(request: Request) {
+ const parsed = Add.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Write what to remember and pick a category" }, { status: 400 });
+ try {
+ return Response.json(addMemory({ ...parsed.data, source: "user" }), { status: 201 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: e instanceof MemoryError ? e.status : 500 });
+ }
+}
diff --git a/src/app/api/assist/projects/[projectId]/route.ts b/src/app/api/assist/projects/[projectId]/route.ts
new file mode 100644
index 00000000..85f73681
--- /dev/null
+++ b/src/app/api/assist/projects/[projectId]/route.ts
@@ -0,0 +1,24 @@
+import { connection } from "next/server";
+import { deleteProject, getProject, ProjectError, updateProject } from "@/server/assist/projects";
+import { ProjectBody } from "@/server/assist/schemas";
+
+export async function GET(_req: Request, ctx: RouteContext<"/api/assist/projects/[projectId]">) {
+ await connection();
+ const p = getProject((await ctx.params).projectId);
+ return p ? Response.json(p) : Response.json({ error: "Not found" }, { status: 404 });
+}
+
+export async function PATCH(request: Request, ctx: RouteContext<"/api/assist/projects/[projectId]">) {
+ const parsed = ProjectBody.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Invalid change" }, { status: 400 });
+ try {
+ return Response.json(updateProject((await ctx.params).projectId, parsed.data));
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: e instanceof ProjectError ? e.status : 500 });
+ }
+}
+
+/** Delete the project, its sources and project memories; its chats move to your chats. */
+export async function DELETE(_req: Request, ctx: RouteContext<"/api/assist/projects/[projectId]">) {
+ return deleteProject((await ctx.params).projectId) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });
+}
diff --git a/src/app/api/assist/projects/[projectId]/sources/[sourceId]/refresh/route.ts b/src/app/api/assist/projects/[projectId]/sources/[sourceId]/refresh/route.ts
new file mode 100644
index 00000000..defccef0
--- /dev/null
+++ b/src/app/api/assist/projects/[projectId]/sources/[sourceId]/refresh/route.ts
@@ -0,0 +1,11 @@
+import { ProjectError, refreshSource } from "@/server/assist/projects";
+
+/** Fetch a link source again. */
+export async function POST(_req: Request, ctx: RouteContext<"/api/assist/projects/[projectId]/sources/[sourceId]/refresh">) {
+ const { projectId, sourceId } = await ctx.params;
+ try {
+ return Response.json(await refreshSource(projectId, sourceId));
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: e instanceof ProjectError ? e.status : 500 });
+ }
+}
diff --git a/src/app/api/assist/projects/[projectId]/sources/[sourceId]/route.ts b/src/app/api/assist/projects/[projectId]/sources/[sourceId]/route.ts
new file mode 100644
index 00000000..52e7aca2
--- /dev/null
+++ b/src/app/api/assist/projects/[projectId]/sources/[sourceId]/route.ts
@@ -0,0 +1,6 @@
+import { deleteSource } from "@/server/assist/projects";
+
+export async function DELETE(_req: Request, ctx: RouteContext<"/api/assist/projects/[projectId]/sources/[sourceId]">) {
+ const { projectId, sourceId } = await ctx.params;
+ return deleteSource(projectId, sourceId) ? new Response(null, { status: 204 }) : Response.json({ error: "That source isn't in this project" }, { status: 404 });
+}
diff --git a/src/app/api/assist/projects/[projectId]/sources/route.ts b/src/app/api/assist/projects/[projectId]/sources/route.ts
new file mode 100644
index 00000000..16d27045
--- /dev/null
+++ b/src/app/api/assist/projects/[projectId]/sources/route.ts
@@ -0,0 +1,44 @@
+import { z } from "zod";
+import { addSource, ProjectError } from "@/server/assist/projects";
+import { contentTypeFor, saveFile } from "@/server/storage";
+
+const MAX_BYTES = 25 * 1024 * 1024;
+/** Documents Assist can read (text) or keep as a reference (PDF), plus media it can pass on as inputs. */
+const ALLOWED = /^(text\/[\w.+-]+|application\/(json|pdf|xml|x-subrip|x-yaml|yaml)|image\/(png|jpeg|webp|gif)|video\/(mp4|webm|quicktime)|audio\/(mpeg|wav|x-wav|ogg|flac|mp4|webm))$/;
+const TEXT_EXT: Record<string, string> = { md: "text/markdown", markdown: "text/markdown", txt: "text/plain", csv: "text/csv", srt: "application/x-subrip", vtt: "text/vtt", json: "application/json", yml: "application/x-yaml", yaml: "application/x-yaml", pdf: "application/pdf" };
+
+const Json = z.discriminatedUnion("kind", [
+ z.object({ kind: z.literal("link"), url: z.string().trim().min(4).max(2000) }),
+ z.object({ kind: z.literal("file"), url: z.string().startsWith("/api/files/"), name: z.string().max(160).optional() }),
+ z.object({ kind: z.literal("element"), elementId: z.string().min(1).max(40) }),
+ z.object({ kind: z.literal("text"), title: z.string().max(160).optional(), text: z.string().min(1).max(20_000) }),
+]);
+
+/**
+ * Add a source: JSON (a link, an uploaded file URL, an element, a note) or multipart "file"
+ * (documents and media are stored like uploads). Links are fetched through the guarded fetcher.
+ */
+export async function POST(request: Request, ctx: RouteContext<"/api/assist/projects/[projectId]/sources">) {
+ const { projectId } = await ctx.params;
+ try {
+ if ((request.headers.get("content-type") ?? "").startsWith("multipart/form-data")) {
+ const form = await request.formData().catch(() => null);
+ const file = form?.get("file");
+ if (!(file instanceof File)) return Response.json({ error: "No file" }, { status: 400 });
+ if (file.size > MAX_BYTES) return Response.json({ error: "That file is over 25 MB" }, { status: 413 });
+ const ext = file.name.split(".").pop()?.toLowerCase() ?? "";
+ const type = TEXT_EXT[ext] ?? (!file.type || file.type === "application/octet-stream" ? contentTypeFor(file.name, "") : file.type);
+ if (!ALLOWED.test(type)) return Response.json({ error: `Assist can't use ${type || "that kind of"} files — add text, Markdown, PDF, images, video or audio` }, { status: 415 });
+ // The stored file's extension comes from the name for types storage doesn't map: keep it a plain one.
+ let name = file.name.replace(/[\\/]/g, "_").replace(/[^\w.\- ()]+/g, "_").slice(-120) || "file";
+ if (!/\.[a-z0-9]{1,8}$/i.test(name)) name = `${name}.${Object.entries(TEXT_EXT).find(([, t]) => t === type)?.[0] ?? "bin"}`;
+ const asset = saveFile({ data: Buffer.from(await file.arrayBuffer()), contentType: type, name, source: "upload" });
+ return Response.json(await addSource(projectId, { kind: "file", url: asset.url, name: file.name.slice(0, 160) }), { status: 201 });
+ }
+ const parsed = Json.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Add a link, a file, an element or a note" }, { status: 400 });
+ return Response.json(await addSource(projectId, parsed.data), { status: 201 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: e instanceof ProjectError ? e.status : 500 });
+ }
+}
diff --git a/src/app/api/assist/projects/route.ts b/src/app/api/assist/projects/route.ts
new file mode 100644
index 00000000..5c863ad3
--- /dev/null
+++ b/src/app/api/assist/projects/route.ts
@@ -0,0 +1,18 @@
+import { connection } from "next/server";
+import { createProject, listProjects, ProjectError } from "@/server/assist/projects";
+import { ProjectBody } from "@/server/assist/schemas";
+
+export async function GET() {
+ await connection();
+ return Response.json({ items: listProjects() });
+}
+
+export async function POST(request: Request) {
+ const parsed = ProjectBody.safeParse(await request.json().catch(() => null));
+ if (!parsed.success || !parsed.data.name) return Response.json({ error: "Give the project a name" }, { status: 400 });
+ try {
+ return Response.json(createProject(parsed.data), { status: 201 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: e instanceof ProjectError ? e.status : 500 });
+ }
+}
diff --git a/src/app/api/assist/skills/[name]/download/route.ts b/src/app/api/assist/skills/[name]/download/route.ts
new file mode 100644
index 00000000..e967e7b6
--- /dev/null
+++ b/src/app/api/assist/skills/[name]/download/route.ts
@@ -0,0 +1,17 @@
+import { connection } from "next/server";
+import { skillMarkdown } from "@/server/skills";
+
+/** The skill as SKILL.md, to keep or share (upload it on another Fuobe, or use it with Claude). */
+export async function GET(_req: Request, ctx: RouteContext<"/api/assist/skills/[name]/download">) {
+ await connection();
+ const { name } = await ctx.params;
+ const md = skillMarkdown(name);
+ if (md === null) return Response.json({ error: "No such skill" }, { status: 404 });
+ return new Response(md, {
+ headers: {
+ "Content-Type": "text/markdown; charset=utf-8",
+ "Content-Disposition": `attachment; filename="${name}-SKILL.md"`,
+ "X-Content-Type-Options": "nosniff",
+ },
+ });
+}
diff --git a/src/app/api/assist/skills/[name]/duplicate/route.ts b/src/app/api/assist/skills/[name]/duplicate/route.ts
new file mode 100644
index 00000000..8fe5116b
--- /dev/null
+++ b/src/app/api/assist/skills/[name]/duplicate/route.ts
@@ -0,0 +1,10 @@
+import { duplicateSkill, SkillError } from "@/server/skills";
+
+/** Copy a skill into My skills (the way to change a built-in). */
+export async function POST(_req: Request, ctx: RouteContext<"/api/assist/skills/[name]/duplicate">) {
+ try {
+ return Response.json(duplicateSkill((await ctx.params).name), { status: 201 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: e instanceof SkillError ? e.status : 500 });
+ }
+}
diff --git a/src/app/api/assist/skills/[name]/route.ts b/src/app/api/assist/skills/[name]/route.ts
new file mode 100644
index 00000000..252200dc
--- /dev/null
+++ b/src/app/api/assist/skills/[name]/route.ts
@@ -0,0 +1,46 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { deleteSkill, getSkill, setSkillEnabled, SkillError, updateSkill } from "@/server/skills";
+
+const Patch = z.object({
+ enabled: z.boolean().optional(),
+ name: z.string().trim().min(1).max(64).optional(),
+ title: z.string().trim().min(1).max(80).optional(),
+ description: z.string().trim().min(1).max(1024).optional(),
+ whenToUse: z.string().trim().max(1024).optional(),
+ body: z.string().min(1).max(60_000).optional(),
+ icon: z.string().max(40).optional(),
+});
+
+const fail = (e: unknown) => Response.json({ error: (e as Error).message }, { status: e instanceof SkillError ? e.status : 500 });
+
+export async function GET(_req: Request, ctx: RouteContext<"/api/assist/skills/[name]">) {
+ await connection();
+ const s = getSkill((await ctx.params).name);
+ return s ? Response.json(s) : Response.json({ error: "No such skill" }, { status: 404 });
+}
+
+/** Switch a skill on or off, or edit one of your own. */
+export async function PATCH(request: Request, ctx: RouteContext<"/api/assist/skills/[name]">) {
+ const parsed = Patch.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Invalid change" }, { status: 400 });
+ const { name } = await ctx.params;
+ try {
+ const { enabled, ...edit } = parsed.data;
+ let s = Object.keys(edit).length ? updateSkill(name, edit) : getSkill(name);
+ if (!s) return Response.json({ error: "No such skill" }, { status: 404 });
+ if (enabled !== undefined) s = setSkillEnabled(s.name, enabled);
+ return Response.json(s);
+ } catch (e) {
+ return fail(e);
+ }
+}
+
+export async function DELETE(_req: Request, ctx: RouteContext<"/api/assist/skills/[name]">) {
+ try {
+ deleteSkill((await ctx.params).name);
+ return new Response(null, { status: 204 });
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/src/app/api/assist/skills/route.ts b/src/app/api/assist/skills/route.ts
new file mode 100644
index 00000000..48e34368
--- /dev/null
+++ b/src/app/api/assist/skills/route.ts
@@ -0,0 +1,20 @@
+import { connection } from "next/server";
+import { SkillBody } from "@/server/assist/schemas";
+import { createSkill, listSkills, SkillError } from "@/server/skills";
+
+/** Every skill: built-in (from skills/) and the user's own. */
+export async function GET() {
+ await connection();
+ return Response.json({ items: listSkills() });
+}
+
+/** Create a skill from the form (name, title, description, when to use, instructions). */
+export async function POST(request: Request) {
+ const parsed = SkillBody.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Give the skill a name, a description and instructions" }, { status: 400 });
+ try {
+ return Response.json(createSkill(parsed.data), { status: 201 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: e instanceof SkillError ? e.status : 500 });
+ }
+}
diff --git a/src/app/api/assist/skills/upload/route.ts b/src/app/api/assist/skills/upload/route.ts
new file mode 100644
index 00000000..796ce3e4
--- /dev/null
+++ b/src/app/api/assist/skills/upload/route.ts
@@ -0,0 +1,18 @@
+import { importSkill, SkillError } from "@/server/skills";
+
+const MAX_BYTES = 5 * 1024 * 1024;
+
+/** Add a skill from a .zip / .skill archive or a SKILL.md (multipart "file"; `?replace=1` overwrites your skill of the same name). */
+export async function POST(request: Request) {
+ const form = await request.formData().catch(() => null);
+ const file = form?.get("file");
+ if (!(file instanceof File)) return Response.json({ error: "Choose a .zip, .skill or SKILL.md file" }, { status: 400 });
+ if (file.size > MAX_BYTES) return Response.json({ error: "That file is over 5 MB — a skill is mostly text; leave large assets out" }, { status: 413 });
+ try {
+ const replace = new URL(request.url).searchParams.get("replace") === "1";
+ const r = importSkill({ name: file.name, data: Buffer.from(await file.arrayBuffer()) }, { replace });
+ return Response.json(r, { status: r.replaced ? 200 : 201 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: e instanceof SkillError ? e.status : 500 });
+ }
+}
diff --git a/src/components/assist-view.tsx b/src/components/assist-view.tsx
index 212d2ba6..863d8d36 100644
--- a/src/components/assist-view.tsx
+++ b/src/components/assist-view.tsx
@@ -275,7 +275,7 @@ function ApprovalCard({ item, live, onAnswer }: { item: Extract<AssistItem, { ro
{j.modelName}
<span className="font-normal text-muted-foreground">
{" · "}
- {j.op === "storyboard" ? `Storyboard · ${j.count} frames` : `${OPERATION_LABELS[j.op] ?? j.op}${j.count > 1 ? ` · ${j.count} takes` : ""}`}
+ {j.op === "storyboard" ? `Storyboard · ${j.count} frames` : j.op === "memory" ? "Remember" : `${OPERATION_LABELS[j.op] ?? j.op}${j.count > 1 ? ` · ${j.count} takes` : ""}`}
</span>
</p>
<p className="mt-0.5 line-clamp-2 text-[13px] text-muted-foreground">{j.prompt}</p>
diff --git a/src/lib/assist.ts b/src/lib/assist.ts
index 75eb6ea3..5c04fe02 100644
--- a/src/lib/assist.ts
+++ b/src/lib/assist.ts
@@ -1,16 +1,22 @@
/**
* Assist: a chat agent that plans a shoot, picks models, shows the cost, asks before spending
* and then runs the generations (Higgsfield's "Supercomputer"). Shared by the server loop and the UI.
+ *
+ * Besides the chat itself this holds the pure parts of Skills (SKILL.md parsing and validation,
+ * `/name` invocation), Memory (categories, import parsing) and the context the agent is given
+ * (rendered once per chat, then updated with append-only "Context update" messages).
*/
import type { Engine, Generation, MediaKind, Operation } from "./catalog/types";
/** One job the agent wants to run, priced before the user approves it. */
export interface PlannedJob {
- tool: "generate" | "create_storyboard";
+ /** The tool that would run it (generate, create_storyboard, remember, a studio tool…). */
+ tool: string;
modelId: string;
modelName: string;
kind: MediaKind;
- op: Operation | "storyboard";
+ /** "memory" for a note the agent wants to remember (no cost). */
+ op: Operation | "storyboard" | "memory";
prompt: string;
/** Generations this job creates (outputs × jobs, or storyboard frames). */
count: number;
@@ -19,30 +25,43 @@ export interface PlannedJob {
demo: boolean;
/** Can't run as planned (missing input, model blocked by engine mode…). */
error?: string;
+ /** A short extra line on the card (a studio's step, what a step waits for). */
+ note?: string;
}
export type AssistItem =
- | { id: string; role: "user"; text: string; attachments?: string[] }
+ | { id: string; role: "user"; text: string; attachments?: string[]; skills?: string[] }
| { id: string; role: "assistant"; text: string }
- | { id: string; role: "tool"; text: string }
+ | { id: string; role: "tool"; text: string; href?: string }
| { id: string; role: "approval"; summary: string; jobs: PlannedJob[]; totalUsd: number | null; status: "pending" | "approved" | "declined" }
| { id: string; role: "generations"; ids: string[]; storyboard?: boolean }
| { id: string; role: "notice"; text: string; tone: "info" | "error" };
export type AssistStatus = "idle" | "running" | "waiting";
+export type AssistAgent = "claude" | "ollama" | "offline";
+
export interface AssistThread {
id: string;
title: string;
status: AssistStatus;
/** "claude" = Claude; "ollama" = a local model through Ollama; "offline" = a rule-based planner (no LLM). */
- agent: "claude" | "ollama" | "offline";
+ agent: AssistAgent;
engine: Engine;
/** Run plans without the approval card. */
autoApprove: boolean;
items: AssistItem[];
createdAt: number;
updatedAt: number;
+ /** The project this chat belongs to (null: a personal chat). */
+ projectId?: string | null;
+ /** How the LLM was chosen (Free / Smart / Manual). */
+ mode?: AssistMode;
+ /** Claude model id, or the Ollama model name (null: the default). */
+ model?: string | null;
+ effort?: AssistEffort | null;
+ /** Skills loaded into this chat (by `/name` or by the agent). */
+ skills?: string[];
}
export interface AssistThreadSummary {
@@ -50,6 +69,7 @@ export interface AssistThreadSummary {
title: string;
status: AssistStatus;
updatedAt: number;
+ projectId?: string | null;
}
export interface AssistThreadView {
@@ -65,3 +85,469 @@ export function threadTitle(text: string): string {
const t = text.trim().replace(/\s+/g, " ");
return t.length > 60 ? `${t.slice(0, 57).replace(/\s+\S*$/, "")}…` : t || "New chat";
}
+
+// ---------------------------------------------------------------------------
+// Modes (Supercomputer's Free / Smart / Manual)
+
+export type AssistMode = "free" | "smart" | "manual";
+export type AssistEffort = "low" | "medium" | "high" | "xhigh" | "max";
+
+export const ASSIST_MODES: { id: AssistMode; label: string; hint: string }[] = [
+ { id: "smart", label: "Smart", hint: "Claude plans, picks models and checks results" },
+ { id: "free", label: "Free", hint: "A local model through Ollama, or the offline planner — no API cost" },
+ { id: "manual", label: "Manual", hint: "Pick the model and how hard it thinks" },
+];
+
+export const ASSIST_EFFORTS: { id: AssistEffort; label: string }[] = [
+ { id: "low", label: "Low" },
+ { id: "medium", label: "Medium" },
+ { id: "high", label: "High" },
+ { id: "xhigh", label: "Extra" },
+ { id: "max", label: "Max" },
+];
+
+/** Claude models Manual mode offers (all take adaptive thinking, effort and mid-chat system messages). */
+export const CLAUDE_MODELS: { id: string; label: string; hint: string }[] = [
+ { id: "claude-opus-5-5", label: "Claude Opus 5.5", hint: "Best plans — the Smart default" },
+ { id: "claude-sonnet-5-5", label: "Claude Sonnet 5.5", hint: "Faster, about half the price" },
+ { id: "claude-haiku-5-5", label: "Claude Haiku 5.5", hint: "Fastest and cheapest" },
+ { id: "claude-fable-5-1", label: "Claude Fable 5.1", hint: "Most capable, slowest, priciest" },
+];
+export const DEFAULT_CLAUDE_MODEL = "claude-opus-5-5";
+export const DEFAULT_EFFORT: AssistEffort = "medium";
+
+/** What the composer's mode picker sends. `agent` only matters in Manual mode. */
+export interface AssistModeChoice {
+ mode: AssistMode;
+ agent?: AssistAgent;
+ model?: string | null;
+ effort?: AssistEffort | null;
+}
+
+/** What the server can run right now (GET /api/assist). */
+export interface AssistAvailability {
+ /** An Anthropic key is set and Settings allows Claude here. */
+ claude: boolean;
+ /** Ollama answered. */
+ ollama: boolean;
+ ollamaModels: string[];
+ ollamaModel: string;
+ /** Settings → AI helper is "none": every chat runs the offline planner. */
+ aiOff: boolean;
+ /** Smart when Claude can run, else Free. */
+ defaultMode: AssistMode;
+}
+
+export function modeLabel(t: Pick<AssistThread, "mode" | "agent" | "model" | "effort">): string {
+ if (t.agent === "offline") return "Offline planner";
+ if (t.agent === "ollama") return t.model ? `Local · ${t.model}` : "Local LLM";
+ const m = CLAUDE_MODELS.find((x) => x.id === (t.model ?? DEFAULT_CLAUDE_MODEL));
+ const effort = ASSIST_EFFORTS.find((e) => e.id === (t.effort ?? DEFAULT_EFFORT))?.label;
+ if (t.mode === "manual") return `${m?.label.replace("Claude ", "") ?? t.model} · ${effort}`;
+ return "Smart";
+}
+
+// ---------------------------------------------------------------------------
+// Skills: SKILL.md (frontmatter + Markdown body), as Anthropic's Agent Skills and Supercomputer use
+
+export interface SkillMeta {
+ /** The id and the `/name` that loads it: lowercase letters, numbers and hyphens. */
+ name: string;
+ title: string;
+ description: string;
+ whenToUse: string;
+ /** A lucide icon name from SKILL_ICONS. */
+ icon?: string;
+ /** A Fuobe page that does the same job by hand. */
+ studio?: string;
+ tags?: string[];
+ /** Hints for the offline planner (no LLM): the kind of job and its defaults. */
+ offline?: { kind?: "image" | "video" | "audio" | "text"; aspect?: string; outputs?: number; style?: string };
+}
+
+export interface Skill extends SkillMeta {
+ body: string;
+ source: "builtin" | "user";
+ enabled: boolean;
+ /** Extra files that came with an uploaded skill (references, examples), readable with load_skill. */
+ files: { path: string; size: number }[];
+ createdAt: number;
+ updatedAt: number;
+}
+
+/** What lists show (no body). */
+export type SkillSummary = Omit<Skill, "body"> & { chars: number };
+
+export const SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
+export const SKILL_LIMITS = { name: 64, title: 80, description: 1024, whenToUse: 1024, body: 60_000 };
+
+const FRONTMATTER = /^?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;
+
+type Yamlish = string | string[] | Record<string, string>;
+
+/** A small YAML subset: `key: value`, quoted values, `|`/`>` blocks, `- item` lists and one level of nested maps. */
+export function parseFrontmatter(src: string): Record<string, Yamlish> {
+ const out: Record<string, Yamlish> = {};
+ const lines = src.split(/\r?\n/);
+ const unquote = (v: string) => {
+ const t = v.trim();
+ if ((t.startsWith('"') && t.endsWith('"') && t.length > 1) || (t.startsWith("'") && t.endsWith("'") && t.length > 1)) {
+ return t.startsWith('"') ? t.slice(1, -1).replace(/\\"/g, '"').replace(/\\n/g, "\n") : t.slice(1, -1).replace(/''/g, "'");
+ }
+ return t.replace(/\s+#.*$/, "");
+ };
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ if (!line.trim() || line.trim().startsWith("#") || /^\s/.test(line)) continue;
+ const m = /^([A-Za-z_][\w-]*)\s*:\s*(.*)$/.exec(line);
+ if (!m) continue;
+ const key = m[1].toLowerCase().replace(/-/g, "_");
+ const rest = m[2];
+ // Indented lines that follow belong to this key.
+ const block: string[] = [];
+ while (i + 1 < lines.length && (/^\s+\S/.test(lines[i + 1]) || (!lines[i + 1].trim() && i + 2 < lines.length && /^\s+\S/.test(lines[i + 2])))) block.push(lines[++i]);
+ if (/^[|>][+-]?\s*$/.test(rest.trim())) {
+ const indent = Math.min(...block.filter((l) => l.trim()).map((l) => /^\s*/.exec(l)![0].length));
+ const text = block.map((l) => l.slice(Number.isFinite(indent) ? indent : 0));
+ out[key] = rest.trim().startsWith(">") ? text.join("\n").replace(/([^\n])\n(?=[^\n])/g, "$1 ").trim() : text.join("\n").trim();
+ } else if (rest.trim()) {
+ const v = rest.trim();
+ out[key] = v.startsWith("[") && v.endsWith("]") ? v.slice(1, -1).split(",").map(unquote).filter(Boolean) : unquote(v);
+ } else if (block.some((l) => /^\s*-\s/.test(l))) {
+ out[key] = block.filter((l) => /^\s*-\s/.test(l)).map((l) => unquote(l.replace(/^\s*-\s/, "")));
+ } else {
+ const map: Record<string, string> = {};
+ for (const l of block) {
+ const mm = /^\s+([A-Za-z_][\w-]*)\s*:\s*(.*)$/.exec(l);
+ if (mm) map[mm[1].toLowerCase().replace(/-/g, "_")] = unquote(mm[2]);
+ }
+ out[key] = map;
+ }
+ }
+ return out;
+}
+
+const str = (v: Yamlish | undefined): string | undefined => (typeof v === "string" ? v : Array.isArray(v) ? v.join(", ") : undefined);
+
+export type SkillParse = { ok: true; skill: SkillMeta & { body: string } } | { ok: false; error: string };
+
+const titleFromName = (name: string) => name.replace(/-/g, " ").replace(/^./, (c) => c.toUpperCase());
+
+/** Parse and validate a SKILL.md. Errors are user-facing ("Check SKILL.md and try again: …"). */
+export function parseSkillMd(text: string): SkillParse {
+ const fail = (why: string): SkillParse => ({ ok: false, error: `Check SKILL.md and try again: ${why}` });
+ const m = FRONTMATTER.exec(text);
+ if (!m) return fail("it needs a frontmatter block between --- lines at the top, with a name and a description.");
+ const fm = parseFrontmatter(m[1]);
+ const name = str(fm.name)?.trim() ?? "";
+ if (!name) return fail("the frontmatter has no name.");
+ if (name.length > SKILL_LIMITS.name || !SKILL_NAME_RE.test(name)) return fail(`“${name.slice(0, 70)}” isn't a valid name — use lowercase letters, numbers and hyphens (up to ${SKILL_LIMITS.name} characters), e.g. product-photos.`);
+ const meta = (fm.metadata && typeof fm.metadata === "object" && !Array.isArray(fm.metadata) ? fm.metadata : {}) as Record<string, string>;
+ const description = (str(fm.description) ?? "").trim();
+ if (!description) return fail("the frontmatter has no description (what the skill does and when to use it).");
+ if (description.length > SKILL_LIMITS.description) return fail(`the description is ${description.length} characters; keep it under ${SKILL_LIMITS.description}.`);
+ const whenToUse = (str(fm.when_to_use) ?? str(fm.whentouse) ?? meta.when_to_use ?? "").trim();
+ if (whenToUse.length > SKILL_LIMITS.whenToUse) return fail(`“when to use” is ${whenToUse.length} characters; keep it under ${SKILL_LIMITS.whenToUse}.`);
+ const title = (str(fm.title) ?? str(fm.display_name) ?? meta.title ?? meta.display_name ?? titleFromName(name)).trim().slice(0, SKILL_LIMITS.title);
+ const body = text.slice(m[0].length).trim();
+ if (!body) return fail("there are no instructions under the frontmatter.");
+ if (body.length > SKILL_LIMITS.body) return fail(`the instructions are ${Math.round(body.length / 1000)}k characters; keep them under ${SKILL_LIMITS.body / 1000}k (move long references into separate files).`);
+ const offlineMap = fm.offline && typeof fm.offline === "object" && !Array.isArray(fm.offline) ? (fm.offline as Record<string, string>) : undefined;
+ const kind = offlineMap?.kind;
+ const tags = Array.isArray(fm.tags) ? fm.tags : str(fm.tags)?.split(",").map((t) => t.trim()).filter(Boolean);
+ return {
+ ok: true,
+ skill: {
+ name,
+ title,
+ description,
+ whenToUse,
+ body,
+ ...(str(fm.icon) && { icon: str(fm.icon) }),
+ ...(str(fm.studio) && { studio: str(fm.studio) }),
+ ...(tags?.length && { tags: tags.slice(0, 8) }),
+ ...(offlineMap && {
+ offline: {
+ ...(kind === "image" || kind === "video" || kind === "audio" || kind === "text" ? { kind } : {}),
+ ...(offlineMap.aspect && { aspect: offlineMap.aspect }),
+ ...(Number(offlineMap.outputs) > 0 && { outputs: Math.min(4, Math.round(Number(offlineMap.outputs))) }),
+ ...(offlineMap.style && { style: offlineMap.style }),
+ },
+ }),
+ },
+ };
+}
+
+const yamlValue = (v: string) => (/^[\w ./(),&+-]*$/.test(v) && !/^\s|\s$/.test(v) && !/^(true|false|null|\d+)$/i.test(v) ? v : JSON.stringify(v));
+
+/** Write a skill back out as SKILL.md (export, and the form's "Create skill"). */
+export function toSkillMd(s: Pick<SkillMeta, "name" | "title" | "description" | "whenToUse" | "icon" | "studio" | "tags"> & { body: string }): string {
+ const lines = ["---", `name: ${s.name}`, `title: ${yamlValue(s.title)}`, `description: ${yamlValue(s.description.replace(/\s*\n\s*/g, " "))}`];
+ if (s.whenToUse) lines.push(`when_to_use: ${yamlValue(s.whenToUse.replace(/\s*\n\s*/g, " "))}`);
+ if (s.icon) lines.push(`icon: ${s.icon}`);
+ if (s.studio) lines.push(`studio: ${s.studio}`);
+ if (s.tags?.length) lines.push(`tags: [${s.tags.map(yamlValue).join(", ")}]`);
+ lines.push("---", "", s.body.trim(), "");
+ return lines.join("\n");
+}
+
+/** A name from a title ("Product photos!" → "product-photos"). */
+export function skillSlug(title: string): string {
+ return (
+ title
+ .toLowerCase()
+ .normalize("NFKD")
+ .replace(/[̀-ͯ]/g, "")
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, SKILL_LIMITS.name)
+ .replace(/-+$/, "") || "my-skill"
+ );
+}
+
+/**
+ * Leading `/name` tokens of a message: "/product-photoshoot /thumbnail-generation a coffee ad"
+ * → skills [product-photoshoot, thumbnail-generation], text "a coffee ad". Unknown names stay in the text.
+ */
+export function slashSkills(text: string, known: (name: string) => boolean): { skills: string[]; text: string } {
+ const skills: string[] = [];
+ let rest = text.trimStart();
+ for (;;) {
+ const m = /^\/([a-z0-9]+(?:-[a-z0-9]+)*)(?=\s|$)/.exec(rest);
+ if (!m || !known(m[1])) break;
+ if (!skills.includes(m[1])) skills.push(m[1]);
+ rest = rest.slice(m[0].length).trimStart();
+ }
+ return { skills, text: rest };
+}
+
+/** The `/partial` being typed at the caret, for the composer's skill menu (null when none). */
+export function slashQuery(text: string, caret: number): { start: number; query: string } | null {
+ const before = text.slice(0, caret);
+ const m = /(?:^|\s)\/([a-z0-9-]*)$/.exec(before);
+ if (!m) return null;
+ // Only skill tokens at the start of the message (after other skill tokens) are recognised.
+ const start = before.length - m[1].length - 1;
+ if (!/^(\s*\/[a-z0-9-]+)*\s*$/.test(text.slice(0, start))) return null;
+ return { start, query: m[1] };
+}
+
+// ---------------------------------------------------------------------------
+// Memory
+
+export const MEMORY_CATEGORIES = ["Preference", "Style", "Communication", "Convention", "Environment", "Tooling", "Troubleshooting", "Notes"] as const;
+export type MemoryCategory = (typeof MEMORY_CATEGORIES)[number];
+
+export const MEMORY_HINTS: Record<MemoryCategory, string> = {
+ Preference: "Formats, lengths, models you like",
+ Style: "Looks, palettes, moods, references",
+ Communication: "How Assist should talk to you",
+ Convention: "Naming, aspect ratios, brand rules",
+ Environment: "Your setup: GPU, keys, where things live",
+ Tooling: "Models and studios to use or avoid",
+ Troubleshooting: "Fixes that worked before",
+ Notes: "Anything else worth keeping",
+};
+
+export type MemoryScope = "personal" | "project";
+
+export interface AssistMemory {
+ id: string;
+ scope: MemoryScope;
+ projectId: string | null;
+ category: MemoryCategory;
+ text: string;
+ /** Who wrote it: you on the Memory page, the agent (remember), or an import. */
+ source: "user" | "agent" | "import";
+ createdAt: number;
+ updatedAt: number;
+}
+
+export const MEMORY_MAX_CHARS = 500;
+
+const CATEGORY_WORDS: [MemoryCategory, RegExp][] = [
+ ["Communication", /\b(reply|replies|respond|answer|tone|concise|brief|verbose|explain|language|speak|call me|address me|emoji|bullet)/i],
+ ["Style", /\b(style|look|aesthetic|palette|colou?rs?|mood|lighting|film|cinematic|minimal|vibe|font|typography|grain)\b/i],
+ ["Convention", /\b(always|never|naming|name files|format|aspect|9:16|16:9|1:1|4:5|brand|logo|watermark|caption|hashtag)/i],
+ ["Environment", /\b(gpu|vram|cuda|mac|windows|linux|server|machine|install|comfyui|ollama|api key|disk|folder|path)\b/i],
+ ["Tooling", /\b(model|seedance|kling|veo|flux|wan|nano banana|midjourney|elevenlabs|studio|tool|workflow|plugin)\b/i],
+ ["Troubleshooting", /\b(fix|fixed|error|fails?|failed|crash|bug|workaround|broken|issue)\b/i],
+ ["Preference", /\b(prefer|like|love|hate|dislike|favou?rite|want|rather|usually|tend to)\b/i],
+];
+
+export function guessCategory(text: string): MemoryCategory {
+ return CATEGORY_WORDS.find(([, re]) => re.test(text))?.[0] ?? "Notes";
+}
+
+const CATEGORY_ALIASES: Record<string, MemoryCategory> = {
+ preference: "Preference",
+ preferences: "Preference",
+ style: "Style",
+ "coding style": "Style",
+ "visual style": "Style",
+ communication: "Communication",
+ convention: "Convention",
+ conventions: "Convention",
+ environment: "Environment",
+ tooling: "Tooling",
+ tools: "Tooling",
+ troubleshooting: "Troubleshooting",
+ notes: "Notes",
+ note: "Notes",
+ other: "Notes",
+};
+
+export const toCategory = (s: string | undefined): MemoryCategory | undefined => (s ? CATEGORY_ALIASES[s.trim().toLowerCase()] : undefined);
+
+/**
+ * Memories pasted from another assistant (Claude, ChatGPT, Codex…): one per bullet, numbered item
+ * or line. A heading or a "Category:" prefix sets the category; otherwise it's guessed from the
+ * words. Boilerplate ("Here is what I remember…"), duplicates and very short lines are dropped.
+ */
+export function parseMemoryImport(text: string): { category: MemoryCategory; text: string }[] {
+ const out: { category: MemoryCategory; text: string }[] = [];
+ const seen = new Set<string>();
+ let heading: MemoryCategory | undefined;
+ let jsonItems: unknown[] | null = null;
+ try {
+ const j = JSON.parse(text) as unknown;
+ if (Array.isArray(j)) jsonItems = j;
+ else if (j && typeof j === "object" && Array.isArray((j as { memories?: unknown[] }).memories)) jsonItems = (j as { memories: unknown[] }).memories;
+ } catch {
+ // Plain text.
+ }
+ const add = (raw: string, cat?: MemoryCategory) => {
+ let t = raw.replace(/\s+/g, " ").trim();
+ const prefix = /^\[?([A-Za-z ]{3,20})\]?\s*[:—–-]\s+(.+)$/.exec(t);
+ const pc = prefix ? toCategory(prefix[1]) : undefined;
+ if (pc) t = prefix![2].trim();
+ t = t.replace(/^["“](.*)["”]$/, "$1").trim();
+ if (t.length < 4 || /^(here (is|are)|below (is|are)|these are|i remember|memories|memory|saved memories)\b.*:?$/i.test(t)) return;
+ const key = t.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
+ if (!key || seen.has(key)) return;
+ seen.add(key);
+ out.push({ category: pc ?? cat ?? guessCategory(t), text: t.slice(0, MEMORY_MAX_CHARS) });
+ };
+ if (jsonItems) {
+ for (const it of jsonItems) {
+ if (typeof it === "string") add(it);
+ else if (it && typeof it === "object") {
+ const o = it as Record<string, unknown>;
+ const t = [o.text, o.content, o.memory, o.value].find((v) => typeof v === "string") as string | undefined;
+ if (t) add(t, toCategory(typeof o.category === "string" ? o.category : typeof o.type === "string" ? o.type : undefined));
+ }
+ }
+ return out.slice(0, 200);
+ }
+ for (const line of text.split(/\r?\n/)) {
+ const l = line.trim();
+ if (!l) continue;
+ const h = /^(?:#{1,6}\s+|\*\*)?([A-Za-z ]{3,24}?)(?:\*\*)?\s*:?\s*$/.exec(l);
+ if (h && toCategory(h[1]) && !/^[-*•]/.test(l)) {
+ heading = toCategory(h[1]);
+ continue;
+ }
+ if (/^#{1,6}\s/.test(l)) continue;
+ const item = l.replace(/^(?:[-*•·]|\d+[.)])\s+/, "").replace(/^\[[ x]\]\s+/i, "");
+ // A paragraph of several sentences becomes one memory per sentence only when it's long.
+ if (item.length > MEMORY_MAX_CHARS) for (const s of item.split(/(?<=[.!?])\s+/)) add(s, heading);
+ else add(item, heading);
+ }
+ return out.slice(0, 200);
+}
+
+// ---------------------------------------------------------------------------
+// Projects
+
+export const MAX_PROJECT_SOURCES = 20;
+export const PROJECT_COLORS = ["iris", "sky", "teal", "lime", "amber", "rose", "slate"] as const;
+export type ProjectColor = (typeof PROJECT_COLORS)[number];
+/** Hues for the project swatches (oklch), matching the Library's folder colours. */
+export const PROJECT_HUE: Record<ProjectColor, number> = { iris: 280, sky: 230, teal: 185, lime: 130, amber: 75, rose: 15, slate: 260 };
+
+export type SourceKind = "link" | "file" | "image" | "video" | "audio" | "element" | "text";
+
+export interface ProjectSource {
+ id: string;
+ kind: SourceKind;
+ title: string;
+ /** /api/files/… for files and media, the page for links. */
+ url?: string;
+ elementId?: string;
+ /** The first lines of the text Assist can read (links, text files, notes). */
+ excerpt?: string;
+ chars?: number;
+ status: "ready" | "error";
+ error?: string;
+ createdAt: number;
+}
+
+export interface AssistProject {
+ id: string;
+ name: string;
+ color: ProjectColor;
+ instructions: string;
+ /** Project skills: when set, the agent can use only these (they also come first). */
+ skills: string[];
+ /** Also give chats in this project your personal memory (project memory is always used). */
+ usePersonalMemory: boolean;
+ sources: ProjectSource[];
+ chats: number;
+ createdAt: number;
+ updatedAt: number;
+}
+
+export const PROJECT_LIMITS = { name: 60, instructions: 8000, sourceText: 40_000, note: 20_000 };
+
+// ---------------------------------------------------------------------------
+// The agent's context: rendered once when a chat starts, then updated by appending messages
+
+export type FactSection = "now" | "project" | "sources" | "memory" | "skills" | "active";
+
+export interface ContextFact {
+ section: FactSection;
+ key: string;
+ text: string;
+}
+
+const SECTION_TITLE: Record<FactSection, string> = {
+ now: "This chat",
+ project: "Project",
+ sources: "Project sources",
+ memory: "Memory (what you know about the user)",
+ skills: "Skills you can load",
+ active: "Skills in use — follow these",
+};
+const SECTION_ORDER: FactSection[] = ["now", "project", "sources", "memory", "skills", "active"];
+
+const factId = (f: Pick<ContextFact, "section" | "key">) => `${f.section}:${f.key}`;
+
+/** The full context block (the second system block of a chat, frozen once rendered). */
+export function renderContext(facts: ContextFact[]): string {
+ return SECTION_ORDER.flatMap((s) => {
+ const items = facts.filter((f) => f.section === s);
+ return items.length ? [`## ${SECTION_TITLE[s]}\n${items.map((f) => f.text).join("\n")}`] : [];
+ }).join("\n\n");
+}
+
+export const factMap = (facts: ContextFact[]): Record<string, string> => Object.fromEntries(facts.map((f) => [factId(f), f.text]));
+
+const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
+
+/**
+ * What changed since the context the model last saw, as one "Context update" message (null when
+ * nothing did). The chat's earlier messages are never edited: the update is appended, so the
+ * prompt cache and earlier thinking stay valid.
+ */
+export function contextUpdate(sent: Record<string, string>, facts: ContextFact[]): string | null {
+ const now = factMap(facts);
+ const parts: string[] = [];
+ for (const s of SECTION_ORDER) {
+ const changed = facts.filter((f) => f.section === s && sent[factId(f)] !== f.text).map((f) => f.text);
+ const gone = Object.keys(sent)
+ .filter((k) => k.startsWith(`${s}:`) && !(k in now))
+ .map((k) => (s === "active" ? `- Stop following the /${k.slice(7)} skill.` : `- No longer applies: ${clip(sent[k].replace(/^[-#\s]+/, "").split("\n")[0], 160)}`));
+ if (changed.length || gone.length) parts.push(`## ${SECTION_TITLE[s]}\n${[...changed, ...gone].join("\n")}`);
+ }
+ return parts.length ? `Context update — these replace the matching parts of your instructions:\n\n${parts.join("\n\n")}` : null;
+}
diff --git a/src/server/assist/memory.ts b/src/server/assist/memory.ts
new file mode 100644
index 00000000..5a080d51
--- /dev/null
+++ b/src/server/assist/memory.ts
@@ -0,0 +1,133 @@
+import "server-only";
+import { nanoid } from "nanoid";
+import { MEMORY_CATEGORIES, MEMORY_MAX_CHARS, type AssistMemory, type MemoryCategory, type MemoryScope } from "@/lib/assist";
+import { db } from "../db";
+
+/**
+ * Assist memory: short typed notes about the user (Supercomputer's Memory). Personal memories
+ * apply to every chat; project memories only inside their project (and a project can leave
+ * personal memory out). The agent adds them with its remember tool; people add, edit, delete
+ * and import them on the Memory page.
+ */
+
+export class MemoryError extends Error {
+ constructor(
+ message: string,
+ readonly status = 400,
+ ) {
+ super(message);
+ }
+}
+
+interface Row {
+ id: string;
+ scope: MemoryScope;
+ project_id: string | null;
+ category: MemoryCategory;
+ text: string;
+ source: AssistMemory["source"];
+ created_at: number;
+ updated_at: number;
+}
+
+const toMemory = (r: Row): AssistMemory => ({
+ id: r.id,
+ scope: r.scope,
+ projectId: r.project_id,
+ category: r.category,
+ text: r.text,
+ source: r.source,
+ createdAt: r.created_at,
+ updatedAt: r.updated_at,
+});
+
+const tidy = (t: string) => t.replace(/\s+/g, " ").trim();
+const key = (t: string) => t.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
+
+/** Memories for a filter, newest first. scope "all" = personal and every project's. */
+export function listMemories(f: { scope?: MemoryScope | "all"; projectId?: string | null } = {}): AssistMemory[] {
+ const where: string[] = [];
+ const args: unknown[] = [];
+ if (f.scope === "personal") where.push("scope = 'personal'");
+ else if (f.scope === "project") {
+ where.push("scope = 'project'");
+ if (f.projectId) {
+ where.push("project_id = ?");
+ args.push(f.projectId);
+ }
+ }
+ const sql = `SELECT * FROM assist_memory ${where.length ? `WHERE ${where.join(" AND ")}` : ""} ORDER BY updated_at DESC LIMIT 1000`;
+ return (db().prepare(sql).all(...args) as Row[]).map(toMemory);
+}
+
+/** What a chat sees: its project's memories, plus personal ones unless the project leaves them out. */
+export function memoriesFor(projectId: string | null, usePersonal = true): AssistMemory[] {
+ const project = projectId ? listMemories({ scope: "project", projectId }) : [];
+ const personal = !projectId || usePersonal ? listMemories({ scope: "personal" }) : [];
+ return [...project, ...personal];
+}
+
+export function getMemory(id: string): AssistMemory | null {
+ const r = db().prepare("SELECT * FROM assist_memory WHERE id = ?").get(id) as Row | undefined;
+ return r ? toMemory(r) : null;
+}
+
+function check(text: string, category: string, scope: MemoryScope, projectId: string | null) {
+ const t = tidy(text);
+ if (!t) throw new MemoryError("Write what to remember");
+ if (t.length > MEMORY_MAX_CHARS) throw new MemoryError(`Keep a memory under ${MEMORY_MAX_CHARS} characters — split it into a few`);
+ if (!(MEMORY_CATEGORIES as readonly string[]).includes(category)) throw new MemoryError(`Pick a category: ${MEMORY_CATEGORIES.join(", ")}`);
+ if (scope === "project" && !projectId) throw new MemoryError("A project memory needs its project");
+ if (scope === "project" && !db().prepare("SELECT 1 FROM assist_projects WHERE id = ?").get(projectId)) throw new MemoryError("That project doesn't exist anymore", 404);
+ return t;
+}
+
+/** Add a memory; the same text in the same place updates the existing one instead of duplicating it. */
+export function addMemory(input: { text: string; category: MemoryCategory; scope?: MemoryScope; projectId?: string | null; source?: AssistMemory["source"] }): AssistMemory {
+ const scope = input.scope ?? (input.projectId ? "project" : "personal");
+ const projectId = scope === "project" ? (input.projectId ?? null) : null;
+ const text = check(input.text, input.category, scope, projectId);
+ const now = Date.now();
+ const same = listMemories({ scope, projectId }).find((m) => key(m.text) === key(text));
+ if (same) {
+ db().prepare("UPDATE assist_memory SET category = ?, text = ?, updated_at = ? WHERE id = ?").run(input.category, text, now, same.id);
+ return getMemory(same.id)!;
+ }
+ const id = nanoid(10);
+ db()
+ .prepare("INSERT INTO assist_memory (id, scope, project_id, category, text, source, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
+ .run(id, scope, projectId, input.category, text, input.source ?? "user", now, now);
+ return getMemory(id)!;
+}
+
+export function updateMemory(id: string, patch: { text?: string; category?: MemoryCategory }): AssistMemory {
+ const cur = getMemory(id);
+ if (!cur) throw new MemoryError("That memory doesn't exist anymore", 404);
+ const text = check(patch.text ?? cur.text, patch.category ?? cur.category, cur.scope, cur.projectId);
+ db().prepare("UPDATE assist_memory SET text = ?, category = ?, updated_at = ? WHERE id = ?").run(text, patch.category ?? cur.category, Date.now(), id);
+ return getMemory(id)!;
+}
+
+export function deleteMemory(id: string): boolean {
+ return db().prepare("DELETE FROM assist_memory WHERE id = ?").run(id).changes > 0;
+}
+
+/** Add many (an import), skipping ones already there. Returns how many were new. */
+export function importMemories(items: { text: string; category: MemoryCategory }[], scope: MemoryScope, projectId: string | null): { added: number; skipped: number } {
+ const existing = new Set(listMemories({ scope, projectId }).map((m) => key(m.text)));
+ let added = 0;
+ db().transaction(() => {
+ for (const it of items.slice(0, 200)) {
+ const t = tidy(it.text).slice(0, MEMORY_MAX_CHARS);
+ if (!t || existing.has(key(t))) continue;
+ existing.add(key(t));
+ addMemory({ text: t, category: it.category, scope, projectId, source: "import" });
+ added++;
+ }
+ })();
+ return { added, skipped: Math.min(items.length, 200) - added };
+}
+
+export function deleteProjectMemories(projectId: string): void {
+ db().prepare("DELETE FROM assist_memory WHERE scope = 'project' AND project_id = ?").run(projectId);
+}
diff --git a/src/server/assist/projects.ts b/src/server/assist/projects.ts
new file mode 100644
index 00000000..4b964a4d
--- /dev/null
+++ b/src/server/assist/projects.ts
@@ -0,0 +1,301 @@
+import "server-only";
+import { nanoid } from "nanoid";
+import { MAX_PROJECT_SOURCES, PROJECT_COLORS, PROJECT_LIMITS, type AssistProject, type ProjectColor, type ProjectSource, type SourceKind } from "@/lib/assist";
+import { db } from "../db";
+import { getElement } from "../elements";
+import { fetchRemote } from "../remote-fetch";
+import { readRef } from "../storage";
+import { deleteProjectMemories } from "./memory";
+
+/**
+ * Assist projects: chats grouped with shared instructions, up to 20 sources (links, files,
+ * images, videos, elements, notes) and project skills (Supercomputer's Projects). New chats in a
+ * project start with its context; its sources are listed to the agent, which reads one in full
+ * with read_source.
+ */
+
+export class ProjectError extends Error {
+ constructor(
+ message: string,
+ readonly status = 400,
+ ) {
+ super(message);
+ }
+}
+
+interface ProjectRow {
+ id: string;
+ name: string;
+ color: string;
+ instructions: string;
+ skills_json: string;
+ use_personal_memory: number;
+ created_at: number;
+ updated_at: number;
+}
+
+interface SourceRow {
+ id: string;
+ project_id: string;
+ kind: SourceKind;
+ title: string;
+ url: string | null;
+ element_id: string | null;
+ content: string | null;
+ status: "ready" | "error";
+ error: string | null;
+ created_at: number;
+}
+
+const EXCERPT = 280;
+
+function toSource(r: SourceRow): ProjectSource {
+ const text = r.content?.trim() ?? "";
+ return {
+ id: r.id,
+ kind: r.kind,
+ title: r.title,
+ ...(r.url && { url: r.url }),
+ ...(r.element_id && { elementId: r.element_id }),
+ ...(text && { excerpt: text.length > EXCERPT ? `${text.slice(0, EXCERPT).replace(/\s+\S*$/, "")}…` : text, chars: text.length }),
+ status: r.status,
+ ...(r.error && { error: r.error }),
+ createdAt: r.created_at,
+ };
+}
+
+function sourcesOf(projectId: string): ProjectSource[] {
+ return (db().prepare("SELECT * FROM assist_project_sources WHERE project_id = ? ORDER BY created_at").all(projectId) as SourceRow[]).map(toSource);
+}
+
+const chatCount = (id: string) => (db().prepare("SELECT COUNT(*) AS n FROM assist_thread_state WHERE project_id = ?").get(id) as { n: number }).n;
+
+function toProject(r: ProjectRow): AssistProject {
+ return {
+ id: r.id,
+ name: r.name,
+ color: (PROJECT_COLORS as readonly string[]).includes(r.color) ? (r.color as ProjectColor) : "iris",
+ instructions: r.instructions,
+ skills: JSON.parse(r.skills_json) as string[],
+ usePersonalMemory: !!r.use_personal_memory,
+ sources: sourcesOf(r.id),
+ chats: chatCount(r.id),
+ createdAt: r.created_at,
+ updatedAt: r.updated_at,
+ };
+}
+
+export function listProjects(): AssistProject[] {
+ return (db().prepare("SELECT * FROM assist_projects ORDER BY updated_at DESC").all() as ProjectRow[]).map(toProject);
+}
+
+export function getProject(id: string): AssistProject | null {
+ const r = db().prepare("SELECT * FROM assist_projects WHERE id = ?").get(id) as ProjectRow | undefined;
+ return r ? toProject(r) : null;
+}
+
+export interface ProjectInput {
+ name?: string;
+ color?: ProjectColor;
+ instructions?: string;
+ skills?: string[];
+ usePersonalMemory?: boolean;
+}
+
+function clean(input: ProjectInput) {
+ const name = input.name?.replace(/\s+/g, " ").trim();
+ if (input.name !== undefined && !name) throw new ProjectError("Give the project a name");
+ if (name && name.length > PROJECT_LIMITS.name) throw new ProjectError(`Keep the name under ${PROJECT_LIMITS.name} characters`);
+ if (input.instructions && input.instructions.length > PROJECT_LIMITS.instructions) throw new ProjectError(`Instructions can be up to ${PROJECT_LIMITS.instructions} characters`);
+ return { ...input, name, skills: input.skills ? [...new Set(input.skills)].slice(0, 30) : undefined };
+}
+
+export function createProject(input: ProjectInput): AssistProject {
+ const c = clean(input);
+ if (!c.name) throw new ProjectError("Give the project a name");
+ const id = nanoid(10);
+ const now = Date.now();
+ db()
+ .prepare("INSERT INTO assist_projects (id, name, color, instructions, skills_json, use_personal_memory, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
+ .run(id, c.name, c.color ?? "iris", c.instructions?.trim() ?? "", JSON.stringify(c.skills ?? []), c.usePersonalMemory === false ? 0 : 1, now, now);
+ return getProject(id)!;
+}
+
+export function updateProject(id: string, input: ProjectInput): AssistProject {
+ const cur = getProject(id);
+ if (!cur) throw new ProjectError("That project doesn't exist anymore", 404);
+ const c = clean(input);
+ db()
+ .prepare("UPDATE assist_projects SET name = ?, color = ?, instructions = ?, skills_json = ?, use_personal_memory = ?, updated_at = ? WHERE id = ?")
+ .run(
+ c.name ?? cur.name,
+ c.color ?? cur.color,
+ c.instructions !== undefined ? c.instructions.trim() : cur.instructions,
+ JSON.stringify(c.skills ?? cur.skills),
+ (c.usePersonalMemory ?? cur.usePersonalMemory) ? 1 : 0,
+ Date.now(),
+ id,
+ );
+ return getProject(id)!;
+}
+
+/** Delete a project with its sources and project memories; its chats become personal chats. */
+export function deleteProject(id: string): boolean {
+ const n = db().transaction(() => {
+ db().prepare("DELETE FROM assist_project_sources WHERE project_id = ?").run(id);
+ deleteProjectMemories(id);
+ db().prepare("UPDATE assist_thread_state SET project_id = NULL WHERE project_id = ?").run(id);
+ return db().prepare("DELETE FROM assist_projects WHERE id = ?").run(id).changes;
+ })();
+ return n > 0;
+}
+
+export function touchProject(id: string): void {
+ db().prepare("UPDATE assist_projects SET updated_at = ? WHERE id = ?").run(Date.now(), id);
+}
+
+// ---------------------------------------------------------------------------
+// Sources
+
+const ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", mdash: "—", ndash: "–", hellip: "…", rsquo: "’", lsquo: "‘", rdquo: "”", ldquo: "“" };
+const decode = (s: string) =>
+ s.replace(/&(#x?[0-9a-f]+|[a-z]+);/gi, (m, e: string) => {
+ if (e[0] === "#") {
+ const n = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
+ return Number.isFinite(n) && n > 0 && n < 0x110000 ? String.fromCodePoint(n) : m;
+ }
+ return ENTITIES[e.toLowerCase()] ?? m;
+ });
+
+/** Readable text from a web page: the title, the description, then the body without scripts, styles or navigation chrome. */
+export function htmlToText(html: string): { title: string; text: string } {
+ const title = decode(/<title[^>]*>([\s\S]*?)<\/title>/i.exec(html)?.[1] ?? "").replace(/\s+/g, " ").trim();
+ const desc = decode(/<meta[^>]+(?:name|property)=["'](?:og:)?description["'][^>]*content=["']([^"']*)["']/i.exec(html)?.[1] ?? "").trim();
+ let body = /<body[^>]*>([\s\S]*)<\/body>/i.exec(html)?.[1] ?? html;
+ body = body
+ .replace(/<!--[\s\S]*?-->/g, " ")
+ .replace(/<(script|style|noscript|svg|template|iframe|nav|footer|form)\b[\s\S]*?<\/\1>/gi, " ")
+ .replace(/<(br|hr)\s*\/?>/gi, "\n")
+ .replace(/<\/(p|div|section|article|li|h[1-6]|tr|blockquote|pre|ul|ol|table|header|main)>/gi, "\n")
+ .replace(/<li[^>]*>/gi, "- ")
+ .replace(/<[^>]+>/g, " ");
+ const text = decode(body)
+ .split("\n")
+ .map((l) => l.replace(/[ \t ]+/g, " ").trim())
+ .filter(Boolean)
+ .join("\n")
+ .replace(/\n{3,}/g, "\n\n");
+ return { title, text: [desc, text].filter(Boolean).join("\n\n") };
+}
+
+const TEXT_TYPE = /^(text\/|application\/(json|xml|x-subrip|x-yaml|yaml|csv|javascript))/;
+
+function insertSource(projectId: string, s: Omit<SourceRow, "id" | "project_id" | "created_at">): ProjectSource {
+ const id = nanoid(10);
+ db()
+ .prepare("INSERT INTO assist_project_sources (id, project_id, kind, title, url, element_id, content, status, error, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
+ .run(id, projectId, s.kind, s.title.slice(0, 160), s.url, s.element_id, s.content?.slice(0, PROJECT_LIMITS.sourceText) ?? null, s.status, s.error, Date.now());
+ touchProject(projectId);
+ return toSource(db().prepare("SELECT * FROM assist_project_sources WHERE id = ?").get(id) as SourceRow);
+}
+
+export type SourceInput =
+ | { kind: "link"; url: string }
+ | { kind: "file"; url: string; name?: string }
+ | { kind: "element"; elementId: string }
+ | { kind: "text"; title?: string; text: string };
+
+/** Fetch a public page through the guarded fetcher (no private addresses, size and time caps). */
+async function fetchLink(url: string): Promise<{ title: string; text: string }> {
+ const res = await fetchRemote(url, { maxBytes: 4_000_000, timeoutMs: 20_000 });
+ const type = res.contentType ?? "";
+ const raw = res.data.toString("utf8");
+ if (/html|xml/.test(type) || /^\s*</.test(raw)) return htmlToText(raw);
+ if (TEXT_TYPE.test(type) || !type) return { title: "", text: raw };
+ throw new Error(`That link is a ${type.split(";")[0]} file, not a page — upload it instead`);
+}
+
+export async function addSource(projectId: string, input: SourceInput): Promise<ProjectSource> {
+ if (!getProject(projectId)) throw new ProjectError("That project doesn't exist anymore", 404);
+ const count = (db().prepare("SELECT COUNT(*) AS n FROM assist_project_sources WHERE project_id = ?").get(projectId) as { n: number }).n;
+ if (count >= MAX_PROJECT_SOURCES) throw new ProjectError(`This project can have up to ${MAX_PROJECT_SOURCES} sources. Remove one to add another.`, 409);
+ switch (input.kind) {
+ case "link": {
+ let url: URL;
+ try {
+ url = new URL(input.url.trim());
+ } catch {
+ throw new ProjectError("That doesn't look like a link — paste the full address, starting with https://");
+ }
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new ProjectError("Only http(s) links can be added");
+ try {
+ const page = await fetchLink(url.toString());
+ if (!page.text.trim()) throw new Error("The page has no readable text (it may need JavaScript)");
+ return insertSource(projectId, { kind: "link", title: page.title || url.hostname + url.pathname.replace(/\/$/, ""), url: url.toString(), element_id: null, content: page.text, status: "ready", error: null });
+ } catch (e) {
+ // Kept with the error so the project still lists the link (and Assist still knows it).
+ return insertSource(projectId, { kind: "link", title: url.hostname + url.pathname.replace(/\/$/, ""), url: url.toString(), element_id: null, content: null, status: "error", error: (e as Error).message.slice(0, 300) });
+ }
+ }
+ case "file": {
+ if (!input.url.startsWith("/api/files/")) throw new ProjectError("Upload the file first");
+ const { data, contentType, name } = await readRef(input.url).catch(() => {
+ throw new ProjectError("That file isn't on this server anymore", 404);
+ });
+ const title = (input.name ?? name).slice(0, 160);
+ const kind: SourceKind = contentType.startsWith("image/") ? "image" : contentType.startsWith("video/") ? "video" : contentType.startsWith("audio/") ? "audio" : "file";
+ if (kind !== "file") return insertSource(projectId, { kind, title, url: input.url, element_id: null, content: null, status: "ready", error: null });
+ if (TEXT_TYPE.test(contentType) || /\.(md|txt|csv|json|srt|vtt|ya?ml)$/i.test(title)) {
+ return insertSource(projectId, { kind: "file", title, url: input.url, element_id: null, content: data.toString("utf8"), status: "ready", error: null });
+ }
+ return insertSource(projectId, {
+ kind: "file",
+ title,
+ url: input.url,
+ element_id: null,
+ content: null,
+ status: "error",
+ error: `Assist can't read ${/\.([a-z0-9]{1,8})$/i.exec(title)?.[1]?.toUpperCase() ?? contentType.split(";")[0]} files yet — paste the text as a note, or add a .txt or .md version`,
+ });
+ }
+ case "element": {
+ const el = getElement(input.elementId);
+ if (!el) throw new ProjectError("That element doesn't exist anymore", 404);
+ const about = [`@${el.handle} — ${el.kind}`, el.description, `${el.references.length} reference photo${el.references.length === 1 ? "" : "s"}`].filter(Boolean).join("\n");
+ return insertSource(projectId, { kind: "element", title: el.name, url: el.references[0] ?? null, element_id: el.id, content: about, status: "ready", error: null });
+ }
+ case "text": {
+ const text = input.text.trim();
+ if (!text) throw new ProjectError("Write the note first");
+ if (text.length > PROJECT_LIMITS.note) throw new ProjectError(`A note can be up to ${PROJECT_LIMITS.note / 1000}k characters`);
+ const title = input.title?.trim() || text.split("\n")[0].slice(0, 60);
+ return insertSource(projectId, { kind: "text", title, url: null, element_id: null, content: text, status: "ready", error: null });
+ }
+ }
+}
+
+/** Fetch a link source again (it failed, or the page changed). */
+export async function refreshSource(projectId: string, sourceId: string): Promise<ProjectSource> {
+ const r = db().prepare("SELECT * FROM assist_project_sources WHERE id = ? AND project_id = ?").get(sourceId, projectId) as SourceRow | undefined;
+ if (!r) throw new ProjectError("That source isn't in this project", 404);
+ if (r.kind !== "link" || !r.url) return toSource(r);
+ try {
+ const page = await fetchLink(r.url);
+ db().prepare("UPDATE assist_project_sources SET title = ?, content = ?, status = 'ready', error = NULL WHERE id = ?").run((page.title || r.title).slice(0, 160), page.text.slice(0, PROJECT_LIMITS.sourceText), sourceId);
+ } catch (e) {
+ db().prepare("UPDATE assist_project_sources SET status = 'error', error = ? WHERE id = ?").run((e as Error).message.slice(0, 300), sourceId);
+ }
+ return toSource(db().prepare("SELECT * FROM assist_project_sources WHERE id = ?").get(sourceId) as SourceRow);
+}
+
+export function deleteSource(projectId: string, sourceId: string): boolean {
+ const n = db().prepare("DELETE FROM assist_project_sources WHERE id = ? AND project_id = ?").run(sourceId, projectId).changes;
+ if (n) touchProject(projectId);
+ return n > 0;
+}
+
+/** A source's full text for the agent (read_source). */
+export function sourceText(projectId: string, sourceId: string): { source: ProjectSource; text: string | null } | null {
+ const r = db().prepare("SELECT * FROM assist_project_sources WHERE id = ? AND project_id = ?").get(sourceId, projectId) as SourceRow | undefined;
+ return r ? { source: toSource(r), text: r.content } : null;
+}
diff --git a/src/server/assist/schemas.ts b/src/server/assist/schemas.ts
index aebc34a9..05e31362 100644
--- a/src/server/assist/schemas.ts
+++ b/src/server/assist/schemas.ts
@@ -1,6 +1,33 @@
import { z } from "zod";
+import { ASSIST_EFFORTS, ASSIST_MODES, MEMORY_CATEGORIES, PROJECT_COLORS } from "@/lib/assist";
export const AssistMessage = z.object({
text: z.string().trim().min(1).max(8000),
attachments: z.array(z.string().startsWith("/api/files/")).max(8).optional(),
});
+
+export const ModeChoice = z.object({
+ mode: z.enum(ASSIST_MODES.map((m) => m.id) as ["free", "smart", "manual"]),
+ agent: z.enum(["claude", "ollama", "offline"]).optional(),
+ model: z.string().max(100).nullish(),
+ effort: z.enum(ASSIST_EFFORTS.map((e) => e.id) as ["low", "medium", "high", "xhigh", "max"]).nullish(),
+});
+
+export const SkillBody = z.object({
+ name: z.string().trim().min(1).max(64),
+ title: z.string().trim().min(1).max(80),
+ description: z.string().trim().min(1).max(1024),
+ whenToUse: z.string().trim().max(1024).optional(),
+ body: z.string().min(1).max(60_000),
+ icon: z.string().max(40).optional(),
+});
+
+export const MemoryCategorySchema = z.enum(MEMORY_CATEGORIES);
+
+export const ProjectBody = z.object({
+ name: z.string().trim().min(1).max(60).optional(),
+ color: z.enum(PROJECT_COLORS).optional(),
+ instructions: z.string().max(8000).optional(),
+ skills: z.array(z.string().max(64)).max(30).optional(),
+ usePersonalMemory: z.boolean().optional(),
+});
diff --git a/src/server/assist/unzip.ts b/src/server/assist/unzip.ts
new file mode 100644
index 00000000..5d876342
--- /dev/null
+++ b/src/server/assist/unzip.ts
@@ -0,0 +1,124 @@
+import "server-only";
+import zlib from "node:zlib";
+
+/**
+ * A small, bounded ZIP reader for skill uploads (.zip / .skill): stored and deflated entries only,
+ * read into memory with per-file and total size caps (a zip bomb stops at the cap). Nothing is
+ * written to disk, so entry paths are only names.
+ */
+
+export interface ZipEntry {
+ name: string;
+ data: Buffer;
+}
+
+export class ZipError extends Error {}
+
+const EOCD = 0x06054b50;
+const CENTRAL = 0x02014b50;
+const LOCAL = 0x04034b50;
+
+export function unzip(buf: Buffer, limits: { maxEntries?: number; maxFileBytes?: number; maxTotalBytes?: number } = {}): ZipEntry[] {
+ const maxEntries = limits.maxEntries ?? 300;
+ const maxFile = limits.maxFileBytes ?? 2_000_000;
+ const maxTotal = limits.maxTotalBytes ?? 8_000_000;
+ // The end-of-central-directory record sits in the last 22 + 65,535 bytes (comment included).
+ let eocd = -1;
+ for (let i = buf.length - 22; i >= Math.max(0, buf.length - 22 - 0xffff); i--) {
+ if (buf.readUInt32LE(i) === EOCD) {
+ eocd = i;
+ break;
+ }
+ }
+ if (eocd < 0) throw new ZipError("That file isn't a ZIP archive");
+ const count = buf.readUInt16LE(eocd + 10);
+ const dirOffset = buf.readUInt32LE(eocd + 16);
+ if (count === 0xffff || dirOffset === 0xffffffff) throw new ZipError("ZIP64 archives aren't supported — zip the skill folder with a standard tool");
+ if (count > maxEntries) throw new ZipError(`The archive has ${count} files; a skill can have up to ${maxEntries}`);
+ const out: ZipEntry[] = [];
+ let total = 0;
+ let p = dirOffset;
+ for (let n = 0; n < count; n++) {
+ if (p + 46 > buf.length || buf.readUInt32LE(p) !== CENTRAL) throw new ZipError("The archive is damaged (central directory)");
+ const flags = buf.readUInt16LE(p + 8);
+ const method = buf.readUInt16LE(p + 10);
+ const compressed = buf.readUInt32LE(p + 20);
+ const size = buf.readUInt32LE(p + 24);
+ const nameLen = buf.readUInt16LE(p + 28);
+ const extraLen = buf.readUInt16LE(p + 30);
+ const commentLen = buf.readUInt16LE(p + 32);
+ const local = buf.readUInt32LE(p + 42);
+ const name = buf.subarray(p + 46, p + 46 + nameLen).toString(flags & 0x800 ? "utf8" : "latin1");
+ p += 46 + nameLen + extraLen + commentLen;
+ if (name.endsWith("/")) continue;
+ if (flags & 0x1) throw new ZipError("The archive is password-protected");
+ if (size > maxFile) throw new ZipError(`${name} is over ${Math.round(maxFile / 1_000_000)} MB`);
+ total += size;
+ if (total > maxTotal) throw new ZipError(`The archive unpacks to more than ${Math.round(maxTotal / 1_000_000)} MB`);
+ if (local + 30 > buf.length || buf.readUInt32LE(local) !== LOCAL) throw new ZipError("The archive is damaged (local header)");
+ const start = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
+ const raw = buf.subarray(start, start + compressed);
+ let data: Buffer;
+ if (method === 0) data = Buffer.from(raw);
+ else if (method === 8) {
+ try {
+ data = zlib.inflateRawSync(raw, { maxOutputLength: maxFile + 1 });
+ } catch {
+ throw new ZipError(`Couldn't unpack ${name}`);
+ }
+ } else throw new ZipError(`${name} uses a compression method Fuobe can't read (${method})`);
+ if (data.length > maxFile) throw new ZipError(`${name} is over ${Math.round(maxFile / 1_000_000)} MB`);
+ out.push({ name, data });
+ }
+ return out;
+}
+
+/** A minimal stored ZIP writer (tests and skill export). */
+export function zipStored(files: { name: string; data: Buffer }[]): Buffer {
+ const crcTable = Array.from({ length: 256 }, (_, n) => {
+ let c = n;
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ return c >>> 0;
+ });
+ const crc32 = (b: Buffer) => {
+ let c = 0xffffffff;
+ for (const x of b) c = crcTable[(c ^ x) & 0xff] ^ (c >>> 8);
+ return (c ^ 0xffffffff) >>> 0;
+ };
+ const locals: Buffer[] = [];
+ const centrals: Buffer[] = [];
+ let offset = 0;
+ for (const f of files) {
+ const name = Buffer.from(f.name, "utf8");
+ const crc = crc32(f.data);
+ const lh = Buffer.alloc(30);
+ lh.writeUInt32LE(LOCAL, 0);
+ lh.writeUInt16LE(20, 4);
+ lh.writeUInt16LE(0x800, 6);
+ lh.writeUInt32LE(crc, 14);
+ lh.writeUInt32LE(f.data.length, 18);
+ lh.writeUInt32LE(f.data.length, 22);
+ lh.writeUInt16LE(name.length, 26);
+ const ch = Buffer.alloc(46);
+ ch.writeUInt32LE(CENTRAL, 0);
+ ch.writeUInt16LE(20, 4);
+ ch.writeUInt16LE(20, 6);
+ ch.writeUInt16LE(0x800, 8);
+ ch.writeUInt32LE(crc, 16);
+ ch.writeUInt32LE(f.data.length, 20);
+ ch.writeUInt32LE(f.data.length, 24);
+ ch.writeUInt16LE(name.length, 28);
+ ch.writeUInt32LE(offset, 42);
+ locals.push(lh, name, f.data);
+ centrals.push(ch, name);
+ offset += 30 + name.length + f.data.length;
+ }
+ const dir = Buffer.concat(centrals);
+ const end = Buffer.alloc(22);
+ end.writeUInt32LE(EOCD, 0);
+ end.writeUInt16LE(files.length, 8);
+ end.writeUInt16LE(files.length, 10);
+ end.writeUInt32LE(dir.length, 12);
+ end.writeUInt32LE(offset, 16);
+ return Buffer.concat([...locals, dir, end]);
+}
diff --git a/src/server/db.ts b/src/server/db.ts
index 73575c8d..31778580 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -175,6 +175,66 @@ const MIGRATIONS: string[] = [
edited_at INTEGER
);
CREATE INDEX IF NOT EXISTS canvases_updated ON canvases(updated_at DESC);`,
+ // Assist (assist-skills): user skills and built-in toggles, projects with their sources, typed
+ // memories, and per-chat state (project, mode, loaded skills, the context the model was given).
+ `CREATE TABLE IF NOT EXISTS skills (
+ name TEXT PRIMARY KEY,
+ title TEXT NOT NULL,
+ description TEXT NOT NULL,
+ when_to_use TEXT NOT NULL DEFAULT '',
+ body TEXT NOT NULL,
+ meta_json TEXT NOT NULL DEFAULT '{}',
+ files_json TEXT NOT NULL DEFAULT '[]',
+ enabled INTEGER NOT NULL DEFAULT 1,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+ );
+ CREATE TABLE IF NOT EXISTS skill_toggles (name TEXT PRIMARY KEY, enabled INTEGER NOT NULL);
+ CREATE TABLE IF NOT EXISTS assist_projects (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ color TEXT NOT NULL DEFAULT 'iris',
+ instructions TEXT NOT NULL DEFAULT '',
+ skills_json TEXT NOT NULL DEFAULT '[]',
+ use_personal_memory INTEGER NOT NULL DEFAULT 1,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+ );
+ CREATE TABLE IF NOT EXISTS assist_project_sources (
+ id TEXT PRIMARY KEY,
+ project_id TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ title TEXT NOT NULL,
+ url TEXT,
+ element_id TEXT,
+ content TEXT,
+ status TEXT NOT NULL DEFAULT 'ready',
+ error TEXT,
+ created_at INTEGER NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS assist_project_sources_project ON assist_project_sources(project_id, created_at);
+ CREATE TABLE IF NOT EXISTS assist_memory (
+ id TEXT PRIMARY KEY,
+ scope TEXT NOT NULL DEFAULT 'personal',
+ project_id TEXT,
+ category TEXT NOT NULL,
+ text TEXT NOT NULL,
+ source TEXT NOT NULL DEFAULT 'user',
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS assist_memory_scope ON assist_memory(scope, project_id, updated_at DESC);
+ CREATE TABLE IF NOT EXISTS assist_thread_state (
+ thread_id TEXT PRIMARY KEY,
+ project_id TEXT,
+ mode TEXT,
+ model TEXT,
+ effort TEXT,
+ skills_json TEXT NOT NULL DEFAULT '[]',
+ context TEXT,
+ sent_json TEXT
+ );
+ CREATE INDEX IF NOT EXISTS assist_thread_state_project ON assist_thread_state(project_id);`,
];
declare global {
diff --git a/src/server/skills.ts b/src/server/skills.ts
new file mode 100644
index 00000000..4f6b2d88
--- /dev/null
+++ b/src/server/skills.ts
@@ -0,0 +1,321 @@
+import "server-only";
+import fs from "node:fs";
+import path from "node:path";
+import { parseSkillMd, SKILL_LIMITS, SKILL_NAME_RE, toSkillMd, type Skill, type SkillMeta, type SkillSummary } from "@/lib/assist";
+import { unzip, ZipError } from "./assist/unzip";
+import { db } from "./db";
+
+/**
+ * Assist skills: SKILL.md playbooks the agent loads on demand (Supercomputer's Skills).
+ * Built-ins are folders in `skills/` at the repo root, read from disk (edits apply on the next
+ * request); people's own skills live in the `skills` table. Built-ins can be switched off
+ * (`skill_toggles`) but not edited — duplicate one to change it.
+ */
+
+export class SkillError extends Error {
+ constructor(
+ message: string,
+ readonly status = 400,
+ ) {
+ super(message);
+ }
+}
+
+const BUILTIN_DIR = path.resolve(/*turbopackIgnore: true*/ process.env.FUOBE_SKILLS_DIR ?? path.join(process.cwd(), "skills"));
+
+/** Text files a skill may carry next to SKILL.md (references, examples, templates). */
+const TEXT_FILE = /\.(md|markdown|txt|json|ya?ml|csv|tsv|srt|vtt|html?|css|xml|js|mjs|ts|py|sh)$/i;
+const MAX_FILES = 30;
+const MAX_FILES_BYTES = 400_000;
+
+interface BuiltinEntry {
+ mtime: number;
+ skill: Omit<Skill, "enabled"> | null;
+ error?: string;
+}
+
+declare global {
+ var __fuobeBuiltinSkills: Map<string, BuiltinEntry> | undefined;
+}
+const cache = (globalThis.__fuobeBuiltinSkills ??= new Map());
+
+function readBuiltin(dir: string): BuiltinEntry {
+ const file = path.join(BUILTIN_DIR, dir, "SKILL.md");
+ const mtime = fs.statSync(file).mtimeMs;
+ const hit = cache.get(dir);
+ if (hit && hit.mtime === mtime) return hit;
+ const parsed = parseSkillMd(fs.readFileSync(file, "utf8"));
+ let entry: BuiltinEntry;
+ if (!parsed.ok) entry = { mtime, skill: null, error: parsed.error };
+ else {
+ const files = fs
+ .readdirSync(path.join(BUILTIN_DIR, dir), { recursive: true, withFileTypes: false })
+ .map(String)
+ .filter((f) => f !== "SKILL.md" && TEXT_FILE.test(f))
+ .slice(0, MAX_FILES)
+ .map((f) => ({ path: f.split(path.sep).join("/"), size: fs.statSync(path.join(BUILTIN_DIR, dir, f)).size }));
+ entry = { mtime, skill: { ...parsed.skill, source: "builtin", files, createdAt: mtime, updatedAt: mtime } };
+ }
+ cache.set(dir, entry);
+ if (entry.error) console.warn(`[skills] skills/${dir}/SKILL.md: ${entry.error}`);
+ return entry;
+}
+
+function builtins(): Omit<Skill, "enabled">[] {
+ let dirs: string[];
+ try {
+ dirs = fs
+ .readdirSync(BUILTIN_DIR, { withFileTypes: true })
+ .filter((d) => d.isDirectory() && fs.existsSync(path.join(BUILTIN_DIR, d.name, "SKILL.md")))
+ .map((d) => d.name);
+ } catch {
+ return [];
+ }
+ return dirs.flatMap((d) => {
+ try {
+ const s = readBuiltin(d).skill;
+ return s ? [s] : [];
+ } catch {
+ return [];
+ }
+ });
+}
+
+interface Row {
+ name: string;
+ title: string;
+ description: string;
+ when_to_use: string;
+ body: string;
+ meta_json: string;
+ files_json: string;
+ enabled: number;
+ created_at: number;
+ updated_at: number;
+}
+
+type StoredFile = { path: string; content: string };
+
+function fromRow(r: Row): Skill {
+ const meta = JSON.parse(r.meta_json) as Pick<SkillMeta, "icon" | "studio" | "tags" | "offline">;
+ const files = JSON.parse(r.files_json) as StoredFile[];
+ return {
+ name: r.name,
+ title: r.title,
+ description: r.description,
+ whenToUse: r.when_to_use,
+ body: r.body,
+ ...meta,
+ source: "user",
+ enabled: !!r.enabled,
+ files: files.map((f) => ({ path: f.path, size: Buffer.byteLength(f.content) })),
+ createdAt: r.created_at,
+ updatedAt: r.updated_at,
+ };
+}
+
+function toggles(): Map<string, boolean> {
+ return new Map((db().prepare("SELECT name, enabled FROM skill_toggles").all() as { name: string; enabled: number }[]).map((r) => [r.name, !!r.enabled]));
+}
+
+const summary = ({ body, ...s }: Skill): SkillSummary => ({ ...s, chars: body.length });
+
+/** Every skill, built-in first (by title), then the user's own (newest first). */
+export function listSkills(): SkillSummary[] {
+ return allSkills().map(summary);
+}
+
+function allSkills(): Skill[] {
+ const t = toggles();
+ const builtin = builtins()
+ .map((s) => ({ ...s, enabled: t.get(s.name) ?? true }))
+ .sort((a, b) => a.title.localeCompare(b.title));
+ const names = new Set(builtin.map((s) => s.name));
+ const own = (db().prepare("SELECT * FROM skills ORDER BY created_at DESC").all() as Row[]).map(fromRow).filter((s) => !names.has(s.name));
+ return [...builtin, ...own];
+}
+
+/** Skills the agent may use (enabled), in list order. */
+export function enabledSkills(): Skill[] {
+ return allSkills().filter((s) => s.enabled);
+}
+
+export function getSkill(name: string): Skill | null {
+ if (!SKILL_NAME_RE.test(name)) return null;
+ const b = builtins().find((s) => s.name === name);
+ if (b) return { ...b, enabled: toggles().get(name) ?? true };
+ const r = db().prepare("SELECT * FROM skills WHERE name = ?").get(name) as Row | undefined;
+ return r ? fromRow(r) : null;
+}
+
+/** A file bundled with a skill (built-in folder or upload), as text. */
+export function skillFile(name: string, file: string): string | null {
+ const s = getSkill(name);
+ if (!s || !s.files.some((f) => f.path === file)) return null;
+ if (s.source === "builtin") {
+ const abs = path.resolve(BUILTIN_DIR, name, file);
+ if (!abs.startsWith(path.join(BUILTIN_DIR, name) + path.sep)) return null;
+ return fs.readFileSync(abs, "utf8");
+ }
+ const r = db().prepare("SELECT files_json FROM skills WHERE name = ?").get(name) as { files_json: string } | undefined;
+ return (JSON.parse(r?.files_json ?? "[]") as StoredFile[]).find((f) => f.path === file)?.content ?? null;
+}
+
+/** The skill as a SKILL.md file (download, duplicate). */
+export function skillMarkdown(name: string): string | null {
+ const s = getSkill(name);
+ return s ? toSkillMd(s) : null;
+}
+
+export interface SkillInput {
+ name?: string;
+ title: string;
+ description: string;
+ whenToUse?: string;
+ body: string;
+ icon?: string;
+ studio?: string;
+ tags?: string[];
+}
+
+/** Validate a form the same way an uploaded SKILL.md is validated. */
+function validated(input: SkillInput & { name: string }) {
+ const parsed = parseSkillMd(toSkillMd({ ...input, whenToUse: input.whenToUse ?? "" }));
+ if (!parsed.ok) throw new SkillError(parsed.error.replace("Check SKILL.md and try again: ", "").replace(/^./, (c) => c.toUpperCase()));
+ return parsed.skill;
+}
+
+/** Names the API routes use. */
+const RESERVED = new Set(["upload", "new"]);
+
+function taken(name: string): string | null {
+ if (RESERVED.has(name)) return `“${name}” is reserved — pick another name`;
+ if (builtins().some((s) => s.name === name)) return `/${name} is a built-in skill — pick another name`;
+ if (db().prepare("SELECT 1 FROM skills WHERE name = ?").get(name)) return `You already have a skill called /${name}`;
+ return null;
+}
+
+function insert(s: SkillMeta & { body: string }, files: StoredFile[] = []): Skill {
+ const now = Date.now();
+ const meta = { ...(s.icon && { icon: s.icon }), ...(s.studio && { studio: s.studio }), ...(s.tags?.length && { tags: s.tags }), ...(s.offline && { offline: s.offline }) };
+ db()
+ .prepare(
+ `INSERT INTO skills (name, title, description, when_to_use, body, meta_json, files_json, enabled, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, ?)`,
+ )
+ .run(s.name, s.title, s.description, s.whenToUse, s.body, JSON.stringify(meta), JSON.stringify(files), now, now);
+ return getSkill(s.name)!;
+}
+
+export function createSkill(input: SkillInput): Skill {
+ const name = input.name?.trim() || "";
+ if (!name) throw new SkillError("Give the skill a name");
+ const conflict = taken(name);
+ if (conflict) throw new SkillError(conflict, 409);
+ return insert(validated({ ...input, name }));
+}
+
+export function updateSkill(name: string, patch: Partial<SkillInput>): Skill {
+ const cur = getSkill(name);
+ if (!cur) throw new SkillError("No such skill", 404);
+ if (cur.source === "builtin") throw new SkillError("Built-in skills can't be edited — duplicate it to make your own version", 403);
+ const next = { ...cur, ...Object.fromEntries(Object.entries(patch).filter(([, v]) => v !== undefined)) } as SkillInput & { name: string };
+ const s = validated({ ...next, name: patch.name?.trim() || name });
+ if (s.name !== name) {
+ const conflict = taken(s.name);
+ if (conflict) throw new SkillError(conflict, 409);
+ }
+ const meta = { ...(s.icon && { icon: s.icon }), ...(s.studio && { studio: s.studio }), ...(s.tags?.length && { tags: s.tags }), ...(cur.offline && { offline: cur.offline }) };
+ db()
+ .prepare("UPDATE skills SET name = ?, title = ?, description = ?, when_to_use = ?, body = ?, meta_json = ?, updated_at = ? WHERE name = ?")
+ .run(s.name, s.title, s.description, s.whenToUse, s.body, JSON.stringify(meta), Date.now(), name);
+ return getSkill(s.name)!;
+}
+
+/** A user copy of any skill (the way to change a built-in). */
+export function duplicateSkill(name: string): Skill {
+ const cur = getSkill(name);
+ if (!cur) throw new SkillError("No such skill", 404);
+ let copy = `${name}-copy`.slice(0, SKILL_LIMITS.name);
+ for (let i = 2; taken(copy); i++) copy = `${name.slice(0, SKILL_LIMITS.name - 8)}-copy-${i}`;
+ const files = cur.files.flatMap((f) => {
+ const content = skillFile(name, f.path);
+ return content === null ? [] : [{ path: f.path, content }];
+ });
+ return insert({ ...cur, name: copy, title: `${cur.title} (copy)`.slice(0, SKILL_LIMITS.title) }, files);
+}
+
+export function deleteSkill(name: string): void {
+ const cur = getSkill(name);
+ if (!cur) throw new SkillError("No such skill", 404);
+ if (cur.source === "builtin") throw new SkillError("Built-in skills can't be deleted — switch it off instead", 403);
+ db().prepare("DELETE FROM skills WHERE name = ?").run(name);
+}
+
+export function setSkillEnabled(name: string, enabled: boolean): Skill {
+ const cur = getSkill(name);
+ if (!cur) throw new SkillError("No such skill", 404);
+ if (cur.source === "builtin") db().prepare("INSERT INTO skill_toggles (name, enabled) VALUES (?, ?) ON CONFLICT(name) DO UPDATE SET enabled = excluded.enabled").run(name, enabled ? 1 : 0);
+ else db().prepare("UPDATE skills SET enabled = ?, updated_at = ? WHERE name = ?").run(enabled ? 1 : 0, Date.now(), name);
+ return getSkill(name)!;
+}
+
+export interface ImportResult {
+ skill: Skill;
+ /** Files in the archive that weren't kept (binary, too many, too big). */
+ skipped: string[];
+ replaced: boolean;
+}
+
+/**
+ * Add a skill from an upload: a SKILL.md, or a .zip / .skill archive with exactly one SKILL.md
+ * (at the top or in one folder). Text files beside it are kept as the skill's references.
+ */
+export function importSkill(file: { name: string; data: Buffer }, opts: { replace?: boolean } = {}): ImportResult {
+ const lower = file.name.toLowerCase();
+ let md: string;
+ let files: StoredFile[] = [];
+ const skipped: string[] = [];
+ if (lower.endsWith(".md") || lower.endsWith(".markdown") || lower.endsWith(".txt")) {
+ md = file.data.toString("utf8");
+ } else if (lower.endsWith(".zip") || lower.endsWith(".skill")) {
+ let entries;
+ try {
+ entries = unzip(file.data);
+ } catch (e) {
+ throw new SkillError(e instanceof ZipError ? `${e.message}.` : "Couldn't open that archive.");
+ }
+ entries = entries.filter((e) => !/(^|\/)(__MACOSX|\.DS_Store)(\/|$)/.test(e.name));
+ const docs = entries.filter((e) => /(^|\/)skill\.md$/i.test(e.name));
+ if (!docs.length) throw new SkillError("Check SKILL.md and try again: the archive has no SKILL.md.");
+ // The shallowest SKILL.md is the skill; nested ones (examples) are plain files.
+ const depth = (n: string) => n.split("/").length;
+ docs.sort((a, b) => depth(a.name) - depth(b.name));
+ if (docs.length > 1 && depth(docs[0].name) === depth(docs[1].name)) throw new SkillError("Check SKILL.md and try again: the archive holds more than one skill — upload them one at a time.");
+ const root = docs[0].name.slice(0, docs[0].name.length - "SKILL.md".length);
+ md = docs[0].data.toString("utf8");
+ let bytes = 0;
+ for (const e of entries) {
+ if (e === docs[0]) continue;
+ const rel = e.name.startsWith(root) ? e.name.slice(root.length) : e.name;
+ if (!TEXT_FILE.test(rel) || e.data.includes(0) || files.length >= MAX_FILES || bytes + e.data.length > MAX_FILES_BYTES) {
+ skipped.push(rel);
+ continue;
+ }
+ bytes += e.data.length;
+ files.push({ path: rel, content: e.data.toString("utf8") });
+ }
+ } else {
+ throw new SkillError("Upload a .zip or .skill archive, or a SKILL.md file");
+ }
+ const parsed = parseSkillMd(md);
+ if (!parsed.ok) throw new SkillError(parsed.error);
+ const s = parsed.skill;
+ if (RESERVED.has(s.name)) throw new SkillError(`Check SKILL.md and try again: “${s.name}” is a reserved name — rename it.`);
+ if (builtins().some((b) => b.name === s.name)) throw new SkillError(`/${s.name} is a built-in skill — rename it in SKILL.md (name: …) and upload again`, 409);
+ const exists = !!db().prepare("SELECT 1 FROM skills WHERE name = ?").get(s.name);
+ if (exists && !opts.replace) throw new SkillError(`You already have a skill called /${s.name}`, 409);
+ if (exists) db().prepare("DELETE FROM skills WHERE name = ?").run(s.name);
+ files = files.slice(0, MAX_FILES);
+ return { skill: insert(s, files), skipped, replaced: exists };
+}