Open source CapCut alternative.
TypeScript
feat(site): teach the cut assistant the new editing surface [rebuild]
David Lea9d99739d9bc
diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.tsindex f7c51710..2ed2544b 100644--- a/site/src/cut/lib/aiContext.ts+++ b/site/src/cut/lib/aiContext.ts@@ -1,7 +1,8 @@"use client";import { getClipSpans, totalDuration, useEditor } from "./store";-import { isCrossStyle, type ClipSpan } from "./types";+import { laneCues, subtitleLaneCount } from "./subtitles";+import { isCrossStyle, rectOf, regionLabel, type ClipSpan, type OverlayClip } from "./types";const r = (n: number) => Math.round(n * 100) / 100;@@ -37,6 +38,7 @@ export function buildAiContext(opts?: { fullCues?: boolean }) {const spans = getClipSpans(s.clips, s.assets);const duration = totalDuration(s.clips);const assetById = new Map(s.assets.map((a) => [a.id, a]));+ const subtitleTracks = subtitleLaneCount(s.subtitles);const selection = (() => {if (!s.selection) return null;@@ -59,6 +61,16 @@ export function buildAiContext(opts?: { fullCues?: boolean }) {const a = s.audioClips.find((x) => x.id === id);return a ? { kind, id, ...describeAudio(a, assetById) } : { kind, id };}+ if (kind === "overlayClip") {+ const c = s.overlayClips.find((x) => x.id === id);+ return c ? { kind, id, ...describeOverlayClip(c, assetById) } : { kind, id };+ }+ if (kind === "cue") {+ const c = s.subtitles.cues.find((x) => x.id === id);+ return c+ ? { kind, id, text: c.text, start: r(c.start), end: r(c.end), track: c.lane ?? 0 }+ : { kind, id };+ }const o = s.overlays.find((x) => x.id === id);return o ? { kind, id, ...describeOverlay(o) } : { kind, id };})();@@ -77,6 +89,17 @@ export function buildAiContext(opts?: { fullCues?: boolean }) {skimmer: s.skimTime === null ? null : r(s.skimTime),playing: s.playing,selection,+ // Every project asset, timeline-placed or not. `origin` marks Cut-made+ // media (generated/voiceover/recording/stock/freeze); no origin = a user+ // import shown in the Media panel.+ media: s.assets.slice(0, cueCap).map((a) => ({+ id: a.id,+ name: a.name,+ type: a.type,+ duration: r(a.duration),+ ...(a.origin ? { origin: a.origin } : {}),+ })),+ mediaTruncated: s.assets.length > cueCap,videoTrack: spans.map((sp, index) => ({index,id: sp.clip.id,@@ -90,6 +113,11 @@ export function buildAiContext(opts?: { fullCues?: boolean }) {muted: sp.clip.muted,framing: sp.clip.fit ?? "fit",speed: r(sp.clip.speed ?? 1),+ // The base track is free-positioned: empty stretches play black.+ ...(() => {+ const prevEnd = index === 0 ? 0 : spans[index - 1].start + spans[index - 1].len;+ return sp.start - prevEnd > 0.005 ? { gapBefore: r(sp.start - prevEnd) } : {};+ })(),...(() => {const t = transitionToNext(sp, index, spans);return t ? { transitionToNext: t } : {};@@ -98,13 +126,25 @@ export function buildAiContext(opts?: { fullCues?: boolean }) {? { panX: r(sp.clip.panX ?? 0), panY: r(sp.clip.panY ?? 0) }: {}),})),+ // Video layers composited with the base: track > 0 above it (topmost+ // full-frame clip covers the rest), track < 0 behind it.+ overlayVideo: s.overlayClips.map((c) => ({ id: c.id, ...describeOverlayClip(c, assetById) })),soundtrack: s.audioClips.map((a) => ({ id: a.id, ...describeAudio(a, assetById) })),titles: s.overlays.map((o) => ({ id: o.id, ...describeOverlay(o) })),subtitles: {count: s.subtitles.cues.length,showOnVideo: s.subtitles.showOnVideo,showOnTimeline: s.subtitles.showOnTimeline,- locale: s.subtitles.locale ?? "en-US",+ // One language per track; the active track is what the panel edits and+ // what generation/translation writes to.+ activeTrack: s.subtitleLane,+ tracks: Array.from({ length: subtitleTracks }, (_, i) => ({+ track: i,+ locale:+ s.subtitles.tracks?.[i]?.locale ??+ (i === 0 ? s.subtitles.locale ?? "en-US" : undefined),+ cues: laneCues(s.subtitles, i).length,+ })),status: s.subtitleStatus,// A window of cues by default; when truncated the model calls get_state// for the whole transcript (e.g. "clean up all the captions").@@ -113,6 +153,7 @@ export function buildAiContext(opts?: { fullCues?: boolean }) {start: r(c.start),end: r(c.end),text: c.text,+ ...(subtitleTracks > 1 ? { track: c.lane ?? 0 } : {}),})),cuesTruncated: s.subtitles.cues.length > cueCap,},@@ -126,7 +167,7 @@ export function buildAiContext(opts?: { fullCues?: boolean }) {}function describeAudio(- a: { assetId: string; start: number; in: number; out: number; volume: number; fadeIn?: number; fadeOut?: number; speed?: number; duck?: number },+ a: { assetId: string; start: number; in: number; out: number; volume: number; fadeIn?: number; fadeOut?: number; speed?: number; duck?: number; lane?: number },assets: Map<string, { name: string }>) {const speed = a.speed && a.speed > 0 ? a.speed : 1;@@ -140,15 +181,37 @@ function describeAudio(fadeIn: r(a.fadeIn ?? 0),fadeOut: r(a.fadeOut ?? 0),...(speed !== 1 ? { speed: r(speed) } : {}),+ ...(a.lane ? { lane: a.lane } : {}),// A voiceover: while it plays, other audio ducks to this gain....(a.duck !== undefined ? { duck: r(a.duck) } : {}),};}+function describeOverlayClip(c: OverlayClip, assets: Map<string, { name: string }>) {+ const speed = c.speed && c.speed > 0 ? c.speed : 1;+ const rect = rectOf(c);+ return {+ asset: assets.get(c.assetId)?.name ?? c.assetId,+ track: c.track,+ start: r(c.start),+ len: r((c.out - c.in) / speed),+ in: r(c.in),+ out: r(c.out),+ muted: c.muted,+ ...(c.hidden ? { hidden: true } : {}),+ // The frame region this layer occupies: Full covers the base; Top/Bottom/+ // Left/Right split it; PiP floats inside it.+ layout: regionLabel(rect),+ region: { x: r(rect.x), y: r(rect.y), w: r(rect.w), h: r(rect.h) },+ fit: c.fit ?? "fit",+ ...(speed !== 1 ? { speed: r(speed) } : {}),+ };+}+function describeOverlay(o: {text: string; start: number; end: number; x: number; y: number;size: number; font: string; weight: number; color: string; shadow: boolean; plate: boolean;- plateRadius?: number;+ plateRadius?: number; lane?: number;}) {return {text: o.text,@@ -163,5 +226,6 @@ function describeOverlay(o: {shadow: o.shadow,plate: o.plate,...(o.plateRadius !== undefined && { plateRadius: r(o.plateRadius) }),+ ...(o.lane ? { lane: o.lane } : {}),};}diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex b25f1792..9e7c1193 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -1,13 +1,34 @@"use client";import { apiFetch, apiJson } from "./api";+import { refFromAsset, refFromStockVideo, type AssetRef } from "./assetRef";import { useGenerate } from "./generate";-import { enrichAsset, ensurePeaks } from "./media";-import { getClipSpans, TIMELINE_H_MAX, TIMELINE_H_MIN, totalDuration, useEditor } from "./store";+import { enrichAsset, ensurePeaks, importImage, importStockVideo } from "./media";+import { characterPrompt, stockTitle } from "./stock";+import { STOCK_IMAGES } from "./stockManifest";+import { STOCK_VIDEOS } from "./stockVideoManifest";+import { getClipSpans, nextFreeStart, TIMELINE_H_MAX, TIMELINE_H_MIN, totalDuration, useEditor } from "./store";import { buildAiContext } from "./aiContext";+import { laneCues, subtitleLaneCount } from "./subtitles";import { resolveVoice, synthesizeSpeech, SPEECH_VOICES } from "./tts";import { DUCK_DEFAULT, generateSubtitlesReadout } from "./voiceover";-import { FRAME, IMAGE_CLIP_SECONDS, mediaUrl, TRANSITION_STYLE_IDS, type AudioClip, type FontId, type MediaAsset, type TransitionStyle } from "./types";+import {+ FRAME,+ IMAGE_CLIP_SECONDS,+ LAYOUTS,+ MAX_SUBTITLE_LANES,+ mediaUrl,+ rectOf,+ regionLabel,+ SPEED_MAX,+ SPEED_MIN,+ TRANSITION_STYLE_IDS,+ type AudioClip,+ type FontId,+ type MediaAsset,+ type OverlayClip,+ type TransitionStyle,+} from "./types";const round2 = (n: number) => Math.round(n * 100) / 100;@@ -64,10 +85,18 @@ export async function runAiTool(}const id = String(input.id ?? "");const pool =- kind === "clip" ? s.clips : kind === "audio" ? s.audioClips : kind === "text" ? s.overlays : null;+ kind === "clip"+ ? s.clips+ : kind === "overlayClip"+ ? s.overlayClips+ : kind === "audio"+ ? s.audioClips+ : kind === "text"+ ? s.overlays+ : null;if (!pool) throw new ToolError(`Unknown kind: ${kind}`);if (!pool.some((x) => x.id === id)) throw new ToolError(`No ${kind} with id ${id}.`);- s.select({ kind: kind as "clip" | "audio" | "text", id });+ s.select({ kind: kind as "clip" | "overlayClip" | "audio" | "text", id });return { selection: { kind, id } };}@@ -87,6 +116,99 @@ export async function runAiTool(return { order: useEditor.getState().clips.map((c) => c.id) };}+ case "place_clip": {+ const clip = requireItem(s.clips, input.clipId, "video clip");+ if (!isNum(input.start)) throw new ToolError("start (seconds) is required.");+ const len = (clip.out - clip.in) / (clip.speed && clip.speed > 0 ? clip.speed : 1);+ const taken = s.clips+ .filter((c) => c.id !== clip.id)+ .map((c) => ({+ start: c.start,+ end: c.start + (c.out - c.in) / (c.speed && c.speed > 0 ? c.speed : 1),+ }));+ const at = nextFreeStart(taken, Math.max(0, input.start), len);+ s.updateClip(clip.id, { start: at });+ useEditor.getState().sortClips();+ return {+ id: clip.id,+ start: round2(at),+ ...(Math.abs(at - Math.max(0, input.start)) > 0.005+ ? { note: "That spot was taken — slid right to the next free one." }+ : {}),+ };+ }++ case "add_overlay_video": {+ const asset = requireItem(s.assets, input.asset_id, "project asset");+ if (asset.type !== "video" && asset.type !== "image")+ throw new ToolError("Only video or image assets can sit on a video track.");+ const start = isNum(input.start) ? Math.max(0, input.start) : s.currentTime;+ const track = isNum(input.track) ? Math.round(input.track) : 1;+ if (track === 0) throw new ToolError("Track 0 is the base track — use place_clip for it.");+ s.addVideoFromAsset(asset.id, { kind: "track", track }, start);+ const cur = useEditor.getState();+ const sel = cur.selection;+ const id = sel?.kind === "overlayClip" ? sel.id : null;+ if (!id) throw new ToolError("Could not create the overlay clip.");+ // Same undo step as the add: the layout rides the transient patch.+ if (typeof input.layout === "string")+ cur.updateOverlayClipTransient(id, layoutPatch(input.layout));+ const c = useEditor.getState().overlayClips.find((x) => x.id === id)!;+ return {+ id: c.id,+ track: c.track,+ start: round2(c.start),+ len: round2((c.out - c.in) / (c.speed && c.speed > 0 ? c.speed : 1)),+ layout: regionLabel(rectOf(c)),+ };+ }++ case "update_overlay_video": {+ const c = requireItem(s.overlayClips, input.id, "overlay video clip");+ const asset = s.assets.find((a) => a.id === c.assetId);+ // A still has no source bound, so its clip can stretch to any length.+ const dur = asset?.type === "image" ? Infinity : asset?.duration ?? c.out;+ const patch: Partial<OverlayClip> = {};+ if (isNum(input.start)) patch.start = Math.max(0, input.start);+ if (isNum(input.in)) patch.in = clamp(input.in, 0, dur - 0.1);+ if (isNum(input.out)) patch.out = clamp(input.out, 0.1, dur);+ if (patch.in !== undefined || patch.out !== undefined) {+ if ((patch.out ?? c.out) - (patch.in ?? c.in) < 0.1)+ throw new ToolError("Clip must stay at least 0.1s long.");+ }+ if (isNum(input.track)) {+ const track = Math.round(input.track);+ if (track === 0) throw new ToolError("Track 0 is the base track.");+ patch.track = track;+ }+ if (typeof input.muted === "boolean") patch.muted = input.muted;+ if (typeof input.hidden === "boolean") patch.hidden = input.hidden || undefined;+ if (typeof input.layout === "string") {+ Object.assign(patch, layoutPatch(input.layout));+ } else if (input.region && typeof input.region === "object") {+ const rg = input.region as Record<string, unknown>;+ if (!isNum(rg.x) || !isNum(rg.y) || !isNum(rg.w) || !isNum(rg.h))+ throw new ToolError("region needs numeric x, y, w, h (frame fractions).");+ const w = clamp(rg.w, 0.05, 1);+ const h = clamp(rg.h, 0.05, 1);+ patch.frame = { x: clamp(rg.x, 0, 1 - w), y: clamp(rg.y, 0, 1 - h), w, h };+ }+ if (input.fit === "fit" || input.fit === "fill") patch.fit = input.fit;+ if (isNum(input.speed)) patch.speed = clamp(input.speed, SPEED_MIN, SPEED_MAX);+ if (Object.keys(patch).length === 0) throw new ToolError("Nothing to change.");+ s.updateOverlayClip(c.id, patch);+ const next = useEditor.getState().overlayClips.find((x) => x.id === c.id)!;+ return {+ id: next.id,+ track: next.track,+ start: round2(next.start),+ layout: regionLabel(rectOf(next)),+ fit: next.fit ?? "fit",+ muted: next.muted,+ ...(next.hidden ? { hidden: true } : {}),+ };+ }+case "trim_clip": {const clip = requireItem(s.clips, input.clipId, "video clip");const asset = s.assets.find((a) => a.id === clip.assetId);@@ -119,9 +241,16 @@ export async function runAiTool(}case "delete_item": {- const kind = String(input.kind) as "clip" | "audio" | "text";+ const kind = String(input.kind) as "clip" | "overlayClip" | "audio" | "text";const id = String(input.id ?? "");- const pool = kind === "clip" ? s.clips : kind === "audio" ? s.audioClips : s.overlays;+ const pool =+ kind === "clip"+ ? s.clips+ : kind === "overlayClip"+ ? s.overlayClips+ : kind === "audio"+ ? s.audioClips+ : s.overlays;if (!pool.some((x) => x.id === id)) throw new ToolError(`No ${kind} with id ${id}.`);s.select({ kind, id });s.deleteSelection();@@ -234,10 +363,19 @@ export async function runAiTool(if (!projectId) throw new ToolError("No project open.");const prompt = String(input.prompt ?? "").trim();if (!prompt) throw new ToolError("A prompt is required.");+ const refs = resolveRefAssets(input.reference_asset_ids);// Hosted image generation is synchronous and quick, so wait it out and- // place the still — it lands in Media (and the panel job list) either way.- const job = await useGenerate.getState().generateImage(projectId, prompt);+ // place the still — it lands in the panel job list either way.+ const job = await useGenerate.getState().generateImage(projectId, prompt, {+ ...(input.aspect === "16:9" || input.aspect === "9:16" || input.aspect === "1:1"+ ? { aspect: input.aspect }+ : {}),+ ...(input.resolution === "1K" || input.resolution === "2K" || input.resolution === "4K"+ ? { resolution: input.resolution }+ : {}),+ ...(refs.length > 0 ? { refs } : {}),+ });if (job.status !== "done" || !job.assetId) {throw new ToolError(job.error ?? "Image generation failed.");}@@ -271,6 +409,10 @@ export async function runAiTool(// Veo renders can outrun the assistant tool bridge's 2-minute cap, so// don't block: start the job and place the clip when it lands.+ const refs =+ input.reference_asset_id === undefined+ ? []+ : resolveRefAssets([input.reference_asset_id]);const addToTimeline = input.add_to_timeline !== false;const promptedIndex = isNum(input.index) ? Math.round(input.index) : undefined;void gen.generateVideo(projectId, prompt, {@@ -278,6 +420,11 @@ export async function runAiTool(durationSeconds: isNum(input.duration_seconds)? clamp(Math.round(input.duration_seconds), 4, 8): undefined,+ ...(input.aspect === "16:9" || input.aspect === "9:16" ? { aspect: input.aspect } : {}),+ ...(input.resolution === "720p" || input.resolution === "1080p"+ ? { resolution: input.resolution }+ : {}),+ ...(refs.length > 0 ? { refs } : {}),onDone: addToTimeline? (asset) => maybeAddGeneratedClip(asset.id, { index: promptedIndex }): undefined,@@ -287,24 +434,159 @@ export async function runAiTool(started: true,addToTimeline,note:- "Rendering with Veo — it lands in Media" +- (addToTimeline ? " and on the timeline" : "") ++ "Rendering with Veo — it lands " ++ (addToTimeline ? "on the timeline" : "in the Video panel's renders") +" in a minute or two. Track it in the Video panel.",};}- case "subtitles_generate": {- if (typeof input.locale === "string" && input.locale) {- s.setSubtitlesView({ locale: input.locale });+ case "generate_character_video": {+ const projectId = s.projectId;+ if (!projectId) throw new ToolError("No project open.");+ const id = String(input.character_id ?? "");+ const character = STOCK_VIDEOS.find((v) => v.id === id && v.persona);+ if (!character)+ throw new ToolError(`No talking character with id ${id}. Call stock_search kind:"character".`);+ const line = String(input.line ?? "").trim();+ if (!line) throw new ToolError("line is required — what should they say?");+ const gen = useGenerate.getState();+ const signedIn = gen.signedIn ?? (await gen.probeNow());+ if (!signedIn) throw new ToolError("Sign in to Donkey to generate video.");+ const addToTimeline = input.add_to_timeline !== false;+ const promptedIndex = isNum(input.index) ? Math.round(input.index) : undefined;+ void gen.generateVideo(projectId, characterPrompt(character.persona!, line), {+ tier: input.tier === "high" ? "high" : "fast",+ durationSeconds: isNum(input.duration_seconds)+ ? clamp(Math.round(input.duration_seconds), 4, 8)+ : undefined,+ aspect: character.aspect,+ // The character's own clip seeds the render so the same person+ // delivers the line — composing would swap the face, so it rides raw.+ refs: [refFromStockVideo(character)],+ composeRefs: false,+ onDone: addToTimeline+ ? (asset) => maybeAddGeneratedClip(asset.id, { index: promptedIndex })+ : undefined,+ });+ return {+ kind: "video",+ started: true,+ character: character.id,+ addToTimeline,+ note:+ "Rendering with Veo — it lands " ++ (addToTimeline ? "on the timeline" : "in the Video panel's renders") ++ " in a minute or two. Track it in the Video panel.",+ };+ }++ case "stock_search": {+ const q = String(input.query ?? "").trim().toLowerCase();+ const kindIn =+ input.kind === "video" || input.kind === "image" || input.kind === "character"+ ? input.kind+ : undefined;+ interface Hit {+ id: string;+ kind: "video" | "image" | "character";+ category: string;+ aspect: string;+ duration?: number;+ persona?: string;+ prompt: string;+ tags: string[];}- await s.generateSubtitles();+ const hits: Hit[] = [];+ for (const v of STOCK_VIDEOS) {+ const kind = v.category === "Characters" ? "character" : "video";+ if (kindIn && kindIn !== kind) continue;+ hits.push({+ id: v.id,+ kind,+ category: v.category,+ aspect: v.aspect,+ duration: round2(v.duration),+ ...(v.persona ? { persona: v.persona } : {}),+ prompt: v.prompt,+ tags: v.tags,+ });+ }+ if (!kindIn || kindIn === "image") {+ for (const i of STOCK_IMAGES) {+ hits.push({+ id: i.id,+ kind: "image",+ category: i.category,+ aspect: i.aspect,+ prompt: i.prompt,+ tags: i.tags,+ });+ }+ }+ const words = q.split(/\s+/).filter(Boolean);+ const matches = hits.filter((h) => {+ const hay = [h.id, h.category, h.prompt, h.persona ?? "", ...h.tags]+ .join(" ")+ .toLowerCase();+ return words.every((w) => hay.includes(w));+ });+ const trim = (t: string, n: number) => (t.length > n ? `${t.slice(0, n - 1)}…` : t);+ return {+ results: matches.slice(0, 12).map((h) => ({+ ...h,+ prompt: trim(h.prompt, 160),+ ...(h.persona ? { persona: trim(h.persona, 160) } : {}),+ tags: h.tags.slice(0, 6),+ })),+ total: matches.length,+ ...(matches.length > 12 ? { truncated: true } : {}),+ };+ }++ case "stock_add": {+ const projectId = s.projectId;+ if (!projectId) throw new ToolError("No project open.");+ const id = String(input.id ?? "");+ const vid = STOCK_VIDEOS.find((v) => v.id === id);+ const img = vid ? undefined : STOCK_IMAGES.find((i) => i.id === id);+ if (!vid && !img)+ throw new ToolError(`No stock item with id ${id}. Call stock_search for ids.`);+ const asset = vid+ ? await importStockVideo(projectId, { url: vid.file, name: stockTitle(vid.id) })+ : await importImage(projectId, { url: img!.file, name: stockTitle(img!.id) });+ const addToTimeline = input.add_to_timeline !== false;+ let clipId: string | null = null;+ if (addToTimeline) {+ useEditor+ .getState()+ .addClipFromAsset(asset.id, isNum(input.start) ? Math.max(0, input.start) : undefined);+ const sel = useEditor.getState().selection;+ clipId = sel?.kind === "clip" ? sel.id : null;+ }+ return {+ assetId: asset.id,+ name: asset.name,+ kind: vid ? "video" : "image",+ duration: round2(vid ? asset.duration : IMAGE_CLIP_SECONDS),+ addedToTimeline: addToTimeline,+ clipId,+ };+ }++ case "subtitles_generate": {+ const lane = targetSubtitleTrack(input);+ if (typeof input.locale === "string" && input.locale)+ useEditor.getState().setSubtitleTrackMeta(lane, { locale: input.locale });+ await useEditor.getState().generateSubtitles();const cur = useEditor.getState();if (cur.subtitleStatus === "error")throw new ToolError(cur.subtitleError ?? "Transcription failed.");- if (cur.subtitles.cues.length > 0 && cur.timelineH < 276) cur.setTimelineH(276);+ const made = laneCues(cur.subtitles, lane).length;+ if (made > 0 && cur.timelineH < 276) cur.setTimelineH(276);return {status: cur.subtitleStatus,- cues: cur.subtitles.cues.length,+ track: lane,+ cues: made,note:cur.subtitleStatus === "empty"? "No speech found — no subtitles were added to the video."@@ -318,14 +600,17 @@ export async function runAiTool(| "clean"| "hook"| "punchy";- await s.generateCaptions(style);+ const lane = targetSubtitleTrack(input);+ await useEditor.getState().generateCaptions(style);const cur = useEditor.getState();if (cur.subtitleStatus === "error")throw new ToolError(cur.subtitleError ?? "Captions failed.");- if (cur.subtitles.cues.length > 0 && cur.timelineH < 276) cur.setTimelineH(276);+ const made = laneCues(cur.subtitles, lane).length;+ if (made > 0 && cur.timelineH < 276) cur.setTimelineH(276);return {status: cur.subtitleStatus,- cues: cur.subtitles.cues.length,+ track: lane,+ cues: made,style: cur.subtitles.style,note:cur.subtitleStatus === "empty"@@ -335,14 +620,78 @@ export async function runAiTool(}case "subtitles_from_visuals": {+ const lane = targetSubtitleTrack(input);if (typeof input.locale === "string" && input.locale)- s.setSubtitlesView({ locale: input.locale });- await s.generateVisualSubtitles();+ useEditor.getState().setSubtitleTrackMeta(lane, { locale: input.locale });+ await useEditor.getState().generateVisualSubtitles();const cur = useEditor.getState();if (cur.subtitleStatus === "error")throw new ToolError(cur.subtitleError ?? "Visual captioning failed.");- if (cur.subtitles.cues.length > 0 && cur.timelineH < 276) cur.setTimelineH(276);- return { status: cur.subtitleStatus, cues: cur.subtitles.cues.length };+ const made = laneCues(cur.subtitles, lane).length;+ if (made > 0 && cur.timelineH < 276) cur.setTimelineH(276);+ return { status: cur.subtitleStatus, track: lane, cues: made };+ }++ case "subtitles_add_track": {+ const count = subtitleLaneCount(s.subtitles);+ if (count >= MAX_SUBTITLE_LANES)+ throw new ToolError(`Already at ${MAX_SUBTITLE_LANES} subtitle tracks.`);+ s.addSubtitleTrack(+ typeof input.language === "string" && input.language.trim()+ ? input.language.trim()+ : undefined+ );+ return { track: count, tracks: count + 1 };+ }++ case "subtitles_remove_track": {+ if (!isNum(input.track)) throw new ToolError("track is required.");+ const lane = Math.round(input.track);+ const count = subtitleLaneCount(s.subtitles);+ if (lane < 0 || lane >= count) throw new ToolError(`No subtitle track ${lane}.`);+ if (count <= 1) throw new ToolError("The last subtitle track can't be removed.");+ s.removeSubtitleTrack(lane);+ return { removed: lane, tracks: count - 1 };+ }++ case "subtitles_translate_track": {+ const language = typeof input.language === "string" ? input.language.trim() : "";+ if (!language) throw new ToolError("language (BCP-47, e.g. ko-KR) is required.");+ const subs = s.subtitles;+ const count = subtitleLaneCount(subs);+ const localeOf = (i: number) =>+ subs.tracks?.[i]?.locale ?? (i === 0 ? subs.locale : undefined);+ const hasCues = (i: number) => laneCues(subs, i).length > 0;+ const lanes = Array.from({ length: count }, (_, i) => i);+ const from = isNum(input.from_track)+ ? Math.round(input.from_track)+ : lanes.find(hasCues) ?? -1;+ if (from < 0 || from >= count || !hasCues(from))+ throw new ToolError("No captions to translate — generate subtitles first.");+ // Reuse the track already set to this language, else add one.+ let target = lanes.find((i) => i !== from && localeOf(i) === language) ?? -1;+ if (target < 0) {+ if (count >= MAX_SUBTITLE_LANES)+ throw new ToolError(+ `Already at ${MAX_SUBTITLE_LANES} subtitle tracks — remove one first.`+ );+ s.addSubtitleTrack(language);+ target = count;+ }+ const st = useEditor.getState();+ st.setSubtitleLane(target);+ st.setSubtitleTrackMeta(target, { locale: language });+ await useEditor.getState().translateSubtitleTrack(from);+ const cur = useEditor.getState();+ if (cur.subtitleStatus === "error")+ throw new ToolError(cur.subtitleError ?? "Translation failed.");+ if (cur.timelineH < 276) cur.setTimelineH(276);+ return {+ track: target,+ language,+ from,+ cues: laneCues(cur.subtitles, target).length,+ };}case "list_voices": {@@ -367,8 +716,9 @@ export async function runAiTool(}case "read_subtitles_aloud": {- if (!s.subtitles.cues.some((c) => c.text.trim()))- throw new ToolError("No subtitles to read — generate subtitles first.");+ const lane = targetSubtitleTrack(input);+ if (!laneCues(useEditor.getState().subtitles, lane).some((c) => c.text.trim()))+ throw new ToolError("No subtitles on that track — generate subtitles first.");const voice = resolveVoice(typeof input.voice === "string" ? input.voice : undefined);// The shared readout also re-times the cues to the generated voice's// pace, keeping the word highlighter in step.@@ -491,8 +841,9 @@ export async function runAiTool(case "merge_cue": {const cue = requireItem(s.subtitles.cues, input.id, "subtitle cue");- if (s.subtitles.cues.findIndex((c) => c.id === cue.id) <= 0)- throw new ToolError("That is the first cue — nothing before it to merge into.");+ const mates = laneCues(s.subtitles, cue.lane ?? 0);+ if (mates.findIndex((c) => c.id === cue.id) <= 0)+ throw new ToolError("That is its track's first cue — nothing before it to merge into.");s.mergeCueIntoPrev(cue.id);return { mergedInto: "previous cue" };}@@ -574,6 +925,53 @@ function requireItem<T extends { id: string }>(pool: T[], id: unknown, label: streturn item;}+/** Resolve a subtitle-track tool param (default: the active track), make it+ * the active track — generation, translation, and readout all write there. */+function targetSubtitleTrack(input: Record<string, unknown>): number {+ const s = useEditor.getState();+ const count = subtitleLaneCount(s.subtitles);+ const lane = isNum(input.track) ? Math.round(input.track) : s.subtitleLane;+ if (lane < 0 || lane >= count)+ throw new ToolError(+ `No subtitle track ${lane} — tracks 0–${count - 1} exist (subtitles_add_track adds one).`+ );+ s.setSubtitleLane(lane);+ return lane;+}++/** Map generation reference ids to project assets. Audio can't be looked at,+ * so only image and video assets resolve. */+function resolveRefAssets(ids: unknown): AssetRef[] {+ if (ids === undefined || ids === null) return [];+ const s = useEditor.getState();+ return (Array.isArray(ids) ? ids : [ids]).map((raw) => {+ const asset = s.assets.find((a) => a.id === String(raw));+ if (!asset)+ throw new ToolError(`No project asset with id ${String(raw)} — see media in the editor state.`);+ if (asset.type === "audio")+ throw new ToolError(`"${asset.name}" is audio — visual references must be images or videos.`);+ return refFromAsset(asset);+ });+}++/** An overlay clip's frame patch for a layout preset name. */+const OVERLAY_LAYOUT_KEYS = {+ full: "full",+ top: "top",+ bottom: "bottom",+ left: "left",+ right: "right",+ pip: "corner",+} as const;++function layoutPatch(layout: string): Partial<OverlayClip> {+ const key = OVERLAY_LAYOUT_KEYS[layout as keyof typeof OVERLAY_LAYOUT_KEYS];+ if (!key)+ throw new ToolError(`Unknown layout "${layout}". Use full, top, bottom, left, right, or pip.`);+ const L = LAYOUTS[key];+ return { frame: key === "full" ? undefined : { ...L.rect }, fit: L.fit };+}+/** Append a generated asset to the video track (default) at an optional index.* Shared by generate_image (inline) and generate_video (on the render's* completion). Respects add_to_timeline:false. */diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex c6c9c885..5671fc1e 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -55,23 +55,30 @@ export const AI_TOOLS: AiToolDef[] = [{name: "select",description:- "Select a clip, soundtrack clip, or title (or clear the selection). Selection drives the inspector panel.",+ "Select a clip, overlay video, soundtrack clip, or title (or clear the selection). Selection drives the inspector panel.",inputSchema: obj({- kind: { type: "string", enum: ["clip", "audio", "text", "none"], description: "What to select" },+ kind: { type: "string", enum: ["clip", "overlayClip", "audio", "text", "none"], description: "What to select" },id: str("The item id (omit for kind=none)"),}, ["kind"]),},{name: "split_at",description:- "Split the video (and a selected soundtrack clip) at a time, like pressing S. Omit t to split at the playhead.",+ "Split the video (or a selected soundtrack/overlay clip) at a time, like pressing S. Omit t to split at the playhead.",inputSchema: obj({ t: num("Timeline seconds to cut at (optional)") }),},{name: "move_clip",- description: "Reorder a video clip to a new index on the magnetic track.",+ description:+ "Reorder a base-track video clip to a new index and re-pack the track end-to-end — this closes every gap. To move one clip in time (keeping gaps), use place_clip.",inputSchema: obj({ clipId: str("Video clip id"), toIndex: num("Target index, 0-based") }, ["clipId", "toIndex"]),},+ {+ name: "place_clip",+ description:+ "Move a base-track video clip to a timeline start time (seconds). The base track is free-positioned: gaps are allowed and play black. If another clip occupies that spot, the clip slides right to the next free one.",+ inputSchema: obj({ clipId: str("Video clip id"), start: num("Target timeline start s") }, ["clipId", "start"]),+ },{name: "trim_clip",description:@@ -91,12 +98,55 @@ export const AI_TOOLS: AiToolDef[] = [},{name: "delete_item",- description: "Delete a video clip, soundtrack clip, or title by id.",+ description:+ "Delete a video clip, overlay video, soundtrack clip, or title by id. Every track is free-positioned, so deleting leaves a gap; close it with move_clip if the cut should stay tight.",inputSchema: obj({- kind: { type: "string", enum: ["clip", "audio", "text"], description: "Item kind" },+ kind: { type: "string", enum: ["clip", "overlayClip", "audio", "text"], description: "Item kind" },id: str("Item id"),}, ["kind", "id"]),},+ {+ name: "add_overlay_video",+ description:+ "Put a project video or image asset on an overlay video track, composited with the base: track 1+ sits above it (the topmost full-frame clip covers everything below), negative tracks sit behind it. Pick a layout to share the frame — halves for a split screen, pip for picture-in-picture. Asset ids come from `media` in the editor state.",+ inputSchema: obj({+ asset_id: str("Project asset id (video or image)"),+ start: num("Timeline start s (default: the playhead)"),+ track: num("Video track, non-zero; 1 = first layer above the base, -1 = behind it (default 1)"),+ layout: {+ type: "string",+ enum: ["full", "top", "bottom", "left", "right", "pip"],+ description: "Frame region (default full = covers the frame)",+ },+ }, ["asset_id"]),+ },+ {+ name: "update_overlay_video",+ description:+ "Update an overlay video clip: move it (start, track), trim (in/out), mute, hide, change its frame region (layout preset, or a custom region rect in frame fractions), fit, or speed.",+ inputSchema: obj({+ id: str("Overlay video clip id"),+ start: num("Timeline start s"),+ in: num("Source in s"),+ out: num("Source out s"),+ track: num("Video track, non-zero; positive above the base, negative behind"),+ muted: bool("Mute the clip's own audio"),+ hidden: bool("Hide the layer without deleting it"),+ layout: {+ type: "string",+ enum: ["full", "top", "bottom", "left", "right", "pip"],+ description: "Frame region preset",+ },+ region: obj({+ x: num("Left edge 0..1"),+ y: num("Top edge 0..1"),+ w: num("Width 0..1"),+ h: num("Height 0..1"),+ }, ["x", "y", "w", "h"]),+ fit: { type: "string", enum: ["fit", "fill"], description: "How the video meets its region" },+ speed: num("Playback rate 0.25–4"),+ }, ["id"]),+ },{name: "add_title",description:@@ -173,9 +223,16 @@ export const AI_TOOLS: AiToolDef[] = [{name: "generate_image",description:- "Generate an AI image from a text prompt (Donkey's hosted image model) and add it to the project as a still clip, composed for the project's aspect. Use for B-roll, cover frames, or backgrounds the user doesn't have footage for; when the user asks you to write or improve the prompt itself, put it in chat and wait for them to ask for the image. Returns when the image has landed. By default it also drops the still onto the timeline; pass add_to_timeline:false to only put it in Media. Needs the user signed in to Donkey (spends their credits).",+ "Generate an AI image from a text prompt (Donkey's hosted image model) and add it to the project as a still clip. Use for B-roll, cover frames, or backgrounds the user doesn't have footage for; when the user asks you to write or improve the prompt itself, put it in chat and wait for them to ask for the image. reference_asset_ids attaches project images/video frames the render should draw from (the user's attached references, a clip to restyle) — the prompt is recomposed around them. Returns when the image has landed. By default it also drops the still onto the timeline; pass add_to_timeline:false to keep it off (it stays in the Image panel's renders, where a \"…\" menu files it into Media or the Library). Needs the user signed in to Donkey (spends their credits).",inputSchema: obj({prompt: str("What to depict — be specific about subject, style, and lighting"),+ aspect: { type: "string", enum: ["16:9", "9:16", "1:1"], description: "Image shape (default: the project aspect)" },+ resolution: { type: "string", enum: ["1K", "2K", "4K"], description: "Output detail (default 1K)" },+ reference_asset_ids: {+ type: "array",+ items: { type: "string" },+ description: "Project asset ids (images or videos) to use as visual references",+ },add_to_timeline: bool("Insert the still on the video track (default true)"),index: num("Insert position on the video track (default: end; 0 = first/cover)"),}, ["prompt"]),@@ -183,32 +240,96 @@ export const AI_TOOLS: AiToolDef[] = [{name: "generate_video",description:- "Generate an AI video clip from a text prompt (Donkey's hosted Veo model), framed for the project's aspect. Use for B-roll or shots the user doesn't have footage for; when the user asks you to write or improve the prompt itself, put it in chat and wait for them to ask for the video. This renders remotely and takes a minute or two, so the tool RETURNS IMMEDIATELY — the clip appears in Media (and on the timeline by default) when it finishes; watch the Video panel. Tell the user it's rendering. Pass add_to_timeline:false to only put it in Media. Needs the user signed in to Donkey (spends their credits).",+ "Generate an AI video clip from a text prompt (Donkey's hosted Veo model). Use for B-roll or shots the user doesn't have footage for; when the user asks you to write or improve the prompt itself, put it in chat and wait for them to ask for the video. reference_asset_id seeds the render with one project image or video frame (it becomes the opening frame when the subject is used as-is). This renders remotely and takes a minute or two, so the tool RETURNS IMMEDIATELY — the clip appears in the Video panel's renders (and on the timeline by default) when it finishes. Tell the user it's rendering. Pass add_to_timeline:false to keep it off the timeline. Needs the user signed in to Donkey (spends their credits).",inputSchema: obj({prompt: str("The shot to generate — describe motion, subject, and mood"),tier: { type: "string", enum: ["fast", "high"], description: "fast = quicker/cheaper (default), high = best quality" },duration_seconds: num("Clip length 4–8 seconds (default 8)"),+ aspect: { type: "string", enum: ["16:9", "9:16"], description: "Clip shape (default: the project aspect)" },+ resolution: { type: "string", enum: ["720p", "1080p"], description: "Output detail (default 720p)" },+ reference_asset_id: str("One project asset id (image or video) to seed the render"),add_to_timeline: bool("Insert the clip on the video track (default true)"),index: num("Insert position on the video track (default: end)"),}, ["prompt"]),},+ {+ name: "generate_character_video",+ description:+ "Generate a UGC-style selfie clip of a stock talking character speaking a line you write (Donkey's hosted Veo model). Pick a character id from stock_search kind:\"character\" — each has a persona and look; the same person then delivers the line to camera. Like generate_video this RETURNS IMMEDIATELY and the clip lands in the Video panel's renders (and on the timeline by default) a minute or two later. Needs the user signed in to Donkey (spends their credits).",+ inputSchema: obj({+ character_id: str("Talking-character id from stock_search"),+ line: str("What the character says, spoken to camera"),+ tier: { type: "string", enum: ["fast", "high"], description: "fast = quicker/cheaper (default), high = best quality" },+ duration_seconds: num("Clip length 4–8 seconds (default 8)"),+ add_to_timeline: bool("Insert the clip on the video track (default true)"),+ index: num("Insert position on the video track (default: end)"),+ }, ["character_id", "line"]),+ },+ {+ name: "stock_search",+ description:+ "Search Cut's bundled stock catalogs: footage clips and stock images across Business/Nature/Travel/City/Technology/Anime/Animal/Food categories, plus talking characters (personas for generate_character_video). Stock is local and free — check it before spending generation credits when existing media could serve. Add a match to the project with stock_add.",+ inputSchema: obj({+ query: str("Words to match against prompts, categories, and tags (omit to browse)"),+ kind: { type: "string", enum: ["video", "image", "character"], description: "Limit to one catalog (default: all)" },+ }),+ },+ {+ name: "stock_add",+ description:+ "Import a stock video or image (by stock_search id) into the project and, by default, drop it on the video track. Free — the media ships with Cut.",+ inputSchema: obj({+ id: str("Stock item id from stock_search"),+ add_to_timeline: bool("Place it on the base video track (default true)"),+ start: num("Timeline start s (default: appended at the end)"),+ }, ["id"]),+ },{name: "subtitles_generate",description:- "Transcribe the cut on-device (Apple speech) and create subtitle captions. Runs in the background; returns when finished. If no speech is found, no subtitles are added.",- inputSchema: obj({ locale: str("BCP-47 locale like en-US (default en-US)") }),+ "Transcribe the cut on-device (Apple speech) and create subtitle captions on a subtitle track (the active one unless `track` says otherwise; other tracks keep their captions). Runs in the background; returns when finished. If no speech is found, no subtitles are added.",+ inputSchema: obj({+ locale: str("Speech language as BCP-47 like en-US (default: the track's language)"),+ track: num("Subtitle track to write, 0-based (default: the active track)"),+ }),},{name: "captions_generate",description:- "Transcribe (if needed) then rewrite the captions into punchy social-video captions — short lines that fit inside the video frame (they may wrap onto two lines but never overflow), a few emoji, a curiosity-hook opener. style: clean | hook | punchy (default hook). Cue timings are preserved.",- inputSchema: obj({ style: str("Caption style: clean, hook, or punchy") }),+ "Transcribe (if needed) then rewrite one subtitle track's captions into punchy social-video captions — short lines that fit inside the video frame (they may wrap onto two lines but never overflow), a few emoji, a curiosity-hook opener. style: clean | hook | punchy (default hook). Cue timings are preserved.",+ inputSchema: obj({+ style: str("Caption style: clean, hook, or punchy"),+ track: num("Subtitle track to rewrite, 0-based (default: the active track)"),+ }),},{name: "subtitles_from_visuals",description:"Caption a cut that has NO usable speech by watching sampled frames and writing timed narration captions (uses the user's Claude login to look at the frames). Use this instead of subtitles_generate when the video is silent b-roll, music-only, or otherwise has nothing to transcribe. Runs in the background; returns when finished.",- inputSchema: obj({ locale: str("BCP-47 locale like en-US (default en-US)") }),+ inputSchema: obj({+ locale: str("Caption language as BCP-47 like en-US (default: the track's language)"),+ track: num("Subtitle track to write, 0-based (default: the active track)"),+ }),+ },+ {+ name: "subtitles_add_track",+ description:+ "Add a subtitle track (up to 3, one language each — e.g. English on track 0, Korean on track 1; each shows as its own caption line, draggable to its own spot). The new track becomes active and starts empty: fill it with subtitles_translate_track, or subtitles_generate in its language.",+ inputSchema: obj({ language: str("The track's language as BCP-47, e.g. ko-KR (optional)") }),+ },+ {+ name: "subtitles_remove_track",+ description: "Remove a subtitle track and its captions; higher tracks shift down.",+ inputSchema: obj({ track: num("Track to remove, 0-based") }, ["track"]),+ },+ {+ name: "subtitles_translate_track",+ description:+ "Translate existing captions into another language on their own subtitle track — the way to answer \"add Korean subtitles\". Reuses the track already set to that language or adds one (max 3), then translates the source track's cues one-to-one, timings kept. The captions must exist first (subtitles_generate).",+ inputSchema: obj({+ language: str("Target language as BCP-47, e.g. ko-KR"),+ from_track: num("Source track, 0-based (default: the first track with captions)"),+ }, ["language"]),},{name: "list_voices",@@ -219,12 +340,12 @@ export const AI_TOOLS: AiToolDef[] = [{name: "voiceover_generate",description:- "Generate a spoken AI voiceover from a script (Donkey's hosted speech model) and drop it on the soundtrack at the playhead (or `start`). Use for 'add a voiceover', 'narrate this', 'read this script aloud'; when the user asks you to write or rework the script itself, put the text in chat and wait for them to ask for the voiceover. Pick a `voice` id from list_voices, or omit for a good default. `direction` steers delivery in natural language; the script itself may carry inline tags like [whispers] or [excited]. `duck` lowers all other audio to that gain while the voice plays (0..1; ~0.3–0.5 is typical, 1 = don't duck). Needs the user signed in to Donkey (spends their credits).",+ "Generate a spoken AI voiceover from a script (Donkey's hosted speech model) and drop it on the soundtrack at the playhead (or `start`). Use for 'add a voiceover', 'narrate this', 'read this script aloud'; when the user asks you to write or rework the script itself, put the text in chat and wait for them to ask for the voiceover. Pick a `voice` id from list_voices, or omit for a good default. `direction` steers delivery in natural language and can ask for another language — 'say it in Spanish' translates the script before synthesis; the script itself may carry inline tags like [whispers] or [excited]. `duck` lowers all other audio to that gain while the voice plays (0..1; ~0.3–0.5 is typical, 1 = don't duck). Needs the user signed in to Donkey (spends their credits).",inputSchema: obj({script: str("What the voice should say"),voice: str("Voice id from list_voices (optional; a sensible default is chosen)"),- direction: str("Delivery instruction, e.g. 'Say warmly, like an old friend' (optional)"),- language: str("Spoken language as BCP-47, e.g. es-US, ja-JP (optional; default auto-detects from the script — write the script in the target language)"),+ direction: str("Delivery instruction, e.g. 'Say warmly, like an old friend'; may include a language ask, which translates the script (optional)"),+ language: str("Pronunciation language as BCP-47, e.g. es-US, ja-JP (optional; default auto-detects — this reads the script as written, it does not translate)"),duck: num("Lower other audio to this gain while the voice plays, 0..1 (default 0.4; 1 = no ducking)"),start: num("Timeline start in seconds (default: the playhead)"),}, ["script"]),@@ -232,12 +353,13 @@ export const AI_TOOLS: AiToolDef[] = [{name: "read_subtitles_aloud",description:- "Speak the existing subtitle cues as an AI voiceover (Donkey's hosted speech model) — each line placed at its own cue time — and add it to the soundtrack. Turns captions into narration. Requires subtitles to exist first (generate them if needed). `duck` lowers other audio under the voice (0..1). Needs the user signed in to Donkey (spends their credits).",+ "Speak one subtitle track's cues as an AI voiceover (Donkey's hosted speech model) — each line placed at its own cue time — and add it to the soundtrack. Turns captions into narration. Requires subtitles to exist first (generate them if needed). `duck` lowers other audio under the voice (0..1). Needs the user signed in to Donkey (spends their credits).",inputSchema: obj({voice: str("Voice id from list_voices (optional)"),- direction: str("Delivery instruction, e.g. 'Narrate briskly, documentary style' (optional)"),- language: str("Spoken language as BCP-47, e.g. es-US, ja-JP (optional; default auto-detects — cues are spoken as written, so translate them first for another language)"),+ direction: str("Delivery instruction, e.g. 'Narrate briskly, documentary style'; may include a language ask, which translates the lines (optional)"),+ language: str("Pronunciation language as BCP-47, e.g. es-US, ja-JP (optional; default auto-detects — reads cues as written; for another language use a translated subtitle track)"),duck: num("Lower other audio to this gain while the voice plays, 0..1 (default 0.4)"),+ track: num("Subtitle track to read, 0-based (default: the active track)"),}),},{@@ -289,7 +411,7 @@ export const AI_TOOLS: AiToolDef[] = [{name: "open_export",description:- "Open the export dialog so the user can render the cut (TikTok 1080p, Quick share 1080p, or Draft 720p). Exporting itself stays a user action.",+ "Open the export dialog so the user can render the cut (presets from Original quality down to Draft 720p). Exporting itself stays a user action.",inputSchema: obj({}),},{@@ -314,7 +436,8 @@ export const AI_TOOLS: AiToolDef[] = [},{name: "merge_cue",- description: "Merge a subtitle cue into the one before it (joins their text and timing). Not valid for the first cue.",+ description:+ "Merge a subtitle cue into the previous cue on its own track (joins their text and timing). Not valid for a track's first cue.",inputSchema: obj({ id: str("Cue id to merge into its predecessor") }, ["id"]),},{@@ -353,24 +476,28 @@ export const AI_TOOLS: AiToolDef[] = [export const AI_SKILLS: Record<string, string> = {"editor-overview": `# Cut editor overviewCut is a local, project-based short-video editor. Each project has an output aspect — 9:16 vertical (1080×1920, TikTok/Reels/Shorts) or 16:9 widescreen (1920×1080, YouTube) — switchable from the pill in the top bar; the current one is in editor_state project.aspect. Layout:-- Left icon rail tabs: Media (project files + Exports list), Library (shared reusable assets), Video (generate AI video), Image (generate AI images), Audio (AI voiceover + audio files), Text (title presets), Subtitles (transcript editor), Publish (caption/tags/sound metadata). Camera/mic recording lives in the top bar next to the aspect picker; recordings land in Media.+- Left icon rail tabs: Media (user-imported files + Exports list), Library (shared reusable assets), Video (stock clip browser — footage + talking characters — beside the AI video generator), Image (stock images beside the AI image generator), Audio (AI voiceover + audio files), Text (title presets), Subtitles (transcript editor), Publish (caption/tags/sound metadata). Camera/mic recording lives in the top bar next to the aspect picker.+- Media shows only what the user imported. Everything Cut makes carries an origin tag (generated, voiceover, recording, stock, freeze — see \`media\` in editor_state) and lives where it was created, e.g. generated clips in the Video panel's job list; a "…" menu on each files it into Media or the Library.- Center: the video preview canvas (composited at the project's frame size) with draggable text overlays and subtitle captions.-- Right: the Inspector — its content follows the selection (video clip, soundtrack clip, or title).-- Bottom: the timeline (resizable by dragging its top border). Tracks top-to-bottom: video (magnetic, clips snap end-to-end), soundtrack (free-positioned green clips), titles (purple bars), subtitles (amber cue bars, when enabled).+- Right: the Inspector — its content follows the selection (video clip, overlay video, soundtrack clip, title, or cue).+- Bottom: the timeline (resizable by dragging its top border). Rows top-to-bottom: overlay video tracks above the base, the base video track, overlay tracks behind it, soundtrack lanes (green), titles (purple), subtitle tracks (amber, when enabled). Every track is free-positioned in time.Everything autosaves to the project folder. Undo/redo is unlimited (⌘Z / ⇧⌘Z).Times are in seconds on the shared timeline. The playhead is currentTime; a skimmer previews under the mouse without moving the playhead.`,"timeline-editing": `# Timeline editing-- Video track is magnetic: clips are ordered by index; there are no gaps. move_clip reorders. A clip's timeline length is (out-in)/speed; total duration = the sum of those minus any cross-style transition overlaps.+- Every track is free-positioned: items carry a start time, gaps are allowed, and a base-track gap plays black (and silence). Deleting leaves a gap. videoTrack entries in editor_state report gapBefore where one exists.+- Two ways to move a base clip: place_clip sets its start (respects gaps, slides right if the spot is taken); move_clip reorders by index and re-packs the whole track end-to-end — the right call for "put this first" or "tighten the cut", wrong when the user laid out deliberate gaps. Index-based inserts (freeze_frame, generated clips) also re-pack.+- Overlay video: a video/image asset can sit on a track above the base (track 1, 2… — topmost wins) or behind it (track -1…). A full-frame overlay covers the base; give it a layout to share the frame — top/bottom/left/right halves for a split screen, pip for a floating corner box, or a custom region rect. add_overlay_video creates one from a media asset; update_overlay_video moves/trims/regions/mutes/hides it. The user makes them by dragging media above/below the base track; they drag the region in the preview.+- A clip's timeline length is (out-in)/speed; total duration runs to the last clip's end, gaps included, minus cross-style transition overlaps.- trim_clip changes in/out inside the source media. in >= 0, out <= source duration, out-in >= 0.1.- set_speed sets a clip's playback rate (0.25–4×); it changes the clip's timeline length, and later titles/captions ripple to stay in sync.- set_transition joins a clip into the next one (0–2s, six styles) — read the transitions-and-fades skill before styling cuts. Splitting or deleting clears the affected transition.-- split_at cuts the clip under that time into two clips at the exact frame. With a soundtrack clip selected it splits that instead.-- delete_item removes items; the video track closes the gap automatically. The user can multi-select (⌘/⇧-click) and delete several at once.+- split_at cuts the base clip under that time into two clips at the exact frame. With a soundtrack or overlay clip selected it splits that instead.+- The user can multi-select (⌘/⇧-click) and delete several items at once; a hover chip on each video clip toggles its own audio.- detach_audio lifts a video clip's sound to the soundtrack track (and mutes the clip) so audio can be cut independently of video.- freeze_frame grabs one frame (default: the playhead — what the user currently sees) as a still clip and inserts it, by default at index 0 as a cover/hook frame ("make this the first frame"). The still is baked at the project's current aspect with the clip's framing applied; if the user later switches aspect they should capture a fresh one.- set_framing: per-clip Fit (letterbox) vs Fill (crop to cover the project frame). In Fill, panX/panY position the crop window; the user can also drag the video directly in the preview. The control lives in the Inspector under "Framing" when a video clip is selected. Landscape footage usually wants fill + a pan that keeps the subject.-- The user can copy/paste any selected segment (video, audio, title) with ⌘C/⌘V; pastes land at the playhead.+- The user can copy/paste any selected segment (video, overlay video, audio, title) with ⌘C/⌘V; pastes aim for the playhead and slide right to free space.- Zoom: set_view pxPerSec (12..800) or fit. The timeline panel height: set_view timelineH (170..600).`,"transitions-and-fades": `# Transitions & fades@@ -394,22 +521,27 @@ Good TikTok titles: short punchy lines, high contrast (white/yellow + shadow orTitles burn into the export exactly as previewed.`,"audio-and-subtitles": `# Audio, voiceover & subtitles-Soundtrack clips: volume 0..1.5, fadeIn/fadeOut seconds (max half the clip), start = timeline position, in/out = trim inside the source. Fades render with ffmpeg afade on export.+Soundtrack clips: volume 0..1.5, fadeIn/fadeOut seconds (max half the clip), start = timeline position, in/out = trim inside the source; clips can spread across several soundtrack lanes (the \`lane\` field), new sounds slide to free space in their lane. Fades render with ffmpeg afade on export.Ducking: a soundtrack clip's \`duck\` (0..1, via update_audio) lowers ALL other audio — video-clip sound and other music — to that gain while the clip plays; 1 clears it. Voiceovers set this so narration sits over quieter music. It applies in both the preview and the export.Voiceover (Donkey's hosted speech model — signed in, spends credits, like image/video generation):-- voiceover_generate(script, voice?, direction?, duck?, start?, language?): synthesizes the script and drops it on the soundtrack at the playhead (or start). Defaults to a 0.4 duck so it sits over other audio. Voices are Gemini's prebuilt set — list_voices returns them (id + one-word character like Warm, Upbeat, Gravelly); omit voice for a good default. \`direction\` steers delivery in natural language ("Say warmly, like an old friend"); the script itself can carry inline tags like [whispers], [excited], [laughs].-- read_subtitles_aloud(voice?, direction?, duck?): speaks the existing subtitle cues, each line at its own cue time — captions become narration. Needs cues first.-Subtitles: subtitles_generate transcribes the cut's audio on-device (Apple speech, macOS 26); cues are caption-sized (≈38 chars). subtitles_from_visuals is the fallback for a cut with NO speech — it watches sampled frames (via the user's Claude login) and writes timed narration captions of what's on screen. So: speech present → subtitles_generate; silent/music-only footage the user wants captioned → subtitles_from_visuals. Never fabricate a spoken transcript.-captions_generate rewrites existing cues into punchy social captions (emoji, curiosity-hook opener) in a style (clean/hook/punchy), keeping timings — use it when the ask is social/TikTok captions rather than a plain transcript.-Editing: update_cue (text or retime), delete_cue, merge_cue. In the panel, Return splits a caption at the cursor onto real word timings; hand-edited text drops its word timings.-subtitles_set_view: showOnVideo (preview + export burn-in), showOnTimeline (amber cue track).-Caption look: the Subtitles panel offers 10 visual presets (clean, hook, punchy, minimal, editorial, typewriter, block, highlight, bubble, neon), a per-word karaoke highlight with accent overrides, and the caption block drags to a new spot in the preview. No tool sets the look — direct the user to the panel. captions_generate's clean/hook/punchy choice shapes the caption text it writes; the visual preset is separate.`,+- voiceover_generate(script, voice?, direction?, duck?, start?, language?): synthesizes the script and drops it on the soundtrack at the playhead (or start). Defaults to a 0.4 duck so it sits over other audio. Voices are Gemini's prebuilt set — list_voices returns them (id + one-word character like Warm, Upbeat, Gravelly); omit voice for a good default. \`direction\` steers delivery in natural language ("Say warmly, like an old friend") and may ask for another language — "say it in Spanish" translates the script before synthesis; the script itself can carry inline tags like [whispers], [excited], [laughs]. \`language\` only pins pronunciation of the text as written.+- read_subtitles_aloud(voice?, direction?, duck?, track?): speaks one subtitle track's cues, each line at its own cue time — captions become narration. Needs cues first. The Inspector offers the same per-clip: "Generate audio for clip" transcribes just that clip when it has no cues yet, then voices it.+Subtitle tracks: a project carries up to 3, one language each (editor_state subtitles.tracks; each cue's \`track\`). Each track shows its own caption line, dragged to its own spot; all share one visual style. The panel and generation write to the ACTIVE track — the track tool param switches it. subtitles_add_track / subtitles_remove_track manage them; subtitles_translate_track("ko-KR") is the whole "add Korean subtitles" flow when captions exist (it adds/reuses the track and translates cue-for-cue).+Generating: subtitles_generate transcribes the cut's audio on-device (Apple speech, macOS 26) onto the target track; cues are caption-sized (≈38 chars). subtitles_from_visuals is the fallback for a cut with NO speech — it watches sampled frames (via the user's Claude login) and writes timed narration captions of what's on screen. So: speech present → subtitles_generate; silent/music-only footage the user wants captioned → subtitles_from_visuals. Never fabricate a spoken transcript.+captions_generate rewrites a track's cues into punchy social captions (emoji, curiosity-hook opener) in a style (clean/hook/punchy), keeping timings — use it when the ask is social/TikTok captions rather than a plain transcript.+Editing: update_cue (text or retime), delete_cue, merge_cue (joins into the previous cue on the same track). In the panel, Return splits a caption at the cursor onto real word timings; hand-edited text drops its word timings.+subtitles_set_view: showOnVideo (preview + export burn-in), showOnTimeline (amber cue rows).+Caption look: the Subtitles panel offers 10 visual presets (clean, hook, punchy, minimal, editorial, typewriter, block, highlight, bubble, neon), a per-word karaoke highlight with accent overrides, and each track's caption drags to a new spot in the preview. No tool sets the look — direct the user to the panel. captions_generate's clean/hook/punchy choice shapes the caption text it writes; the visual preset is separate.`,- "ai-generation": `# AI image & video generation-Cut can generate media the user doesn't have footage for, through Donkey's hosted models (generation — images, video, voiceovers — is the signed-in, credit-spending feature; everything else is local and free). Both land the result in the project's Media and, by default, drop it on the timeline.-- generate_image(prompt, add_to_timeline?, index?): a hosted image model renders the prompt; the image is baked into an 8s still clip framed for the project aspect. Great for a cover/hook frame (index 0), a background, or a b-roll still. Slower footage the user lacks → generate it rather than asking them to find it.-- generate_video(prompt, tier?, duration_seconds?, add_to_timeline?, index?): a hosted Veo model renders a short clip (4–8s) with audio, framed for the project aspect. tier "fast" (default) is quicker/cheaper, "high" is best quality. This takes a minute or two, so the tool returns right away and the clip appears in Media (and on the timeline by default) when it finishes — tell the user it's rendering. Don't call it again for the same shot while one is in flight.-Both compose for editor_state project.aspect, so set the aspect first if the user wants a different frame. If either fails with a sign-in or credits message, relay that plainly — generation needs the user signed in to Donkey with credits; it is not a local fallback. Write vivid, specific prompts (subject, style, lighting, motion); the user's request is usually shorthand, so flesh it out.`,+ "ai-generation": `# Stock media & AI generation+Two ways to get footage the user doesn't have: bundled stock (local, free) and hosted generation (signed in, spends credits). Prefer stock when it genuinely fits; generate when the shot needs to be specific.+Stock: stock_search browses the bundled catalogs — footage clips and images in 8 categories plus ~20 UGC talking characters — matching prompts, categories, and tags. stock_add imports an item into the project (origin "stock") and drops it on the timeline. In the UI these live in the Video and Image tabs beside the generators; clicking a stock tile seeds the generate panel with its prompt.+Generation:+- generate_image(prompt, aspect?, resolution?, reference_asset_ids?, add_to_timeline?, index?): the hosted image model renders the prompt at 16:9, 9:16, or 1:1 (default: project aspect) and 1K/2K/4K. The image rides the base track as a still clip (8s default, stretchable). Great for a cover/hook frame (index 0), a background, or a b-roll still.+- generate_video(prompt, tier?, duration_seconds?, aspect?, resolution?, reference_asset_id?, add_to_timeline?, index?): a hosted Veo model renders a 4–8s clip with audio. tier "fast" (default) is quicker/cheaper, "high" is best quality. This takes a minute or two, so the tool returns right away and the clip appears in the Video panel's renders (and on the timeline by default) when it finishes — tell the user it's rendering. Don't call it again for the same shot while one is in flight.+- generate_character_video(character_id, line, …): a stock talking character delivers a line to camera, same async render as generate_video. Characters come from stock_search kind:"character" — each has a persona; you write the line (chat deliverable rules apply: asked for "a script", write it in chat first).+References: users attach images/clips to their message or the generate panels; project asset ids (see \`media\` in editor_state, including attachments — OS drops become project assets) pass through reference_asset_ids / reference_asset_id. A model recomposes the prompt around them: for video at most one image survives as the literal opening frame; for images any number can be drawn from. When the user says "use this clip/image", pass the reference — don't just describe it in the prompt.+If generation fails with a sign-in or credits message, relay that plainly — it needs the user signed in to Donkey with credits; it is not a local fallback. Write vivid, specific prompts (subject, style, lighting, motion); the user's request is usually shorthand, so flesh it out.`,"publish-and-export": `# Publish & exportPublish tab fields (set_publish): caption (TikTok limit 4,000 chars INCLUDING tags/emoji; hook in the first line), tags (3–5 focused tags recommended; stored space-separated, rendered as #tags), soundTitle (TikTok lets you rename the sound once after posting), handle (shown as @handle in platform previews).@@ -430,7 +562,7 @@ Rules:- Read list_skills / read_skill before working in an area you're unsure about — they document every setting.- Don't transcribe a video with no speech. If the user wants captions on silent footage, use subtitles_from_visuals (it narrates what's on screen). Never invent a spoken transcript.- Voiceovers duck other audio by default so they stay audible. Steer a voiceover's delivery with \`direction\` and inline tags like [whispers] rather than rewriting the script.-- generate_image / generate_video / voiceover_generate / read_subtitles_aloud make media through hosted models (spends the user's Donkey credits, needs sign-in); call them when the user asked for the media itself — a request for the prompt or script gets text in chat. Default to adding the result to the timeline; write a rich, specific prompt from their shorthand. generate_video takes a minute or two.+- generate_image / generate_video / generate_character_video / voiceover_generate / read_subtitles_aloud make media through hosted models (spends the user's Donkey credits, needs sign-in); call them when the user asked for the media itself — a request for the prompt or script gets text in chat. Bundled stock media (stock_search / stock_add) is free — use it when it fits. Media the user attached is in \`media\`; pass those asset ids as generation references when they say "use this". Default to adding the result to the timeline; write a rich, specific prompt from their shorthand. Video renders take a minute or two.- capture_frame shows you the actual rendered frame when visual judgment matters.`;}