Open source CapCut alternative.
TypeScript
feat(site): give the Cut assistant a generate_music tool [rebuild]
David Le584c222b612a
diff --git a/site/scripts/eval-cut-chat.ts b/site/scripts/eval-cut-chat.tsindex 561a30ec..4e720e01 100644--- a/site/scripts/eval-cut-chat.ts+++ b/site/scripts/eval-cut-chat.ts@@ -640,6 +640,23 @@ function cases(audio: { dataBase64: string; mimeType: string }): EvalCase[] {},},},+ {+ // Background music goes straight to generate_music (not voiceover, which+ // is speech; not generate_scene, which is a whole narrated production).+ name: "music-ask-single-generate",+ input: () => [userTurn("add some chill background music to this video")],+ reply: /music|track|bed|chill|background/i,+ requiredTools: ["generate_music"],+ maxToolCalls: 3,+ stubs: {+ generate_music: {+ assetId: "a-music1",+ name: "chill background music",+ duration: 30,+ addedToTimeline: false,+ },+ },+ },{// Fast path: a direct edit is one trim_clip on the clip in the snapshot.name: "trim-ask-single-tool",diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 265d55fd..e901e17b 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -26,6 +26,8 @@ import { STOCK_VIDEOS } from "./stockVideoManifest";import { baseClips, getClipSpans, nextFreeStart, overlayLayers, TIMELINE_H_MAX, TIMELINE_H_MIN, totalDuration, useEditor } from "./store";import { buildAiContext } from "./aiContext";import { laneCues, subtitleLaneCount } from "./subtitles";+import { synthesizeMusic } from "./audioGen";+import { stockAssetInDoc } from "./genvideo/docWriter";import { resolveVoice, synthesizeSpeech, SPEECH_VOICES } from "./tts";import { DUCK_DEFAULT, generateSubtitlesReadout } from "./voiceover";import {@@ -1264,6 +1266,66 @@ export async function runAiTool();}+ case "generate_music": {+ const projectId = s.projectId;+ if (!projectId) throw new ToolError("No project open.");+ const prompt = String(input.prompt ?? "").trim();+ if (!prompt) throw new ToolError("A prompt is required.");+ const gen = useGenerate.getState();+ // An unprobed session (null) resolves before we spend the user's credits.+ const signedIn = gen.signedIn ?? (await gen.probeNow());+ if (!signedIn) throw new ToolError("Sign in to Donkey to generate music.");+ const variant = input.length === "song" ? "song" : "clip";+ // Default to a vocal-free bed; the model opts into a sung song explicitly.+ const instrumental = input.instrumental !== false;+ // Captured before synthesis: the track files under the chat that asked,+ // even if the user switches threads while it renders.+ const chatId = chatOwner();+ const asset = await synthesizeMusic(projectId, prompt, { variant, instrumental });+ const cur = useEditor.getState();+ // The render can outlast the open project: if the user switched away while+ // it ran, save it into the project it was made for — never the one now on+ // screen — and don't touch the current store.+ if (cur.projectId !== projectId) {+ void stockAssetInDoc(projectId, asset).catch(() => {});+ return {+ assetId: asset.id,+ name: asset.name,+ duration: round2(asset.duration),+ addedToTimeline: false,+ note: "The music finished and was saved to the project it was generated for; the user has since switched projects, so it isn't on this one.",+ };+ }+ cur.addAsset(asset);+ tagChatAsset(asset.id, chatId);+ void enrichAsset(asset);+ if (!wantsTimeline(input, "start")) {+ return {+ assetId: asset.id,+ name: asset.name,+ duration: round2(asset.duration),+ addedToTimeline: false,+ note: "The music previews in this chat — the user can play it and drag it onto the soundtrack; pass add_to_timeline or start when they ask for it in the cut.",+ };+ }+ const start = isNum(input.start) ? Math.max(0, input.start) : cur.currentTime;+ cur.addAudioFromAsset(asset.id, start);+ // Sits under speech at a soft bed volume by default; the model can raise it.+ const volume = isNum(input.volume) ? clamp(input.volume, 0, 1.5) : 0.4;+ const sel = useEditor.getState().selection;+ const clipId = sel?.kind === "audio" ? sel.id : null;+ if (clipId) useEditor.getState().updateAudio(clipId, { volume });+ return {+ assetId: asset.id,+ name: asset.name,+ audioClipId: clipId,+ start: round2(start),+ duration: round2(asset.duration),+ volume,+ addedToTimeline: true,+ };+ }+case "read_subtitles_aloud": {const lane = targetSubtitleTrack(input);if (!laneCues(useEditor.getState().subtitles, lane).some((c) => c.text.trim()))diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 51474977..5a1e5b31 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -524,6 +524,19 @@ export const AI_TOOLS: AiToolDef[] = [start: num("Timeline start in seconds (passing it implies add_to_timeline; default when placed: the playhead)"),}, ["script"]),},+ {+ name: "generate_music",+ description:+ "Generate a music track from a text prompt (Donkey's hosted music model, Gemini/Lyria) — a full song with sung vocals, or an instrumental bed. Describe mood, genre, instruments, and tempo. By default it renders an instrumental bed (instrumental:true); pass instrumental:false for a full song, where the model writes and sings its own lyrics — or include your own with [Verse]/[Chorus] tags and a singer description in the prompt. length \"clip\" is ~30s (default), \"song\" a longer ~2-minute track. When the user asks you to write or refine the lyrics or brief itself, put it in chat and wait for them to ask for the music. It RETURNS once the track has landed and previews as a playable card in this chat; pass add_to_timeline:true (or a `start`) to drop it on the soundtrack when the user asked for it in the cut. For \"background music for this video\", read the timeline (videoTrack, project duration) to fit the mood and length, keep it instrumental so any speech stays on top, and set those clips' `duck` so the bed dips under them. This is SUNG music — a spoken narration is voiceover_generate. Needs the user signed in to Donkey (spends their credits).",+ inputSchema: obj({+ prompt: str("The music to generate — mood, genre, instruments, tempo; for a song, the theme to sing about, or your own [Verse]/[Chorus] lyrics"),+ instrumental: bool("Vocal-free background bed (default true). Pass false to let the model write and sing a full song"),+ length: { type: "string", enum: ["clip", "song"], description: "clip = ~30s (default), song = ~2-minute track" },+ volume: num("Bed volume 0..1.5 when placed (default 0.4 so it sits under speech)"),+ add_to_timeline: bool("Place it on the soundtrack (default false — it stays on its chat card until the user asks)"),+ start: num("Timeline start in seconds (passing it implies add_to_timeline; default when placed: the playhead)"),+ }, ["prompt"]),+ },{name: "read_subtitles_aloud",description:@@ -724,6 +737,8 @@ Ducking: a soundtrack clip's \`duck\` (0..1, via update_audio) lowers ALL otherVoiceover (Donkey's hosted speech model — signed in, spends credits, like image/video generation):- voiceover_generate(script, voice?, direction?, duck?, add_to_timeline?, start?, language?): synthesizes the script into a playable chat card; add_to_timeline:true (or a start) also drops it on the soundtrack at the playhead (or start) when the user asked for it in the cut. Defaults to a 0.4 duck when placed 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.+Music (Donkey's hosted music model, Gemini/Lyria — signed in, spends credits):+- generate_music(prompt, instrumental?, length?, add_to_timeline?, start?, volume?): renders a track from a mood/genre/tempo brief — a full song with sung vocals (instrumental:false; the model writes the lyrics, or pass your own [Verse]/[Chorus] lines) or a vocal-free bed (instrumental:true, the default). length "clip" (~30s, default) or "song" (~2min). It returns when the track lands and previews as a chat card; add_to_timeline (or a start) drops it on the soundtrack at a soft bed volume. For "background music for this video", keep it instrumental, read videoTrack/duration to fit the mood and length, and set any speech clips' \`duck\` so the bed sits under them. This is sung music — a spoken narration is voiceover_generate; the Audio tab's Voice/Music sub-tabs mirror the two.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.@@ -780,7 +795,7 @@ Rules:- Read list_skills / read_skill before working in an area you're unsure about — they document every setting.- Transcription tools write tracks the user sees — run subtitles_generate / captions_generate only when captions were asked for, never just to read the words: existing cues are in editor_state, and audio plays to you via listen_audio. Don't transcribe a video with no speech (subtitles_from_visuals narrates silent footage), and 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 / 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", and place project assets in the cut with add_clip when they ask for them there ("make a movie from these photos"). Generated media previews on a chat card the user can expand, drag in, or file away; add it to the timeline (add_to_timeline:true or an index) only when they asked for it in the cut. Write a rich, specific prompt from their shorthand. Video renders take a minute or two. "Generate a video of/about X" means one generate_video clip; only when they name a narrated multi-shot production (a story, episode, narrated short) does generate_scene plan it and stop at the shot list — confirm with the user, then call approve_scene, since it renders many paid shots (regenerate_shot / recut_scene / restyle_scene revise it after).+- generate_image / generate_video / generate_character_video / voiceover_generate / read_subtitles_aloud / generate_music 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. generate_music makes a music track — a vocal-free background bed by default ("add music to this video"), or a full sung song (instrumental:false); it's sung music, so a spoken narration is voiceover_generate. 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", and place project assets in the cut with add_clip when they ask for them there ("make a movie from these photos"). Generated media previews on a chat card the user can expand, drag in, or file away; add it to the timeline (add_to_timeline:true or an index) only when they asked for it in the cut. Write a rich, specific prompt from their shorthand. Video renders take a minute or two. "Generate a video of/about X" means one generate_video clip; only when they name a narrated multi-shot production (a story, episode, narrated short) does generate_scene plan it and stop at the shot list — confirm with the user, then call approve_scene, since it renders many paid shots (regenerate_shot / recut_scene / restyle_scene revise it after).- You can see and hear: audio the user attaches to their message plays right in it — answer "what does this say" from what you hear, no tool call. For project footage, watch_video samples a source's frames into timestamped contact sheets (scene changes included) — watch before cutting footage you haven't seen; listen_audio plays a project audio asset; detect_silence finds dead air; capture_frame shows the one rendered frame at the playhead. The watching-and-cutting skill has the flow.`;}