Open source CapCut alternative.
TypeScript
"use client";
import { readFolder, sharedFolderPage } from "@/cut/lib/folderBrowse";
import { parseFolderLink } from "@/cut/lib/folderReference";
import { cloudRequest } from "@/cut/lib/backend/cloud";
import { assetTypeOf, importFileToProject } from "@/cut/lib/media";
import { saveSvgSticker } from "@/cut/lib/svgSticker";
import { linkIdForAsset, uploadLinkedFile, syncLinkedLibrary, isLinkedType } from "@/cut/lib/linkedLibrary/registry";
import { formatBytes } from "@/lib/bytes";
import { projectRevision } from "@/cut/lib/projectRevision";
import { assertProjectCommand } from "./projectCommands";
import { projectOperation, type ProjectOperation } from "./projectOperation";
import { captureRenderSnapshot, renderDoc } from "./renderSnapshot";
import { submitPreviewSnapshot } from "./exportClient";
import { ITEM_KIND_IDS, ITEM_KINDS, ROW_ITEM_KINDS, type ItemKind, type TimelineClipboardItem } from "./itemKinds";
import { insertItemRow, packRows } from "./laneTracks";
import { timelineBlocker, timelineCopies, timelineItem } from "./timelineItems";
import { movePreviewSelection, previewSelectionSnapshot } from "@/cut/lib/previewSelection";
import { libraryShareTargetSchema, shareSettingsSchema, librarySharePath } from "@/cut/lib/librarySharing";
import { requestSharing } from "@/cut/lib/sharingClient";
import { copyLibraryForSharing } from "@/cut/lib/libraryShareCopy";
import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";
import { GUIDE_IDS, guideFits, guidePreset, isGuideId, safeAreaOf, sanitizeGuideLines, type GuideId } from "./guides";
import { textSpots } from "./textPlace";
import {
OUTPUT_SPACES,
ALL_EFFECT_IDS,
CLIP_EFFECT_IDS,
type ClipEffect,
autoGrade,
colorStatsFromImageData,
GRADE_BASIC_FIELDS,
GRADE_DETAIL_FIELDS,
GRADE_PRESETS,
HSL_BANDS,
matchGrade,
recipeStatsRender,
normalizeGrade,
SOURCE_PROFILES,
WHEEL_LABELS,
WHEEL_ZONES,
type SourceProfile,
normalizeSound,
retimeOf,
semanticMasterCurve,
SOUND_PRESETS,
SPEED_CURVE_MAX,
SPEED_CURVE_MIN,
SPEED_CURVE_PRESET_IDS,
speedCurveOf,
type ClipSound,
type ColorStats,
type CurvePoint,
type EffectId,
type GradeCurves,
type HslBand,
type SpeedNode,
type WheelTuple,
type Mask,
OVERLAY_ANIM_DEFAULT_SECONDS,
EDGE_STAGGER_MAX,
edgeMaxSeconds,
EDGE_BLUR_MAX,
EDGE_DISTANCE_MAX,
EDGE_ORDERS,
EDGE_REEL_EM_MAX,
EDGE_SETTLE_MAX,
DIVE_ANIM_STYLE_IDS,
REEL_DIRECTIONS,
type ReelDirection,
EASE_IDS,
type EaseId,
type EdgeOrder,
letterSequence,
OVERLAY_ANIM_MIN_SECONDS,
OVERLAY_ANIM_STYLE_IDS,
TEXT_ONLY_ANIM_STYLE_IDS,
OVERLAY_LOOP_STYLE_IDS,
hasOverlayAnim,
WORD_EFFECT_IDS,
WORD_SWELL_MAX,
WORD_SWELL_MIN,
type OverlayAnim,
type OverlayAnimStyle,
type OverlayLoopStyle,
CARET_BLINKS_MAX,
displayWords,
edgeMotion,
keepCaret,
OVERLAY_HIT_DEFAULT_SECONDS,
OVERLAY_HIT_MAX_SECONDS,
OVERLAY_HIT_MIN_SECONDS,
OVERLAY_HIT_STYLE_IDS,
type OverlayCaret,
STROKE_FEATHER_MAX,
STROKE_OFFSET_MAX,
STROKE_STYLES,
STROKE_WIDTH_MAX,
MASK_FEATHER_MAX,
MASK_KINDS,
MASK_RADIUS_MAX,
maskHasRadius,
PEN_MIN_POINTS,
penClosed,
type RemovalStroke,
type StrokeStyleId,
CYCLE_HOLD_MAX,
CYCLE_HOLD_MIN,
CYCLE_SCALE_MAX,
CYCLE_SCALE_MIN,
FONT_CYCLE_FACES_MAX,
FONT_CYCLE_RATE,
FONT_CYCLE_RATE_MAX,
FONT_CYCLE_RATE_MIN,
TEXT_WEIGHTS,
LEAK_COURSES,
type LeakCourse,
GLITCH_KINDS,
type GlitchKind,
FLASH_RATE_MAX,
FLASH_RATE_MIN,
FLASH_FADE_CHOICES,
FLASH_FADES,
FLASH_FADE_NONE,
FLASH_RHYTHMS,
loopPeriod,
FLASH_TONES,
TEXT_TEXTURES,
type CycleFace,
type FlashFade,
type FlashRhythm,
type TextWeight,
} from "@donkeycut/effects-kit";
import { INTERFACE_LANGUAGE_LIST, languageName, type AiPanelToolName } from "@/cut/components/AiPanel.tools";
import { isLocale } from "@/i18n/locales";
import { changeInterfaceLanguage } from "./interfaceLanguage";
import { beatSwitches, clipBeatTimes, switchProblem, tidySwitches, timedFontCycle, validBeatStep } from "./fontCycleTiming";
import { LOOP_SPEED_MAX, LOOP_SPEED_MIN, type OverlayAnimationToolName } from "@/cut/components/AnimationTiles.tools";
import type { AudioToolName } from "@/cut/components/AudioPanel.tools";
import type { CameraCardToolName } from "@/cut/components/CameraCardSection.tools";
import type { EditorToolName } from "@/cut/components/Editor.tools";
import type { EffectsToolName } from "@/cut/components/EffectsPanel.tools";
import { SHAPE_KINDS, SVG_STICKER_MAX_CHARS, type ElementsToolName } from "@/cut/components/ElementsPanel.tools";
import type { VideoGenToolName } from "@/cut/components/GeneratePanel.tools";
import type { CreditToolName } from "@/cut/components/GenerateCost.tools";
import type { ImageGenToolName } from "@/cut/components/ImageGenPanel.tools";
import { STICKER_W_MIN, type InspectorToolName } from "@/cut/components/Inspector.tools";
import type { GroupPanelToolName } from "@/cut/components/GroupPanel.tools";
import { CAMERA_SCALE_MAX, CAMERA_SCALE_MIN, CAMERA_WORLD_MAX, CAMERA_WORLD_MIN, ELEMENT_BLUR_MAX, SHUTTER_MAX, SHUTTER_MIN, TILT_MAX, isEaseId, upsertKey as upsertCameraKey, type CameraKey } from "@donkeycut/effects-kit";
import { cleanInks, LETTER_SPACING_MAX, LETTER_SPACING_MIN, PATTERN_KINDS, SHADOW_BLUR_MAX, SHADOW_OFFSET_MAX, STRIPE_GAP_MAX, STRIPE_LINE_MAX, STRIPE_LINE_MIN, STRIPES_DEFAULT, type PatternSpec, type ShadowSpec } from "@donkeycut/effects-kit";
import { groupCameraOf, groupCameraPoseAt } from "@/cut/lib/groupCamera";
import { CUT_MOTION } from "@/cut/lib/motionSettings";
import type { LibraryToolName } from "@/cut/components/LibraryView.tools";
import type { PreviewToolName } from "@/cut/components/Preview.tools";
import type { RemovalToolName } from "@/cut/components/RemovalPanel.tools";
import type { SceneToolName } from "@/cut/components/SceneCard.tools";
import type { SidePanelToolName } from "@/cut/components/SidePanel.tools";
import type { StockToolName } from "@/cut/components/StockPanels.tools";
import type { SubtitlesToolName } from "@/cut/components/SubtitlesPanel.tools";
import { TEXT_SIZE_MAX, TEXT_SIZE_MIN, type TimelineToolName } from "@/cut/components/Timeline.tools";
import type { TopBarToolName } from "@/cut/components/TopBar.tools";
import type { TransitionsToolName } from "@/cut/components/TransitionsPanel.tools";
import { apiFetch, apiJson, getBackend } from "./backend";
import { refFromAsset, refFromStockVideo, type AssetRef } from "./assetRef";
import { chatOwner, tagChatAsset } from "./chatAssets";
import { checkFacts, factCheckToolOutput } from "./factCheck";
import { queueMessageFromAgent } from "./chatQueue";
import { applyOwnership, useGenerate, type VideoAttempt, type VideoGenOptions } from "./generate";
import { useGenScene } from "./genScene";
import { switchTimeline } from "./timelineSwitch";
import { folderWithin } from "./folderTree";
import { anchorRefused } from "./genvideo/shotAttempts";
import {
addProjectTemplateToTimeline,
addTemplateToProject,
createLibraryFolder,
deleteFromLibrary,
deleteLibraryFolder,
deleteTemplate,
fetchLibrary,
folderDeleteTakes,
importLibraryAsset,
moveLibraryItem,
renameTemplate,
updateLibraryFolder,
saveAssetToLibrary,
} from "./library";
import { forgetLinkedCopies } from "./linkedLibrary";
import { itemName } from "./itemName";
import { renameLibraryFile } from "./libraryRename";
import { fetchNotes } from "./notes";
import { noteInLibraryFolder } from "./noteReference";
import {
captureFreezeFrame,
beatlessFor,
detectAssetBeats,
detectSilenceClientSide,
measureSourceLevel,
enrichAsset,
ensurePeaks,
importImage,
importStockAudio,
importStockVideo,
importUrlMedia,
composeSheets,
makeStillFrame,
renderAudioSpanWav,
sampleWatchFrames,
scanSourceSpeech,
watchGeometry,
} from "./media";
import { convertModeIn } from "./convertMode";
import { convertAssetToMp4 } from "./mediaConvert";
import { isLottieAsset } from "./lottieAssets";
import { AIR, MIN_AIR, placeEdge, REACH, settleJoint, type Pace, type PlacedEdge } from "./cutRefine";
import { requestSidePanel } from "./panelRequest";
import {
confirmMatteBake,
ensureMatteBake,
ensureCardMatte,
jobTarget as matteJobTarget,
matteBakesAvailable,
useMatteBakes,
} from "./removal/bakeJobs";
import {
blobToInlineAudio,
MAX_AUDIO_BYTES,
refToInlineAudio,
visualRefs,
type InlineImage,
} from "./refMedia";
import { characterPrompt, stockAspectDims, stockTitle } from "./stock";
import { STOCK_IMAGES } from "./stockManifest";
import { STOCK_VIDEOS } from "./stockVideoManifest";
import { STOCK_SFX } from "./stockSfxManifest";
import { storedMediaUrl } from "./mediaSync";
import { parseProjectLink, PROJECT_PAGE_DEFAULT, PROJECT_PAGE_MAX } from "./projectLink";
import { landReferenceAssets as landReferenceAssetsInto, listOwnProjects, openReference, referenceMediaUrl, type LandedAsset, type ReferenceProject } from "./projectReference";
import { clampLayersToAssets, mediaTypeFits, templateFromDoc } from "./projectTemplate";
import { isSoundPresetTemplate, listSoundPresets, saveSoundPreset } from "./soundPresets";
import { isGradePresetTemplate, listSavedGrades, saveGradePreset } from "./gradePresets";
import { isStylePresetTemplate } from "./stylePresets";
import { findLibraryAsset, listLibrary } from "./libraryList";
import { loadLibraryLut, lutIdOf, lutLabel } from "./linkedLibrary";
import { type RawFrame, type ReadGrade, rawFrameAt, sampleClipRawFrame, sourceProfileOf, toBaseRendering, toGradedRendering } from "./baseFrame";
import { applyOverlayPatchSettled, assetClipUses, assetIdsOnAnyTimeline, clipLen, footprints, nextFreeStart, track0Clips, laneGapAt, getClipSpans, overlayLaneOrder, overlayLayers, parkedTransitions, projectDuration, resolveTransitions, totalDuration, useEditor, CHAT_TURN_LABEL } from "./store";
import { playheadAt } from "./playhead";
import { mixSpecFor, renderProjectFrame } from "./exportRender";
import { renderMix } from "./audioMix";
import { measureLoudnessSliced, roundedLoudness, type LoudnessMeasure } from "./loudness";
import { frameAt, framesAt, readMediaFileSize } from "./mediaRead";
import { bundledFaces, inkMaskOf, inkOffset, rankFaces } from "./fontMatch";
import { fontKind, fontLook } from "./fontCatalog";
import { CUT_FONT_MATCH } from "./fontMatchSettings";
import { COMPARE_MODES, MAX_COMPARE, SWEEP_TARGET } from "./frameDiff";
import { compareMoments, sweepSource } from "./sourceCompare";
import { findPicture, sampleColors, scanCuts, sourcePictureAt, trackCamera, trackElement, trackLetters, type FrameBox } from "./measure/sourceMeasure";
import { FULL_FRAME, isFullFrame } from "./measure/picture";
import { zoomAnchor } from "./measure/camera";
import { DETECT_CHANGES_MAX, DETECT_CUTS_MAX, DETECT_CUTS_SPAN_MAX, SAMPLE_COLOR_MAX, SAMPLE_COLORS_K_MAX, TRACK_FRAMES_MAX, CAMERA_FRAMES_MAX, TRACK_MATCHES, TRACK_PATH_MAX, TRACK_TOLERANCE_DEFAULT } from "./measure/limits";
import { renderStageFrame, storeStageStill } from "./stageFrame";
import { createRasterCanvas, decodeRasterImageUrl, rasterCanvasToDataUrl } from "./raster";
import { buildAiContext, centreBox, describeCameraCard, describeDoc, describeParkedTimeline, hiddenFromChat, OTHER_CHATS_MEDIA_NOTE, roundT } from "./aiContext";
import { CARD_SIDES, newCard, normalizeCard, type CardSide } from "./cameraCard";
import { CAPTION_STYLES, captionEmphasis, cueSpot, EMPHASIS_SCALE_MAX, EMPHASIS_SCALE_MIN, laneCues, subtitleLaneCount, trackLocale } from "./subtitles";
import { cueEmphasis, emphasisIndicesOf, emphasizedWords } from "./captionEmphasis";
import { findHighlights } from "./highlights";
import { fuseTimeline, renderFusedTimeline, speechOnsets, speechOver } from "./watch/fuse";
import {
mergeHeard,
mergeWatch,
mergeWatchNotes,
nextUncoveredSpan,
uncoveredSeconds,
unnotedSpans,
} from "./watch/merge";
import { syncLines } from "./lyricSync";
import { transcriptWords as cueWords, wordTimesFor } from "./textWords";
import {
composeTextRun,
TEXT_LAYOUT_IDS,
type ComposeLine,
type TextLayout,
type TextVariation,
} from "./textCompose";
import {
cueWordCount,
MAX_WORDS_PER_CUE,
MIN_WORDS_PER_CUE,
} from "./cueChunk";
import { partialWrites, syncToSpeech, type SyncReport } from "./cueSync";
import { requireTextLook, type TextLook } from "./textLooks";
import {
MOVE_STRENGTH_MAX,
MOVE_STRENGTH_MIN,
TEXT_MOVE_IDS,
type TextMoveId,
} from "./textMotion";
import { queueWatchSweep, withSweepPaused } from "./watch/sweep";
import { retryFailedUploads, uploadInFlight } from "./importQueue";
import { ConnectionLostError, fetchDropped, isOffline } from "./network";
import { synthesizeMusic } from "./audioGen";
import { composeMusicPrompt } from "./composeGen";
import { stockAssetInDoc } from "./genvideo/docWriter";
import { resolveVoiceAsk, synthesizeSpeech, SPEECH_VOICES } from "./tts";
import { hostedFetch, hostedPost } from "./hosted";
import { readHostedFailure } from "./hostedError";
import { UserError } from "./userError";
import { creditPriceQuote, type CreditPriceSheet } from "@/lib/credits/price-sheet";
import { creditsFromDollars } from "@/lib/credits/format-credits";
import { BLOCK_MAX_SECONDS, BLOCK_MIN_SECONDS, BLOCKOUT_MAX, blockAsset } from "./blockSource";
import { CUT_CLIP, CUT_JUDGE } from "./chatRuntime";
import { FOLLOW_MODES } from "./trackKeys";
import { trackMotion } from "./trackMotion";
import { TRACK_TARGET_IDS, TRACK_USES } from "./trackTargets";
import { askJudgeChunked, noul } from "./judge";
import { SWEEP_CHUNK, sweepPicks, sweepQuestions, sweepState, type SweepCandidate } from "./sweepSelect";
import { clampVideoDuration, defaultVideoAspects, videoResolutionOf } from "./videoModels";
import { DUCK_DEFAULT, generateSubtitlesReadout } from "./voiceover";
import {
allFonts,
ANIM_DEFAULT_SECONDS,
ANIM_STYLE_IDS,
assetIsSilent,
CLIP_MAX_ZOOM,
clipCovers,
DEFAULT_BACKGROUND,
clampKeyPos,
clampOverlayPos,
CLIP_MIN_SECONDS,
previewUrl,
clipZoom,
fontStack,
frameOf,
IMAGE_CLIP_SECONDS,
isEffectOverlay,
isTextOverlay,
laneOf,
LAYOUTS,
MAX_SUBTITLE_LANES,
nearestAspect,
normalizeAspect,
overlayAnimStyle,
projectBackground,
rectOf,
REGION_MAX_SCALE,
regionLabel,
SHAPE_LABELS,
SIDE_PANEL_TABS,
SPEED_FLOOR,
isTimelineId,
parkedTimeline,
TIMELINE_IDS,
TIMELINE_LABELS,
TRANSITION_STYLE_IDS,
type AnimStyle,
type AssetWatch,
type CaptionStyleId,
type WordEffectId,
type AudioClip,
type ClipShadow,
type ColorGrade,
type EffectOverlay,
type FontId,
isLinkedAssetType,
type MediaAsset,
type Selection,
type ShapeKind,
type SidePanelTab,
type StoredAsset,
type TransitionStyle,
type VideoClip,
uploadedFontId,
WATCH_DETAIL_NOTES,
WATCH_DETAILS,
type WatchDetail,
} from "./types";
import { BAND_STYLES, clampBand, clampFeather, takesBand } from "./transitionShape";
import { importEach } from "./urlBatch";
import { findMedia } from "./findMedia";
import { soundSourceOf, SPLIT_EDIT_MAX_S } from "./soundSource";
import { bindRecording, unbindRecording } from "./soundBind";
const round2 = (n: number) => Math.round(n * 100) / 100;
/** A time written out to the millisecond — 0.367 for 22/60, as the tools
* report it — sits a hair past its frame, so that frame still shows what came
* before. One within half a millisecond of a frame at a common rate (the
* 1/600 s grid holds 24, 25, 30, 50 and 60 fps) lands on it exactly. Grid
* points are 1.67 ms apart, so no time is in reach of two, and a frame
* written to the millisecond is at most a third of one off. */
const FRAME_GRID = 600;
const FRAME_SNAP_S = 0.0005;
const onFrame = (t: number) => {
const n = Math.round(t * FRAME_GRID);
return Math.abs(t - n / FRAME_GRID) < FRAME_SNAP_S ? n / FRAME_GRID : t;
};
/** Tool fields that hold seconds: a timeline or source time, or a length. */
const SECONDS_FIELDS: ReadonlySet<string> = new Set([
"start",
"end",
"in",
"out",
"at",
"t",
"times",
"seconds",
"from",
"to",
"source",
"delta",
"hold",
"duration",
"lead",
"tail",
"hit_at",
"font_cycle_at",
"font_cycle_seconds",
"font_cycle_switches",
]);
/** A tool's input with every seconds field on the frame it names, walked
* through lists and nested records (keys, lines, spans, blocks), so every
* tool takes a time the way the tools report one. Example: { start: 0.367 }
* → { start: 22/60 }. */
function snapSeconds(value: unknown, field?: string): unknown {
if (typeof value === "number") {
return field !== undefined && SECONDS_FIELDS.has(field) && Number.isFinite(value) ? onFrame(value) : value;
}
if (Array.isArray(value)) {
return value.map((v) => snapSeconds(v, field));
}
if (value !== null && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, snapSeconds(v, k)]));
}
return value;
}
/** A rotation input in degrees, kept to tenths: a screen in the shot can lean
* a fraction of a degree, and whatever is fitted onto it has to match. */
const degInput = (n: number) => Math.round(clamp(n, -180, 180) * 10) / 10;
/** The timeline rows a mutation touched, small enough to ride every result:
* ids, starts, and lengths for track 0 and the soundtrack, read fresh after
* the store settled. The model keeps editing from these — new ids after a
* split, closed-up starts after a delete — with no get_state poll between
* steps.
*
* `parkedTransitions` rides along: a bar the edit left lining up with
* nothing. The model sees its own debris the moment it makes it, in the same
* payload it already reads, so a stranded blend gets cleared or reattached
* inside the turn instead of sitting on the row. */
function tracksAfter() {
const cur = useEditor.getState();
const row = track0Clips(cur.clips).map((c) => ({
id: c.id,
start: roundT(c.start),
len: roundT(clipLen(c)),
}));
const lanes = cur.audioClips.map((a) => ({
id: a.id,
lane: a.lane ?? 0,
start: roundT(a.start),
len: roundT(a.out - a.in),
}));
const parked = parkedTransitions(cur.clips, cur.transitions);
return {
track0: row.slice(0, 60),
...(row.length > 60 ? { track0Truncated: true } : {}),
soundtrack: lanes.slice(0, 60),
...(lanes.length > 60 ? { soundtrackTruncated: true } : {}),
...(parked.length > 0
? {
parkedTransitions: parked.map((t) => ({
id: t.id,
start: roundT(t.start),
seconds: roundT(t.seconds),
style: t.style,
})),
parkedTransitionsNote:
"These transition bars line up with no cut or clip edge and play nothing. Clear each one with remove_transition, or reattach it with set_transition/set_animation on the edge it belongs to. If it isn't clear which the user wanted, say what's there and ask.",
}
: {}),
};
}
/** The model crosses the transition and animation vocabularies — the retired
* edge styles (fadein/zoomin/…) especially. Style ids arrive as structured
* tool input, so resolve each known synonym to the nearest supported style. */
const TRANSITION_STYLE_SYNONYMS: Record<string, TransitionStyle> = {
fade: "crossfade",
fadein: "crossfade",
fadeout: "crossfade",
dissolve: "crossfade",
zoom: "crosszoom",
zoomin: "crosszoom",
zoomout: "crosszoom",
slideleft: "pushleft",
slideright: "pushright",
slideup: "pushup",
slidedown: "pushdown",
};
const ANIM_STYLE_SYNONYMS: Record<string, AnimStyle> = {
crossfade: "fade",
fadein: "fade",
fadeout: "fade",
dipblack: "fade",
dipwhite: "fade",
blur: "fade",
crosszoom: "zoom",
zoomin: "zoom",
zoomout: "zoom",
pushleft: "slideleft",
pushright: "slideright",
pushup: "slideup",
pushdown: "slidedown",
wipeleft: "slideleft",
wiperight: "slideright",
wipeup: "slideup",
wipedown: "slidedown",
};
/** The sliders the grade tool patches — the panel's basic and detail lists
* plus the legacy pair, so the schema and handler can never disagree. */
const GRADE_KEYS = [
...GRADE_BASIC_FIELDS.map((f) => f.key),
...GRADE_DETAIL_FIELDS.map((f) => f.key),
"brightness",
"hue",
] as const;
/** Color stats for a grading reference: a clip's current frame as the base
* rendering (through the source conversion, before any grade — what Auto
* reads), or `graded` through the clip's LUT, preset and adjustments too, or
* an image asset's pixels. */
/** A clip's code values and recipe: the preview's decoded frame when it has
* one, else a decode of the file at the middle of the trim — off screen, or
* not decoded yet. */
async function clipRawFrame(
s: ReturnType<typeof useEditor.getState>,
clip: VideoClip,
w: number,
h: number
): Promise<RawFrame> {
const shown = sampleClipRawFrame(clip.id, w, h);
if (shown) return shown;
const asset = s.assets.find((a) => a.id === clip.assetId);
if (!asset?.url) throw new ToolError("Could not decode a frame of that clip's file.");
// A still on the track has no frames to seek: draw the image itself.
if (asset.type === "image") {
const img = await decodeRasterImageUrl(asset.url);
if (!img || !img.width) throw new ToolError("Could not decode a frame of that clip's file.");
const c = createRasterCanvas(w, h);
const ctx = c.getContext("2d") as CanvasRenderingContext2D | null;
if (!ctx) throw new ToolError("Could not decode a frame of that clip's file.");
ctx.drawImage(img.source, 0, 0, w, h);
return { px: ctx.getImageData(0, 0, w, h).data, recipe: { profile: sourceProfileOf(asset), output: "sdr", size: 0 } };
}
// The file the cut plays: a light proxy reads faster than its master, and
// carries its own color recipe.
const raw = await rawFrameAt(previewUrl(asset), (clip.in + clip.out) / 2, { width: w, height: h, fit: "fill" });
if (!raw) throw new ToolError("Could not decode a frame of that clip's file.");
return raw;
}
/** A clip's frame as the base rendering, or through its whole grade. */
async function clipFrameData(
s: ReturnType<typeof useEditor.getState>,
clip: VideoClip,
w: number,
h: number,
graded?: ReadGrade
): Promise<Uint8ClampedArray> {
const { px, recipe } = await clipRawFrame(s, clip, w, h);
return graded ? toGradedRendering(px, recipe.profile, recipe, graded) : toBaseRendering(px, recipe.profile, recipe);
}
/** The grade a clip's graded reads render through: its own, with the library
* LUT it names loaded. */
async function readGradeOf(clip: VideoClip): Promise<ReadGrade | undefined> {
if (!clip.grade) return undefined;
const lutId = lutIdOf(clip.grade);
return { grade: clip.grade, userLut: lutId ? await loadLibraryLut(lutId) : undefined };
}
async function colorStatsForRef(
s: ReturnType<typeof useEditor.getState>,
ref: { clipId?: string; assetId?: string; at?: number; graded?: boolean }
): Promise<ColorStats> {
if (ref.clipId) {
const clip = requireItem(s.clips, ref.clipId, "video clip");
// Graded reads run the clip's whole recipe on its code values, the way
// the preview draws it: a log clip's grade works in scene light.
const data = await clipFrameData(s, clip, 192, 108, ref.graded ? await readGradeOf(clip) : undefined);
const stats = colorStatsFromImageData(data);
if (!stats) throw new ToolError("Could not read pixels off that clip's frame.");
return stats;
}
if (ref.assetId) {
const asset = requireItem(s.assets, ref.assetId, "project asset");
if (asset.type === "video") {
// A reference video reads at a second, inside the picture its measuring
// tools found, so a screen recording's grade is the shot's, not the app's.
if (!isNum(ref.at))
throw new ToolError("A video reference needs ref_at, the second of it to match (a moment inside the shot).");
const at = clamp(ref.at, 0, Math.max(0, asset.duration - 0.001));
const px = await withSweepPaused(() => sourcePictureAt(asset.url, at, asset.picture ?? FULL_FRAME)).catch((e) => {
throw new ToolError(e instanceof Error ? e.message : `Could not read "${asset.name}".`, { cause: e });
});
const stats = colorStatsFromImageData(px.data);
if (!stats) throw new ToolError(`Could not read pixels off "${asset.name}" at ${roundT(at)}s.`);
return stats;
}
if (asset.type !== "image")
throw new ToolError("Color stats read images, video frames and clip frames — that asset has no picture.");
const img = await decodeRasterImageUrl(asset.url);
if (!img || !img.width) throw new ToolError("Could not decode that image.");
const w = 192;
const h = Math.max(1, Math.round((img.height / img.width) * w));
const c = createRasterCanvas(w, h);
const ctx = c.getContext("2d") as CanvasRenderingContext2D | null;
if (!ctx) throw new ToolError("Could not read that image's pixels.");
ctx.drawImage(img.source, 0, 0, w, h);
// A still cut from log footage carries its source's profile.
const stats = colorStatsFromImageData(toBaseRendering(ctx.getImageData(0, 0, w, h).data, sourceProfileOf(asset)));
if (!stats) throw new ToolError("Could not read pixels off that image.");
return stats;
}
throw new ToolError("Pass clipId or assetId.");
}
/** Stats shaped for the model: rounded, with the quantile probes labeled. */
function statsReport(stats: ColorStats) {
const r1 = (v: number) => Math.round(v * 100) / 100;
return {
quantiles: "values 0..255 at p2, p10, p25, p50, p75, p90, p98",
r: stats.r,
g: stats.g,
b: stats.b,
luma: stats.luma,
meanR: Math.round(stats.meanR),
meanG: Math.round(stats.meanG),
meanB: Math.round(stats.meanB),
meanSat: r1(stats.meanSat),
warmth: r1(stats.warmth),
};
}
/** track_element with match letters: how a line of type comes in letter by
* letter, as the per-letter entrance set_overlay_animation plays back. */
async function trackLettersResult(
asset: MediaAsset,
input: Record<string, unknown>,
opts: { from: number; to: number | undefined; seed: FrameBox; color: string | undefined; area: FrameBox }
) {
if (asset.type !== "video") throw new ToolError(`"${asset.name}" is a still image — letters coming in need a video.`);
const text = typeof input.text === "string" ? input.text.trim() : "";
if (!text) throw new ToolError("Pass text: the line's words exactly as they read once every letter has landed.");
if (opts.to === undefined)
throw new ToolError("Pass to: a source second just after the last letter lands, with the whole line at rest — from is where the first letter is still out of sight.");
const run = await withSweepPaused(() =>
trackLetters(asset.url, {
from: opts.from,
to: opts.to!,
seed: opts.seed,
text,
...(opts.color ? { color: opts.color } : {}),
maxFrames: TRACK_FRAMES_MAX,
area: opts.area,
})
).catch((e) => {
throw new ToolError(e instanceof Error ? e.message : `Could not read "${asset.name}".`, { cause: e });
});
const r2 = (v: number) => Math.round(v * 100) / 100;
const e = run.edge;
// A first letter already moving as the stretch opens starts at its opening.
const start = e ? Math.max(opts.from, e.start) : undefined;
return {
color: run.color,
match: "letters",
...(run.fps > 0 ? { fps: Math.round(run.fps * 100) / 100 } : {}),
framesRead: run.framesRead,
letters: run.letters.map((l) => ({
letter: l.char,
index: l.index,
shows: l.shows === null ? null : roundT(l.shows),
starts: l.starts === null ? null : roundT(l.starts),
lands: l.lands === null ? null : roundT(l.lands),
...(l.alpha !== null ? { alpha: r2(l.alpha) } : {}),
...(l.soft !== null ? { soft: Math.round(l.soft) } : {}),
...(l.error !== null ? { error: Math.round(l.error * 1000) / 1000 } : {}),
})),
...(e && start !== undefined && e.reel
? {
entrance: {
starts: roundT(start),
in_style: "slot",
in_seconds: r2(e.seconds),
in_stagger: r2(Math.min(0.95, e.stagger)),
in_sequence: e.sequence,
in_sequence_at: e.sequenceAt.map((v) => Math.round(v * 1000) / 1000),
in_reel: e.reel.dir,
in_reel_pitch: Math.round(e.reel.pitch),
in_reel_band: Math.round(e.reel.band),
in_overshoot: Math.round(e.reel.overshoot),
...(e.reel.settle !== null ? { in_settle: r2(e.reel.settle) } : {}),
in_fade: e.fade,
},
entranceNote:
"The letters roll in on a slot reel, read off every frame: the way it turns (from how each letter arrives at its slot — a fast spin aliases between frames, so trust this over a contact sheet), how far apart its characters sit and how far the band reaches either side of the line's middle (design px), how far each letter lands past its slot and how long it takes settling back, the order and hand-off. Set the title's size first (the lengths are kept in em of it), begin it on the timeline second `starts` maps to, and pass these to set_overlay_animation as they are.",
}
: e && start !== undefined && e.typed
? {
entrance: {
starts: roundT(start),
in_style: "typewriter",
in_seconds: r2(e.seconds),
},
entranceNote:
"The letters appear where they stand, one at a time, without moving: typed. A typewriter shows each character (spaces included) once its share of in_seconds has passed, so with the title beginning on the timeline second `starts` maps to, each letter lands on the frame the reference shows it. Compare the letters' `shows` with that spacing: a turn far off it is a beat the typing holds, which a typewriter cannot — split the title there.",
}
: e && start !== undefined
? {
entrance: {
starts: roundT(start),
in_style: e.direction === "up" ? "rise" : "drop",
in_seconds: r2(e.seconds),
in_stagger: r2(Math.min(0.95, e.stagger)),
in_sequence: e.sequence,
in_sequence_at: e.sequenceAt.map((v) => Math.round(v * 1000) / 1000),
in_distance: Math.round(e.distance),
...(e.ease ? { in_ease: e.ease } : {}),
in_fade: typeof e.fade === "number" ? Math.round(e.fade * 100) / 100 : e.fade,
in_blur: Math.round(Math.min(EDGE_BLUR_MAX, e.blur)),
},
entranceNote:
"The entrance as set_overlay_animation takes it, read off every frame: each letter's move fitted on one ease and one distance, the order their moves start in, the hand-off spread across them, whether they fade in and how soft they start. Set the title to begin on the timeline second `starts` maps to, and pass these as they are; one letter's move is in_seconds × (1 − in_stagger). Leave motion_blur off unless the letters streak along their fall — a soft start is in_blur.",
}
: {
entranceNote:
"Not every letter was seen coming in: widen from/to so the stretch opens before the first letter shows and closes once the last has landed.",
}),
...(run.passes.length
? {
crosses: run.passes.map((p) => ({
color: p.color,
box: { x: rF(p.box.x), y: rF(p.box.y), w: rF(p.box.w), h: rF(p.box.h) },
letters: p.letters,
})),
crossesNote:
"Other ink the letters pass over on their way in. front: the letters cover it, so the title sits on a lower lane (nearer 0) than that element; behind: it covers them, so it sits nearer 0.",
}
: {}),
...(run.truncated ? { truncated: true } : {}),
...pictureReport(opts.area),
source: sourceRef(asset),
};
}
/** The measuring tools (detect_cuts, sample_color, track_element) read the
* source's own pixels: a video, or for "picture" also a still image. */
function measuredSource(s: Editor, input: Record<string, unknown>, wants: "video" | "picture"): MediaAsset {
const asset = requireItem(s.assets, input.asset_id, "project asset");
if (asset.type === "audio")
throw new ToolError(`"${asset.name}" is audio — listen_audio hears it, and it has no picture to measure.`);
if (asset.type === "image" && wants === "video")
throw new ToolError(`"${asset.name}" is a still image — one frame, no cuts.`);
if (asset.type !== "image" && !(asset.duration > 0))
throw new ToolError(`"${asset.name}" has no length yet — its import is still being read. Try again in a moment.`);
return asset;
}
/** A {x, y, w, h} box from a tool argument, clamped to the frame. */
function frameBoxOf(raw: unknown, name: string): FrameBox | null {
if (raw === undefined || raw === null) return null;
const r = raw as Record<string, unknown>;
if (!isNum(r.x) || !isNum(r.y) || !isNum(r.w) || !isNum(r.h) || r.w <= 0 || r.h <= 0)
throw new ToolError(`${name} needs x, y (its centre) and w, h (its size), all frame fractions.`);
return { x: clamp(r.x, 0, 1), y: clamp(r.y, 0, 1), w: clamp(r.w, 0, 1), h: clamp(r.h, 0, 1) };
}
/** A tracked path as a model reads it: an entry wherever the box changes by
* a pixel or more, or the element comes or goes — a hold is one entry — and
* evenly thinned past TRACK_PATH_MAX. */
function trackPath(boxes: { t: number; box: FrameBox | null }[]) {
const listed: { t: number; box: FrameBox | null }[] = [];
const PIXEL = 1 / 1080;
for (let i = 0; i < boxes.length; i++) {
const b = boxes[i];
const last = listed[listed.length - 1];
const changed =
!last ||
i === boxes.length - 1 ||
!b.box !== !last.box ||
(b.box && last.box && (["x", "y", "w", "h"] as const).some((k) => Math.abs(b.box![k] - last.box![k]) >= PIXEL));
if (changed) listed.push(b);
}
const thinned = listed.length > TRACK_PATH_MAX;
const kept = thinned
? Array.from({ length: TRACK_PATH_MAX }, (_, i) => listed[Math.round((i * (listed.length - 1)) / (TRACK_PATH_MAX - 1))])
: listed;
return {
path: kept.map((b) => ({
t: roundT(b.t),
...(b.box ? { x: rF(b.box.x), y: rF(b.box.y), w: rF(b.box.w), h: rF(b.box.h) } : { box: null }),
})),
thinned,
};
}
/** The part of a source's frame a reading tool reads: `picture` as passed
* ("full" for the whole frame, or a box), else the picture box stored on the
* asset, else the whole frame. */
function pictureArea(asset: MediaAsset, input: Record<string, unknown>): FrameBox {
if (input.picture === "full") return FULL_FRAME;
if (typeof input.picture === "string")
throw new ToolError(`picture is a box {x, y, w, h} in frame fractions, or "full" for the whole frame — got "${input.picture}".`);
return frameBoxOf(input.picture, "picture") ?? asset.picture ?? FULL_FRAME;
}
/** Find a video's picture over [from, to) and keep it on the asset — the
* whole frame when nothing around a picture holds still. */
async function storePicture(asset: MediaAsset, from: number, to: number) {
const found = await withSweepPaused(() => findPicture(asset.url, { from, to })).catch((e) => {
throw new ToolError(e instanceof Error ? e.message : `Could not read "${asset.name}".`, { cause: e });
});
useEditor.getState().updateAsset(asset.id, { picture: found?.box ?? FULL_FRAME });
return found;
}
/** The picture box a reading read inside, for its result: the box and what
* its numbers are fractions of. Nothing when it read the whole frame. */
function pictureReport(area: FrameBox) {
if (isFullFrame(area)) return {};
return {
picture: { x: rF(area.x), y: rF(area.y), w: rF(area.w), h: rF(area.h) },
pictureNote: PICTURE_NOTE,
};
}
/** What a reading inside a picture box says about its own numbers. */
const PICTURE_NOTE =
"This read only the source's picture box (`picture`, centre and size as fractions of the whole recorded frame) — the part the picture fills, apart from the bars or app around it. " +
'Every x, y, w, h passed in or handed back here is a fraction of that box, so it lands on the cut\'s frame as it is. picture: "full" reads the whole recorded frame; find_picture sets the box.';
/** Frame fractions to the 1/10,000: a pixel of a 1080 frame is 0.0009. */
const rF = (n: number) => Math.round(n * 10000) / 10000;
/** The side of the box a point is read over, as a frame fraction. */
const POINT_SIZE = 0.004;
/** A measuring pass gives back what it covered by this, inside the tool
* bridge's deadline. */
const MEASURE_BUDGET_MS = 90_000;
/** Long side of a captured frame: enough for the model to read a title, small
* enough to ride a turn. */
const CAPTURE_LONG_SIDE = 640;
/** A trim that leaves a clip under one frame. */
const CLIP_TOO_SHORT = `A clip runs at least one frame (${Math.round(CLIP_MIN_SECONDS * 1000) / 1000}s at 60 fps).`;
/** What a comparison's reply teaches about its own numbers. */
const COMPARE_NOTE =
"Source on the left, your cut on the right, one picture per moment. diff is how far your frame is from the source's: the mean difference per pixel, 0 (the same) to 255, and under " +
`${SWEEP_TARGET} reads as the same picture. grid is that difference over the frame in 4×4 cells, top row first, so the hot cells are where to look. ` +
"shift means the source matches your frame better that many seconds away: positive, your cut shows it early, so move what is there later by that much; negative, earlier. " +
"block names a block standing in for footage, which keeps a difference no edit removes, so judge those moments by the cells over your titles and shapes. " +
"Name what differs — colour, the words and their face, where a thing sits, its size, what is moving and how far along it is — fix it with the tools and check again. A moment that matches needs no edit.";
const SWEEP_NOTE =
"diff is the mean difference per pixel between your frame and the source's, 0 (the same) to 255; median is the typical frame, p95 the bad tail, max the worst. " +
"worst lists the stretches most off, worst first, each with its peak frame (at on the cut, source on the source) and that frame's 4×4 grid, top row first. " +
"edges lists stretches whose difference runs along whole edges of the frame (top, bottom, left, right) while the middle matches: a border, band or letterbox one side has and the other lacks. Thin bars barely move the mean, so these come back under target too. The picture box is already cut out of any app around it, so a band inside it is part of the picture, never the recording's: build it. " +
"titles lists titles whose letters read another colour than the source's under them over from-to, ink yours and sourceInk the source's at the worst frame. ink null where the source's letters show means yours are hidden there: a picture effect treats everything over the footage, titles included, so a flash whites them out and a ground the letters sit on is a block or a shape on a row behind them, never an effect; or an element on a row in front covers them; or the title is not up yet. sourceInk null means the source shows no letters there: yours is up early, or the source's are washed out. A small label barely moves the score, so restack, retime or recolour each to what the source draws. " +
"Look at them: compare_to_source with times [{at, source}] at those peaks, fix what differs, then sweep again, until the median is under target and each stretch in worst and edges is fixed or sits over a block standing in for footage, the one difference no edit removes: a glow, a tint, a blurred or soft edge, a flash are all built, so a stretch over what you built is yours to fix. " +
"shift on a stretch, or timing for the whole span, means the source matches better that many seconds away: positive, move it later by that much; negative, earlier. " +
"onBlocks is the share of samples over blocks standing in for footage; those keep a difference no edit removes.";
/** Faces suggest_font hands back by default, and at most. */
const FONT_SUGGESTIONS = 5;
const FONT_SUGGESTIONS_MAX = 10;
/** The longest side a suggest_font crop is read at, px: type this tall is
* already far finer than the grid it is scored on. */
const FONT_CROP_MAX = 1600;
/** Ink a line of type runs tall in the source, px, under which its glyphs
* blur into their proportions: a serif and a condensed sans of the same
* shape score alike, so the ranking no longer names the face. */
const FONT_SMALL_INK_PX = 24;
/** Design px on a frame's short side, the unit a title's size is in. */
const DESIGN_SHORT_SIDE = 1080;
const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));
const isNum = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
const isTextWeight = (v: unknown): v is TextWeight => (TEXT_WEIGHTS as readonly unknown[]).includes(v);
/** A flash fade's ease from a tool call: linear, the even ramp, stores as absence. */
const fadeEaseOf = (v: unknown): EaseId | undefined => {
if (!isEaseId(v)) throw new ToolError(`fade_ease is one of ${EASE_IDS.join(", ")}.`);
return v === "linear" ? undefined : v;
};
/** A flash rhythm from a tool call: strobe, the default, stores as absence. */
const flashRhythm = (v: unknown): FlashRhythm | undefined => {
if (!(FLASH_RHYTHMS as readonly unknown[]).includes(v)) {
throw new ToolError(`rhythm is one of ${FLASH_RHYTHMS.join(", ")}.`);
}
return v === "flicker" ? "flicker" : undefined;
};
/** A camera card places its clip's footage itself, so a framing write on
* one of `fields` would change nothing anyone sees: refused, naming the
* card's own controls. */
function refuseCardFraming(clip: VideoClip, input: Record<string, unknown>, fields: string[]): void {
if (!clip.card || !fields.some((f) => input[f] !== undefined)) return;
throw new ToolError(
"This clip is laid out as a camera card, which places its footage itself: set_camera_card scale, offset_x and offset_y move it (flips still apply through set_framing)."
);
}
/** The row an element tool was aimed at, if it named one. Rows are how
* elements stack, row 0 at the front: two on the same row slide clear of each
* other, so a title that has to sit over a shape names a lower row than it. */
const aimedLane = (input: Record<string, unknown>): { lane?: number } | undefined =>
isNum(input.lane) ? { lane: Math.max(0, Math.round(input.lane)) } : undefined;
/** One placed element as add_title and add_shape report it. */
type Placed = { id: string } & Record<string, unknown>;
/** Run a placing tool over its list (`titles`, `shapes`) or over the call as
* one item. Every item is checked before the first is placed, so a bad one
* refuses the whole call and leaves nothing behind; the call is already one
* undo step. Example: { titles: [{ text: "A" }, { text: "B" }] } →
* { ids: [a, b], titles: [{ id: a, … }, { id: b, … }] }. */
function placeEach(
input: Record<string, unknown>,
key: "titles" | "shapes",
check: (item: Record<string, unknown>) => void,
place: (item: Record<string, unknown>) => Placed
): unknown {
// A one-item call keeps the result it always had.
const list = input[key];
if (list === undefined) {
check(input);
return place(input);
}
// The list holds at least one item and stands alone: fields beside it
// would be dropped unread.
if (!Array.isArray(list) || list.length === 0) {
throw new ToolError(`${key} is a list of one or more items.`);
}
const beside = Object.keys(input).filter((k) => k !== key);
if (beside.length > 0) {
throw new ToolError(`Pass ${beside.join(", ")} inside each of ${key}; nothing was placed.`);
}
// Every item is checked before any is placed, naming the one refused.
const items = list.map((raw: unknown, i) => {
const item = (raw !== null && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
try {
check(item);
} catch (e) {
const why = e instanceof Error ? e.message : String(e);
throw new ToolError(`${key}[${i}]: ${why} Nothing was placed.`, { cause: e });
}
return item;
});
// Placed in order, so the ids line up with the items.
const placed = items.map(place);
return { ids: placed.map((p) => p.id), [key]: placed };
}
/** add_title's refusals, run before the title exists. */
function checkTitle(input: Record<string, unknown>): void {
if (typeof input.text !== "string" || !input.text.trim()) {
throw new ToolError("text is required.");
}
overlayPatch(input, "text");
}
/** Place one checked title. */
function placeTitle(input: Record<string, unknown>): Placed {
const s = useEditor.getState();
if (isNum(input.start)) {
s.seek(input.start);
}
s.addOverlay({ ...aimedLane(input), seed: "defaults" });
const sel = useEditor.getState().selection;
if (sel?.kind !== "overlay") {
throw new ToolError("Could not create the title.");
}
applyOverlayPatchSettled(sel.id, overlayPatch({ ...input, id: sel.id }, "text"));
const o = useEditor.getState().overlays.find((x) => x.id === sel.id)!;
return { id: o.id, ...(isTextOverlay(o) ? { text: o.text } : {}), start: o.start, end: o.end };
}
/** add_shape's refusals, run before the shape exists. */
function checkShape(input: Record<string, unknown>): void {
if (!(String(input.shape) in SHAPE_LABELS)) {
throw new ToolError(`shape must be one of ${SHAPE_KINDS.join(", ")}.`);
}
overlayPatch(input, "shape");
}
/** Place one checked shape. */
function placeShape(input: Record<string, unknown>): Placed {
const s = useEditor.getState();
const shape = String(input.shape) as ShapeKind;
if (isNum(input.start)) {
s.seek(input.start);
}
s.addShape(shape, aimedLane(input));
const sel = useEditor.getState().selection;
if (sel?.kind !== "overlay") {
throw new ToolError("Could not create the shape.");
}
applyOverlayPatchSettled(sel.id, overlayPatch({ ...input, id: sel.id }, "shape"));
const o = useEditor.getState().overlays.find((x) => x.id === sel.id)!;
return { id: o.id, shape, start: roundT(o.start), end: roundT(o.end) };
}
/** Every tool that runs in the browser: the full catalog minus the
* `server: true` skills tools the engine answers itself. */
type BrowserToolName = Exclude<
| AiPanelToolName
| AudioToolName
| CameraCardToolName
| CreditToolName
| EditorToolName
| EffectsToolName
| ElementsToolName
| GroupPanelToolName
| ImageGenToolName
| InspectorToolName
| LibraryToolName
| OverlayAnimationToolName
| PreviewToolName
| RemovalToolName
| SceneToolName
| SidePanelToolName
| StockToolName
| SubtitlesToolName
| TimelineToolName
| TopBarToolName
| TransitionsToolName
| VideoGenToolName,
"list_skills" | "read_skill"
>;
type Editor = ReturnType<typeof useEditor.getState>;
type ToolRun = (s: Editor, input: Record<string, unknown>, operation?: ProjectOperation) => Promise<unknown> | unknown;
/** The browser handler for every tool, keyed by the names the `*.tools.ts`
* modules beside the components export, so a tool added, removed, or renamed
* there refuses to compile until this map matches. */
const toolRuns: Record<BrowserToolName, ToolRun> = {
add_shape: (_s, input) => placeEach(input, "shapes", checkShape, placeShape),
add_sticker: async (s, input) => {
const svg = typeof input.svg === "string" && input.svg.trim() ? input.svg : undefined;
let assetId = typeof input.asset_id === "string" && input.asset_id ? input.asset_id : undefined;
if (!assetId && !svg) throw new ToolError("Pass asset_id, or svg markup to draw the sticker from.");
if (svg && !assetId) {
if (!s.projectId) throw new ToolError("No project open.");
if (svg.length > SVG_STICKER_MAX_CHARS) throw new ToolError(`svg is over ${SVG_STICKER_MAX_CHARS} characters.`);
const name = typeof input.name === "string" && input.name.trim() ? input.name.trim() : "Drawn sticker";
const drawn = await saveSvgSticker(s.projectId, svg, name).catch((e: unknown) => {
throw new ToolError(e instanceof Error ? e.message : String(e), { cause: e });
});
assetId = drawn.id;
s = useEditor.getState();
}
const stickerAsset = s.assets.find((a) => a.id === assetId);
if (stickerAsset?.type !== "image") throw new ToolError(`No image asset with id ${assetId}.`);
if (isNum(input.start)) s.seek(input.start);
s.addSticker({ assetId: assetId!, ...(isLottieAsset(stickerAsset) ? { lottie: true } : {}), ...aimedLane(input) });
const sel = useEditor.getState().selection;
if (sel?.kind !== "overlay") throw new ToolError("Could not create the sticker.");
applyOverlayPatchSettled(sel.id, overlayPatch({ ...input, id: sel.id }, "sticker"));
const o = useEditor.getState().overlays.find((x) => x.id === sel.id)!;
return { id: o.id, assetId, start: roundT(o.start), end: roundT(o.end) };
},
create_sticker: async (s, input) => {
const idea = String(input.idea ?? "").trim();
if (!idea) throw new ToolError("idea is required.");
if (!s.projectId) throw new ToolError("No project open.");
const { createCustomSticker } = await import("./stickerCreate");
const asset = await createCustomSticker(s.projectId, idea);
if (isNum(input.start)) s.seek(input.start);
useEditor.getState().addSticker({ assetId: asset.id, ...aimedLane(input) });
const sel = useEditor.getState().selection;
if (sel?.kind !== "overlay") throw new ToolError("Could not place the sticker.");
applyOverlayPatchSettled(sel.id, overlayPatch({ ...input, id: sel.id }, "sticker"));
const o = useEditor.getState().overlays.find((x) => x.id === sel.id)!;
return { id: o.id, assetId: asset.id, start: roundT(o.start), end: roundT(o.end) };
},
add_effect: (s, input) => {
const effect = String(input.effect ?? "");
if (!(ALL_EFFECT_IDS as string[]).includes(effect))
throw new ToolError(`effect must be one of ${ALL_EFFECT_IDS.join(", ")}.`);
if (isNum(input.start)) s.seek(input.start);
s.addEffect(effect as EffectId, aimedLane(input));
const sel = useEditor.getState().selection;
if (sel?.kind !== "overlay") throw new ToolError("Could not create the effect.");
applyOverlayPatchSettled(sel.id, overlayPatch({ ...input, id: sel.id }, "effect"));
// Where a zoom holds: the rest of the effects fill the frame, so the
// point only means anything for this one.
if (effect === "zoom" && (isNum(input.focus_x) || isNum(input.focus_y))) {
useEditor.getState().updateOverlay(sel.id, {
focus: {
x: clamp(isNum(input.focus_x) ? input.focus_x : 0.5, 0, 1),
y: clamp(isNum(input.focus_y) ? input.focus_y : 0.5, 0, 1),
},
});
}
const settings = effectSettings(effect as EffectId, input);
if (Object.keys(settings).length) useEditor.getState().updateOverlay(sel.id, settings);
const o = useEditor.getState().overlays.find((x) => x.id === sel.id)!;
return { id: o.id, effect, start: roundT(o.start), end: roundT(o.end) };
},
set_overlay_animation: (s, input) => {
const o = requireItem(s.overlays, input.id, "overlay element");
const anim: OverlayAnim = { ...(o.anim ?? {}) };
const edge = (slot: "in" | "out", styleKey: string, secondsKey: string) => {
const raw = input[styleKey];
// The cap is the style's the slot ends up with (a count runs longer).
const styled = typeof raw === "string" && raw !== "none" ? raw : anim[slot]?.style;
const secs = isNum(input[secondsKey])
? clamp(input[secondsKey], OVERLAY_ANIM_MIN_SECONDS, edgeMaxSeconds(styled))
: undefined;
if (typeof raw === "string") {
if (raw === "none") {
delete anim[slot];
return;
}
if (!(OVERLAY_ANIM_STYLE_IDS as string[]).includes(raw))
throw new ToolError(`Unknown ${slot} style: ${raw}`);
if ((TEXT_ONLY_ANIM_STYLE_IDS as string[]).includes(raw) && (o.kind ?? "text") !== "text")
throw new ToolError(`${raw} animates titles only.`);
const caret = keepCaret(anim[slot], raw);
anim[slot] = {
style: raw as OverlayAnimStyle,
// A long count's length shrinks to the new style's cap.
seconds: Math.min(edgeMaxSeconds(raw), secs ?? anim[slot]?.seconds ?? OVERLAY_ANIM_DEFAULT_SECONDS),
...(caret ? { caret } : {}),
};
} else if (secs !== undefined && anim[slot]) {
anim[slot] = { ...anim[slot]!, seconds: secs };
}
// The letter hand-off rides the slot; a negative hands it back to
// the style's own.
const stagger = input[`${slot}_stagger`];
if (isNum(stagger) && anim[slot]) {
const rest = { ...anim[slot]! };
delete rest.stagger;
anim[slot] = stagger < 0 ? rest : { ...rest, stagger: clamp(stagger, 0, EDGE_STAGGER_MAX) };
}
// The order and the reach ride the slot too; "reading" and 0 hand
// them back to the style's own.
const order = input[`${slot}_order`];
if (typeof order === "string" && anim[slot]) {
if (!(EDGE_ORDERS as readonly string[]).includes(order))
throw new ToolError(`Unknown ${slot}_order: ${order}. Use one of: ${EDGE_ORDERS.join(", ")}.`);
const rest = { ...anim[slot]! };
delete rest.order;
anim[slot] = order === "reading" ? rest : { ...rest, order: order as EdgeOrder };
}
const sequence = input[`${slot}_sequence`];
if (Array.isArray(sequence) && anim[slot]) {
const rest = { ...anim[slot]! };
if (Array.isArray(rest.order)) delete rest.order;
const text = (o.kind ?? "text") === "text" ? ((o as { text?: string }).text ?? "") : "";
const order = letterSequence(text, sequence as number[]);
if (sequence.length > 0 && order.length === 0)
throw new ToolError(`${slot}_sequence names no letter of "${text}": count its letters from 0, skipping spaces.`);
delete rest.orderAt;
anim[slot] = order.length > 0 ? { ...rest, order } : rest;
}
// Each named letter's own turn, as a share of the hand-off.
const sequenceAt = input[`${slot}_sequence_at`];
if (Array.isArray(sequenceAt) && anim[slot]) {
const rest = { ...anim[slot]! };
delete rest.orderAt;
const named = Array.isArray(rest.order) ? rest.order.length : 0;
if (sequenceAt.length > 0 && sequenceAt.length !== named)
throw new ToolError(`${slot}_sequence_at needs one share per letter of ${slot}_sequence (${named}), in its order.`);
const at = (sequenceAt as unknown[]).map((v) => (isNum(v) ? clamp(v, 0, 1) : 0));
anim[slot] = at.length > 0 ? { ...rest, orderAt: at } : rest;
}
const ease = input[`${slot}_ease`];
if (typeof ease === "string" && anim[slot]) {
if (ease !== "style" && !isEaseId(ease))
throw new ToolError(`Unknown ${slot}_ease: ${ease}. Use one of: ${EASE_IDS.join(", ")}, or "style".`);
const rest = { ...anim[slot]! };
delete rest.ease;
anim[slot] = ease === "style" ? rest : { ...rest, ease: ease as EaseId };
}
// false keeps it solid, a share of the move fades it up over that much,
// true hands back the style's own.
const fade = input[`${slot}_fade`];
if ((typeof fade === "boolean" || isNum(fade)) && anim[slot]) {
const rest = { ...anim[slot]! };
delete rest.fade;
anim[slot] =
fade === true || (isNum(fade) && fade >= 1) ? rest : fade === false || fade <= 0 ? { ...rest, fade: false } : { ...rest, fade: clamp(fade, 0.01, 1) };
}
const distance = input[`${slot}_distance`];
if (isNum(distance) && anim[slot]) {
const rest = { ...anim[slot]! };
delete rest.distance;
anim[slot] = distance <= 0 ? rest : { ...rest, distance: clamp(distance, 1, EDGE_DISTANCE_MAX) };
}
// A soft start: 0 keeps a soft style sharp, a negative hands it back.
const blur = input[`${slot}_blur`];
if (isNum(blur) && anim[slot]) {
const rest = { ...anim[slot]! };
delete rest.blur;
anim[slot] = blur < 0 ? rest : { ...rest, blur: clamp(blur, 0, EDGE_BLUR_MAX) };
}
// A slot's reel as a reference sets it. Lengths come in design px, as
// track_element reads them, and are kept in em of the title's size so
// they follow it when it is resized; 0 (or "style") hands each back.
const reel = input[`${slot}_reel`];
if (typeof reel === "string" && anim[slot]) {
if (reel !== "style" && !(REEL_DIRECTIONS as readonly string[]).includes(reel))
throw new ToolError(`Unknown ${slot}_reel: ${reel}. Use one of: ${REEL_DIRECTIONS.join(", ")}, or "style".`);
const rest = { ...anim[slot]! };
delete rest.reel;
anim[slot] = reel === "style" ? rest : { ...rest, reel: reel as ReelDirection };
}
const size = (o.kind ?? "text") === "text" ? (o as { size?: number }).size ?? 0 : 0;
for (const [key, field] of [
[`${slot}_reel_pitch`, "pitch"],
[`${slot}_reel_band`, "band"],
[`${slot}_overshoot`, "overshoot"],
] as const) {
const px = input[key];
if (!isNum(px) || !anim[slot]) continue;
if (!(size > 0)) throw new ToolError(`${key} sets a title's slot reel; this element has no type size.`);
const rest = { ...anim[slot]! };
delete rest[field];
anim[slot] = px <= 0 ? rest : { ...rest, [field]: Math.min(EDGE_REEL_EM_MAX, px / size) };
}
const settle = input[`${slot}_settle`];
if (isNum(settle) && anim[slot]) {
const rest = { ...anim[slot]! };
delete rest.settle;
anim[slot] = settle <= 0 ? rest : { ...rest, settle: clamp(settle, 0.05, EDGE_SETTLE_MAX) };
}
// A dive's anchor comes as the frame point the zoom holds still, as
// track_camera reads it, and is kept as an offset from the element's
// rest so it moves with the element; "none" hands back the deepest ink.
const anchor = input[`${slot}_anchor`];
if (anchor !== undefined && anim[slot]) {
const rest = { ...anim[slot]! };
delete rest.anchor;
if (anchor === "none" || anchor === null) {
anim[slot] = rest;
} else {
const a = (anchor ?? {}) as Record<string, unknown>;
if (!isNum(a.x) || !isNum(a.y))
throw new ToolError(`${slot}_anchor is {x, y}, the frame point the zoom holds still as frame fractions, or "none".`);
if (!DIVE_ANIM_STYLE_IDS.includes(rest.style))
throw new ToolError(`${slot}_anchor sets where a dive zooms; this edge is ${rest.style}.`);
const fr = frameOf(s.aspect);
anim[slot] = {
...rest,
anchor: {
x: Math.round((clamp(a.x, -1, 2) - o.x) * fr.w * 10) / 10,
y: Math.round((clamp(a.y, -1, 2) - o.y) * fr.h * 10) / 10,
},
};
}
}
};
edge("in", "in_style", "in_seconds");
edge("out", "out_style", "out_seconds");
if (typeof input.move === "string") {
if (input.move === "none") delete anim.move;
else {
if (!TEXT_MOVE_IDS.includes(input.move))
throw new ToolError(`Unknown move: ${input.move}. Use one of: ${TEXT_MOVE_IDS.join(", ")}.`);
const strength = isNum(input.move_strength)
? clamp(input.move_strength, MOVE_STRENGTH_MIN, MOVE_STRENGTH_MAX)
: (anim.move?.strength ?? 1);
anim.move = { style: input.move, strength };
}
} else if (isNum(input.move_strength) && anim.move) {
anim.move = {
...anim.move,
strength: clamp(input.move_strength, MOVE_STRENGTH_MIN, MOVE_STRENGTH_MAX),
};
}
const rawLoop = input.loop_style;
const speed = isNum(input.loop_speed) ? clamp(input.loop_speed, LOOP_SPEED_MIN, LOOP_SPEED_MAX) : undefined;
if (typeof rawLoop === "string") {
if (rawLoop === "none") delete anim.loop;
else if (!(OVERLAY_LOOP_STYLE_IDS as string[]).includes(rawLoop))
throw new ToolError(`Unknown loop style: ${rawLoop}`);
else anim.loop = { style: rawLoop as OverlayLoopStyle, speed: speed ?? anim.loop?.speed ?? 1 };
} else if (speed !== undefined && anim.loop) {
anim.loop = { ...anim.loop, speed };
}
const rawWords = input.words_style;
const wordColor = typeof input.words_color === "string" ? input.words_color : undefined;
const wordScale = isNum(input.words_scale)
? clamp(input.words_scale, WORD_SWELL_MIN, WORD_SWELL_MAX)
: undefined;
const wordDim = isNum(input.words_dim) ? clamp(input.words_dim, 0, 1) : undefined;
if (typeof rawWords === "string") {
if (rawWords === "none") delete anim.words;
else if (!(WORD_EFFECT_IDS as string[]).includes(rawWords))
throw new ToolError(`Unknown word effect: ${rawWords}`);
else if ((o.kind ?? "text") !== "text")
throw new ToolError("Word effects play a title's words; they need a title.");
else {
const color = wordColor ?? anim.words?.color;
const scale = wordScale ?? anim.words?.scale;
const dim = wordDim ?? anim.words?.dim;
// The transcript is the clock the effect follows. It is read now,
// against whatever the cut has been transcribed to say; with nothing
// to read, the words share the element's own span.
const times = isTextOverlay(o) ? wordTimesFor(o, s.subtitles.cues) : undefined;
anim.words = {
style: rawWords as WordEffectId,
...(color ? { color } : {}),
...(scale !== undefined ? { scale } : {}),
...(dim !== undefined ? { dim } : {}),
...(times ? { times } : {}),
};
}
} else if ((wordColor || wordScale !== undefined || wordDim !== undefined) && anim.words) {
anim.words = {
...anim.words,
...(wordColor ? { color: wordColor } : {}),
...(wordScale !== undefined ? { scale: wordScale } : {}),
...(wordDim !== undefined ? { dim: wordDim } : {}),
};
}
applyCaretInput(o, anim, input);
applyHitInput(o, anim, input);
applyFontCycleInput(s, o, anim, input);
s.updateOverlay(o.id, { anim: hasOverlayAnim(anim) ? anim : undefined });
const next = useEditor.getState().overlays.find((x) => x.id === o.id)!;
// The loop's real cycle, so a rate set to match a measured one can be
// checked without reading it off frames.
const cycle = loopPeriod(next.anim);
return { id: next.id, anim: next.anim ?? null, ...(cycle ? { loop_cycle_seconds: Math.round(cycle * 1000) / 1000 } : {}) };
},
set_overlay_keyframes: (s, input) => {
const o = requireItem(s.overlays, input.id, "overlay element");
const raw = input.keys;
if (!Array.isArray(raw)) throw new ToolError("keys must be a list.");
const dur = Math.max(0.1, o.end - o.start);
let kf = o.kf;
const sent = new Set<number>();
if (raw.length === 0) {
s.clearOverlayKeys(o.id);
kf = undefined;
} else {
// Each key builds on the pose already at its time, so a key that only
// names `x` keeps whatever the element was doing otherwise.
s.pushHistory();
// replace starts the track over, in the same undo step as its keys.
if (input.replace === true) s.updateOverlaysTransient([{ id: o.id, patch: { kf: undefined } }]);
for (const k of raw as Record<string, unknown>[]) {
if (!isNum(k.t)) throw new ToolError("Every key needs a time `t`.");
sent.add(roundT(onFrame(clamp(k.t, 0, dur))));
s.setOverlayKey(
o.id,
onFrame(clamp(k.t, 0, dur)),
{
...(isNum(k.x) ? { x: clampKeyPos(k.x, o) } : {}),
...(isNum(k.y) ? { y: clampKeyPos(k.y, o) } : {}),
...(isNum(k.scale) ? { scale: clamp(k.scale, 0.1, 4) } : {}),
...(isNum(k.scale_x) ? { scaleX: clamp(k.scale_x, 0, 4) } : {}),
...(isNum(k.scale_y) ? { scaleY: clamp(k.scale_y, 0, 4) } : {}),
...(isNum(k.rotation) ? { rotation: degInput(k.rotation) } : {}),
...(isNum(k.tilt_x) ? { tiltX: clamp(Math.round(k.tilt_x), -TILT_MAX, TILT_MAX) } : {}),
...(isNum(k.tilt_y) ? { tiltY: clamp(Math.round(k.tilt_y), -TILT_MAX, TILT_MAX) } : {}),
...(isNum(k.opacity) ? { opacity: clamp(k.opacity, 0, 1) } : {}),
...(isNum(k.blur) ? { blur: clamp(k.blur, 0, ELEMENT_BLUR_MAX) } : {}),
...(k.ease !== undefined ? { ease: easeInput(k.ease) } : {}),
},
{ transient: true }
);
}
kf = useEditor.getState().overlays.find((x) => x.id === o.id)?.kf;
}
// A merge keeps keys this call never named; say which, so a key meant to
// go is not sent around again and again.
const kept = raw.length && input.replace !== true ? (kf ?? []).map((k) => roundT(k.t)).filter((t) => !sent.has(t)) : [];
return {
id: o.id,
keys: (kf ?? []).map((k) => ({ ...k, t: roundT(k.t) })),
...(kept.length
? { kept, note: `Keys at ${kept.join(", ")}s were already on the track and stay; pass replace true with the full list to drop them.` }
: {}),
};
},
set_group_camera: (s, input) => {
const memberIds = Array.isArray(input.ids) ? input.ids.map(String) : [];
const groupId =
typeof input.group_id === "string" && input.group_id
? input.group_id
: memberIds.map((id) => s.overlays.find((o) => o.id === id)?.groupId).find(Boolean);
if (!groupId) throw new ToolError("Pass group_id, or ids of elements in a group (group_items makes one).");
const view = groupCameraOf(s.overlays, groupId);
if (!view) throw new ToolError(`Group ${groupId} has no titles, shapes or stickers for a camera to film.`);
let keys = view.keys;
if (input.keys !== undefined) {
if (!Array.isArray(input.keys)) throw new ToolError("keys must be a list.");
keys = [];
for (const k of input.keys as Record<string, unknown>[]) {
if (!isNum(k.t)) throw new ToolError("Every key needs a time `t`.");
const t = clamp(k.t, 0, Math.max(0.1, view.end - view.start));
// Omitted fields hold the camera where it already was at that time.
const was = groupCameraPoseAt(view, t);
const key: CameraKey = {
t,
x: isNum(k.x) ? clamp(k.x, CAMERA_WORLD_MIN, CAMERA_WORLD_MAX) : was.x,
y: isNum(k.y) ? clamp(k.y, CAMERA_WORLD_MIN, CAMERA_WORLD_MAX) : was.y,
scale: isNum(k.scale) ? clamp(k.scale, CAMERA_SCALE_MIN, CAMERA_SCALE_MAX) : was.scale,
rotation: isNum(k.rotation) ? clamp(k.rotation, -180, 180) : was.rotation,
};
const ease = k.ease !== undefined ? easeInput(k.ease) : undefined;
if (ease) key.ease = ease;
keys = upsertCameraKey(keys, key);
}
}
const motionBlur = shutterInput(input, view.motionBlur);
s.setGroupCamera(groupId, { keys, ...(motionBlur ? { motionBlur } : {}) });
const next = groupCameraOf(useEditor.getState().overlays, groupId)!;
return {
groupId,
start: roundT(next.start),
keys: next.keys.map((k) => ({ ...k, t: roundT(k.t), x: round2(k.x), y: round2(k.y), scale: round2(k.scale) })),
motionBlur: next.motionBlur ?? null,
};
},
set_clip_keyframes: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
const raw = input.keys;
const dur = clipLen(clip);
let kf = clip.kf;
// The shutter rides beside the track: on, off, or kept. With no keys
// in the call it is the whole edit and its own undo step; with keys it
// joins theirs.
const motionBlur = shutterInput(input, clip.motionBlur);
if (raw === undefined) {
if (motionBlur !== clip.motionBlur) {
s.pushHistory();
s.updateClipTransient(clip.id, { motionBlur });
}
return { id: clip.id, keys: (kf ?? []).map((k) => ({ ...k, t: roundT(k.t) })), motionBlur: motionBlur ?? null };
}
if (!Array.isArray(raw)) throw new ToolError("keys must be a list.");
if (raw.length === 0) {
s.clearClipKeys(clip.id);
kf = undefined;
} else {
// Each key builds on the pose already at its time, so a key that only
// names `x` keeps whatever the clip was doing otherwise.
s.pushHistory();
for (const k of raw as Record<string, unknown>[]) {
if (!isNum(k.t)) throw new ToolError("Every key needs a time `t`.");
s.setClipKey(
clip.id,
clamp(k.t, 0, dur),
{
...(isNum(k.x) ? { x: clamp(k.x, -0.5, 1.5) } : {}),
...(isNum(k.y) ? { y: clamp(k.y, -0.5, 1.5) } : {}),
...(isNum(k.scale) ? { scale: clamp(k.scale, 0.1, 4) } : {}),
...(isNum(k.rotation) ? { rotation: degInput(k.rotation) } : {}),
...(isNum(k.opacity) ? { opacity: clamp(k.opacity, 0, 1) } : {}),
...(isNum(k.blur) ? { blur: clamp(k.blur, 0, ELEMENT_BLUR_MAX) } : {}),
},
{ transient: true }
);
}
kf = useEditor.getState().clips.find((c) => c.id === clip.id)?.kf;
}
if (motionBlur !== clip.motionBlur) {
useEditor.getState().updateClipTransient(clip.id, { motionBlur });
}
return { id: clip.id, keys: (kf ?? []).map((k) => ({ ...k, t: roundT(k.t) })), motionBlur: motionBlur ?? null };
},
set_mask: (s, input) => {
// One id space: an overlay element or a video clip on any track.
const o = s.overlays.find((x) => x.id === input.id);
const clip = o ? undefined : s.clips.find((c) => c.id === input.id);
if (!o && !clip)
throw new ToolError("No overlay element or video clip with that id.");
if (o && isEffectOverlay(o)) throw new ToolError("Effect elements have no pixels to mask.");
const current = o ? o.mask : clip!.mask;
const setMask = (mask: Mask | undefined) =>
o ? s.updateOverlay(o.id, { mask }) : s.updateClip(clip!.id, { mask });
if (input.kind === "none") {
setMask(undefined);
return { id: input.id, mask: null };
}
const kind =
typeof input.kind === "string"
? input.kind
: (current?.kind ?? "rect");
if (!(MASK_KINDS as string[]).includes(kind))
throw new ToolError(`Unknown mask kind. Use one of: ${MASK_KINDS.join(", ")}, none.`);
const geom = (k: Record<string, unknown>) => ({
...(isNum(k.x) ? { x: clamp(k.x, -1, 1) } : {}),
...(isNum(k.y) ? { y: clamp(k.y, -1, 1) } : {}),
...(isNum(k.w) ? { w: clamp(k.w, 0.01, 2) } : {}),
...(isNum(k.h) ? { h: clamp(k.h, 0.01, 2) } : {}),
...(isNum(k.rotation) ? { rotation: degInput(k.rotation) } : {}),
...(isNum(k.feather) ? { feather: clamp(k.feather, 0, MASK_FEATHER_MAX) } : {}),
...(isNum(k.radius) ? { radius: clamp(k.radius, 0, MASK_RADIUS_MAX) } : {}),
});
const mask: Mask = {
...(current ?? {}),
...geom(input),
kind: kind as Mask["kind"],
...(typeof input.invert === "boolean" ? { invert: input.invert || undefined } : {}),
...(isNum(input.radius) ? { radius: clamp(input.radius, 0, MASK_RADIUS_MAX) || undefined } : {}),
};
// A radius belongs to a box; a shape that has no corners to round drops it.
if (!maskHasRadius(mask.kind)) delete mask.radius;
// A pen outline is its corners; every other kind has no use for them.
if (mask.kind === "pen") {
if (Array.isArray(input.points)) {
const pts = (input.points as unknown[]).map((p) => {
const q = p as Record<string, unknown>;
if (!isNum(q?.x) || !isNum(q?.y))
throw new ToolError("Every pen point needs numeric x and y.");
return { x: clamp(q.x, -2, 2), y: clamp(q.y, -2, 2) };
});
if (pts.length < PEN_MIN_POINTS)
throw new ToolError(`A pen outline needs at least ${PEN_MIN_POINTS} points.`);
mask.points = pts;
}
if (!penClosed(mask))
throw new ToolError(`A pen mask needs \`points\`: at least ${PEN_MIN_POINTS} corners.`);
} else {
delete mask.points;
}
// An element newly masked by the person starts behind them — the common
// ask — unless the call named a direction; invert false shows it only on
// the person. Clips keep the plain direction (Subject keeps the person).
if (
o &&
mask.kind === "subject" &&
current?.kind !== "subject" &&
typeof input.invert !== "boolean"
) {
mask.invert = true;
}
// A circle with no explicit h is a perfect circle: w and h are fractions
// of different frame edges, so round means unequal fractions.
if (mask.kind === "circle" && !isNum(input.h)) {
const fr = frameOf(s.aspect);
mask.h = clamp(((mask.w ?? 0.5) * fr.w) / fr.h, 0.01, 2);
}
const dur = o ? Math.max(0.1, o.end - o.start) : clipLen(clip!);
setMask(mask);
// Keys layer on after the mask lands, so each one captures against the
// geometry the call just set.
const raw = input.keys;
if (Array.isArray(raw)) {
const st = useEditor.getState();
if (raw.length === 0) {
if (o) st.clearOverlayMaskKeys(o.id);
else st.clearClipMaskKeys(clip!.id);
} else {
for (const k of raw as Record<string, unknown>[]) {
if (!isNum(k.t)) throw new ToolError("Every mask key needs a time `t`.");
const t = clamp(k.t, 0, dur);
if (o) st.setOverlayMaskKey(o.id, t, geom(k), { transient: true });
else st.setClipMaskKey(clip!.id, t, geom(k), { transient: true });
}
}
}
const after = useEditor.getState();
const next = o
? after.overlays.find((x) => x.id === o.id)?.mask
: after.clips.find((c) => c.id === clip!.id)?.mask;
return { id: input.id, mask: next ?? null };
},
track_motion: async (_s, input) => {
const target = TRACK_TARGET_IDS.find((t) => t === input.target);
if (!target) throw new ToolError(`target must be one of: ${TRACK_TARGET_IDS.join(", ")}.`);
const use = TRACK_USES.find((u) => u === input.use);
if (!use) throw new ToolError(`use must be one of: ${TRACK_USES.join(", ")}.`);
const follow = input.follow_mode === undefined ? undefined : FOLLOW_MODES.find((m) => m === input.follow_mode);
if (input.follow_mode !== undefined && !follow) throw new ToolError(`follow_mode must be one of: ${FOLLOW_MODES.join(", ")}.`);
return trackMotion({
id: String(input.id ?? ""),
target,
use,
...(typeof input.source_id === "string" ? { sourceId: input.source_id } : {}),
...(isNum(input.from) ? { from: input.from } : {}),
...(isNum(input.to) ? { to: input.to } : {}),
...(follow ? { follow } : {}),
...(isNum(input.feather) ? { feather: input.feather } : {}),
...(typeof input.invert === "boolean" ? { invert: input.invert } : {}),
}).catch((e) => {
throw new ToolError(e instanceof Error ? e.message : "Could not track the footage.", { cause: e });
});
},
set_transition: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
// A transition joins a clip to the next one on its own track.
const row = s.clips.filter((c) => c.track === clip.track);
if (row.findIndex((c) => c.id === clip.id) === row.length - 1)
throw new ToolError("That is its track's last clip — nothing after it to transition into.");
if (!isNum(input.seconds)) throw new ToolError("seconds is required (0 clears the transition).");
let style: TransitionStyle | undefined;
if (input.style !== undefined) {
const requested = TRANSITION_STYLE_SYNONYMS[input.style as string] ?? input.style;
style = TRANSITION_STYLE_IDS.find((x) => x === requested);
if (!style) throw new ToolError(`Unknown style. Use one of: ${TRANSITION_STYLE_IDS.join(", ")}.`);
}
// Refused before anything lands, so a failed call changes nothing.
if (isNum(input.band) && input.seconds > 0 && !takesBand(style ?? clip.transitionStyle ?? "crossfade"))
throw new ToolError(`band is for the wipes only (${BAND_STYLES.join(", ")}).`);
s.setClipTransition(clip.id, input.seconds, style);
let after = useEditor.getState();
// The bar's own id rides the result so remove_transition can round-trip it.
const roles = resolveTransitions(after.clips, after.transitions);
const bar = after.transitions.find((t) =>
(roles.get(t.id) ?? []).some((r) => r.kind !== "in" && r.clipId === clip.id)
);
// The softness and the band land on the bar inside the same undo step.
if (bar && isNum(input.feather)) {
const feather = clampFeather(input.feather);
after.updateTransitionTransient(bar.id, { feather: feather > 0 ? feather : undefined });
after = useEditor.getState();
}
if (bar && isNum(input.band) && takesBand(bar.style)) {
const band = clampBand(input.band);
after.updateTransitionTransient(bar.id, { band: band > 0 ? band : undefined });
after = useEditor.getState();
}
const next = after.clips.find((c) => c.id === clip.id)!;
return {
id: next.id,
transitionId: bar?.id ?? null,
transition: next.transition ?? 0,
style: next.transitionStyle ?? "crossfade",
...(next.transitionFeather ? { feather: next.transitionFeather } : {}),
...(next.transitionBand ? { band: next.transitionBand } : {}),
};
},
remove_transition: (s, input) => {
const id = String(input.transitionId ?? "");
if (!s.transitions.some((t) => t.id === id))
throw new ToolError(`No transition bar with id ${id}.`);
s.removeTransition(id);
return { removed: id, ...tracksAfter() };
},
set_transition_hidden: (s, input) => {
const id = String(input.transitionId ?? "");
const bar = s.transitions.find((t) => t.id === id);
if (!bar) throw new ToolError(`No transition bar with id ${id}.`);
const hidden = Boolean(input.hidden);
s.updateTransition(id, { hidden: hidden || undefined });
return { id, hidden, style: bar.style, seconds: bar.seconds };
},
set_animation: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
const which = input.which === "in" || input.which === "out" ? input.which : null;
if (!which) throw new ToolError('which must be "in" or "out".');
if (input.style === "none") {
s.setClipAnim(clip.id, which, null);
return { id: clip.id, which, style: "none" };
}
const requested = ANIM_STYLE_SYNONYMS[input.style as string] ?? input.style;
const style = ANIM_STYLE_IDS.find((x) => x === requested);
if (!style)
throw new ToolError(`Unknown style. Use one of: ${ANIM_STYLE_IDS.join(", ")}, none.`);
if (clip.track > 0 && overlayAnimStyle(style) !== style)
throw new ToolError("Upper-track clips animate with fade or zoom only.");
const seconds = isNum(input.seconds) ? input.seconds : ANIM_DEFAULT_SECONDS;
s.setClipAnim(clip.id, which, { style, seconds });
const after = useEditor.getState();
const next = after.clips.find((c) => c.id === clip.id)!;
const anim = which === "in" ? next.animIn : next.animOut;
if (anim) return { id: next.id, which, style: anim.style, seconds: anim.seconds };
// The bar did not take this edge. A clip butting against this one on
// its track turns the bar into the cut between the two, so the clip has
// no entrance or exit of its own there; say so, so the reply never
// claims an animation the clip lacks.
const edge = which === "in" ? next.start : next.start + clipLen(next);
const neighbour = after.clips.find(
(c) =>
c.track === next.track &&
c.id !== next.id &&
Math.abs((which === "in" ? c.start + clipLen(c) : c.start) - edge) <= ANIM_TOUCH_SECONDS
);
const name = (c: VideoClip) => after.assets.find((a) => a.id === c.assetId)?.name ?? c.id;
return {
id: next.id,
which,
style: "none",
seconds: 0,
note: neighbour
? `Not set: "${name(neighbour)}" (${neighbour.id}) ${which === "in" ? "ends" : "starts"} at ${roundT(edge)}s on track ${next.track}, so the bar plays as the cut between the two and this clip has no ${which === "in" ? "entrance" : "exit"}. Leave a gap between them (update_overlay_video start or out) or move one to another track, then set it again.`
: `Not set: the bar did not land on this clip's ${which} edge at ${roundT(edge)}s.`,
};
},
get_state: (s, input) => {
if (input.timeline !== undefined && !isTimelineId(input.timeline))
throw new ToolError(`timeline must be one of ${TIMELINE_IDS.join(", ")}.`);
// The tool result carries the whole transcript; the per-message context
// snapshot trims it, so this is how the model pulls every cue when needed.
// A parked timeline reads as its items alone.
const full = (
isTimelineId(input.timeline) && input.timeline !== s.timeline
? describeParkedTimeline(input.timeline)
: buildAiContext({ fullCues: true })
) as Record<string, unknown>;
const want: unknown[] = Array.isArray(input.sections) ? input.sections : [];
if (want.length === 0) return full;
// A big cut read whole runs past what a tool result can carry; a read
// that names its sections stays small enough to check an edit with.
const names = Object.keys(full);
const bad = want.filter((k) => typeof k !== "string" || !names.includes(k));
if (bad.length > 0) throw new ToolError(`Unknown section ${bad.join(", ")}; sections are ${names.join(", ")}.`);
return Object.fromEntries(
names.filter((k) => k === "playhead" || k === "timeline" || want.includes(k)).map((k) => [k, full[k]])
);
},
get_asset_info: async (s, input) => {
const asset = requireItem(s.assets, input.asset_id, "project asset");
if (asset.block) throw new ToolError("This placeholder has no source file.");
const sizeBytes = asset.sizeBytes ?? await readMediaFileSize(asset.url);
return {
id: asset.id, name: asset.name, fileName: asset.fileName, kind: asset.type,
sizeBytes, fileSize: formatBytes(sizeBytes, "en"), duration: roundT(asset.duration), width: asset.width, height: asset.height,
};
},
find_media: (s, input) => {
// The same media the snapshot would show this chat, past its cap.
const placed = assetIdsOnAnyTimeline(s);
const chatId = chatOwner();
const visible = s.assets.filter((a) => !isLinkedAssetType(a.type) && !hiddenFromChat(a, chatId, placed));
const type = input.type === "video" || input.type === "image" || input.type === "audio" ? input.type : undefined;
const query = typeof input.query === "string" ? input.query : undefined;
const found = findMedia(visible, {
query,
type,
limit: isNum(input.limit) ? input.limit : undefined,
offset: isNum(input.offset) ? input.offset : undefined,
});
// Matches the chat can't see still exist, and the answer says so.
const held = findMedia(
s.assets.filter((a) => !isLinkedAssetType(a.type) && hiddenFromChat(a, chatId, placed)),
{ query, type }
).total;
return {
total: found.total,
assets: found.page.map((a) => ({
id: a.id,
name: a.name,
type: a.type,
fileName: a.fileName,
duration: roundT(a.duration),
...(a.width !== undefined ? { width: a.width, height: a.height } : {}),
...(a.folderId != null ? { folderId: a.folderId } : {}),
})),
...(found.next !== undefined ? { next: found.next } : {}),
...(held > 0 ? { heldByOtherChats: held, note: OTHER_CHATS_MEDIA_NOTE } : {}),
};
},
render_preview: async (s, _input, operation) => {
if (!s.projectId || !s.loaded) throw new ToolError("No project open.");
return submitPreviewSnapshot(captureRenderSnapshot(operation ?? projectOperation(s.projectId), renderDoc(s)));
},
capture_frame: async (s, input) => {
// Composited through the render path, so the frame carries what the
// finished file would carry — clips, transitions, effects, elements,
// captions — the preview's video layer alone leaves its DOM elements
// floating above it. The cut runs as long as anything on it does, so a
// cut of shapes and titles alone is reachable past 0.
const total = projectDuration(s);
const at = clamp(isNum(input.t) ? input.t : playheadAt(), 0, Math.max(0, total - 0.001));
const frame = frameOf(s.aspect);
const k = CAPTURE_LONG_SIDE / Math.max(frame.w, frame.h);
const canvas = await renderProjectFrame(
{
aspect: s.aspect,
assets: s.assets,
clips: s.clips,
audioClips: s.audioClips,
overlays: s.overlays,
subtitles: s.subtitles,
background: s.background,
},
at,
{ width: Math.round(frame.w * k), height: Math.round(frame.h * k) },
(asset) => asset.url
).catch((e) => {
throw new ToolError(e instanceof Error ? e.message : "Could not draw the frame.", { cause: e });
});
return { image: await rasterCanvasToDataUrl(canvas, "image/jpeg", 0.75), at };
},
compare_to_source: async (s, input) => {
// Building from a reference and looking at the reference are separate
// acts, and until they are put side by side nothing checks the first
// against the second. The picture call renders the cut at a few
// moments beside the source's frames and scores each pair; the sweep
// scores a whole stretch with no pictures, to find what to look at.
const asset = requireItem(s.assets, input.asset_id, "project asset");
if (asset.type === "audio")
throw new ToolError(`"${asset.name}" is audio — listen_audio hears it, and a frame is a picture.`);
// Without a length every moment clamps to 0 and the comparison hands
// back the same opening frame under four different stamps.
if (!(asset.duration > 0))
throw new ToolError(`"${asset.name}" has no length yet — its import is still being read. Try again in a moment.`);
if (input.mode !== undefined && !(COMPARE_MODES as readonly unknown[]).includes(input.mode)) {
throw new ToolError(`mode is one of ${COMPARE_MODES.join(", ")}.`);
}
const offset = isNum(input.offset) ? input.offset : 0;
const total = projectDuration(s);
const doc = {
aspect: s.aspect,
assets: s.assets,
clips: s.clips,
audioClips: s.audioClips,
overlays: s.overlays,
subtitles: s.subtitles,
background: s.background,
};
const failed = (fallback: string) => (e: unknown) => {
throw new ToolError(e instanceof Error ? e.message : fallback, { cause: e });
};
// Only the source's picture box is held against the cut's frame.
const area = pictureArea(asset, input);
// A source of another shape is letterboxed unless the call asks it to fill.
const fit = input.fit === "fill" ? "fill" : "letterbox";
// The sweep: numbers over a span, at a step, under a time budget.
if (input.mode === "sweep") {
const sweep = await sweepSource(
doc,
asset,
{
from: isNum(input.from) ? input.from : 0,
to: isNum(input.to) ? input.to : total,
step: isNum(input.step) ? input.step : undefined,
offset,
},
total,
area,
fit
).catch(failed(`Could not sweep "${asset.name}".`));
return {
...sweep,
...pictureReport(area),
source: sourceRef(asset),
note:
(sweep.stopped
? `The source stopped decoding, so the sweep ends at ${sweep.coveredTo}s: ${sweep.stopped} Sweep again from a little past it for the rest. `
: sweep.coveredTo !== undefined
? `The sweep ran out of time at ${sweep.coveredTo}s; sweep again from there for the rest. `
: "") +
(sweep.lost
? `Source frames at ${sweep.lost.map((l) => `${l.source}s`).join(", ")} did not decode (${sweep.lost[0].error}) and are left out of the scores. `
: "") +
silenceNote(s, asset) +
SWEEP_NOTE,
};
}
// The picture call: a few moments, each a picture and a score.
const raw = Array.isArray(input.times) ? input.times : [];
const moments = raw
.map((x) => {
const rec = (x ?? {}) as Record<string, unknown>;
const at = isNum(x) ? (x as number) : isNum(rec.at) ? (rec.at as number) : NaN;
const sourceAt = isNum(rec.source) ? (rec.source as number) : at + offset;
return { at, sourceAt };
})
.filter((m) => Number.isFinite(m.at) && Number.isFinite(m.sourceAt));
if (moments.length === 0)
throw new ToolError("Pass times: [seconds] — the moments of the cut to check, or [{at, source}] when the cut sits at a different second than the source does. To score the whole cut first, pass mode: \"sweep\".");
if (moments.length > MAX_COMPARE)
throw new ToolError(`That is ${moments.length} moments — ${MAX_COMPARE} is the most one call reads. Check these, fix what is off, then call again for the rest; mode: "sweep" scores every frame without pictures.`);
const out = await compareMoments(doc, asset, moments, total, area, fit).catch(failed("Could not compare the frames."));
return {
...out,
...pictureReport(area),
// The same shape every look returns, so a record opened by a
// comparison knows what the other senses may ask of this source.
source: sourceRef(asset),
note: silenceNote(s, asset) + COMPARE_NOTE,
};
},
find_picture: async (s, input) => {
// Where the picture sits inside the source's frame: found from what
// changes over time, or set as the model sees it. Kept on the asset,
// where every source-reading tool reads inside it from then on.
const asset = measuredSource(s, input, "picture");
let found: Awaited<ReturnType<typeof findPicture>> = null;
let box: FrameBox;
if (input.box === "full") {
box = FULL_FRAME;
} else if (input.box !== undefined && input.box !== null) {
box = frameBoxOf(input.box, "box")!;
} else {
if (asset.type === "image")
throw new ToolError(`"${asset.name}" is a still — nothing in it changes to find its picture by. Pass box: the picture's {x, y, w, h} as you see it.`);
const from = clamp(isNum(input.from) ? input.from : 0, 0, asset.duration);
const to = isNum(input.to) ? clamp(input.to, from, asset.duration) : asset.duration;
if (!(to > from)) throw new ToolError("from/to describe an empty range of the source.");
found = await storePicture(asset, from, to);
box = found?.box ?? FULL_FRAME;
}
useEditor.getState().updateAsset(asset.id, { picture: box });
// Its size in the source's pixels, when the source's size is known.
const pw = asset.width ? box.w * asset.width : 0;
const ph = asset.height ? box.h * asset.height : 0;
const full = isFullFrame(box);
return {
picture: { x: rF(box.x), y: rF(box.y), w: rF(box.w), h: rF(box.h) },
full,
...(found ? { active: found.active } : {}),
...(pw > 0 && ph > 0 ? { pixels: { width: Math.round(pw), height: Math.round(ph) }, aspect: round2(pw / ph) } : {}),
source: sourceRef(asset),
note:
input.box === undefined && !found
? "Too little of the frame changes to tell the picture from what is around it, so the tools read the whole frame. Pass box once you can see where the picture sits (watch_video at detail original)."
: full
? "The picture fills the whole frame; the tools read all of it."
: "The picture fills this box of the recorded frame (centre and size as frame fractions). detect_cuts, sample_color, track_element, suggest_font and compare_to_source read inside it from now on, and their x, y, w, h are fractions of it, so they land on the cut's frame as they are. " +
"aspect is its shape; set_aspect to match when the copy should. A box that is off — check it on a watch_video frame at detail original — is set with box.",
};
},
detect_cuts: async (s, input) => {
// Every frame of the span, scored against the one before: the cuts a
// sampled watch can step over, each on its own frame.
const asset = measuredSource(s, input, "video");
const from = clamp(isNum(input.from) ? input.from : 0, 0, asset.duration);
const asked = isNum(input.to) ? clamp(input.to, 0, asset.duration) : asset.duration;
const to = Math.min(asked, from + DETECT_CUTS_SPAN_MAX);
if (!(to > from)) throw new ToolError("from/to describe an empty range of the source.");
// A source read for the first time has its picture found and kept, so
// a change that fills the picture counts in full when the picture is a
// small part of a recorded frame.
const keepsPicture = input.picture === undefined && !asset.picture;
if (keepsPicture) {
await storePicture(asset, 0, asset.duration);
}
const area = pictureArea(useEditor.getState().assets.find((a) => a.id === asset.id) ?? asset, input);
const scan = await withSweepPaused(() =>
scanCuts(asset.url, {
from,
to,
maxCuts: DETECT_CUTS_MAX,
maxChanges: DETECT_CHANGES_MAX,
budgetMs: MEASURE_BUDGET_MS,
...(isFullFrame(area) ? {} : { area }),
})
).catch((e) => {
throw new ToolError(e instanceof Error ? e.message : `Could not read "${asset.name}".`, { cause: e });
});
const fps = Math.round(scan.fps * 100) / 100;
// The shots between the cuts, from the span's start to where the pass
// reached, each with its length in frames.
const edges = [from, ...scan.cuts.map((c) => c.t), scan.coveredTo];
const shots = edges.slice(1).map((end, i) => ({
from: roundT(edges[i]),
to: roundT(end),
frames: Math.round((end - edges[i]) * scan.fps),
}));
// Every shot's middle and the frame each change settles on: watch_video
// lands a frame on each, so a card shorter than its step is still read.
const settled = scan.changes.map((c) => c.t + c.frames / scan.fps);
shotMoments.set(asset.id, [
...(shotMoments.get(asset.id) ?? []).filter((t) => t < from || t >= scan.coveredTo),
...shots.map((sh) => (sh.from + sh.to) / 2),
...settled.filter((t) => t < scan.coveredTo),
]);
// The span bound ends a pass the caller asked to run further.
const truncated = scan.truncated || to < asked;
const more = truncated || to < asset.duration - 0.001;
return {
fps,
framesRead: scan.frames,
from: roundT(from),
coveredTo: roundT(scan.coveredTo),
truncated,
cuts: scan.cuts.map((c) => ({ t: roundT(c.t), frame: c.frame, change: c.change })),
shots,
changes: scan.changes.map((c) => ({
t: roundT(c.t),
frame: c.frame,
frames: c.frames,
change: c.change,
box: { x: roundT(c.box.x), y: roundT(c.box.y), w: roundT(c.box.w), h: roundT(c.box.h) },
...(c.flicker ? { flicker: true as const } : {}),
})),
...(scan.fades.length
? {
fades: scan.fades.map((f) => ({
t: roundT(f.t),
frame: f.frame,
seconds: roundT(f.seconds),
fade: f.fade,
tone: f.tone,
amount: Math.round(f.amount * 100) / 100,
ease: f.ease,
})),
fadesNote:
"The whole picture fading into the tone (fade to) or out of it (fade from), each read off every frame: add_effect flash with fade, tone, amount and fade_ease as they are, start t and end t + seconds, on the front row. A fade whose end runs a frame or two past the source's end is one the source cuts off: end the effect with the cut.",
}
: {}),
...pictureReport(area),
...(keepsPicture ? { pictureKept: true as const } : {}),
source: sourceRef(asset),
note:
(scan.cuts.length === 0 ? "No hard cut in this span. " : "") +
(more
? `The source runs on past ${roundT(scan.coveredTo)}s — call again with from: ${roundT(scan.coveredTo)} for the rest. The last shot listed runs on past it.`
: "Shot n runs from one cut to the next; the first from `from`, the last to the end."),
};
},
sample_color: async (s, input) => {
const asset = measuredSource(s, input, "picture");
const raw = Array.isArray(input.samples) ? input.samples : [];
if (raw.length === 0)
throw new ToolError("Pass samples: [{t, x, y, w?, h?}] — a source second and a box (or a point) on the frame, as fractions.");
if (raw.length > SAMPLE_COLOR_MAX)
throw new ToolError(`That is ${raw.length} samples — ${SAMPLE_COLOR_MAX} is the most one call reads. Read these, then call again for the rest.`);
const samples = raw.map((x, i) => {
const rec = (x ?? {}) as Record<string, unknown>;
if (!isNum(rec.x) || !isNum(rec.y)) throw new ToolError(`Sample ${i + 1} needs x and y, the centre as frame fractions.`);
if (asset.type === "video" && !isNum(rec.t)) throw new ToolError(`Sample ${i + 1} needs t, the source second to read.`);
const point = !isNum(rec.w) || !isNum(rec.h);
const t = asset.type === "video" ? clamp(rec.t as number, 0, Math.max(0, asset.duration - 0.001)) : 0;
// A point is the few pixels around it: one decoded pixel is grain.
const box: FrameBox = {
x: clamp(rec.x, 0, 1),
y: clamp(rec.y, 0, 1),
w: point ? POINT_SIZE : clamp(rec.w as number, 0, 1),
h: point ? POINT_SIZE : clamp(rec.h as number, 0, 1),
};
return { t, box, point };
});
const k = isNum(input.colors) ? clamp(Math.round(input.colors), 1, SAMPLE_COLORS_K_MAX) : 1;
const area = pictureArea(asset, input);
const read = await withSweepPaused(() => sampleColors(asset.url, asset.type === "image" ? "image" : "video", samples, k, area)).catch((e) => {
throw new ToolError(e instanceof Error ? e.message : `Could not read "${asset.name}".`, { cause: e });
});
return {
samples: samples.map((smp, i) => ({
...(asset.type === "video" ? { t: roundT(smp.t) } : {}),
x: rF(smp.box.x),
y: rF(smp.box.y),
...(smp.point ? {} : { w: rF(smp.box.w), h: rF(smp.box.h) }),
...read[i],
})),
...(read.some((r) => r.stripes)
? {
stripesNote:
"A sample with `stripes` is laid in parallel lines: lay a block in its ground colour, then the same box over it as add_shape with fill the line colour, pattern stripes and pattern_width, pattern_gap and pattern_angle as they are.",
}
: {}),
...pictureReport(area),
source: sourceRef(asset),
};
},
track_element: async (s, input) => {
const asset = measuredSource(s, input, "picture");
const seed = frameBoxOf(input.seed, "seed");
if (!seed) throw new ToolError("Pass seed: {x, y, w, h} — a box on the element at from, centre and size as frame fractions.");
const within = input.within === undefined || input.within === null ? undefined : frameBoxOf(input.within, "within");
const color = typeof input.color === "string" && input.color.trim() ? input.color.trim() : undefined;
if (color && !/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.test(color)) throw new ToolError(`color "${color}" is not a hex colour — pass #RRGGBB.`);
const match = TRACK_MATCHES.includes(input.match as (typeof TRACK_MATCHES)[number])
? (input.match as (typeof TRACK_MATCHES)[number])
: "shape";
const end = Math.max(0, asset.duration - 0.001);
const from = asset.type === "video" ? clamp(isNum(input.from) ? input.from : 0, 0, end) : 0;
const to = asset.type === "video" && isNum(input.to) && input.to > from ? clamp(input.to, 0, asset.duration) : undefined;
const area = pictureArea(asset, input);
if (match === "letters") return trackLettersResult(asset, input, { from, to, seed, color, area });
const run = await withSweepPaused(() =>
trackElement(asset.url, asset.type === "image" ? "image" : "video", {
area,
from,
...(to !== undefined ? { to } : {}),
seed,
...(within ? { within } : {}),
...(color ? { color } : {}),
tolerance: isNum(input.tolerance) ? clamp(input.tolerance, 0, 255) : TRACK_TOLERANCE_DEFAULT,
match,
maxFrames: TRACK_FRAMES_MAX,
})
).catch((e) => {
throw new ToolError(e instanceof Error ? e.message : `Could not read "${asset.name}".`, { cause: e });
});
const found = run.boxes.filter((b) => b.box).length;
if (found === 0)
throw new ToolError(
`Nothing of ${run.color} ${match === "ink" ? "inside the seed" : "under or near the seed"} in ${run.boxes.length} frame${run.boxes.length === 1 ? "" : "s"}. ` +
"Check the colour with sample_color at a moment the element shows, pass it as color, and raise tolerance for a soft or shaded fill."
);
const { path, thinned } = trackPath(run.boxes);
return {
color: run.color,
match,
...(run.fps > 0 ? { fps: Math.round(run.fps * 100) / 100 } : {}),
framesRead: run.boxes.length,
framesFound: found,
path,
...(thinned ? { thinned: true } : {}),
moves: run.moves.map((m) => ({
prop: m.prop,
from: roundT(m.from),
to: roundT(m.to),
start: rF(m.start),
end: rF(m.end),
ease: m.ease,
error: Math.round(m.error * 1000) / 1000,
})),
...(to !== undefined ? { coveredTo: roundT(run.coveredTo), truncated: run.truncated } : {}),
...pictureReport(area),
source: sourceRef(asset),
};
},
track_camera: async (s, input) => {
const asset = measuredSource(s, input, "video");
const end = Math.max(0, asset.duration - 0.001);
const from = clamp(isNum(input.from) ? input.from : 0, 0, end);
if (!isNum(input.to) || input.to <= from) throw new ToolError("Pass to, the source second the stretch ends, after from.");
const to = clamp(input.to, 0, asset.duration);
const area = pictureArea(asset, input);
const run = await withSweepPaused(() => trackCamera(asset.url, { from, to, area, maxFrames: CAMERA_FRAMES_MAX })).catch((e) => {
throw new ToolError(e instanceof Error ? e.message : `Could not read "${asset.name}".`, { cause: e });
});
if (run.path.length < 2) throw new ToolError(`Only ${run.path.length} frame between ${from}s and ${to}s — give a longer stretch.`);
const r3 = (v: number) => Math.round(v * 1000) / 1000;
const anchor = zoomAnchor(run.path);
return {
...(run.fps > 0 ? { fps: Math.round(run.fps * 100) / 100 } : {}),
framesRead: run.path.length,
still: run.still,
path: run.path.map((p) => ({
t: roundT(p.t),
scale: r3(p.scale),
dx: r3(p.dx),
dy: r3(p.dy),
rotation: Math.round(p.rotation * 10) / 10,
residual: Number.isFinite(p.residual) ? Math.round(p.residual * 10) / 10 : null,
...(p.second
? {
second: {
scale: r3(p.second.scale),
dx: r3(p.second.dx),
dy: r3(p.second.dy),
rotation: Math.round(p.second.rotation * 10) / 10,
share: Math.round(p.second.share * 100) / 100,
},
}
: {}),
})),
moves: run.moves.map((m) => ({
prop: m.prop,
from: roundT(m.from),
to: roundT(m.to),
start: m.prop === "rotation" ? Math.round(m.start * 10) / 10 : r3(m.start),
end: m.prop === "rotation" ? Math.round(m.end * 10) / 10 : r3(m.end),
ease: m.ease,
error: Math.round(m.error * 1000) / 1000,
})),
coveredTo: roundT(run.coveredTo),
truncated: run.truncated,
...(anchor
? {
anchor: { x: r3(anchor.x), y: r3(anchor.y) },
anchorNote:
"The zoom holds this frame point still: everything grows away from it. A zoom into a title's letter until its ink fills the frame is a dive exit with out_anchor this point (set_overlay_animation); a punch-in on footage keys the clip about it.",
}
: {}),
...pictureReport(area),
source: sourceRef(asset),
};
},
watch_video: async (s, input) => {
// A look at a reference project's footage decides a mapping and writes
// nothing: no note owed, no frame map kept, no sweep started.
const reference = await resolveReferenceWatch(input);
const { asset, clip, speed, from, to } = reference ?? resolveWatchRange(s, input);
// The reading of the last look comes before the next one. Without it a
// long source is watched into a conversation that keeps dropping the
// sheets, and the tail arrives with the head already gone.
const owed = reference ? undefined : unwritten.get(asset.id);
if (owed && !spanIsNoted(asset.watch, owed))
throw new ToolError(
`You watched ${round2(owed.from)}-${round2(owed.to)}s of "${asset.name}" and have not written down what it showed. ` +
"Those sheets leave this conversation as it grows, so record them while you can still see them: call note_source with what that stretch showed — the on-screen text word for word, what happens, how it is shot, the timings — then watch on."
);
if (asset.type === "audio")
throw new ToolError(`"${asset.name}" is audio — listen_audio hears it, detect_silence finds its dead air.`);
// One path for both backends: the browser decodes the source (the same
// URL the preview plays) and the shared selector keeps distinct frames.
const detail: WatchDetail = WATCH_DETAILS.includes(input.detail as WatchDetail)
? (input.detail as WatchDetail)
: "scan";
if (asset.type === "image") {
const body = await makeStillFrame(asset.url, detail).catch((e) => {
throw new ToolError(e instanceof Error ? e.message : "Could not read the image.", { cause: e });
});
return {
images: [body.frames[0].image],
source: { assetId: asset.id, name: asset.name },
note: "A still image — one frame, no time axis.",
};
}
// Where the frames go: the steady sweep, plus a candidate on each line
// the source speaks. What it says and what it shows move together.
const aimed = speechOnsets(
sourceSpeech(s, asset, reference ? null : clip, from, to ?? asset.duration),
from,
to ?? asset.duration,
);
// The sweep yields its decoders to this call for its whole duration.
// The budget keeps the call inside the tool bridge's 120s deadline: a
// slow decode salvages what it covered (truncated + coveredTo) rather
// than timing out with nothing.
const body = await withSweepPaused(() =>
sampleWatchFrames(asset.url, {
from,
...(to !== undefined ? { to } : {}),
...(isNum(input.interval_seconds) ? { interval: input.interval_seconds } : {}),
detail,
at: aimed,
shots: shotMoments.get(asset.id) ?? [],
// A screen recording is watched inside its picture, as it is measured.
...(asset.picture ? { picture: asset.picture } : {}),
budgetMs: 90_000,
})
).catch((e) => {
throw new ToolError(e instanceof Error ? e.message : "Could not watch the video.", { cause: e });
});
// The metadata persists on the asset (it saves with the project and
// dies with the asset), so what has been seen survives this thread.
// Merge against the asset's CURRENT record — a sweep segment may have
// landed while this call was decoding, and a merge computed from the
// pre-decode snapshot would overwrite it.
const st = useEditor.getState();
const liveAsset = reference ? undefined : st.assets.find((x) => x.id === asset.id);
if (liveAsset) {
// A pass that covered nothing records nothing.
if (body.coveredTo > from) {
st.updateAsset(asset.id, {
watch: mergeWatch(liveAsset.watch, {
from,
to: body.coveredTo,
frames: body.frames.map((f) => ({ t: f.t, via: f.via })),
sceneChanges: body.sceneChanges,
readClosely: detail !== "scan",
}),
});
}
// A source with more to see owes a reading of what just went past:
// the next watch of it asks for this span's notes first.
if (body.coveredTo > from && asset.duration - body.coveredTo > 0.5)
unwritten.set(asset.id, { from: roundT(from), to: roundT(body.coveredTo) });
else unwritten.delete(asset.id);
// A first look queues the quiet background sweep of the rest of the
// source — metadata only, merged in as segments land.
queueWatchSweep(asset.id);
}
const seen = reference
? asset.watch
: useEditor.getState().assets.find((x) => x.id === asset.id)?.watch;
const unwatched = uncoveredSeconds(seen, asset.duration);
// Seen and read are separate measures: a stretch surveyed at scan is
// covered, and its words are still unknown.
const closeRanges = { ranges: seen?.read ?? [] };
const unread = uncoveredSeconds(closeRanges, asset.duration);
const nextUnread = nextUncoveredSpan(closeRanges, asset.duration);
// Tile the kept frames 3×3 and stamp each cell's source time.
const sheets = await composeSheets(body.frames, detail).catch(() => null);
const keptTimes = body.frames.map((f) => f.t);
// Kept frames woven into the speech on one clock, so the model reads
// precomputed frame↔speech alignment instead of matching by eye.
const speech = sourceSpeech(
s,
liveAsset ?? asset,
reference ? null : clip,
from,
body.coveredTo,
);
let timelineText: string | undefined;
if (speech.length > 0) {
timelineText = renderFusedTimeline(
fuseTimeline(keptTimes, speech, { from, to: body.coveredTo })
).slice(0, 4000);
}
// Each cell's time plus why the selector kept it — "global" a hard cut,
// "action" local motion, "settled" new settled detail (text, ink, UI).
const cellInfo = body.frames.map((f) => ({ t: roundT(f.t), via: f.via }));
// Where a card could sit over what was just watched: the quiet parts of
// the picture, inside whatever the project's guides keep clear. The
// watch already measured the busy ones to choose these frames.
const showing = s.guides.filter((g) => guideFits(g, s.aspect));
const safe = safeAreaOf(showing.length > 0 ? showing : ["margins"], s.aspect);
const spots = safe && !reference ? textSpots(body.edges, safe) : [];
const perSheet = sheets ? sheets.map((sh) => sh.frames.length) : [cellInfo.length];
let cellAt = 0;
// How to read the images, and what the rest of the ladder is for. The
// frames are the same moments at every detail; only the pixels differ,
// and small type is unreadable until they are spent on it.
const tiled =
watchGeometry(detail).grid > 1
? `Cells read left→right then top→bottom; each stamp is SOURCE seconds${reference ? " of the reference's file" : ""}. `
: `One frame per image, in sheetFrames order — SOURCE seconds${reference ? " of the reference's file" : ""}, no burned stamp. `;
const ladder =
detail === "original"
? "These are the source's own pixels: quote on-screen text exactly and name the type, weight, spacing and colours you can see. "
: `Detail is "${detail}" (${WATCH_DETAIL_NOTES[detail]}). If type, UI or fine treatment is too small to read here, re-watch that stretch with detail "${detail === "scan" ? "read" : "original"}" — the same moments with more pixels on each, fewer per call — rather than guessing at what it says. `;
return {
images: sheets ? sheets.map((sh) => sh.image) : body.frames.map((f) => f.image),
sheetFrames: perSheet.map((n) => cellInfo.slice(cellAt, (cellAt += n))),
distinctFrames: body.frames.length,
candidates: body.candidates,
// The span this pass covered and how closely it looked at it. A
// stretch seen only at "scan" has been surveyed, not read.
detail,
from: roundT(from),
// Seconds no pass has read at a detail that carries type, and where
// the next close pass would start.
unreadSeconds: unread,
...(nextUnread ? { unreadFrom: round2(nextUnread.from) } : {}),
sceneChanges: body.sceneChanges.map(roundT),
coveredTo: round2(body.coveredTo),
truncated: body.truncated,
// What NOBODY has looked at, anywhere in the source — the union of
// every watched span subtracted from its length, so a watch aimed at
// the middle counts the head it skipped as well as the tail it never
// reached. `truncated` only says whether the sampler stopped early,
// and a caller who passed a short `to` gets truncated: false; this is
// the honest number, stated in the payload and in the note.
unwatchedSeconds: unwatched,
// The written record of this source, which outlives the sheets: what
// was already noted about the stretch on screen now, and the spans of
// the source nothing has been written about yet.
recorded: notesIn((liveAsset ?? asset).watch, from, body.coveredTo),
unnoted: unnotedSpans((liveAsset ?? asset).watch, asset.duration).map((g) => ({
from: roundT(g.from),
to: roundT(g.to),
})),
source: sourceRef(asset),
...(reference
? { reference: { projectId: reference.ref.projectId, name: reference.ref.doc.name ?? "" } }
: {}),
...(clip
? {
clip: {
id: clip.id,
timelineStart: roundT(clip.start),
in: roundT(clip.in),
out: roundT(clip.out),
speed: round2(speed),
...(clip.reverse ? { reverse: true } : {}),
...(clip.smoothSlow ? { smooth: true } : {}),
...(speedCurveOf(clip)
? {
speedCurve: speedCurveOf(clip)!.map(([at, rate]) => [round2(at), round2(rate)]),
note: `this clip has a speed curve (average ${round2(speed)}×${clip.reverse ? ", played backward" : ""}): source_t maps to the timeline through the curve, with the clip occupying [${roundT(clip.start)}, ${round2(clip.start + retimeOf(clip).len)}]; work in source seconds here`,
}
: clip.reverse
? {
note: `this clip plays backward: timeline_t = ${roundT(clip.start)} + (${roundT(clip.out)} - source_t) / ${round2(speed)}, for source_t in [${roundT(clip.in)}, ${roundT(clip.out)}]`,
}
: {
note: `timeline_t = ${roundT(clip.start)} + (source_t - ${roundT(clip.in)}) / ${round2(speed)}, for source_t in [${roundT(clip.in)}, ${roundT(clip.out)}]`,
}),
},
}
: {}),
...(timelineText ? { timeline: timelineText } : {}),
// Boxes (centre and size), quietest first: where a title or caption
// can go over this stretch without covering the picture or the
// platform's UI.
...(spots.length > 0 ? { textFits: spots.map((sp) => ({ ...sp, ...centreBox(sp) })) } : {}),
// The picture box found or set on this source, so what the sheets
// show and what the measuring tools read are told apart.
...(asset.picture && !isFullFrame(asset.picture)
? {
picture: { x: rF(asset.picture.x), y: rF(asset.picture.y), w: rF(asset.picture.w), h: rF(asset.picture.h) },
pictureNote:
"The source's picture fills this box of its frame (centre and size, frame fractions); the sheets show the whole frame. detect_cuts, sample_color, track_element, suggest_font and compare_to_source read inside the box and speak in its fractions.",
}
: {}),
note: reference
? tiled +
"This is a look at a reference project for deciding which of this project's sources plays its part — nothing is written to the reference and no note is owed. " +
ladder +
(sheets ? "" : " (Sheets unavailable — each image is one frame; sheetFrames lists the times.)")
: tiled +
"Frames are distinct moments (near-duplicates removed), so gaps between stamps mean nothing changed there. " +
"sheetFrames says why each was kept: global = hard cut, action = local motion, text = type landing or swapping, settled = other new settled detail. " +
ladder +
(unwatched > 0.5
? ` You have seen ${round2(from)}-${round2(body.coveredTo)}s of a ${round2(asset.duration)}s source; ` +
`${unwatched}s of it has NOT been looked at (this call's range plus anything else already watched)` +
(body.truncated ? " (this call hit its budget)" : " (your own `to` ended this call)") +
`. Call again with from=${round2(body.coveredTo)} to continue — and do continue before describing, summarizing, or reproducing the source as a whole.`
: "") +
" These sheets are in this conversation only, and it drops the oldest media as it grows. Write what they showed into note_source now — text word for word, what happens, the timings — and the reading stays on the source for every later turn and every later chat." +
(sheets ? "" : " (Sheets unavailable — each image is one frame; sheetFrames lists the times.)"),
};
},
note_source: (s, input) => {
const { asset } = resolveWatchTarget(s, input);
const raw = Array.isArray(input.notes) ? input.notes : [];
const notes = raw
.filter((n): n is Record<string, unknown> => typeof n === "object" && n !== null)
.map((n) => ({
from: isNum(n.from) ? clamp(n.from, 0, asset.duration) : 0,
to: isNum(n.to) ? clamp(n.to, 0, asset.duration) : asset.duration,
text: typeof n.text === "string" ? n.text.trim() : "",
}))
.filter((n) => n.text.length > 0);
if (notes.length === 0)
throw new ToolError("Pass notes: [{from, to, text}] — source seconds and what that stretch showed.");
s.updateAsset(asset.id, { watch: mergeWatchNotes(asset.watch, notes) });
const cur = useEditor.getState().assets.find((a) => a.id === asset.id);
const owed = unwritten.get(asset.id);
if (owed && spanIsNoted(cur?.watch, owed)) unwritten.delete(asset.id);
const unnoted = unnotedSpans(cur?.watch, asset.duration);
return {
source: sourceRef(asset),
notes: (cur?.watch?.notes ?? []).map((n) => ({
from: roundT(n.from),
to: roundT(n.to),
text: n.text,
})),
unnoted: unnoted.map((g) => ({ from: roundT(g.from), to: roundT(g.to) })),
note:
"Written onto the source: it saves with the project, rides the editor state from here on, and outlives this conversation's images." +
(unnoted.length > 0
? ` Still undescribed: ${unnoted
.map((g) => `${round2(g.from)}-${round2(g.to)}s`)
.join(", ")}.`
: " The whole source is described."),
};
},
detect_silence: async (s, input) => {
const { projectId, asset, clip, speed, from, to } = resolveWatchRange(s, input);
if (asset.type === "image") throw new ToolError(`"${asset.name}" is an image — it has no audio.`);
const silences = await fetchSilences(projectId, asset, {
from,
...(to !== undefined ? { to } : {}),
...(isNum(input.threshold_db) ? { thresholdDb: input.threshold_db } : {}),
...(isNum(input.min_silence) ? { minSilence: input.min_silence } : {}),
});
// Pre-map each silence's overlap with the clip's trimmed range onto the
// timeline so the model cuts on ready numbers.
const toTimeline = (t: number) =>
roundT(clip!.start + retimeOf(clip!).tAt(clamp(t, clip!.in, clip!.out)));
return {
silences: silences.map((x) => ({
start: roundT(x.start),
end: roundT(x.end),
duration: roundT(x.duration),
...(clip && x.end > clip.in && x.start < clip.out
? { timeline: { start: toTimeline(x.start), end: toTimeline(x.end) } }
: {}),
})),
source: sourceRef(asset),
...(clip
? {
clip: {
id: clip.id,
timelineStart: roundT(clip.start),
in: roundT(clip.in),
out: roundT(clip.out),
speed: round2(speed),
},
}
: {}),
...(silences.length === 0
? { note: "No silence at these settings — a higher threshold_db or shorter min_silence hears more." }
: {}),
};
},
find_filler: async (s, input) => {
const lane = targetSubtitleTrack(input);
const cues = laneCues(s.subtitles, lane).filter((c) => c.text.trim());
if (cues.length === 0) throw new ToolError(`Subtitle track ${lane} has no cues — transcribe first.`);
const clipId = typeof input.clip_id === "string" ? input.clip_id : undefined;
const clip = clipId ? s.clips.find((c) => c.id === clipId) : undefined;
if (clipId && !clip) throw new ToolError(`No clip ${clipId}.`);
// Every word with its timeline span: the transcriber's own timings, or an
// even split of the cue when a hand edit dropped them.
const words = cues.flatMap((c) => {
const timed = c.words && c.words.length > 0;
return cueWords([c]).map((w, i) => ({
key: `word::${c.id}::${i}`,
cueId: c.id,
i,
w: w.w,
t0: w.t0,
t1: w.t1,
estimated: !timed,
}));
});
if (clip) {
const inRange = words.filter((w) => w.t1 > clip.start && w.t0 < clip.start + retimeOf(clip).tAt(clip.out));
words.splice(0, words.length, ...inRange);
}
if (words.length === 0) throw new ToolError("No transcript words in that range.");
const questions = Object.fromEntries(
words.map((w) => [
w.key,
noul(
`In \`cues\`, is word ${w.i} of cue "${w.cueId}" a disfluency or false start a careful editor would cut out of the speech — an um, uh, er, hmm; a stranded "like", "you know", "I mean", "sort of"; a stutter or an immediately repeated word — judged in the sentence it sits in?`,
{
true: "The word carries no meaning in its sentence and the speech reads cleaner without it.",
false: "The word is part of what is being said, including a \"like\" or \"so\" doing real work in the sentence.",
},
),
]),
);
const state = (keys: string[]) => {
const wanted = new Set(keys);
return {
cues: cues
.map((c) => ({
id: c.id,
text: c.text,
words: words.filter((w) => w.cueId === c.id).map((w) => ({ i: w.i, w: w.w, judged: wanted.has(w.key) })),
}))
.filter((c) => c.words.some((w) => w.judged)),
};
};
const post = (payload: Record<string, unknown>, signal?: AbortSignal) =>
hostedPost("/api/inference/judge", payload, signal);
let answers: Record<string, { type: string; noul?: number }>;
try {
answers = (await askJudgeChunked(post, state, questions, FILLER_JUDGE_CHUNK)) as Record<string, { type: string; noul?: number }>;
} catch (e) {
throw new ToolError(`Filler detection is unavailable: ${e instanceof Error ? e.message : String(e)}`);
}
const floor = CUT_JUDGE.fillerCut;
const toSource = clip ? (t: number) => roundT(retimeOf(clip).srcAt(clamp(t - clip.start, 0, Infinity))) : null;
// Neighbouring filler words are one span: "you know" is a single cut,
// and every span the caller gets is a cut it can make in one call.
const kept = words.filter((w) => (answers[w.key]?.noul ?? 0) >= floor);
const spans: { cueId: string; words: string[]; t0: number; t1: number; estimated: boolean }[] = [];
let prev: (typeof kept)[number] | null = null;
for (const w of kept) {
const last = spans[spans.length - 1];
const runsOn =
prev !== null &&
last !== undefined &&
prev.cueId === w.cueId &&
(prev.i === w.i - 1 || w.t0 - prev.t1 <= WORD_GAP);
if (last && runsOn) {
last.words.push(w.w);
last.t1 = w.t1;
last.estimated = last.estimated || w.estimated;
} else {
spans.push({ cueId: w.cueId, words: [w.w], t0: w.t0, t1: w.t1, estimated: w.estimated });
}
prev = w;
}
const fillers = spans.map((sp) => ({
cue_id: sp.cueId,
text: sp.words.join(" "),
start: roundT(sp.t0),
end: roundT(sp.t1),
...(sp.estimated ? { estimated: true } : {}),
...(toSource ? { source: { start: toSource(sp.t0), end: toSource(sp.t1) } } : {}),
}));
return {
fillers,
count: fillers.length,
track: lane,
...(clip ? { clip: { id: clip.id, timelineStart: roundT(clip.start), in: roundT(clip.in), out: roundT(clip.out) } } : {}),
...(fillers.some((f) => f.estimated)
? { note: "Words marked estimated sit in cues with no word timings; their spans split the cue evenly, so confirm them with listen_audio before a tight cut." }
: {}),
...(fillers.length === 0 ? { note: "No filler words on this track." } : {}),
};
},
suggest_font: async (s, input) => {
// Which bundled face a reference's type is set in: its ink in the
// region against every face this process can draw, set in the same
// words. Reads one frame of the source.
const asset = requireItem(s.assets, input.asset_id, "project asset");
if (asset.type === "audio")
throw new ToolError(`"${asset.name}" is audio — it has no type to read. Pass the video or image the words show on.`);
const text = typeof input.text === "string" ? input.text.trim() : "";
if (!text) throw new ToolError("Pass text: the words the region shows, as they read, with a line break where the type breaks.");
const r = (input.region ?? {}) as Record<string, unknown>;
if (![r.x, r.y, r.w, r.h].every(isNum) || !((r.w as number) > 0 && (r.h as number) > 0))
throw new ToolError("Pass region: {x, y, w, h} in frame fractions, x/y its centre, around the type and little else.");
const t = clamp(isNum(input.t) ? input.t : 0, 0, Math.max(0, asset.duration - 0.001));
// A stand-in already picked is scored alone, so its size and place come
// from the frame too.
const named = Array.isArray(input.fonts) ? input.fonts.filter((f): f is string => typeof f === "string") : [];
const faces = named.length > 0 ? bundledFaces().filter((f) => named.includes(f.font)) : bundledFaces();
const unknown = named.filter((id) => !faces.some((f) => f.font === id));
if (unknown.length > 0) {
throw new ToolError(`No face ${unknown.join(", ")} to set a title in. fonts takes ids from the font list (a font's id, as add_title's font).`);
}
// The frame, then the region of it at a size the scoring can use.
let source: CanvasImageSource;
let fw: number;
let fh: number;
if (asset.type === "image") {
const img = await decodeRasterImageUrl(asset.url);
if (!img) throw new ToolError(`Could not read "${asset.name}".`);
({ source, width: fw, height: fh } = img);
} else {
const frame = await frameAt(asset.url, t).catch((e) => {
throw new ToolError(e instanceof Error ? e.message : `Could not read "${asset.name}".`, { cause: e });
});
if (!frame) throw new ToolError(`Could not read "${asset.name}" at ${round2(t)}s.`);
source = frame.canvas as CanvasImageSource;
fw = frame.canvas.width;
fh = frame.canvas.height;
}
// The region is in the picture box's fractions; the crop is the frame's.
const area = pictureArea(asset, input);
const left = area.x - area.w / 2;
const top = area.y - area.h / 2;
// A region centred near an edge is cut at the frame.
const rx0 = (left + (clamp(r.x as number, 0, 1) - (r.w as number) / 2) * area.w) * fw;
const ry0 = (top + (clamp(r.y as number, 0, 1) - (r.h as number) / 2) * area.h) * fh;
const x0 = Math.max(0, rx0);
const y0 = Math.max(0, ry0);
const sw = Math.max(1, Math.min(fw, rx0 + (r.w as number) * area.w * fw) - x0);
const sh = Math.max(1, Math.min(fh, ry0 + (r.h as number) * area.h * fh) - y0);
const k = Math.min(1, FONT_CROP_MAX / Math.max(sw, sh));
const cw = Math.max(1, Math.round(sw * k));
const ch = Math.max(1, Math.round(sh * k));
const crop = createRasterCanvas(cw, ch);
const ctx = crop.getContext("2d") as CanvasRenderingContext2D | null;
if (!ctx) throw new ToolError("No 2D context to read the frame on.");
ctx.drawImage(source, x0, y0, sw, sh, 0, 0, cw, ch);
// Type set at an angle is read upright: the crop turned back by the
// title's rotation. One line of words in a region taller than wide is
// a column word, read both ways round when no rotation is given.
const lines = text.split("\n").filter((l) => l.trim()).length;
const rotations = isNum(input.rotation)
? [input.rotation]
: lines === 1 && text.trim().length > 1 && ch > cw * 1.3
? [-90, 90]
: [0];
const reads = [];
for (const rotation of rotations) {
const a = (rotation * Math.PI) / 180;
const [cos, sin] = [Math.abs(Math.cos(a)), Math.abs(Math.sin(a))];
const uw = Math.max(1, Math.round(cw * cos + ch * sin));
const uh = Math.max(1, Math.round(cw * sin + ch * cos));
const upright = rotation === 0 ? crop : createRasterCanvas(uw, uh);
const uctx = upright.getContext("2d") as CanvasRenderingContext2D | null;
if (!uctx) throw new ToolError("No 2D context to read the frame on.");
if (upright !== crop) {
uctx.translate(uw / 2, uh / 2);
uctx.rotate(-a);
uctx.drawImage(crop as CanvasImageSource, -cw / 2, -ch / 2);
}
const ref = inkMaskOf(uctx.getImageData(0, 0, upright.width, upright.height).data, upright.width, upright.height);
const size = { w: upright.width, h: upright.height };
if (upright !== crop) upright.width = 0;
if (!ref.box) continue;
// Every face ranked; the size each would need to fill the ink's height.
const ranked = await rankFaces(ref, text, faces, fontStack).then(
(r) => r,
(e) => {
// A guess at the angle that reads wrong is one of the guesses.
if (rotations.length > 1) return null;
throw new ToolError(e instanceof Error ? e.message : "Could not set the faces.", { cause: e });
}
);
if (ranked) reads.push({ rotation, ref, ranked, size });
}
crop.width = 0;
if (reads.length === 0)
throw new ToolError("No type stands out from its ground in that region. Check where the words sit with watch_video at detail original, then pass a region around them.");
const { rotation, ref, ranked, size: upSize } = reads.reduce((a, b) => ((b.ranked[0]?.score ?? 0) > (a.ranked[0]?.score ?? 0) ? b : a));
const inkBox = ref.box!;
// The ink's box, turned back onto the crop: its centre, and the frame-
// aligned box it fills there.
const a = (rotation * Math.PI) / 180;
const [ux, uy] = [inkBox.x + inkBox.w / 2 - upSize.w / 2, inkBox.y + inkBox.h / 2 - upSize.h / 2];
const inkCx = ux * Math.cos(a) - uy * Math.sin(a) + cw / 2;
const inkCy = ux * Math.sin(a) + uy * Math.cos(a) + ch / 2;
const inkW = Math.abs(inkBox.w * Math.cos(a)) + Math.abs(inkBox.h * Math.sin(a));
const inkH = Math.abs(inkBox.w * Math.sin(a)) + Math.abs(inkBox.h * Math.cos(a));
const count = Math.round(clamp(isNum(input.count) ? input.count : FONT_SUGGESTIONS, 1, FONT_SUGGESTIONS_MAX));
const labels = new Map(allFonts().map((f) => [f.id, f.label]));
const round3 = (v: number) => Math.round(v * 1000) / 1000;
const ink = {
x: ((x0 + inkCx / k) / fw - left) / area.w,
y: ((y0 + inkCy / k) / fh - top) / area.h,
};
// A title is set from the middle of its line, not of its ink, so each
// face says where its title sits for its ink to land on the reference's:
// the ink's centre less that face's offset, turned as the title is.
const frame = frameOf(s.aspect);
const matches = await Promise.all(
ranked.slice(0, count).map(async (m) => {
const size = m.typePx > 0 ? Math.round((m.typePx / k / Math.min(fw * area.w, fh * area.h)) * DESIGN_SHORT_SIDE) : null;
const off = size ? await inkOffset(m, size, m.tracking, text, fontStack) : null;
const [ox, oy] = off ? [off.dx * Math.cos(a) - off.dy * Math.sin(a), off.dx * Math.sin(a) + off.dy * Math.cos(a)] : [0, 0];
return {
font: m.font,
label: labels.get(m.font) ?? m.font,
weight: m.weight,
...(m.italic ? { italic: true } : {}),
score: m.score,
size,
tracking: m.tracking,
x: round3(ink.x - ox / frame.w),
y: round3(ink.y - oy / frame.h),
};
})
);
const good = CUT_FONT_MATCH.goodScore;
const best = matches[0];
// How tall a line of the ink runs in the source's own pixels.
const inkPx = Math.round(inkBox.h / k / lines);
const small = inkPx < FONT_SMALL_INK_PX;
const kinds: Record<string, string[]> = {};
for (const f of allFonts()) {
const kind = fontKind(f.id);
if (kind) (kinds[kind] ??= []).push(`${f.id} — ${fontLook(f.id)}`);
}
return {
t: round2(t),
text,
ink: {
x: round3(ink.x),
y: round3(ink.y),
w: round3(inkW / k / fw / area.w),
h: round3(inkH / k / fh / area.h),
},
...(rotation !== 0 ? { rotation } : {}),
...pictureReport(area),
verdict: best && best.score >= good && !small ? "match" : "no_match",
matches,
inkPx,
...(small ? { small: true } : {}),
...(small || !(best && best.score >= good) ? { kinds } : {}),
note: small
? `The type is ${inkPx}px a line in the source, too small for its glyphs to tell faces apart: the ranking above follows its proportions, not its face, and can put a condensed sans over a serif. Name the face from the frame at detail original — serif or sans, its weight, how narrow — and set the closest face of that kind from \`kinds\`, at the size above.`
: best && best.score >= good
? `${best.label} ${best.weight}${best.italic ? " italic" : ""} matches (a match scores ${good}+). Set it with its weight, size (px at the 1080 short side, for the same ink height) and tracking (em)${rotation !== 0 ? `, at rotation ${rotation} as the type stands` : ""}; faces scoring near it are close cuts worth a look with compare_to_source.`
: `Nothing bundled matches closely (best ${best?.score ?? 0}; a match scores ${good}+), so the reference is likely set in a face Donkey does not bundle. Tell the user so, name the closest face of its kind (\`kinds\`) as the stand-in you use, and say the Library takes their own font files.`,
};
},
detect_beats: async (s, input) => {
const { asset, clip, speed, from, to } = resolveWatchRange(s, input);
if (assetIsSilent(asset)) throw new ToolError(`"${asset.name}" carries no audio.`);
// A stored grid holds the user's hand edits, so it answers as it stands;
// regenerate re-scans the source and replaces it. A source a scan has
// already read and heard nothing in answers empty without scanning
// again — asking about three clips of one interview is one scan.
const stored = asset.beats;
const known = stored ?? (beatlessFor(asset.id) ? { beats: [], bpm: 0 } : null);
const grid =
known && input.regenerate !== true
? known
: await detectAssetBeats(asset).catch((e) => {
throw new ToolError(e instanceof Error ? e.message : "Could not read the audio.", { cause: e });
});
const beats = grid.beats.filter((b) => b >= from && (to === undefined || b <= to));
const toTimeline = (t: number) => roundT(clip!.start + retimeOf(clip!).tAt(t));
return {
bpm: grid.bpm,
beats: beats.map(round2),
...(clip
? {
timelineBeats: grid.beats.filter((b) => b >= clip.in && b <= clip.out).map(toTimeline),
clip: {
id: clip.id,
timelineStart: roundT(clip.start),
in: roundT(clip.in),
out: roundT(clip.out),
speed: round2(speed),
},
}
: {}),
source: sourceRef(asset),
note:
grid.beats.length === 0
? "No steady pulse heard — the source reads as speech or ambience. The user can place beats by hand (⌥-click the clip bar)."
: "The grid lives on the asset: its clips draw the beats as dots and every drag or trim snaps to them." +
(stored && input.regenerate !== true
? " This is the stored grid, the user's hand edits included; pass regenerate to re-scan."
: ""),
};
},
measure_level: async (s, input) => {
const ids = Array.isArray(input.ids) ? input.ids.map(String) : [];
const wantsMix = input.mix === true;
if (ids.length === 0 && !wantsMix)
throw new ToolError("ids is required: the clip ids to measure, or mix: true for the whole mix.");
const mix = wantsMix ? await measureMix(s) : undefined;
if (ids.length === 0) return { mix };
const targetId = input.target_id === undefined || input.target_id === null ? ids[0] : String(input.target_id);
if (!ids.includes(targetId)) ids.push(targetId);
type Row = {
id: string;
name: string;
kind: "video" | "soundtrack";
sourceDb: number;
loudestFrameDb: number;
loudestAt?: number;
loudestAtTimeline?: number;
samplePeakDb?: number;
audibleSeconds: number;
volume: number;
levelDb: number;
integratedLufs: number | null;
truePeakDbtp: number | null;
muted?: boolean;
};
const rows = new Map<string, Row | { id: string; name: string; kind: "video" | "soundtrack"; noAudio: string }>();
await eachScanned(ids, async (id) => {
const { asset, clip, from, to } = resolveWatchRange(s, { clip_id: id });
const c = clip!;
const soundtrack = s.audioClips.some((a) => a.id === clip!.id);
const kind = soundtrack ? "soundtrack" : "video";
if (asset.type === "image") {
rows.set(id, { id, name: asset.name, kind, noAudio: "An image has no sound." });
return;
}
// A source with no audio track is reported, and the rest of the
// list still measures: "balance these three" must not fail on the
// one silent generated clip among them.
let level: Awaited<ReturnType<typeof measureSourceLevel>>;
try {
level = await sourceLevel(asset, from, to);
} catch (e) {
rows.set(id, { id, name: asset.name, kind, noAudio: e instanceof Error ? e.message : "Could not read the audio." });
return;
}
const { volume = 1, muted = false } = clip as { volume?: number; muted?: boolean };
rows.set(id, {
id,
name: asset.name,
kind,
sourceDb: level.rmsDb,
loudestFrameDb: level.loudestFrameDb,
// Where the loudest sample lands — a click's hit, a drum's attack —
// on the clip's source clock and on the timeline.
...(level.peakAt !== undefined
? {
loudestAt: Math.round(level.peakAt * 1000) / 1000,
loudestAtTimeline:
Math.round((c.start + retimeOf(c).tAt(clamp(level.peakAt, c.in, c.out))) * 1000) / 1000,
samplePeakDb: level.samplePeakDb,
}
: {}),
audibleSeconds: level.audibleSeconds,
volume: round2(volume),
// A muted clip plays nothing; its level is what it would play unmuted.
levelDb: round2(level.rmsDb + gainDb(volume)),
// BS.1770 loudness and true peak as it plays, volume applied.
...playedLoudness(level.loudness, volume),
...(muted ? { muted: true } : {}),
});
});
const target = rows.get(targetId)!;
if ("noAudio" in target) throw new ToolError(`"${target.name}" (the target) has no sound to match: ${target.noAudio}`);
// The volume that would land each clip at the target's level, from the
// media's own level — so a clip turned all the way down still has a
// number to come back up to. The volume range is 0..3, so a clip too
// quiet to reach the target says how far it gets.
const clips = ids.map((id) => {
const row = rows.get(id)!;
if (id === targetId || "noAudio" in row) return row;
const wanted = 10 ** ((target.levelDb - row.sourceDb) / 20);
const volumeToMatch = round2(clamp(wanted, 0, 3));
return {
...row,
volumeToMatch,
...(wanted > 3 ? { shortfallDb: round2(20 * Math.log10(wanted / 3)) } : {}),
};
});
return { targetId, clips, ...(mix ? { mix } : {}) };
},
listen_audio: async (s, input) => {
const { projectId, asset, clip, from, to } = resolveWatchRange(s, input);
if (asset.type === "image")
throw new ToolError(`"${asset.name}" is an image — it has no sound. watch_video shows it.`);
// A whole audio asset rides its own file bytes. A video, or any trimmed
// range, gets its audio track pulled off by the engine first — so the
// muxed video never travels and a long source still fits the inline cap.
const wholeAudio = asset.type === "audio" && !clip && !isNum(input.from) && !isNum(input.to);
const whole = wholeAudio ? await refToInlineAudio(refFromAsset(asset)) : null;
// A whole audio file that clears the cap falls through to the same
// fitting path a range takes, so length truncates instead of refusing.
const heard = whole
? { inline: whole, from, to: asset.duration }
: await listenSpan(projectId, asset, from, to);
// Listening shows interest in the source's sound — queue the background
// sweep so its transcript (and, for video, its visual map) fills in.
queueWatchSweep(asset.id);
const live = useEditor.getState().assets.find((x) => x.id === asset.id);
if (live && heard.to > from)
s.updateAsset(asset.id, { watch: mergeHeard(live.watch, { from, to: heard.to }) });
const listened = {
ranges: useEditor.getState().assets.find((x) => x.id === asset.id)?.watch?.heard ?? [],
};
const unheard = uncoveredSeconds(listened, asset.duration);
const nextUnheard = nextUncoveredSpan(listened, asset.duration);
// The `audio` data URL leaves the JSON in the chat transport and rides
// to the model as an input_audio part, the way attachments do.
return {
name: asset.name,
source: sourceRef(asset),
duration: roundT(asset.duration),
...(clip ? { clipId: clip.id } : {}),
from: roundT(heard.from),
...(soundSourceOf(asset, s.assets).bound
? { soundFrom: soundSourceOf(asset, s.assets).asset.name }
: {}),
// Where this play stopped, and how much of the source nobody has
// heard — the sound's answer to coveredTo and unwatchedSeconds. The
// cap is bytes, so the seconds that fit depend on the source.
coveredTo: round2(heard.to),
truncated: heard.to < (to ?? asset.duration) - 0.05,
unheardSeconds: unheard,
...(nextUnheard ? { unheardFrom: round2(nextUnheard.from) } : {}),
// The language its speech is transcribed in, for a model that takes
// the sound as its words.
locale: asset.language ?? trackLocale(s.subtitles, 0),
audio: `data:${heard.inline.mimeType};base64,${heard.inline.data}`,
};
},
seek: (s, input) => {
if (!isNum(input.t)) throw new ToolError("t (seconds) is required.");
s.seek(input.t);
return { playhead: playheadAt() };
},
set_playing: (s, input) => {
s.setPlaying(Boolean(input.playing));
return { playing: Boolean(input.playing) };
},
move_selection: (s, input) => {
if (!isNum(input.dx) || !isNum(input.dy)) throw new ToolError("dx and dy must be finite frame fractions.");
const positions = previewSelectionSnapshot(s, playheadAt());
if (!positions.length) throw new ToolError("Select visual items before moving them.");
s.pushHistory();
movePreviewSelection(s, positions, input.dx, input.dy);
return { moved: positions.length };
},
select: (s, input) => {
const kind = String(input.kind);
if (kind === "none") {
s.select(null);
return { selection: null };
}
const id = String(input.id ?? "");
if (!ITEM_KIND_IDS.includes(kind as ItemKind)) throw new ToolError(`Unknown kind: ${kind}`);
const selKind = kind as ItemKind;
if (!timelineItem(s, { kind: selKind, id })) throw new ToolError(`No ${kind} with id ${id}.`);
if (input.additive === true) s.toggleSelect({ kind: selKind, id });
else s.select({ kind: selKind, id });
return { selection: useEditor.getState().selection, multiSelection: useEditor.getState().multiSelection };
},
set_side_panel: (_s, input) => {
const panel = String(input.panel);
if (panel !== "none" && !SIDE_PANEL_TABS.some((t) => t === panel))
throw new ToolError(`Unknown panel: ${panel}`);
requestSidePanel(panel === "none" ? null : (panel as SidePanelTab));
return { panel };
},
select_items: async (s, input) => {
const kind = String(input.kind) as ItemKind;
if (!ITEM_KIND_IDS.includes(kind)) throw new ToolError(`Unknown kind: ${kind}`);
const describe = String(input.describe ?? "").trim();
if (!describe) throw new ToolError("describe is required — say what the wanted items have in common.");
const items = sweepCandidates(s, kind);
if (items.length === 0) throw new ToolError(`Nothing of kind "${kind}" on the timeline.`);
const post = (payload: Record<string, unknown>, signal?: AbortSignal) =>
hostedPost("/api/inference/judge", payload, signal);
let answers: Record<string, { type: string; noul?: number }>;
try {
answers = (await askJudgeChunked(
post,
(keys) => sweepState(describe, items, keys),
sweepQuestions(describe, items),
SWEEP_CHUNK
)) as Record<string, { type: string; noul?: number }>;
} catch (e) {
throw new ToolError(`Finding items is unavailable: ${e instanceof Error ? e.message : String(e)}`);
}
const hits = sweepPicks(
answers as Record<string, { type: "noul"; noul: number } | undefined>,
items,
CUT_JUDGE.sweepFit
).sort((a, b) => b.fit - a.fit);
const kept = isNum(input.limit) ? hits.slice(0, Math.max(1, Math.floor(input.limit))) : hits;
return {
kind,
searched: items.length,
// The tools that take `ids` land one change on all of them at once.
ids: kept.map((c) => c.id),
matched: kept.map((c) => ({ id: c.id, is: c.label })),
};
},
group_items: (s) => {
const groupId = s.groupSelection();
if (!groupId) throw new ToolError("Select at least two timeline items to group.");
return { groupId, selection: useEditor.getState().multiSelection };
},
ungroup_items: (s) => {
s.ungroupSelection();
return { selection: useEditor.getState().multiSelection };
},
move_timeline_selection: (s, input) => {
if (!isNum(input.delta)) throw new ToolError("delta is required.");
return { delta: s.moveTimelineSelection(input.delta), selection: useEditor.getState().multiSelection };
},
insert_item_row: (_s, input) => {
if (!ROW_ITEM_KINDS.includes(input.kind as ItemKind) || typeof input.id !== "string" || !isNum(input.before_row)) throw new ToolError("kind, id and before_row are required.");
insertItemRow(input.kind as ItemKind, input.id, input.before_row);
return { ...tracksAfter() };
},
pack_lanes: (_s, input) => {
const band = input.band === "soundtrack" || input.band === "elements" ? input.band : "both";
const soundtrack = band === "elements" ? undefined : packRows("audio");
const elements = band === "soundtrack" ? undefined : packRows("overlay");
return {
...(soundtrack ? { soundtrack: { before: soundtrack.before, after: soundtrack.after } } : {}),
...(elements ? { elements: { before: elements.before, after: elements.after } } : {}),
moved: (soundtrack?.moved ?? 0) + (elements?.moved ?? 0),
};
},
split_at: (s, input) => {
const ids = Array.isArray(input.ids) ? input.ids.filter((id): id is string => typeof id === "string") : [];
const items = ids.map((id) => {
const kind = ITEM_KIND_IDS.find((k) => ITEM_KINDS[k].list(s).some((item) => item.id === id));
if (!kind) throw new ToolError(`No timeline item ${id}.`);
return { kind, id };
});
const before = ITEM_KIND_IDS.reduce((n, kind) => n + ITEM_KINDS[kind].list(s).length, 0);
s.splitAtPlayhead(isNum(input.t) ? input.t : undefined, items);
const after = useEditor.getState();
const made = ITEM_KIND_IDS.reduce((n, kind) => n + ITEM_KINDS[kind].list(after).length, 0) - before;
if (made === 0) {
// An item splits only strictly inside its span: on its edge it is cut already.
if (items.length) throw new ToolError("Nothing to split: none of those items runs across that time.");
if (s.multiSelection.length || s.selection)
throw new ToolError("Nothing to split: the selection doesn't run across that time. Name what to split with ids.");
throw new ToolError(
"Nothing to split: with nothing selected only the track-0 video splits, and none of it runs across that time (a clip edge is a cut already). Name an overlay clip, title or other item with ids."
);
}
return { split: made, selection: after.multiSelection, ...tracksAfter() };
},
move_clip: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
// Reordering by index is a base-sequence operation; a layer clip is
// free-positioned — move it with update_overlay_video (start/track).
if (clip.track !== 0)
throw new ToolError(
"That clip is on an overlay track — use update_overlay_video to move it."
);
if (!isNum(input.toIndex)) throw new ToolError("toIndex is required.");
const row = track0Clips(s.clips);
s.moveClip(clip.id, clamp(Math.round(input.toIndex), 0, row.length - 1));
return { moved: clip.id, ...tracksAfter() };
},
place_clip: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
if (!isNum(input.start)) throw new ToolError("start (seconds) is required.");
s.select({ kind: "clip", id: clip.id });
const delta = s.moveTimelineSelection(Math.max(0, input.start) - clip.start);
const at = clip.start + delta;
return {
id: clip.id,
start: roundT(at),
...(Math.abs(at - Math.max(0, input.start)) > 0.005
? { note: "That spot was taken — slid right to the next free one." }
: {}),
...tracksAfter(),
};
},
add_clip: (s, input) => {
// A run of blocks is the same placement with nothing to play yet: the
// shots of a cut that has been laid out before its footage exists.
if (Array.isArray(input.blocks)) return placeBlocks(s, input.blocks, input);
const asset = requireItem(s.assets, input.asset_id, "project asset");
// Spans cut the source apart as they land: one clip per stretch, in
// order, with the material between them left out.
if (Array.isArray(input.spans))
return placeAssetSpans(
asset,
(input.spans as unknown[])
.filter((sp): sp is Record<string, unknown> => !!sp && typeof sp === "object")
.map((sp) => ({
from: isNum(sp.from) ? sp.from : 0,
to: isNum(sp.to) ? sp.to : 0,
})),
input,
);
return placeAssetOnTimeline(asset, input);
},
add_overlay_video: (s, input) => {
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) : playheadAt();
// Tracks stack bottom-up from track 0; overlays live on 1+. A stale
// negative (the old behind-track model) clamps to the first layer.
const track = isNum(input.track) ? Math.max(1, Math.round(input.track)) : 1;
if (isNum(input.track) && Math.round(input.track) === 0)
throw new ToolError("Track 0 holds the timeline clips — use place_clip for it.");
// A stack grounds on its lowest row, so an overlay over an empty track 0
// would become the base clip itself.
if (track0Clips(s.clips).length === 0)
throw new ToolError(
"Track 0 is empty, and an overlay over nothing becomes the base clip itself. Put the clip it sits over on track 0 first (add_clip), then add this."
);
// Its length goes in with the add, so the landing makes room for the
// clip it will be: `end` when given, else an image stops where track 0
// does, e.g. a still at 50.9 over a cut ending at 52.8 runs 1.9s, not
// 8s past the close over black.
if (isNum(input.end) && input.end < start + CLIP_MIN_SECONDS - 1e-9)
throw new ToolError(`end must come after the clip's start (${roundT(start)}s).`);
const cutEnd = totalDuration(s.clips);
const len = isNum(input.end)
? input.end - start
: asset.type === "image" && cutEnd > start + CLIP_MIN_SECONDS
? Math.min(IMAGE_CLIP_SECONDS, cutEnd - start)
: undefined;
s.addVideoFromAsset(asset.id, { kind: "track", track }, start, len);
const cur = useEditor.getState();
const sel = cur.selection;
const id = sel?.kind === "clip" ? 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.updateClipTransient(id, layoutPatch(input.layout));
const c = useEditor.getState().clips.find((x) => x.id === id)!;
return {
id: c.id,
track: c.track,
start: roundT(c.start),
end: roundT(c.start + clipLen(c)),
len: roundT(clipLen(c)),
layout: regionLabel(rectOf(c)),
};
},
update_overlay_video: (s, input) => {
const c = requireItem(overlayLayers(s.clips), 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<VideoClip> = {};
if (isNum(input.start)) patch.start = Math.max(0, input.start);
if (isNum(input.in)) patch.in = clamp(input.in, 0, dur - CLIP_MIN_SECONDS);
if (isNum(input.out)) patch.out = clamp(input.out, CLIP_MIN_SECONDS, dur);
if (patch.in !== undefined || patch.out !== undefined) {
if ((patch.out ?? c.out) - (patch.in ?? c.in) < CLIP_MIN_SECONDS - 1e-9)
throw new ToolError(CLIP_TOO_SHORT);
}
if (isNum(input.track)) {
const track = Math.round(input.track);
if (track === 0) throw new ToolError("Track 0 holds the timeline clips — overlays are 1 or higher.");
patch.track = Math.max(1, track);
}
if (typeof input.muted === "boolean") patch.muted = input.muted;
if (typeof input.hidden === "boolean") patch.hidden = input.hidden || undefined;
// A preset and a box both name the region; taking one silently left
// the other unapplied and the model setting it again round after round.
if (typeof input.layout === "string" && input.region)
throw new ToolError("Pass layout or region, not both: layout is a preset box, region a box of your own.");
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).");
// x/y name the box's centre, as every box the chat reads or writes
// does; the store keeps its top-left corner. The box may hang past
// the frame's edges, as the preview's handles let it (a screen in the
// shot that runs off the frame); the frame crops it. A sliver always
// stays on the frame so it can't vanish.
const w = clamp(rg.w, 0.05, REGION_MAX_SCALE);
const h = clamp(rg.h, 0.05, REGION_MAX_SCALE);
const keep = 0.05;
patch.frame = {
x: clamp(rg.x - w / 2, keep - w, 1 - keep),
y: clamp(rg.y - h / 2, keep - h, 1 - keep),
w,
h,
};
}
refuseCardFraming(c, input, ["fit", "zoom"]);
if (input.fit === "fit" || input.fit === "fill") patch.fit = input.fit;
if (isNum(input.zoom)) {
const z = clamp(input.zoom, 1, CLIP_MAX_ZOOM);
patch.zoom = z > 1 ? z : undefined;
}
if (typeof input.flipH === "boolean") patch.flipH = input.flipH || undefined;
if (typeof input.flipV === "boolean") patch.flipV = input.flipV || undefined;
if (isNum(input.rotation)) {
const deg = degInput(input.rotation);
patch.rotation = deg === 0 ? undefined : deg;
}
if (isNum(input.opacity)) {
const o = clamp(input.opacity, 0, 1);
patch.opacity = o >= 1 ? undefined : o;
}
if (isNum(input.speed)) patch.speed = Math.max(SPEED_FLOOR, input.speed);
if (Object.keys(patch).length === 0) throw new ToolError("Nothing to change.");
s.updateClip(c.id, patch);
const next = useEditor.getState().clips.find((x) => x.id === c.id)!;
const overhang = frameOverhang(rectOf(next));
return {
id: next.id,
track: next.track,
start: roundT(next.start),
layout: regionLabel(rectOf(next)),
region: centreBox(rectOf(next)),
...(overhang ? { offFrame: overhang } : {}),
fit: next.fit ?? "fit",
...(clipZoom(next) > 1 ? { zoom: clipZoom(next) } : {}),
...(next.flipH ? { flipH: true } : {}),
...(next.flipV ? { flipV: true } : {}),
...(next.rotation ? { rotation: next.rotation } : {}),
...((next.opacity ?? 1) < 1 ? { opacity: next.opacity } : {}),
muted: next.muted,
...(next.hidden ? { hidden: true } : {}),
};
},
trim_clip: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
const asset = s.assets.find((a) => a.id === clip.assetId);
// A still has no source bound, so its clip can stretch to any length.
const dur = asset?.type === "image" ? Infinity : asset?.duration ?? clip.out;
const nextIn = isNum(input.in) ? clamp(input.in, 0, dur - CLIP_MIN_SECONDS) : clip.in;
const nextOut = isNum(input.out) ? clamp(input.out, CLIP_MIN_SECONDS, dur) : clip.out;
if (nextOut - nextIn < CLIP_MIN_SECONDS - 1e-9) throw new ToolError(CLIP_TOO_SHORT);
// Trim through the store's resize path so track 0 keeps its no-overlap
// invariant: extending a clip pushes the following run right.
s.setClipTrim(clip.id, nextIn, nextOut);
return {
in: nextIn,
out: nextOut,
len: Math.round((nextOut - nextIn) * 100) / 100,
...tracksAfter(),
};
},
find_highlights: async (s, input) => {
const { asset, clip, from, to } = resolveWatchRange(s, input);
if (asset.type === "image")
throw new ToolError(`"${asset.name}" is a still — there is no stretch of it to clip.`);
const said = sourceSpeech(s, asset, clip, from, to ?? asset.duration);
if (said.length === 0)
throw new ToolError(
`Nothing is transcribed for "${asset.name}" over that stretch, and the moments are found in what is said. ` +
"listen_audio starts the transcript, which fills in behind you; call this again once it has.",
);
const count = isNum(input.count) ? clamp(Math.round(input.count), 1, 20) : 5;
const post = (payload: Record<string, unknown>, signal?: AbortSignal) =>
hostedPost("/api/inference/judge", payload, signal);
const clips = await findHighlights(post, said, CUT_CLIP, count).catch((e) => {
throw new ToolError(`Finding the moments is unavailable: ${e instanceof Error ? e.message : String(e)}`);
});
const settings = CUT_CLIP;
return {
source: sourceRef(asset),
searched: { from: roundT(from), to: roundT(to ?? asset.duration) },
clips: clips.map((c, i) => ({
n: i + 1,
rank: c.rank,
seconds: c.seconds,
spans: c.spans.map((sp) => ({ from: sp.from, to: sp.to, said: sp.text })),
})),
note:
clips.length === 0
? `Nothing in that stretch scored above the floor (${settings.rankFloor}) — the source may be one continuous thread with no part of it that stands alone.`
: "Ranked best first, in SOURCE seconds. A clip with two spans is two moments that belong together with the middle cut out; " +
"add_clip with `spans` lays one down as it stands. The ranking reads what is SAID — watch_video before you commit to a look, " +
"since a moment that reads well can still be someone glancing away from the camera.",
};
},
refine_speech_cuts: async (s, input) => {
const projectId = s.projectId;
if (!projectId) throw new ToolError("No project open.");
const ids = Array.isArray(input.clip_ids) ? input.clip_ids.map(String) : [];
if (ids.length === 0)
throw new ToolError("clip_ids is required — the recut clips whose edges are speech cuts.");
const chosen = ids.map((id) => requireItem(s.clips, id, "video clip"));
const pace: Pace =
input.pace === "fast" || input.pace === "relaxed" ? input.pace : "natural";
// Every trim is planned before anything is written, so the re-lay below
// can preserve the spacing the cut already has. A plan carries the word
// boundaries its edges were placed against: repairing a joint has to
// know where the words are too, or the repair clips one.
interface Plan { in: number; out: number; inBound: number; outBound: number }
const plans = new Map<string, Plan>();
const flags = new Map<string, string[]>();
const flag = (id: string, note: string) =>
flags.set(id, [...(flags.get(id) ?? []), note]);
await eachScanned(chosen, async (clip) => {
const asset = s.assets.find((a) => a.id === clip.assetId);
if (!asset || asset.type === "image" || !(asset.duration > 0)) {
flag(clip.id, "no audio-bearing source — skipped");
return;
}
// The scan needs the reach an edge may travel plus enough room
// around it to measure the recording's own levels. One window
// spanning both edges when the clip is short, else one per edge.
const win = REACH + 1;
const short = clip.out - clip.in <= 2 * win;
const ranges: [number, number][] = short
? [[clip.in - win, clip.out + win]]
: [
[clip.in - win, clip.in + win],
[clip.out - win, clip.out + win],
];
const scans = await Promise.all(
ranges.map(([a, b]) =>
fetchSpeech(asset, clamp(a, 0, asset.duration), clamp(b, 0, asset.duration))
)
).catch((e: unknown) => {
flag(clip.id, e instanceof Error ? `${e.message} — left as cut` : "could not read the audio — left as cut");
return null;
});
if (!scans) return;
const inScan = scans[0];
const outScan = short ? scans[0] : scans[1];
if (inScan.segments.length === 0 && outScan.segments.length === 0) {
flag(clip.id, "no speech around either edge — left as cut");
return;
}
if (!inScan.separated || !outScan.separated)
flag(clip.id, "room tone sits close to the voice here — placed on the best read of it");
const inEdge = placeEdge(inScan.segments, clip.in, "in", pace, inScan);
const outEdge = placeEdge(outScan.segments, clip.out, "out", pace, outScan);
if (!inEdge.placed)
flag(clip.id, "no word within reach of the in edge — left alone");
if (!outEdge.placed)
flag(clip.id, "no word within reach of the out edge — left alone");
const nextIn = clamp(inEdge.t, 0, asset.duration);
const nextOut = clamp(outEdge.t, 0, asset.duration);
if (nextOut - nextIn >= 0.15)
plans.set(clip.id, {
in: nextIn,
out: nextOut,
inBound: clamp(inEdge.bound, 0, asset.duration),
outBound: clamp(outEdge.bound, 0, asset.duration),
});
else flag(clip.id, "refining would collapse the clip — left as cut");
});
// Two sides of one removed stretch never cross back into each other's
// material, so no word plays twice across a joint. Where the pace would
// push them past each other the pause between the words was shorter than
// the air both sides wanted, so both give ground and the joint sits
// inside that pause — reverting to the cut's own numbers is what put an
// edge back on top of a word.
const rows = new Map<number, VideoClip[]>();
for (const c of s.clips) rows.set(c.track, [...(rows.get(c.track) ?? []), c]);
for (const row of rows.values()) {
row.sort((a, b) => a.start - b.start);
for (let i = 0; i + 1 < row.length; i++) {
const a = row[i];
const b = row[i + 1];
if (a.assetId !== b.assetId || a.out > b.in + 1e-3) continue;
const pa = plans.get(a.id);
const pb = plans.get(b.id);
const left: PlacedEdge = { t: pa?.out ?? a.out, placed: true, bound: pa?.outBound ?? a.out };
const right: PlacedEdge = { t: pb?.in ?? b.in, placed: true, bound: pb?.inBound ?? b.in };
if (left.t <= right.t + 1e-6) continue;
const joint = settleJoint(left, right);
if (joint === null) {
if (pa) pa.out = a.out;
if (pb) pb.in = b.in;
for (const c of [a, b])
if (plans.has(c.id)) flag(c.id, "speech runs across this joint — that edge left as cut");
continue;
}
if (pa) pa.out = joint;
if (pb) pb.in = joint;
for (const c of [a, b])
if (plans.has(c.id)) flag(c.id, "the pause at this joint was short — the two edges meet inside it");
}
}
// Drop no-op plans so the report says which edges already sat right.
for (const [id, plan] of [...plans]) {
const c = chosen.find((x) => x.id === id)!;
if (Math.abs(plan.in - c.in) < 0.005 && Math.abs(plan.out - c.out) < 0.005)
plans.delete(id);
}
// One write for the whole call: each planned clip takes its new trim in
// place, and every clip after it on the track shifts by the length
// change — butted joints stay butted, deliberate beats keep their width,
// and a tightened clip closes up instead of opening a gap.
if (plans.size > 0) {
const before = s.clips;
s.pushHistory();
const patches: { id: string; patch: Partial<VideoClip> }[] = [];
for (const row of rows.values()) {
let delta = 0;
for (const c of row) {
const plan = plans.get(c.id);
const patch: Partial<VideoClip> = {};
if (Math.abs(delta) > 1e-6) patch.start = Math.max(0, c.start + delta);
if (plan) {
patch.in = plan.in;
patch.out = plan.out;
delta += retimeOf({ ...c, in: plan.in, out: plan.out }).len - retimeOf(c).len;
}
if (plan || patch.start !== undefined) patches.push({ id: c.id, patch });
}
}
useEditor.getState().updateClipsTransient(patches);
useEditor.getState().sortClips();
// Every edge here moved because the audio said so, and the run behind
// each one shifted with it — a retime, so the bars ride along.
useEditor.getState().reanchorBars(before);
}
return {
pace,
refined: chosen.map((clip) => {
const plan = plans.get(clip.id);
const notes = flags.get(clip.id);
return {
clipId: clip.id,
...(plan
? {
in: { from: roundT(clip.in), to: roundT(plan.in) },
out: { from: roundT(clip.out), to: roundT(plan.out) },
}
: {}),
...(notes
? { notes }
: plan
? {}
: { notes: ["edges already sit where the words leave them"] }),
};
}),
note: `Every moved edge is measured from the word itself: ~${AIR[pace].out}s after the last one finishes, ~${AIR[pace].in}s before the next one starts, never under ${MIN_AIR.out}s/${MIN_AIR.in}s. Clip spacing is preserved. Listen at any flagged edge.`,
...tracksAfter(),
};
},
set_clip_muted: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
s.updateClip(clip.id, { muted: Boolean(input.muted) });
return { muted: Boolean(input.muted) };
},
set_clip_volume: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
if (!isNum(input.volume)) throw new ToolError("volume is required (0..3).");
const volume = clamp(input.volume, 0, 3);
s.updateClip(clip.id, { volume: Math.abs(volume - 1) < 1e-4 ? undefined : volume });
const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;
return { id: next.id, volume: next.volume ?? 1 };
},
sync_audio: async (s, input) => {
const clip = input.clipId !== undefined ? requireItem(s.clips, input.clipId, "video clip") : undefined;
const video = requireItem(s.assets, clip?.assetId ?? input.assetId, "video asset");
if (video.type !== "video") throw new ToolError(`"${video.name}" is not a video.`);
if (input.clear === true || input.audio_asset_id === null) {
unbindRecording(video.id);
return { id: video.id, soundFrom: null, note: `"${video.name}" plays its own sound again.` };
}
return syncVideoSound(s, video, input.audio_asset_id, clip);
},
set_split_edit: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
const side = (v: unknown, name: string) => {
if (v === undefined) return undefined;
if (!isNum(v)) throw new ToolError(`${name} is seconds, 0..${SPLIT_EDIT_MAX_S}.`);
const secs = Math.round(clamp(v, 0, SPLIT_EDIT_MAX_S) * 1000) / 1000;
return secs > 0 ? secs : 0;
};
const lead = side(input.lead, "lead");
const tail = side(input.tail, "tail");
if (lead === undefined && tail === undefined) throw new ToolError("Pass lead, tail, or both, in seconds (0 clears).");
s.updateClip(clip.id, {
...(lead !== undefined ? { audioLead: lead || undefined } : {}),
...(tail !== undefined ? { audioTail: tail || undefined } : {}),
});
const next = useEditor.getState();
const live = next.clips.find((c) => c.id === clip.id)!;
const sp = getClipSpans(next.clips, next.assets, live.track).find((x) => x.clip.id === clip.id);
const playing = { lead: round2(sp?.soundLead ?? 0), tail: round2(sp?.soundTail ?? 0) };
const short = (asked: number | undefined, got: number) => asked !== undefined && asked - got > 0.01;
return {
id: clip.id,
audioLead: live.audioLead ?? 0,
audioTail: live.audioTail ?? 0,
playing,
...(short(lead, playing.lead) || short(tail, playing.tail)
? {
note: "Part of the split edit does not play: a transition owns that cut, the source ends there, or the timeline starts there. `playing` is what sounds.",
}
: {}),
};
},
rename_item: (s, input) => {
// One pair, or `names` for a whole cut's worth in one call.
const pairs = (Array.isArray(input.names) ? input.names : [input]).map((p: unknown) => {
const rec = (p ?? {}) as Record<string, unknown>;
return { id: String(rec.id ?? ""), name: String(rec.name ?? "").trim().slice(0, 60) || undefined };
});
// Every id is found before any name is written.
const writers = pairs.map(({ id }) => {
if (s.clips.some((c) => c.id === id)) {
return (name: string | undefined) => s.updateClip(id, { name });
}
if (s.audioClips.some((a) => a.id === id)) {
return (name: string | undefined) => s.updateAudio(id, { name });
}
if (s.overlays.some((o) => o.id === id)) {
return (name: string | undefined) => s.updateOverlay(id, { name });
}
throw new ToolError(`No clip, soundtrack clip, or element with id ${id}; nothing was renamed.`);
});
pairs.forEach(({ name }, i) => writers[i](name));
const named = pairs.map(({ id, name }) => ({ id, name: name ?? null }));
return named.length === 1 ? named[0] : { named };
},
set_clip_hidden: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
s.updateClip(clip.id, { hidden: input.hidden ? true : undefined });
return { id: clip.id, hidden: Boolean(input.hidden) };
},
set_clip_sound: async (s, input) => {
const target = soundTarget(s, input.clipId);
let next: ClipSound | undefined;
if (typeof input.preset === "string" && input.preset.trim()) {
const wanted = input.preset.trim().toLowerCase();
// The dropdown labels the shipped presets by name, so a name is what
// the user says; the ids are what the catalog lists.
const shipped = SOUND_PRESETS.find(
(p) => p.id === wanted || p.name.toLowerCase() === wanted
);
if (shipped) {
next = shipped.sound;
} else {
const saved = (await listSoundPresets()).find(
(p) => p.name.toLowerCase() === wanted || p.id === input.preset
);
if (!saved)
throw new ToolError(
`No sound preset called "${String(input.preset)}". Shipped: ${SOUND_PRESETS.map((p) => p.name).join(", ")}.`
);
next = saved.sound;
}
} else {
const patch: ClipSound = { ...(target.current ?? {}) };
if ("eq" in input) {
if (input.eq === null) delete patch.eq;
else if (Array.isArray(input.eq)) patch.eq = input.eq.map((v) => (isNum(v) ? v : 0));
else throw new ToolError("eq must be an array of dB values, one per band.");
}
if ("compressor" in input) {
const c = input.compressor as Record<string, unknown> | null;
if (c === null) delete patch.compressor;
else if (c && isNum(c.threshold) && isNum(c.ratio) && isNum(c.attack) && isNum(c.release))
patch.compressor = { threshold: c.threshold, ratio: c.ratio, attack: c.attack, release: c.release };
else throw new ToolError("compressor needs threshold, ratio, attack and release.");
}
if ("limiter" in input) {
const l = input.limiter as Record<string, unknown> | null;
if (l === null) delete patch.limiter;
else if (l && isNum(l.ceiling)) patch.limiter = { ceiling: l.ceiling };
else throw new ToolError("limiter needs a ceiling.");
}
for (const stage of Array.isArray(input.clear) ? input.clear : []) {
if (stage === "eq") delete patch.eq;
else if (stage === "compressor") delete patch.compressor;
else if (stage === "limiter") delete patch.limiter;
else throw new ToolError(`clear takes eq, compressor or limiter; got "${String(stage)}".`);
}
if (
!("eq" in input) &&
!("compressor" in input) &&
!("limiter" in input) &&
!Array.isArray(input.clear)
)
throw new ToolError("Pass a preset, a clear list, or eq / compressor / limiter.");
next = patch;
}
const sound = normalizeSound(next);
target.write(sound);
return { id: target.id, kind: target.kind, sound: soundTarget(useEditor.getState(), target.id).current ?? null };
},
save_sound_preset: async (s, input) => {
const target = soundTarget(s, input.clipId);
const name = typeof input.name === "string" ? input.name.trim() : "";
if (!name) throw new ToolError("name is required.");
if (!target.current) throw new ToolError("That clip's sound is flat; shape it first.");
if (!s.projectId) throw new ToolError("No open project.");
const saved = await saveSoundPreset(s.projectId, name, target.current);
if (!saved) throw new ToolError("The preset could not be saved.");
return { id: saved.id, name: saved.name, residency: saved.residency, sound: saved.sound };
},
reorder_track: (s, input) => {
if (!isNum(input.from) || !isNum(input.to) || input.from < 0 || input.to < 0)
throw new ToolError("from and to must be 0 or higher.");
const from = Math.round(input.from);
const to = Math.round(input.to);
const kind = String(input.kind);
const rows =
kind === "video"
? [...new Set(s.clips.map((c) => c.track))].sort((a, b) => a - b)
: kind === "soundtrack"
? [...new Set(s.audioClips.map((a) => a.lane ?? 0))].sort((a, b) => a - b)
: kind === "text"
? overlayLaneOrder(s.overlays)
: null;
if (!rows) throw new ToolError("kind must be video, soundtrack, or text.");
if (rows.length < 2) throw new ToolError(`There is only one ${kind} row, so nothing to reorder.`);
const i = rows.indexOf(from);
if (i < 0) throw new ToolError(`No ${kind} row ${from} — rows ${rows.join(", ")} exist.`);
const j = Math.min(rows.length - 1, rows.indexOf(to) >= 0 ? rows.indexOf(to) : to);
if (i === j) return { kind, from: i, to: j, rows: rows.length, moved: false };
if (kind === "video") s.moveVideoTrack(i, j);
else if (kind === "soundtrack") s.moveAudioLane(i, j);
else s.moveOverlayLane(i, j);
return { kind, from: i, to: j, rows: rows.length, moved: true };
},
set_track_hidden: (s, input) => {
// The transitions row is the one row there is only one of, so it names
// no track.
if (input.kind !== "transitions" && (!isNum(input.track) || input.track < 0))
throw new ToolError("track must be 0 or higher.");
const track = isNum(input.track) ? Math.round(input.track) : 0;
const hidden = Boolean(input.hidden);
switch (input.kind) {
case "video": {
const n = s.clips.filter((c) => c.track === track).length;
if (!n) throw new ToolError(`No clips on video track ${track}.`);
s.setTrackHidden(track, hidden);
return { kind: "video", track, hidden, clips: n };
}
case "soundtrack": {
const n = s.audioClips.filter((a) => (a.lane ?? 0) === track).length;
if (!n) throw new ToolError(`No clips on soundtrack lane ${track}.`);
s.setAudioLaneHidden(track, hidden);
return { kind: "soundtrack", track, hidden, clips: n };
}
case "text": {
const n = s.overlays.filter((o) => (o.lane ?? 0) === track).length;
if (!n) throw new ToolError(`No titles on text track ${track}.`);
s.setTextLaneHidden(track, hidden);
return { kind: "text", track, hidden, titles: n };
}
case "subtitles": {
const count = subtitleLaneCount(s.subtitles);
if (track >= count)
throw new ToolError(`No subtitle track ${track} — tracks 0–${count - 1} exist.`);
s.setSubtitleTrackMeta(track, { hidden: hidden ? true : undefined });
return { kind: "subtitles", track, hidden, cues: laneCues(s.subtitles, track).length };
}
case "transitions": {
// One row holds every bar, so the track index has nothing to pick.
const n = s.transitions.length;
if (!n) throw new ToolError("There are no transitions on the timeline.");
s.setTransitionsHidden(hidden);
return { kind: "transitions", hidden, transitions: n };
}
default:
throw new ToolError(
'`kind` must be "video", "soundtrack", "text", "subtitles", or "transitions".'
);
}
},
set_track_muted: (s, input) => {
if (!isNum(input.track) || input.track < 0)
throw new ToolError("track must be 0 or higher.");
const track = Math.round(input.track);
const n = s.clips.filter((c) => c.track === track).length;
if (!n) throw new ToolError(`No clips on video track ${track}.`);
s.setTrackMuted(track, Boolean(input.muted));
return { track, muted: Boolean(input.muted), clips: n };
},
detach_audio: (s, input) => {
// A cut blocked out as empty shots has no clip of the reference to lift
// from, and its sound is what the cuts were timed to; naming the asset
// puts that whole track on the soundtrack with nothing else placed.
if (input.assetId) {
const asset = requireItem(s.assets, input.assetId, "project asset");
if (asset.type === "image" || (assetIsSilent(asset) && !soundSourceOf(asset, s.assets).bound))
throw new ToolError(`"${asset.name}" carries no audio.`);
const start = isNum(input.start) ? Math.max(0, input.start) : 0;
s.addAudioFromAsset(asset.id, start);
void ensurePeaks(asset);
const sel = useEditor.getState().selection;
return { audioClipId: sel?.kind === "audio" ? sel.id : null };
}
const id = input.clipId ? String(input.clipId) : s.selection?.kind === "clip" ? s.selection.id : null;
if (!id) throw new ToolError("Pass clipId, assetId, or select a video clip first.");
const clip = requireItem(s.clips, id, "video clip");
if (clip.muted) throw new ToolError("That clip's audio is muted — nothing to detach.");
s.select({ kind: "clip", id: clip.id });
s.detachAudio();
const asset = s.assets.find((a) => a.id === clip.assetId);
if (asset) void ensurePeaks(asset);
const sel = useEditor.getState().selection;
return { audioClipId: sel?.kind === "audio" ? sel.id : null };
},
delete_item: (s, input) => {
const kind = String(input.kind) as ItemKind;
const id = String(input.id ?? "");
if (!ITEM_KIND_IDS.includes(kind)) throw new ToolError(`Unknown kind: ${kind}`);
if (!timelineItem(s, { kind, id })) throw new ToolError(`No ${kind} with id ${id}.`);
s.select({ kind, id });
const deleted = useEditor.getState().multiSelection;
s.deleteSelection();
return { deleted, ...tracksAfter() };
},
remove_gap: (s, input) => {
if (!isNum(input.at)) throw new ToolError("at (seconds) is required.");
const track = isNum(input.track) ? input.track : 0;
const lane = { kind: "video", index: track } as const;
const gap = laneGapAt(s, lane, input.at);
if (!gap) throw new ToolError(`No track-${track} gap at ${input.at}s — pass a time inside the empty span.`);
s.removeLaneGap(lane, input.at);
return { closed: { track, ...gap }, ...tracksAfter() };
},
set_magnet: (s, input) => {
if (typeof input.on !== "boolean") {
throw new ToolError("on (true or false) is required.");
}
if (s.magnet !== input.on) {
s.toggleMagnet();
}
return { magnet: useEditor.getState().magnet, ...tracksAfter() };
},
add_title: (_s, input) => placeEach(input, "titles", checkTitle, placeTitle),
add_text_sequence: (s, input) => {
const look = requireTextLook(input.look);
const lane = isNum(input.lane) ? Math.max(0, Math.round(input.lane)) : 0;
const wantCards =
typeof input.cards === "boolean" ? input.cards : look.frame.cards.length > 0;
const cards = wantCards && look.frame.cards.length > 0 ? look.frame.cards : [];
const lines = textSequenceLines(s, input);
if (lines.length === 0)
throw new ToolError(
"Pass lines: [{text, start, end}], or from_captions: true to build the sequence from the caption track."
);
const variation: TextVariation =
input.variation === "none" || input.variation === "subtle" || input.variation === "bold"
? input.variation
: (look.defaultVariation ?? "bold");
if (typeof input.layout === "string" && !TEXT_LAYOUT_IDS.includes(input.layout as TextLayout))
throw new ToolError(`Unknown layout. Use one of: ${TEXT_LAYOUT_IDS.join(", ")}.`);
const layout = typeof input.layout === "string" ? (input.layout as TextLayout) : undefined;
if (paintsFrame(look, input.background)) s.setBackground(look.frame.background);
// Row 0 is the front of the element stack, so the words take the row the
// caller named and each card goes one row under them. Cards over words
// would paint the line out.
const cardLane = lane + 1;
const composed = composeTextRun(lines, look, {
variation,
layout,
frame: frameOf(s.aspect),
cards,
});
const made: { id: string; start: number; end: number; text: string }[] = [];
composed.forEach((line, i) => {
const card = cards.length > 0 ? cards[i % cards.length] : null;
if (card) {
useEditor.getState().seek(line.start);
useEditor.getState().addShape("rect", { lane: cardLane });
const sel = useEditor.getState().selection;
if (sel?.kind === "overlay")
applyOverlayPatchSettled(sel.id, {
start: line.start,
end: line.end,
x: 0.5,
y: 0.5,
w: 1,
h: 1,
fill: card,
});
}
useEditor.getState().seek(line.start);
useEditor.getState().addOverlay({ lane, seed: "defaults" });
const sel = useEditor.getState().selection;
if (sel?.kind !== "overlay") return;
applyOverlayPatchSettled(sel.id, {
start: line.start,
end: line.end,
text: line.text,
x: line.x,
y: line.y,
rotation: line.rotation,
size: line.size,
font: line.font,
weight: line.weight,
color: line.color,
italic: line.italic || look.text.italic,
letterSpacing: look.text.letterSpacing,
lineHeight: look.text.lineHeight,
stroke: look.text.stroke,
plate: look.text.plate ?? false,
plateColor: look.text.plateColor,
plateOpacity: look.text.plateOpacity,
shadow: look.text.shadow ?? false,
align: "center",
});
useEditor.getState().updateOverlay(sel.id, { anim: line.anim });
const o = useEditor.getState().overlays.find((x) => x.id === sel.id);
if (o) made.push({ id: o.id, start: roundT(o.start), end: roundT(o.end), text: line.text });
});
const faces = [...new Set(composed.map((l) => l.font))];
const moves = [...new Set(composed.map((l) => l.move))].filter((m) => m !== "none");
return {
look: look.id,
variation,
layout: layout ?? (variation === "none" ? "center" : look.ensemble.layout),
count: made.length,
lanes: cards.length > 0 ? { cards: cardLane, text: lane } : { text: lane },
background: useEditor.getState().background,
faces,
moves,
items: made.slice(0, 40),
...(made.length > 40 ? { itemsTruncated: true } : {}),
note:
cards.length > 0
? `Words on row ${lane} with their cards on row ${cardLane} behind them, colors cycling ${look.frame.cards.join(" \u2192 ")}.`
: look.keepsFrame
? `Words on row ${lane} over the cut as it already looks; the frame color is untouched.`
: `Words on row ${lane} over the ${look.frame.background} frame.`,
};
},
set_caption_look: async (s, input) => {
const patch: Parameters<typeof s.setSubtitlesView>[0] = {};
if (typeof input.look === "string") {
const look = requireTextLook(input.look);
patch.style = look.captions.style;
patch.wordHighlight = look.captions.wordHighlight;
if (look.captions.size !== undefined) patch.size = look.captions.size;
if (look.captions.font) patch.font = look.captions.font;
if (look.captions.accentColor) patch.accentColor = look.captions.accentColor;
if (look.captions.accentMode) patch.accentMode = look.captions.accentMode;
if (paintsFrame(look, input.background)) s.setBackground(look.frame.background);
}
if (typeof input.style === "string") {
if (!(input.style in CAPTION_STYLES))
throw new ToolError(`Unknown caption style. Use one of: ${Object.keys(CAPTION_STYLES).join(", ")}.`);
patch.style = input.style as CaptionStyleId;
}
if (isNum(input.size)) patch.size = clamp(Math.round(input.size), 16, 200);
if (input.font !== undefined) {
patch.font = knownFont(input.font);
}
if (typeof input.word_highlight === "boolean") patch.wordHighlight = input.word_highlight;
if (typeof input.accent_color === "string") patch.accentColor = input.accent_color;
if (isNum(input.accent_scale))
patch.accentScale = clamp(input.accent_scale, WORD_SWELL_MIN, WORD_SWELL_MAX);
if (isNum(input.accent_dim)) patch.accentDim = clamp(input.accent_dim, 0, 1);
if ((WORD_EFFECT_IDS as string[]).includes(input.accent_mode as string)) {
patch.accentMode = input.accent_mode as WordEffectId;
// Naming an effect is asking for it, so it comes on with the pick
// unless this same call turned it off.
if (patch.wordHighlight === undefined && !s.subtitles.wordHighlight)
patch.wordHighlight = true;
}
if (isNum(input.y)) patch.y = clamp(input.y, 0.02, 0.98);
if (isNum(input.x)) patch.x = clamp(input.x, 0.02, 0.98);
if (typeof input.emphasis_font === "string") {
if (!allFonts().some((f) => f.id === input.emphasis_font))
throw new ToolError(`Unknown font id "${input.emphasis_font}".`);
patch.emphasisFont = input.emphasis_font;
}
if (typeof input.emphasis_color === "string") patch.emphasisColor = input.emphasis_color;
if (typeof input.emphasis_italic === "boolean") patch.emphasisItalic = input.emphasis_italic;
if (input.emphasis_weight !== undefined) {
if (!isTextWeight(input.emphasis_weight))
throw new ToolError(`emphasis_weight is one of ${TEXT_WEIGHTS.join(", ")}.`);
patch.emphasisWeight = input.emphasis_weight;
}
if (isNum(input.emphasis_scale))
patch.emphasisScale = clamp(input.emphasis_scale, EMPHASIS_SCALE_MIN, EMPHASIS_SCALE_MAX);
const per = isNum(input.words_per_cue)
? clamp(Math.round(input.words_per_cue), MIN_WORDS_PER_CUE, MAX_WORDS_PER_CUE)
: null;
if (Object.keys(patch).length === 0 && per === null)
throw new ToolError("Nothing to change.");
if (Object.keys(patch).length > 0) s.setSubtitlesView(patch);
// Re-cutting the captions rewrites the track and measures it against the
// mix, so the tool waits for the tracks it reports on.
const before = per !== null ? useEditor.getState().subtitles.cues.length : 0;
if (per !== null) await useEditor.getState().setSubtitleWordsPerCue(per);
const cur = useEditor.getState().subtitles;
return {
style: cur.style ?? "clean",
size: cur.size,
font: cur.font,
wordsPerCue: cueWordCount(cur),
...(per !== null ? { cues: cur.cues.length, cuesBefore: before } : {}),
wordHighlight: cur.wordHighlight === true,
accentColor: cur.accentColor,
accentMode: cur.accentMode,
accentScale: cur.accentScale,
accentDim: cur.accentDim,
emphasis: captionEmphasis(cur),
};
},
set_caption_emphasis: (s, input) => {
const marks = Array.isArray(input.marks) ? (input.marks as Record<string, unknown>[]) : [];
if (marks.length === 0 && input.clear_all !== true)
throw new ToolError("Pass marks (cue_id with indices or words), or clear_all.");
// Every mark is resolved against its cue before anything is written, so
// one bad id or word leaves the track as it was.
const edits: { id: string; indices: number[]; on?: boolean }[] = [];
for (const m of marks) {
const cue = requireItem(s.subtitles.cues, m.cue_id, "subtitle cue");
const count = displayWords(cue.text).length;
const indices: number[] = [];
if (Array.isArray(m.indices)) {
for (const i of m.indices) {
if (!isNum(i) || !Number.isInteger(i) || i < 0 || i >= count)
throw new ToolError(`Cue ${cue.id} has words 0..${count - 1}; index ${String(i)} is not one of them.`);
indices.push(i);
}
}
if (Array.isArray(m.words)) {
const found = emphasisIndicesOf(cue, m.words.map(String));
if (found.missing.length > 0)
throw new ToolError(
`Cue ${cue.id} reads "${cue.text}" and has no word ${found.missing.map((w) => `"${w}"`).join(", ")}.`
);
indices.push(...found.indices);
}
if (indices.length === 0) throw new ToolError(`Name the words of cue ${cue.id} by indices or words.`);
edits.push({ id: cue.id, indices, on: m.on !== false });
}
const clear =
input.clear_all === true
? isNum(input.track)
? { lane: Math.round(input.track) }
: {}
: undefined;
s.setCueEmphasis(edits, clear);
const cur = useEditor.getState().subtitles;
const touched = new Set(edits.map((e) => e.id));
return {
cues: cur.cues
.filter((c) => touched.has(c.id))
.map((c) => ({ id: c.id, text: c.text, emphasis: emphasizedWords(c).map(([, w]) => w) })),
emphasizedCues: cur.cues.filter((c) => cueEmphasis(c).length > 0).length,
...(cur.showOnVideo ? {} : { note: "Captions are hidden on the video; subtitles_set_view shows them." }),
};
},
sync_lyrics: async (s, input) => {
const text = typeof input.text === "string" ? input.text : "";
const lines = text
.split(/\r?\n/)
.map((l) => l.trim())
.filter((l) => l.length > 0);
if (lines.length === 0) throw new ToolError("Pass text — the lyrics or script, one line per screen.");
const lane = targetSubtitleTrack(input);
// The recording's own clock. Existing captions serve; without them the
// cut is transcribed first, which is what puts times on the words.
let cues = laneCues(useEditor.getState().subtitles, lane);
if (cues.length === 0) {
await useEditor.getState().generateSubtitles();
const cur = useEditor.getState();
if (cur.subtitleStatus === "error")
throw new ToolError(cur.subtitleError ?? "Could not transcribe the audio.");
cues = laneCues(cur.subtitles, lane);
}
const st = useEditor.getState();
const span = {
from: isNum(input.from) ? Math.max(0, input.from) : 0,
to: isNum(input.to) ? input.to : Math.max(projectDuration(st), cues[cues.length - 1]?.end ?? 0),
};
const timed = syncLines(lines, cueWords(cues), span);
// The transcript's clock only covers the words it recognized. Every other
// line here was interpolated between them, so the run is measured against
// the mix itself before it is written — the same pass the captions got,
// reaching wider because these times are guesses.
const mix = await st.cutMixSamples();
const report = mix
? syncToSpeech(timed, mix.samples, mix.sampleRate, { reach: 0.6 })
: null;
st.setLaneCues(lane, report?.evidence ? report.items : timed);
if (typeof input.look === "string") {
const look = requireTextLook(input.look);
st.setSubtitlesView({
style: look.captions.style,
wordHighlight: look.captions.wordHighlight,
...(look.captions.size !== undefined ? { size: look.captions.size } : {}),
...(look.captions.font ? { font: look.captions.font } : {}),
...(look.captions.accentColor ? { accentColor: look.captions.accentColor } : {}),
...(look.captions.accentMode ? { accentMode: look.captions.accentMode } : {}),
});
if (paintsFrame(look, input.background)) st.setBackground(look.frame.background);
}
const heardWords = cueWords(cues).length;
// What the track now carries, which is what the assistant must reason
// against: the aligned times when the mix moved them, the transcript's
// own otherwise.
const written = report?.evidence ? report.items : timed;
return {
track: lane,
count: written.length,
lines: written.slice(0, 40).map((l) => ({ start: l.start, end: l.end, text: l.text })),
...(written.length > 40 ? { linesTruncated: true } : {}),
aligned: report?.evidence === true,
...(report?.evidence ? { movedOntoSpeech: report.moved.length, maxShift: report.maxShift } : {}),
note:
`Your text is on the track verbatim, timed against ${heardWords} recognized words. ` +
(report?.evidence
? `${report.moved.length} line(s) then moved onto the speech in the mix itself (farthest ${report.maxShift}s). `
: "The mix offered no readable speech edges to check them against, so the lines carry the transcript's clock alone. ") +
"Spot-check a line or two with seek + capture_frame, and retime with update_cue.",
};
},
align_to_audio: async (s, input) => {
if (!s.projectId) throw new ToolError("No project open.");
const target = input.target === "elements" ? "elements" : "captions";
const reach = isNum(input.reach) ? clamp(input.reach, 0.1, 2) : 0.6;
const only = Array.isArray(input.ids) ? new Set(input.ids.map(String)) : null;
const mix = await useEditor.getState().cutMixSamples();
if (!mix)
throw new ToolError(
"Nothing audible on the timeline to measure against — the audio or video the words belong to has to be in the cut."
);
if (target === "captions") {
const lane = targetSubtitleTrack(input);
// The whole track is measured even when only some cues are being
// written: the pass weighs the transcript against the mix as a whole
// before it moves anything, and a handful of cues out of a hundred
// look like a mix about something else.
const cues = laneCues(useEditor.getState().subtitles, lane);
if (cues.length === 0)
throw new ToolError(`Subtitle track ${lane} has no captions to align.`);
const report = syncToSpeech(cues, mix.samples, mix.sampleRate, { reach });
// Writing part of an aligned track fits the written cues between the
// ones left where they were; captions on a track may not overlap.
const writes = partialWrites(report.items, cues, (c) => !only || only.has(c.id));
if (report.evidence)
useEditor.getState().retimeItems({
cues: writes.map((c) => ({
id: c.id,
start: c.start,
end: c.end,
...(c.words ? { words: c.words } : {}),
})),
});
return {
target,
track: lane,
count: cues.length,
...syncResult(report, cues, only),
};
}
const overlays = useEditor.getState().overlays;
const row = isNum(input.lane) ? Math.max(0, Math.round(input.lane)) : 0;
const picked = only
? [...only].map((id) => requireItem(overlays, id, "overlay element"))
: overlays.filter((o) => (o.lane ?? 0) === row);
if (picked.length === 0)
throw new ToolError(`No elements on row ${row} to align — pass ids, or the row the run sits on.`);
// Rows are measured whole, one at a time. A row's items are what may not
// overlap each other, and the fit against the mix is read over the whole
// run rather than the few elements being written.
const lanes = [...new Set(picked.map((o) => o.lane ?? 0))].sort((a, b) => a - b);
const writes = new Map<string, { id: string; start: number; end: number }>();
const partners: { from: { start: number; end: number }; to: { start: number; end: number } }[] = [];
const reports = lanes.map((lane) => {
const items = overlays
.filter((o) => (o.lane ?? 0) === lane)
.sort((a, b) => a.start - b.start);
const report = syncToSpeech(
items.map((o) => ({
id: o.id,
text: isTextOverlay(o) ? o.text : o.kind ?? "element",
start: o.start,
end: o.end,
})),
mix.samples,
mix.sampleRate,
{ reach }
);
if (report.evidence) {
// Part of a row may be written while the rest stays; each written
// item is fitted between the neighbours it lands among, since items
// sharing a row may never overlap.
const fitted = partialWrites(report.items, items, (next) =>
picked.some((p) => p.id === next.id)
);
for (const next of fitted) {
const was = items.find((o) => o.id === next.id)!;
writes.set(next.id, { id: next.id, start: next.start, end: next.end });
// Only a move that is actually being written can carry a partner
// with it: a card following a word that stayed put would be the
// desync this ride-along exists to prevent.
partners.push({ from: { start: was.start, end: was.end }, to: next });
}
}
return { lane, items, report };
});
// A look's color cards sit on the row under its words, one per line and
// timed to it. They belong to the line, so an element elsewhere holding
// exactly a moved item's old window rides along — otherwise the words
// land on the speech and their cards stay behind.
const EPS = 0.05;
for (const o of overlays) {
if (writes.has(o.id) || lanes.includes(o.lane ?? 0)) continue;
const pair = partners.find(
(p) => Math.abs(p.from.start - o.start) <= EPS && Math.abs(p.from.end - o.end) <= EPS
);
if (pair) writes.set(o.id, { id: o.id, start: pair.to.start, end: pair.to.end });
}
if (writes.size > 0) useEditor.getState().retimeItems({ overlays: [...writes.values()] });
return {
target,
lane: lanes[0],
...(lanes.length > 1 ? { lanes } : {}),
count: reports.reduce((n, r) => n + r.items.length, 0),
...syncResult(
mergeReports(reports.map((r) => r.report)),
reports.flatMap((r) =>
r.items.map((o) => ({ id: o.id, text: isTextOverlay(o) ? o.text : o.kind ?? "element" }))
),
only
),
};
},
update_overlay: (s, input) => {
const ids = Array.isArray(input.ids) && input.ids.length ? input.ids.map(String) : null;
if (!ids && typeof input.id !== "string") throw new ToolError("Pass id or ids.");
const targets = (ids ?? [String(input.id)]).map((id) => requireItem(s.overlays, id, "overlay element"));
// An effect's own settings — its course, kind, tone, strobe — change
// in place, so the element keeps its id, lane and timing. Read them all
// first: a bad value refuses the call before anything is written.
const settings = new Map(targets.flatMap((o) => (isEffectOverlay(o) ? [[o.id, effectSettings(o.effect, input)] as const] : [])));
// One undo step for the whole write, however many elements it lands on.
s.pushHistory();
for (const o of targets) {
applyOverlayPatchSettled(o.id, overlayPatch(input, o.kind ?? "text", o));
const own = settings.get(o.id);
if (own && Object.keys(own).length) useEditor.getState().updateOverlaysTransient([{ id: o.id, patch: own }]);
}
const report = (id: string) => {
const next = useEditor.getState().overlays.find((x) => x.id === id)!;
return {
id: next.id,
kind: next.kind ?? "text",
...(isTextOverlay(next) ? { text: next.text, color: next.color, size: next.size } : {}),
start: roundT(next.start),
end: roundT(next.end),
};
};
return ids ? { overlayIds: targets.map((o) => o.id), updated: targets.map((o) => report(o.id)) } : report(targets[0].id);
},
update_audio: (s, input) => {
const a = requireItem(s.audioClips, input.id, "soundtrack clip");
const len = retimeOf(a).len;
const patch: Partial<AudioClip> = {};
if (input.lane !== undefined) patch.lane = audioLaneInput(input.lane);
if (isNum(input.volume)) patch.volume = clamp(input.volume, 0, 3);
if (isNum(input.fadeIn)) patch.fadeIn = clamp(input.fadeIn, 0, len / 2);
if (isNum(input.fadeOut)) patch.fadeOut = clamp(input.fadeOut, 0, len / 2);
if (isNum(input.start)) patch.start = Math.max(0, input.start);
if (isNum(input.in)) patch.in = Math.max(0, input.in);
if (isNum(input.out)) patch.out = input.out;
if (isNum(input.speed))
patch.speed =
Math.abs(input.speed - 1) < 1e-4 ? undefined : Math.max(SPEED_FLOOR, input.speed);
if (typeof input.reverse === "boolean") patch.reverse = input.reverse || undefined;
// duck >= 1 clears ducking (undefined); below 1 sets the gain.
if (isNum(input.duck)) patch.duck = input.duck >= 1 ? undefined : clamp(input.duck, 0, 1);
if (typeof input.hidden === "boolean") patch.hidden = input.hidden || undefined;
if (isNum(patch.in ?? NaN) || isNum(patch.out ?? NaN)) {
const nIn = patch.in ?? a.in;
const nOut = patch.out ?? a.out;
if (nOut - nIn < 0.1) throw new ToolError("Audio clip must stay at least 0.1s long.");
}
if (!("duck" in patch) && Object.keys(patch).length === 0)
throw new ToolError("Nothing to change.");
s.updateAudio(a.id, patch);
// Report where the clip actually sits: the store slides a committed move
// to the lane's next free slot when the requested start overlaps.
const landed = useEditor.getState().audioClips.find((c) => c.id === a.id)!;
return {
id: a.id,
...patch,
lane: landed.lane ?? 0,
...("start" in patch ? { start: roundT(landed.start) } : {}),
...audioPackHint(a.id),
};
},
set_framing: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
refuseCardFraming(clip, input, ["mode", "zoom", "panX", "panY"]);
// Only what the call names changes; the rest of the framing stays as
// the user left it.
const mode = input.mode === "fill" || input.mode === "fit" ? input.mode : clip.fit ?? "fit";
const zoom = isNum(input.zoom) ? clamp(input.zoom, 1, CLIP_MAX_ZOOM) : clipZoom(clip);
// Pan only means something once something overflows the box.
const pannable = mode === "fill" || zoom > 1;
const pan = (axis: "panX" | "panY") =>
!pannable ? 0 : isNum(input[axis]) ? clamp(input[axis], -1, 1) : clip[axis] ?? 0;
s.updateClip(clip.id, {
fit: mode,
zoom: zoom > 1 ? zoom : undefined,
panX: pan("panX"),
panY: pan("panY"),
...(typeof input.flipH === "boolean" ? { flipH: input.flipH || undefined } : {}),
...(typeof input.flipV === "boolean" ? { flipV: input.flipV || undefined } : {}),
});
const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;
return {
id: next.id,
fit: next.fit,
zoom: clipZoom(next),
panX: next.panX ?? 0,
panY: next.panY ?? 0,
flipH: !!next.flipH,
flipV: !!next.flipV,
};
},
set_clip_effects: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
if (!Array.isArray(input.effects)) throw new ToolError("effects must be a list; [] removes them all.");
// Each entry names a clip effect once, with an optional amount in range;
// a flash also takes its tone, strobe rate and rhythm, a negative its
// strobe rate.
const effects: ClipEffect[] = [];
for (const e of input.effects as { effect?: unknown; amount?: unknown; tone?: unknown; rate?: unknown; rhythm?: unknown; fade?: unknown; fade_ease?: unknown }[]) {
const effect = CLIP_EFFECT_IDS.find((id) => id === e?.effect);
if (!effect) throw new ToolError(`effect must be one of ${CLIP_EFFECT_IDS.join(", ")}.`);
if (effects.some((x) => x.effect === effect)) throw new ToolError(`${effect} is listed twice; a clip wears an effect once.`);
const entry: ClipEffect = isNum(e.amount) ? { effect, amount: Math.max(0.05, Math.min(1, e.amount)) } : { effect };
if (effect === "negative" && isNum(e.rate) && e.rate > 0) entry.rate = clamp(e.rate, FLASH_RATE_MIN, FLASH_RATE_MAX);
if (effect === "flash") {
if (e.tone !== undefined && !(FLASH_TONES as readonly unknown[]).includes(e.tone)) {
throw new ToolError(`tone is one of ${FLASH_TONES.join(", ")}.`);
}
if (e.tone === "black") {
entry.tone = "black";
}
if (isNum(e.rate) && e.rate > 0) {
entry.rate = clamp(e.rate, FLASH_RATE_MIN, FLASH_RATE_MAX);
}
const rhythm = e.rhythm === undefined ? undefined : flashRhythm(e.rhythm);
if (rhythm) {
entry.rhythm = rhythm;
}
// A fade runs across the clip: "from" lands it as the tone alone.
if (e.fade !== undefined && e.fade !== FLASH_FADE_NONE) {
if (!(FLASH_FADES as readonly unknown[]).includes(e.fade)) throw new ToolError(`fade is one of ${FLASH_FADE_CHOICES.join(", ")}.`);
entry.fade = e.fade as FlashFade;
const ease = e.fade_ease === undefined ? undefined : fadeEaseOf(e.fade_ease);
if (ease) entry.fadeEase = ease;
}
}
effects.push(entry);
}
s.updateClip(clip.id, { effects: effects.length ? effects : undefined });
return { id: clip.id, effects };
},
set_clip_style: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
if (input.clear === true) {
s.updateClip(clip.id, { boxStyle: undefined });
return { id: clip.id, boxStyle: null };
}
if (clip.card)
throw new ToolError(
"This clip is laid out as a camera card, which draws its own corners and shadow: set_camera_card radius and shadow set them."
);
const bs = { ...clip.boxStyle };
if (isNum(input.radius)) bs.radius = Math.max(0, input.radius) || undefined;
if (isNum(input.border_width)) bs.borderWidth = Math.max(0, input.border_width) || undefined;
if (typeof input.border_color === "string") bs.borderColor = input.border_color;
const shadowTouched =
isNum(input.shadow_blur) ||
isNum(input.shadow_x) ||
isNum(input.shadow_y) ||
typeof input.shadow_color === "string" ||
isNum(input.shadow_opacity);
if (shadowTouched) {
const sh: ClipShadow = {
blur: Math.max(0, isNum(input.shadow_blur) ? input.shadow_blur : bs.shadow?.blur ?? 24),
...(isNum(input.shadow_x)
? input.shadow_x !== 0 && { x: input.shadow_x }
: bs.shadow?.x !== undefined && { x: bs.shadow.x }),
...(isNum(input.shadow_y)
? input.shadow_y !== 0 && { y: input.shadow_y }
: bs.shadow?.y !== undefined && { y: bs.shadow.y }),
...(typeof input.shadow_color === "string"
? { color: input.shadow_color }
: bs.shadow?.color !== undefined && { color: bs.shadow.color }),
...(isNum(input.shadow_opacity)
? { opacity: clamp(input.shadow_opacity, 0, 1) }
: bs.shadow?.opacity !== undefined && { opacity: bs.shadow.opacity }),
};
// A shadow with no blur and no throw is no shadow.
bs.shadow = sh.blur > 0 || sh.x || sh.y ? sh : undefined;
}
const boxStyle =
bs.radius || bs.borderWidth || bs.shadow ? bs : undefined;
s.updateClip(clip.id, { boxStyle });
return { id: clip.id, boxStyle: boxStyle ?? null };
},
set_camera_card: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
if (input.clear === true) {
s.updateClip(clip.id, { card: undefined });
return { id: clip.id, card: null };
}
// Only what the call names changes; a first call starts from the
// defaults. Naming a side hands top and width back to its defaults
// unless the call names them too.
const side = input.side === "auto" ? undefined : (CARD_SIDES as readonly unknown[]).includes(input.side) ? (input.side as CardSide) : null;
if (input.side !== undefined && side === null)
throw new ToolError(`side must be one of ${[...CARD_SIDES, "auto"].join(", ")}.`);
const card = normalizeCard({
...(clip.card ?? newCard()),
...(input.side !== undefined ? { side: side ?? undefined, top: undefined, width: undefined } : {}),
...(isNum(input.top) ? { top: input.top } : {}),
...(isNum(input.width) ? { width: input.width } : {}),
...(isNum(input.radius) ? { radius: input.radius } : {}),
...(isNum(input.side_bleed) ? { sideBleed: input.side_bleed } : {}),
...(typeof input.pop_out === "boolean" ? { popOut: input.pop_out } : {}),
...(isNum(input.feather) ? { feather: input.feather } : {}),
...(isNum(input.shadow) ? { shadow: input.shadow } : {}),
...(isNum(input.scale) ? { scale: input.scale } : {}),
...(isNum(input.offset_x) ? { offsetX: input.offset_x } : {}),
...(isNum(input.offset_y) ? { offsetY: input.offset_y } : {}),
});
s.updateClip(clip.id, { card });
if (card.popOut) ensureCardMatte(clip.id);
const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;
const owed = !!next.card?.popOut && !next.card.matte;
return {
id: clip.id,
card: describeCameraCard(next, true, {
aspect: useEditor.getState().aspect,
assetById: new Map(useEditor.getState().assets.map((a) => [a.id, a])),
}),
...(owed
? {
note: matteBakesAvailable
? "The head's person matte is baking in the background — wait_for_renders reports when it lands. Until then the card shows without the head."
: "The card is set. The head's person matte bakes the next time the project is open in the editor; until then the card shows without the head.",
}
: {}),
};
},
set_removal: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
const mode = String(input.mode ?? "");
if (mode === "off") {
// Off keeps the removal and its baked matte on the clip — it just
// stops rendering and baking — so switching back on costs nothing.
if (!clip.removal) return { id: clip.id, removal: null };
s.updateClip(clip.id, { removal: { ...clip.removal, off: true } });
return { id: clip.id, mode, note: "The cutout is off; its matte and settings stay stored." };
}
// Any on-mode clears a stored Off, whatever else it sets.
const prev = { ...clip.removal };
delete prev.off;
const bakeNote = matteBakesAvailable
? "The cutout matte is baking in the background — wait_for_renders reports when it lands."
: "The cutout is set; its matte bakes the next time the project is open in the editor.";
// The direction: `remove` "subject" inverts the cutout — the selection
// goes and the rest of the picture stays. Omitted, an existing
// direction holds; "background" clears it. The selection (and its
// baked matte) is the same either way, so flipping re-bakes nothing.
const dir =
input.remove === "subject"
? { invert: true }
: input.remove === "background"
? { invert: undefined }
: {};
if (mode === "auto") {
// The tool call is the explicit ask, so it carries `requested` — the
// panel's Apply press. `refine` asks for the hosted quality pass on
// top; that rung spends credits.
const refine = input.refine === true ? { refine: true } : {};
s.updateClip(clip.id, {
removal: { ...prev, mode: "auto", requested: true, ...refine, ...dir },
});
ensureMatteBake(clip.id);
return { id: clip.id, mode, note: bakeNote };
}
if (mode !== "custom") throw new ToolError('mode must be "off", "auto", or "custom".');
const subject = typeof input.subject === "string" ? input.subject.trim() : "";
if (!subject || subject.length > 100)
throw new ToolError('mode "custom" needs `subject` — what to keep, in a few words.');
// A named subject replaces any painted selection: the seeds point at
// whatever the user brushed before, and the words are the new ask.
s.updateClip(clip.id, {
removal: {
...prev,
mode: "custom",
subject,
seeds: { prompts: [] },
requested: true,
...dir,
},
});
confirmMatteBake(clip.id);
return { id: clip.id, mode, subject, note: bakeNote };
},
set_removal_stroke: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
const removal = clip.removal;
if (!removal) throw new ToolError("The clip has no cutout yet — call set_removal first.");
const style = String(input.style ?? "");
if (style === "none") {
s.updateClip(clip.id, { removal: { ...removal, stroke: undefined } });
return { id: clip.id, stroke: null };
}
if (!(STROKE_STYLES as readonly string[]).includes(style))
throw new ToolError(`style must be one of ${[...STROKE_STYLES, "none"].join(", ")}.`);
const prev = removal.stroke;
// Canvas silently ignores an invalid fillStyle, so a bad color would
// store and draw as whatever came before it.
if (typeof input.color === "string" && input.color && !/^#[0-9a-f]{6}$/i.test(input.color))
throw new ToolError("color must be #rrggbb.");
const stroke: RemovalStroke = {
style: style as StrokeStyleId,
color:
typeof input.color === "string" && input.color
? input.color.toLowerCase()
: prev?.color ?? "#ffffff",
...(isNum(input.width)
? { width: clamp(input.width, 1, STROKE_WIDTH_MAX) }
: prev?.width !== undefined && { width: prev.width }),
...(isNum(input.feather)
? input.feather !== 0 && { feather: clamp(input.feather, 0, STROKE_FEATHER_MAX) }
: prev?.feather !== undefined && { feather: prev.feather }),
...(isNum(input.offset_x)
? input.offset_x !== 0 && {
offsetX: clamp(input.offset_x, -STROKE_OFFSET_MAX, STROKE_OFFSET_MAX),
}
: prev?.offsetX !== undefined && { offsetX: prev.offsetX }),
...(isNum(input.offset_y)
? input.offset_y !== 0 && {
offsetY: clamp(input.offset_y, -STROKE_OFFSET_MAX, STROKE_OFFSET_MAX),
}
: prev?.offsetY !== undefined && { offsetY: prev.offsetY }),
};
s.updateClip(clip.id, { removal: { ...removal, stroke } });
return { id: clip.id, stroke };
},
set_removal_background: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
const removal = clip.removal;
if (!removal) throw new ToolError("The clip has no cutout yet — call set_removal first.");
const kind = String(input.kind ?? "");
if (kind === "none") {
s.updateClip(clip.id, { removal: { ...removal, backdrop: undefined } });
return { id: clip.id, background: null };
}
if (kind === "color") {
if (typeof input.color === "string" && input.color && !/^#[0-9a-f]{6}$/i.test(input.color))
throw new ToolError("color must be #rrggbb.");
const color =
typeof input.color === "string" && input.color
? input.color.toLowerCase()
: removal.backdrop?.color ?? "#101014";
s.updateClip(clip.id, { removal: { ...removal, backdrop: { kind: "color", color } } });
return { id: clip.id, background: { kind, color } };
}
if (kind !== "image") throw new ToolError('kind must be "none", "color", or "image".');
const assetId = typeof input.asset_id === "string" ? input.asset_id : "";
const bgAsset = s.assets.find((a) => a.id === assetId);
if (bgAsset?.type !== "image")
throw new ToolError(
assetId ? `No image asset with id ${assetId}.` : "asset_id is required for kind \"image\"."
);
s.updateClip(clip.id, { removal: { ...removal, backdrop: { kind: "image", assetId } } });
return { id: clip.id, background: { kind, assetId } };
},
replace_item: (s, input) => {
const id = typeof input.id === "string" ? input.id : "";
const asset = requireItem(s.assets, input.asset_id, "project asset");
const clip = s.clips.find((c) => c.id === id);
if (clip) {
if (asset.type !== "video" && asset.type !== "image")
throw new ToolError(`"${asset.name}" is ${asset.type} — a video clip plays video or a still.`);
const before = clipLen(clip);
s.replaceClipAsset(clip.id, asset.id, { keepMask: input.keep_mask === true });
const next = useEditor.getState().clips.find((c) => c.id === clip.id);
if (!next || next.assetId !== asset.id) throw new ToolError("That clip could not take this source.");
return {
id: next.id,
kind: "clip",
sourceId: asset.id,
name: asset.name,
start: roundT(next.start),
lenBefore: roundT(before),
lenAfter: roundT(clipLen(next)),
...tracksAfter(),
};
}
const audio = s.audioClips.find((a) => a.id === id);
if (audio) {
if (asset.type !== "audio")
throw new ToolError(`"${asset.name}" is ${asset.type} — a soundtrack clip plays audio.`);
const before = audio.out - audio.in;
s.replaceAudioAsset(audio.id, asset.id);
const next = useEditor.getState().audioClips.find((a) => a.id === id);
if (!next || next.assetId !== asset.id) throw new ToolError("That clip could not take this source.");
return {
id: next.id,
kind: "audio",
sourceId: asset.id,
name: asset.name,
start: roundT(next.start),
lenBefore: roundT(before),
lenAfter: roundT(next.out - next.in),
};
}
const overlay = s.overlays.find((o) => o.id === id);
if (overlay && overlay.kind === "sticker") {
if (asset.type !== "image")
throw new ToolError(`"${asset.name}" is ${asset.type} — a sticker shows a still.`);
// A Lottie document animates and a still does not; the flag is read off
// the source, so it moves with it or the export plays the wrong one.
s.updateOverlay(overlay.id, { assetId: asset.id, lottie: isLottieAsset(asset) || undefined });
return { id: overlay.id, kind: "sticker", sourceId: asset.id, name: asset.name };
}
throw new ToolError(
`Nothing with id "${id}" carries a source. Clips, soundtrack clips and stickers do; text and shapes are edited with update_overlay.`
);
},
freeze_frame: async (s, input) => {
const projectId = s.projectId;
if (!projectId) throw new ToolError("No project open.");
const spans = getClipSpans(s.clips, s.assets);
if (spans.length === 0) throw new ToolError("The timeline is empty.");
const total = totalDuration(s.clips);
const t = clamp(isNum(input.t) ? input.t : playheadAt(), 0, Math.max(0, total - 0.001));
const span = spans.find((sp) => t >= sp.start && t < sp.start + sp.len) ?? spans[spans.length - 1];
// Timeline seconds run at the clip's speed in source time, so a sped-up
// clip freezes the frame the preview actually shows.
const srcTime = retimeOf(span.clip).srcAt(t - span.start);
let body: MediaAsset;
const freezeDur = Math.min(10, Math.max(0.5, isNum(input.duration) ? input.duration : 1));
if (input.with_elements === true) {
// The whole picture, as the preview shows it — titles, captions and
// effects burned in. Same render path the canvas's Copy frame uses,
// so a still the assistant makes and one the user copies match.
const png = await renderStageFrame(t).catch((e) => {
throw new ToolError(e instanceof Error ? e.message : "Could not draw the frame.", { cause: e });
});
body = {
...(await storeStageStill(projectId, png, t, "Could not render the freeze frame.")),
duration: freezeDur,
};
} else if (getBackend().kind !== "local") {
// No engine to bake a still video — grab the frame in the browser and
// store it as a project image; image clips carry their own length,
// sized below to the requested duration, mirroring the engine's
// /freeze clamps (default 1s, 0.5..10s).
body = await captureFreezeFrame(projectId, span.asset.url, srcTime, freezeDur, {
frame: frameOf(s.aspect),
cover: clipCovers(span.clip),
zoom: clipZoom(span.clip),
panX: span.clip.panX ?? 0,
panY: span.clip.panY ?? 0,
flipH: span.clip.flipH,
flipV: span.clip.flipV,
}).catch(
(e) => {
throw new ToolError(
e instanceof Error ? e.message : "Could not render the freeze frame."
);
}
);
} else {
const res = await apiFetch(`/api/cut/projects/${projectId}/freeze`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
file: span.asset.fileName,
srcTime,
duration: isNum(input.duration) ? input.duration : 1,
// Bake the still at the current project frame, framed exactly as
// the preview shows it. Switching aspect later letterboxes this
// still — capture a fresh one to re-fit.
frame: frameOf(s.aspect),
framing: {
fit: span.clip.fit ?? "fit",
zoom: clipZoom(span.clip),
panX: span.clip.panX ?? 0,
panY: span.clip.panY ?? 0,
flipH: !!span.clip.flipH,
flipV: !!span.clip.flipV,
},
}),
});
const made = await apiJson<MediaAsset>(res);
if (!res.ok) throw new ToolError(made.error ?? "Could not render the freeze frame.");
body = made;
}
const asset: MediaAsset = {
...body,
url: await storedMediaUrl(projectId, body.fileName),
origin: "freeze",
// A frame grabbed off the source keeps its code values, so the still
// carries the source's profile and draws through the same conversion;
// a stage render is already the finished picture.
...(input.with_elements !== true && span.asset.color ? { color: span.asset.color } : {}),
...(input.with_elements !== true && span.asset.colorProfile ? { colorProfile: span.asset.colorProfile } : {}),
};
const cur = useEditor.getState();
cur.addAsset(asset);
cur.addClipFromAsset(asset.id); // lands at the end, selected
const sel = useEditor.getState().selection;
// A cloud freeze is a still image, placed at the default image-clip
// length — resize it to the requested duration (the engine path bakes a
// video whose duration addClipFromAsset adopts on its own).
if (sel?.kind === "clip" && body.type === "image" && body.duration > 0) {
cur.updateClip(sel.id, { out: body.duration });
}
const index = clamp(isNum(input.index) ? Math.round(input.index) : 0, 0, useEditor.getState().clips.length - 1);
if (sel?.kind === "clip") cur.moveClip(sel.id, index);
void enrichAsset(asset);
return {
assetId: asset.id,
clipId: sel?.kind === "clip" ? sel.id : null,
index,
duration: body.duration,
from: { time: Math.round(t * 100) / 100, source: span.asset.name },
};
},
generate_image: async (s, input) => {
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 refs = resolveRefAssets(input.reference_asset_ids);
// Captured before the render: the image files under the chat that
// asked, even if the user switches threads while it generates. Ownership
// rides the job from creation, so neither the job row nor the landed
// asset ever touches the Image panel.
const chatId = chatOwner();
// Hosted image generation is synchronous and quick, so wait it out.
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 } : {}),
...(chatId ? { chatId } : {}),
});
if (job.status !== "done" || !job.assetId) {
throw new ToolError(job.error ?? "Image generation failed.");
}
const cur = useEditor.getState();
const asset = cur.assets.find((a) => a.id === job.assetId);
if (!asset) throw new ToolError("The generated image did not land in the project.");
const placed = wantsTimeline(input, "index")
? addVideoTrackClip(asset.id, promptedIndex(input))
: NOT_PLACED;
return {
assetId: asset.id,
name: asset.name,
kind: "image",
// A still has no source length; report its default placed length.
duration: IMAGE_CLIP_SECONDS,
addedToTimeline: placed.added,
clipId: placed.clipId,
index: placed.index,
};
},
generate_video: async (s, input) => {
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();
// The render is fire-and-forget below, so a signed-out user must be
// caught here — an unprobed session (null) resolves before we claim
// success. Deeper errors surface in the panel's job list.
const signedIn = gen.signedIn ?? (await gen.probeNow());
if (!signedIn) throw new ToolError("Sign in to Donkey to generate video.");
// Video renders can outrun the assistant tool bridge's 2-minute cap, so
// don't block: start the job and let its completion place the clip.
const refs =
input.reference_asset_id === undefined
? []
: resolveRefAssets([input.reference_asset_id]);
// Audio references carry no picture: they ride in `refs` for the compose
// pass to hear, while anchor rungs take the first ref that has a frame.
const anchors = visualRefs(refs);
// The model renders the whole clip with audio in one pass; the knobs
// are the shape, the output size, and an optional length (unset lets
// the model pick).
const resolution = videoResolutionOf(input.resolution);
const durationSeconds = clampVideoDuration(
typeof input.duration_seconds === "number" ? input.duration_seconds : undefined
);
const baseOpts: Omit<VideoGenOptions, "onDone"> = {
...(input.aspect === "16:9" || input.aspect === "9:16" ? { aspect: input.aspect } : {}),
...(resolution ? { resolution } : {}),
...(durationSeconds !== undefined ? { durationSeconds } : {}),
};
// A one-off render walks the same identity ladder as a scene shot:
// seed image first (the strongest anchor), the picture as an identity
// reference second, text-only last — so a safety-blocked anchor
// degrades the render instead of killing it. The text rung is gated
// exactly like a scene shot's: it runs only when the provider refused
// the image anchor itself. An ordinary failure (timeout, 5xx) must
// fail the job — a render that never saw the user's picture is not a
// success to show them.
const asReference = (anchor: AssetRef): VideoAttempt => ({
prompt,
opts: { ...baseOpts, referenceImages: [anchor] },
});
const textOnly: VideoAttempt = { prompt, opts: { ...baseOpts }, gate: anchorRefused };
// "Animate this image": the referenced frame is the product, so it seeds
// the render untouched — no image-model redesign in between, and no
// text-only rung (a render without the image isn't what was asked).
if (refs.length > 0 && input.animate_reference === true) {
if (anchors.length === 0)
throw new ToolError(
"animate_reference needs an image or video reference — audio has no frame to animate."
);
return launchVideoJob(
projectId,
input,
[
{ prompt, opts: { ...baseOpts, refs: [anchors[0]], composeRefs: false } },
asReference(anchors[0]),
],
{
note: "Animating the referenced image as the literal opening frame — the clip previews in this chat when it lands, in a minute or two.",
}
);
}
// Staged, like the scene pipeline: reference work happens in the image
// model first — it holds identity far better than any video model — and
// the video model then animates the approved frame. The still lands as
// a chat asset (its card previews above the render's), and the render
// seeds from it with the prompt as written. Text-only asks skip
// straight to video; a failed still degrades to the composed-seed hop.
if (anchors.length > 0) {
const still = await gen.generateImage(projectId, prompt, {
refs,
aspect:
input.aspect === "16:9" || input.aspect === "9:16"
? input.aspect
: nearestAspect(useEditor.getState().aspect, defaultVideoAspects()),
chatId: chatOwner() ?? undefined,
});
const stillAsset =
still.status === "done" && still.assetId
? useEditor.getState().assets.find((a) => a.id === still.assetId)
: undefined;
if (stillAsset) {
return launchVideoJob(
projectId,
input,
[
{ prompt, opts: { ...baseOpts, refs: [refFromAsset(stillAsset)], composeRefs: false } },
asReference(anchors[0]),
textOnly,
],
{
extra: { stillAssetId: stillAsset.id },
note: "Designed the opening frame from the reference first (the image card above the render), then started the video from that exact frame — it previews in this chat when it lands, in a minute or two.",
}
);
}
return launchVideoJob(projectId, input, [
{ prompt, opts: { ...baseOpts, refs } },
asReference(anchors[0]),
textOnly,
]);
}
// Audio-only reference: no frame to anchor, so a single rung renders with
// the compose pass folding what it hears into the prompt.
if (refs.length > 0) {
return launchVideoJob(projectId, input, [{ prompt, opts: { ...baseOpts, refs } }]);
}
// No reference: text is the whole request, so the single rung runs ungated.
return launchVideoJob(projectId, input, [{ prompt, opts: { ...baseOpts } }]);
},
queue_message: (_s, input) => {
const text = String(input.text ?? "").trim();
if (!text) throw new ToolError("queue_message needs the message text.");
queueMessageFromAgent(text);
return { queued: true, note: "It runs as its own turn after this one finishes." };
},
set_interface_language: async (_s, input) => {
const locale = input.locale;
if (!isLocale(locale)) {
throw new ToolError(`Unknown interface language ${String(locale)} — pick from ${INTERFACE_LANGUAGE_LIST}.`);
}
const language = languageName(locale);
const where = await changeInterfaceLanguage(locale).catch((err: unknown) => {
throw new ToolError(err instanceof Error ? err.message : String(err), { cause: err });
});
return where === "page"
? { locale, language, saved: "account", note: `The editor reloads in ${language} as this reply finishes, and the account keeps it.` }
: { locale, language, saved: "account", note: `No editor page is open in this session, so the account's language is saved; Donkey Cut opens in ${language} the next time it loads.` };
},
wait_for_renders: async (s) => {
const projectId = s.projectId;
if (!projectId) throw new ToolError("No project open.");
const watched = useGenerate
.getState()
.jobs.filter(
(j) => j.kind === "video" && j.status === "running" && j.projectId === projectId
)
.map((j) => j.id);
// Cutout matte bakes settle here too, so "the background is removed"
// waits for the matte the claim rests on.
const watchedBakes = Object.entries(useMatteBakes.getState().jobs)
.filter(([, j]) => j.status === "running")
.map(([clipId]) => clipId);
if (watched.length === 0 && watchedBakes.length === 0) {
return { renders: [], note: "No renders or cutout bakes in flight — check `renders` in the state for recent outcomes." };
}
// Poll the job store rather than the settlement promises: it also tracks
// renders another tab owns. Stay under the tool bridge's 2-minute cap;
// whatever hasn't settled reports as still rendering.
const deadline = Date.now() + 100_000;
while (Date.now() < deadline) {
const jobs = useGenerate.getState().jobs;
const bakes = useMatteBakes.getState().jobs;
const busy =
watched.some((id) => jobs.find((j) => j.id === id)?.status === "running") ||
watchedBakes.some((id) => bakes[id]?.status === "running");
if (!busy) break;
await new Promise((r) => setTimeout(r, 1000));
}
const jobs = useGenerate.getState().jobs;
const cur = useEditor.getState();
const renders = watched.map((id) => {
const j = jobs.find((x) => x.id === id);
if (!j) return { jobId: id, status: "dismissed" as const };
const asset = j.assetId ? cur.assets.find((a) => a.id === j.assetId) : undefined;
return {
jobId: id,
status: j.status,
...(asset ? { assetId: asset.id, name: asset.name, duration: asset.duration } : {}),
...(j.status === "error" && j.error ? { error: j.error } : {}),
};
});
const bakes = useMatteBakes.getState().jobs;
const cutouts = watchedBakes.map((key) => {
// A camera card's person matte reports beside the clip's cutout.
const { clipId, slot } = matteJobTarget(key);
const forCard = slot === "card" ? { for: "camera card" } : {};
const j = bakes[key];
if (!j) {
const c = cur.clips.find((x) => x.id === clipId);
const m = slot === "card" ? c?.card?.matte : c?.removal?.matte;
return { clipId, ...forCard, status: "done" as const, ...(m ? { quality: m.quality } : {}) };
}
return {
clipId,
...forCard,
status: j.status,
quality: j.quality,
...(j.error ? { error: j.error } : {}),
};
});
const stillRunning =
renders.filter((x) => x.status === "running").length +
cutouts.filter((c) => c.status === "running").length;
return {
renders,
...(cutouts.length > 0 ? { cutouts } : {}),
...(stillRunning > 0
? { note: `${stillRunning} still rendering — call wait_for_renders again to keep waiting.` }
: {}),
};
},
wait_for_uploads: async (s) => {
// Files this page is sending to storage, and failed ones a retry may
// land. A process with no page sends none.
const watched = s.assets.filter((a) => a.upload && uploadInFlight(a.id)).map((a) => a.id);
if (watched.length === 0 && !isOffline()) {
return { uploads: [], note: "No uploads in flight, and the connection is up." };
}
if (!isOffline()) {
retryFailedUploads();
}
// Poll the store: an upload settles by dropping its `upload` mark, or
// by carrying an error. Stay under the tool bridge's 2-minute cap.
const deadline = Date.now() + 100_000;
const settled = () =>
!isOffline() &&
watched.every((id) => {
const a = useEditor.getState().assets.find((x) => x.id === id);
return !a?.upload || a.upload.error !== undefined;
});
while (Date.now() < deadline && !settled()) {
await new Promise((r) => setTimeout(r, 1000));
}
const assets = useEditor.getState().assets;
const uploads = watched.map((id) => {
const a = assets.find((x) => x.id === id);
if (!a) {
return { assetId: id, status: "removed" as const };
}
if (!a.upload) {
return { assetId: id, name: a.name, status: "done" as const };
}
if (a.upload.error) {
return { assetId: id, name: a.name, status: "failed" as const, error: a.upload.error };
}
return { assetId: id, name: a.name, status: "uploading" as const, percent: Math.round(a.upload.progress * 100) };
});
const offline = isOffline();
const waiting = uploads.filter((u) => u.status === "uploading").length;
return {
uploads,
...(offline ? { offline: true, note: "The browser is still offline; uploads and hosted work resume when the connection returns. Call wait_for_uploads again to keep waiting." } : {}),
...(!offline && waiting > 0 ? { note: `${waiting} still uploading — call wait_for_uploads again to keep waiting.` } : {}),
};
},
generate_character_video: async (s, input) => {
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.");
return launchVideoJob(
projectId,
input,
[
{
prompt: characterPrompt(character.persona!, line),
opts: {
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, and there is no weaker rung: another anchor is another face.
refs: [refFromStockVideo(character)],
composeRefs: false,
},
},
],
{ extra: { character: character.id } }
);
},
generate_scene: async (s, input) => {
const projectId = s.projectId;
if (!projectId) throw new ToolError("No project open.");
const gen = useGenerate.getState();
const signedIn = gen.signedIn ?? (await gen.probeNow());
if (!signedIn) throw new ToolError("Sign in to Donkey to generate a video.");
const brief = String(input.brief ?? "").trim();
const fromAudio =
input.from_audio_asset_id !== undefined ? String(input.from_audio_asset_id) : undefined;
if (!brief && !fromAudio)
throw new ToolError("A brief is required (or from_audio_asset_id to animate existing audio).");
if (fromAudio) {
const asset = s.assets.find((a) => a.id === fromAudio);
const audio = s.assets.filter((a) => a.type === "audio");
const hint = audio.length
? ` The project's audio: ${audio.map((a) => `${a.id} ("${a.name}")`).join(", ")}.`
: " This project has no audio asset — omit from_audio_asset_id to write a fresh narration instead.";
if (!asset) throw new ToolError(`No project asset with id ${fromAudio}.${hint}`);
if (asset.type !== "audio")
throw new ToolError(`"${asset.name}" is ${asset.type}, not audio — from_audio_asset_id must be the audio to animate.${hint}`);
// The scene transcriber keys its recognizer off asset.language; a
// mismatched recognizer turns foreign speech into garbage the plan
// then depicts.
const lang = typeof input.audio_language === "string" ? input.audio_language.trim() : "";
if (lang) s.updateAsset(fromAudio, { language: lang });
}
// Plan up to the shot list and stop; approve_scene starts the paid renders.
// Tag every asset the run creates to the asking chat, so intermediates and
// shots stay off the Media/Video/Image/Audio panels.
const res = await useGenScene.getState().start(projectId, {
chatId: chatOwner(),
...(brief ? { brief } : {}),
...(fromAudio ? { fromAudioAssetId: fromAudio } : {}),
...(isNum(input.target_seconds)
? { targetSeconds: clamp(Math.round(input.target_seconds), 6, 90) }
: {}),
...(typeof input.style === "string" && input.style.trim() ? { style: input.style.trim() } : {}),
...(Array.isArray(input.reference_asset_ids)
? { referenceAssetIds: input.reference_asset_ids.map(String) }
: {}),
});
if (!res.started) throw new ToolError(res.message);
return {
planned: true,
shots: res.shotCount,
note: `${res.message} A storyboard card below shows each shot's opening frame for the user, so keep your reply to one short line — don't re-describe the shots or the timing. Ask them to review it; if they want a frame changed, call regenerate_shot (at this stage it just redraws that frame, no credits). When they approve, call approve_scene — that starts the paid video renders, so don't approve on your own.`,
};
},
approve_scene: () => {
const res = useGenScene.getState().approve();
if (!res.ok) throw new ToolError(res.message);
return { rendering: true, note: res.message };
},
cancel_scene: () => {
const res = useGenScene.getState().cancel();
if (!res.ok) throw new ToolError(res.message);
return { stopped: true, note: res.message };
},
regenerate_shot: (_s, input) => {
if (!isNum(input.n)) throw new ToolError("n (the 1-based shot number) is required.");
const note = typeof input.note === "string" && input.note.trim() ? input.note.trim() : undefined;
const res = useGenScene.getState().regenerateShot(Math.round(input.n), note);
if (!res.ok) throw new ToolError(res.message);
return { note: res.message };
},
recut_scene: (_s, input) => {
if (!isNum(input.from_shot) || !isNum(input.to_shot))
throw new ToolError("from_shot and to_shot (1-based, inclusive) are required.");
const instruction = String(input.instruction ?? "").trim();
if (!instruction) throw new ToolError("An instruction is required — what should this span become?");
const res = useGenScene
.getState()
.recutShots(Math.round(input.from_shot), Math.round(input.to_shot), instruction);
if (!res.ok) throw new ToolError(res.message);
return { note: res.message };
},
restyle_scene: (_s, input) => {
const style = String(input.style ?? "").trim();
if (!style) throw new ToolError("style is required — the new look for the whole video.");
const res = useGenScene.getState().restyle(style);
if (!res.ok) throw new ToolError(res.message);
return { note: res.message };
},
stock_search: async (s, input) => {
const q = String(input.query ?? "").trim();
const kindIn =
input.kind === "video" ||
input.kind === "image" ||
input.kind === "character" ||
input.kind === "sound"
? input.kind
: undefined;
interface Hit {
id: string;
kind: "video" | "image" | "character" | "sound";
category: string;
aspect?: string;
duration?: number;
persona?: string;
prompt: string;
tags: string[];
}
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: roundT(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,
});
}
}
if (!kindIn || kindIn === "sound") {
for (const x of STOCK_SFX) {
hits.push({
id: x.id,
kind: "sound",
category: x.category,
duration: roundT(x.duration),
prompt: x.prompt,
tags: x.tags,
});
}
}
// A query ranks every candidate by a judged fit; no query browses the
// catalog in manifest order.
const matches = q ? await rankStock(q, hits) : hits;
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 } : {}),
};
},
stock_add: async (s, input) => {
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);
const sfx = vid || img ? undefined : STOCK_SFX.find((x) => x.id === id);
if (!vid && !img && !sfx)
throw new ToolError(`No stock item with id ${id}. Call stock_search for ids.`);
// Captured before the import: the media files under the chat that
// asked, even if the user switches threads while it downloads.
const chatId = chatOwner();
const asset = vid
? await importStockVideo(projectId, {
url: vid.file,
name: stockTitle(vid.id),
duration: vid.duration,
...stockAspectDims(vid.aspect),
})
: sfx
? await importStockAudio(projectId, {
url: sfx.file,
name: stockTitle(sfx.id),
duration: sfx.duration,
})
: await importImage(projectId, { url: img!.file, name: stockTitle(img!.id) });
tagChatAsset(asset.id, chatId);
const addToTimeline = wantsTimeline(input, "start");
const start = isNum(input.start) ? Math.max(0, input.start) : undefined;
let clipId: string | null = null;
if (addToTimeline) {
// A sound lands on the soundtrack at the playhead (or `start`), on the
// first lane with room; footage and stills go to the video track.
if (sfx) useEditor.getState().addAssetAtPlayhead(asset.id, start);
else useEditor.getState().addClipFromAsset(asset.id, start);
const sel = useEditor.getState().selection;
clipId = sel?.kind === "clip" || sel?.kind === "audio" ? sel.id : null;
}
return {
assetId: asset.id,
name: asset.name,
kind: vid ? "video" : sfx ? "sound" : "image",
duration: roundT(vid || sfx ? asset.duration : IMAGE_CLIP_SECONDS),
addedToTimeline: addToTimeline,
clipId,
fromRef: { scope: "stock", id },
};
},
import_url: async (s, input) => {
const projectId = s.projectId;
if (!projectId) throw new ToolError("No project open.");
// Captured before the download: the media files under the chat that
// asked, even if the user switches threads while it downloads.
const chatId = chatOwner();
const describe = (assets: MediaAsset[]) =>
assets.map((asset) => ({
assetId: asset.id,
name: asset.name,
kind: asset.type,
fileName: asset.fileName,
sizeBytes: asset.sizeBytes,
width: asset.width,
height: asset.height,
duration: roundT(asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration),
}));
// A list downloads a few at a time; each URL answers on its own row.
if (Array.isArray(input.urls) && input.urls.length > 0) {
const rows = await importEach(input.urls.map(String), async (u) => {
const { assets } = await importUrlMedia(projectId, u, { audio: input.audio_only === true });
for (const asset of assets) tagChatAsset(asset.id, chatId);
return describe(assets);
}).catch((e) => {
throw new ToolError(e instanceof Error ? e.message : String(e), { cause: e });
});
const results = rows.filter((r) => !("notStarted" in r)).map((r) => ("value" in r ? { url: r.url, assets: r.value } : r));
const notStarted = rows.filter((r) => "notStarted" in r).map((r) => r.url);
const pending = rows.some((r) => "pending" in r);
return {
results,
...(notStarted.length ? { notStarted } : {}),
// A long list answers in parts, inside the tool call's time.
...(pending || notStarted.length
? {
note: `${pending ? "Pending links are still downloading and land in the project on their own; don't import them again. " : ""}${notStarted.length ? "Call import_url again with the notStarted urls." : ""}`.trim(),
}
: {}),
};
}
const url = String(input.url ?? "").trim();
if (!url) throw new ToolError("A URL is required.");
const { assets, text } = await importUrlMedia(projectId, url, {
audio: input.audio_only === true,
});
for (const asset of assets) tagChatAsset(asset.id, chatId);
return {
assets: describe(assets),
...(text ? { sourceText: text } : {}),
};
},
check_facts: async (_s, input) => {
const { results } = await checkFacts(input);
return factCheckToolOutput(results);
},
list_projects: async (s, input) => {
const { projects, unreachable } = await listOwnProjects();
const offset = typeof input.offset === "number" && Number.isSafeInteger(input.offset) && input.offset > 0 ? input.offset : 0;
const limit = typeof input.limit === "number" && input.limit >= 1 ? Math.min(Math.floor(input.limit), PROJECT_PAGE_MAX) : PROJECT_PAGE_DEFAULT;
const page = projects.slice(offset, offset + limit);
return {
projects: page.map((p) => ({
id: p.id,
name: p.name,
residency: p.residency,
edited: new Date(p.updatedAt).toISOString(),
...(p.id === s.projectId ? { open: true } : {}),
})),
total: projects.length,
...(offset + page.length < projects.length ? { next: offset + page.length } : {}),
// A shelf that did not answer may hold the project the user means.
...(unreachable.length ? { unreachable } : {}),
};
},
read_project: async (_s, input) => {
const ref = await openReferenceLink(input.link);
const reference = describeDoc(ref.doc, { fullCues: true, chatId: chatOwner() });
// Video sources nothing describes: neither a note nor a transcript. A
// role for these is decided by name, length and a reference look.
const unobserved = (ref.doc.assets ?? [])
.filter((a) => a.type === "video" && !a.watch?.notes?.length && !(a.speech && !a.speech.noSpeech))
.map((a) => a.id);
return {
source: {
kind: ref.link.kind,
id: ref.projectId,
name: ref.doc.name ?? "",
residency: ref.residency,
},
...(ref.partial.length ? { partial: ref.partial } : {}),
reference,
unobserved,
note:
"Every item carries the id replicate_project takes; media[].id are the source asset ids for its `media` mapping and for copy_project_media. The document is the edit — watch a reference source (watch_video with project_link) only when its notes and transcript leave what it shows unclear.",
};
},
replicate_project: async (s, input) => {
const projectId = s.projectId;
if (!projectId) throw new ToolError("No project open.");
const ref = await openReferenceLink(input.link);
const items = Array.isArray(input.items) && input.items.length > 0 ? input.items.map(String) : undefined;
const whole = !items;
const built = templateFromDoc(ref.doc, { items });
if (built.unknownItems.length)
throw new ToolError(
`The reference has no items with ids ${built.unknownItems.join(", ")}. read_project lists every item and its id.`
);
const t = built.template;
if (t.layers.length === 0 && t.audio.length === 0 && t.texts.length === 0 && t.cues.length === 0)
throw new ToolError(whole ? "The reference's timeline is empty." : "None of those items can be placed.");
// The role mapping: each reference source the chosen items use plays
// from this project's own asset, or copies across.
const docAssets = ref.doc.assets ?? [];
const mapping = new Map<string, string>();
const rawMedia = Array.isArray(input.media) ? input.media : [];
for (const entry of rawMedia) {
if (!entry || typeof entry !== "object") continue;
const e = entry as Record<string, unknown>;
const sid = String(e.source_asset_id ?? "");
const aid = String(e.asset_id ?? "");
const source = docAssets.find((a) => a.id === sid);
if (!source) throw new ToolError(`No asset with id ${sid} in the reference. read_project's media lists them.`);
const target = s.assets.find((a) => a.id === aid);
if (!target) throw new ToolError(`No asset with id ${aid} in this project. See media in the editor state.`);
if (!mediaTypeFits(source.type, target.type))
throw new ToolError(
`"${target.name}" is ${target.type}; the reference's "${source.name}" is ${source.type}, so it cannot play that part.`
);
mapping.set(sid, aid);
}
const chatId = chatOwner();
const toCopy = built.sourceAssets.filter((a) => !mapping.has(a.id));
const landed = await landReferenceAssets(ref, toCopy, projectId, chatId, new Set(mapping.keys()));
const landedBySource = new Map(landed.map((l) => [l.sourceId, l.asset]));
const assetIds = built.assetByMedia.map(
(sid) => mapping.get(sid) ?? landedBySource.get(sid)?.id ?? ""
);
// A title or the captions set in a font the reference uploaded now
// point at the copy of that font.
const fontMap = new Map(
landed
.filter((l) => l.asset.type === "font")
.map((l) => [uploadedFontId(l.sourceId), uploadedFontId(l.asset.id)])
);
const texts = t.texts.map((o) =>
isTextOverlay(o) && fontMap.has(o.font) ? { ...o, font: fontMap.get(o.font)! } : o
);
const captions =
t.captions?.font && fontMap.has(t.captions.font)
? { ...t.captions, font: fontMap.get(t.captions.font)! }
: t.captions;
const pool = [...useEditor.getState().assets];
const { template: clamped, adjustments } = clampLayersToAssets({ ...t, texts }, assetIds, pool, {
layers: built.itemByLayer.map((id) => `clip ${id}`),
audio: built.itemByAudio.map((id) => `soundtrack clip ${id}`),
});
const chosenClips = (ref.doc.clips ?? []).filter((c) => whole || items!.includes(c.id));
const skipped = chosenClips
.filter((c) => c.removal)
.map((c) => `background removal on clip ${c.id} stayed behind (its matte was baked from the reference's footage)`);
const frame = input.frame === undefined ? whole : input.frame === true;
const captionLook = input.caption_look === undefined ? whole : input.caption_look === true;
const cues = whole && input.captions !== true ? [] : clamped.cues;
const st = useEditor.getState();
const before = {
clips: new Set(st.clips.map((c) => c.id)),
audio: new Set(st.audioClips.map((c) => c.id)),
overlays: new Set(st.overlays.map((o) => o.id)),
transitions: new Set(st.transitions.map((x) => x.id)),
cues: new Set(st.subtitles.cues.map((c) => c.id)),
};
st.beginHistoryBatch();
try {
if (frame && t.project) {
st.setAspect(t.project.aspect);
st.setBackground(t.project.background);
}
if (captionLook && captions && Object.keys(captions).length > 0) st.setSubtitlesView(captions);
st.insertTemplate({ ...clamped, cues, id: "", addedAt: 0 }, assetIds, playheadAt());
} finally {
useEditor.getState().endHistoryBatch();
}
const after = useEditor.getState();
const fresh = <T extends { id: string }>(list: T[], seen: Set<string>) =>
list.filter((x) => !seen.has(x.id)).map((x) => x.id);
return {
replicated: whole ? "the whole edit" : `${items!.length} items`,
from: { id: ref.projectId, name: ref.doc.name ?? "" },
clipIds: fresh(after.clips, before.clips),
audioClipIds: fresh(after.audioClips, before.audio),
overlayIds: fresh(after.overlays, before.overlays),
transitionIds: fresh(after.transitions, before.transitions),
cueIds: fresh(after.subtitles.cues, before.cues),
mapped: [...mapping].map(([sourceId, assetId]) => ({ sourceId, assetId })),
assetIds: landed.filter((l) => !l.reused).map((l) => l.asset.id),
copied: landed.map((l) => ({
sourceId: l.sourceId,
assetId: l.asset.id,
name: l.asset.name,
kind: l.asset.type,
...(l.reused ? { reused: true } : {}),
})),
adjustments: adjustments.map((a) => ({ ...a, from: roundT(a.from), to: roundT(a.to) })),
skipped,
frame: frame && !!t.project,
captionLook: captionLook && !!captions && Object.keys(captions).length > 0,
captions: cues.length > 0 ? "cues copied" : "none copied",
...tracksAfter(),
};
},
copy_project_media: async (s, input) => {
const projectId = s.projectId;
if (!projectId) throw new ToolError("No project open.");
const ref = await openReferenceLink(input.link);
const ids = Array.isArray(input.asset_ids) ? input.asset_ids.map(String) : [];
if (ids.length === 0) throw new ToolError("asset_ids is required — the reference assets to copy.");
const docAssets = ref.doc.assets ?? [];
const chatId = chatOwner();
// Another chat's unplaced media is not the reference's to hand over.
const placed = assetIdsOnAnyTimeline({
clips: ref.doc.clips ?? [],
audioClips: ref.doc.audioClips ?? [],
overlays: ref.doc.overlays ?? [],
transitions: ref.doc.transitions ?? [],
subtitles: ref.doc.subtitles,
timelines: ref.doc.timelines ?? {},
assets: docAssets,
});
const assets = ids.map((id) => {
const a = docAssets.find((x) => x.id === id);
if (!a || hiddenFromChat(a, chatId, placed))
throw new ToolError(`No asset with id ${id} in the reference. read_project's media lists them.`);
return a;
});
const landed = await landReferenceAssets(ref, assets, projectId, chatId);
return {
assets: landed.map((l) => ({
assetId: l.asset.id,
sourceId: l.sourceId,
name: l.asset.name,
kind: l.asset.type,
duration: roundT(l.asset.type === "image" ? IMAGE_CLIP_SECONDS : l.asset.duration),
...(l.reused ? { reused: true } : {}),
})),
note: "The copies preview on cards in this chat; add_clip places one when the user asks for it in the cut. A source this project already held a copy of comes back as that copy, marked reused.",
};
},
library_share: async (_s, input) => {
const parsed = libraryShareTargetSchema.safeParse({ kind: input.kind, id: input.id });
if (!parsed.success) throw new ToolError("Pass a library folder or asset id and kind.");
const action = input.action;
if (action !== "get" && action !== "save" && action !== "remove") throw new ToolError("Unknown sharing action.");
const settings = action === "save" ? shareSettingsSchema.safeParse({ access: input.access, emails: input.emails }) : null;
if (settings && !settings.success) throw new ToolError("Save requires access and a valid email list.");
const library = await fetchLibrary();
let target = parsed.data;
const item = target.kind === "folder"
? library.folders.find((f) => f.id === target.id)
: library.assets.find((a) => a.id === target.id);
if (!item) throw new ToolError("Library item not found.");
if (item.residency !== "cloud") {
if (action !== "save" || input.copy_to_cloud !== true)
throw new ToolError("Sharing a local item requires a cloud copy. Use save with copy_to_cloud:true.");
target = await copyLibraryForSharing(target, item.residency, library);
}
const result = await requestSharing({ libraryTarget: target },
action === "save" ? "PUT" : action === "remove" ? "DELETE" : "GET",
settings?.success ? settings.data : undefined).catch((error: unknown) => {
throw new ToolError(`Sharing failed for cloud ${target.kind} ${target.id}: ${error instanceof Error ? error.message : "Request failed."}`);
});
return { target, share: result.share ?? null,
...(result.share ? { url: `${DONKEYCUT_CANONICAL}${librarySharePath(result.share.id)}` } : {}),
...(action === "remove" ? { removed: true } : {}) };
},
read_folder: async (_s, input) => readFolder(input),
library_list: async (_s, input) => {
const lib = await fetchLibrary();
return listLibrary({
folders: lib.folders,
assets: lib.assets,
templates: lib.templates
.filter((t) => !isSoundPresetTemplate(t) && !isStylePresetTemplate(t) && !isGradePresetTemplate(t))
.map((t) => ({
id: t.id,
name: t.name,
duration: t.duration,
parts: t.layers.length + t.audio.length + t.texts.length + t.cues.length,
folderId: t.folderId,
})),
}, input);
},
note_save: async (_s, input) => (await import("@/cut/lib/notes")).writeNoteFromTool(input),
read_note: async (_s, input) => (await import("@/cut/lib/notes")).readNote(input),
notes_list: async () => {
const { notes, folders, labels } = await fetchNotes();
const folderName = new Map(folders.map((f) => [f.id, f.name]));
const labelName = new Map(labels.map((l) => [l.id, l.name]));
return {
folders: folders.map((f) => ({
id: f.id,
name: f.name,
...(f.parentId ? { parentId: f.parentId } : {}),
})),
labels: labels.map((l) => l.name),
notes: notes.map((n) => {
const worn = n.labelIds
.map((id) => labelName.get(id))
.filter((name): name is string => !!name);
return {
id: n.id,
title: n.title,
body: n.body,
libraryLocation: n.libraryLocation,
...(n.folderId ? { folder: folderName.get(n.folderId) ?? n.folderId } : {}),
...(worn.length > 0 ? { labels: worn } : {}),
updatedAt: new Date(n.updatedAt).toISOString(),
};
}),
};
},
library_add: async (s, input) => {
const projectId = s.projectId;
if (!projectId) throw new ToolError("No project open.");
if (input.share_link) {
const ref = parseFolderLink(String(input.share_link));
if (!ref || ref.scope !== "shared") throw new ToolError("Provide a shared Library link.");
if (typeof input.folder_id === "string") ref.folderId = input.folder_id;
const offset = input.offset ?? 0;
if (typeof offset !== "number" || !Number.isSafeInteger(offset) || offset < 0) throw new ToolError("Invalid page offset.");
const chatId = chatOwner();
const page = await sharedFolderPage(ref, offset);
const templateFile = typeof input.template_file === "string"
? page.templates.find((t) => t.id === input.id)?.files.find((f) => f.fileName === input.template_file)
: undefined;
const source = templateFile
? { ...templateFile, id: String(input.id), type: assetTypeOf(new File([], templateFile.fileName)) }
: page.assets.find((a) => a.id === input.id);
if (!source || !source.type) throw new ToolError("That asset is not on this shared page. Read the folder for its folder_id and offset.");
const params = new URLSearchParams({ resolve: "1" });
if (templateFile) { params.set("template", source.id); params.set("file", source.fileName); }
const res = await cloudRequest(`/api/cut-shared/library/${encodeURIComponent(ref.shareToken)}/media/${encodeURIComponent(source.id)}?${params}`);
if (!res.ok) throw new ToolError(`Could not read the shared asset (${res.status}).`);
const { url: mediaUrl } = await res.json() as { url: string };
const media = await fetch(mediaUrl);
if (!media.ok) throw new ToolError(`Could not download the shared asset (${media.status}).`);
const file = new File([await media.blob()], source.fileName);
if (isLinkedType(source.type)) {
const linkedId = await uploadLinkedFile(file);
return { name: source.name, kind: source.type,
...(source.type === "font" ? { fontId: linkedId } : { lutId: linkedId }) };
}
const asset = await importFileToProject(projectId, file);
if (!asset) throw new ToolError("This shared file cannot be imported into the project.");
asset.name = source.name;
useEditor.getState().addAsset(asset);
void enrichAsset(asset);
tagChatAsset(asset.id, chatId);
const place = input.add_to_timeline === true || isNum(input.start) || isNum(input.index);
return { assetId: asset.id, name: asset.name, kind: asset.type, duration: roundT(asset.duration),
...(place ? { addedToTimeline: true, clip: placeAssetOnTimeline(asset, input) } : { addedToTimeline: false }) };
}
const found = findLibraryAsset((await fetchLibrary()).assets, String(input.id ?? ""));
// A turn routed away from the stock area doesn't see stock_add, so the
// miss names the area to request as well as the tool.
if (!found && STOCK_SFX.some((x) => x.id === input.id))
throw new ToolError(`"${String(input.id)}" is a stock sound effect, not a Library asset: add it with stock_add (the stock area; call request_tools with ["stock"] if stock_add isn't declared to you).`);
if (!found)
throw new ToolError(`No library asset with id or name "${String(input.id)}". Call library_list with a query for ids; stock sound effects come from stock_search and stock_add in the stock area (request_tools ["stock"] if you don't see them).`);
if ("candidates" in found)
throw new ToolError(`Several Library assets are named "${String(input.id)}": ${JSON.stringify(found.candidates)}. Pass one id.`);
const lib = found.asset;
if (isLinkedType(lib.type)) {
await syncLinkedLibrary();
const linkedId = linkIdForAsset(lib.id);
if (!linkedId) throw new ToolError(`Could not load "${lib.name}" from the Library.`);
return { libraryId: lib.id, name: lib.name, kind: lib.type,
...(lib.type === "font" ? { fontId: linkedId } : { lutId: linkedId }) };
}
// Captured before the import: the media files under the chat that asked,
// even if the user switches threads while it copies.
const chatId = chatOwner();
const asset = await importLibraryAsset(projectId, lib);
tagChatAsset(asset.id, chatId);
const place =
input.add_to_timeline === true || isNum(input.start) || isNum(input.index);
return {
assetId: asset.id,
name: asset.name,
kind: asset.type,
duration: roundT(asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration),
...(place
? { addedToTimeline: true, clip: placeAssetOnTimeline(asset, input) }
: { addedToTimeline: false }),
fromRef: { scope: "library", id: lib.id },
};
},
template_add: async (s, input) => {
const projectId = s.projectId;
if (!projectId) throw new ToolError("No project open.");
const id = String(input.id ?? "");
// A template saved into this project's own Media is already here, media
// and all; a Library one has to be carried in first.
const own = useEditor.getState().templates.find((x) => x.id === id);
const shelved = own ? null : (await fetchLibrary()).templates.find((x) => x.id === id);
const t = own ?? shelved;
if (!t)
throw new ToolError(`No template with id ${id}. Call library_list for ids.`);
const chatId = chatOwner();
const before = new Set(s.assets.map((a) => a.id));
if (shelved) await addTemplateToProject(projectId, shelved);
else await addProjectTemplateToTimeline(projectId, t);
// Chat-fetched media files under the asking thread, like stock/library
// imports; the template's clips reference it, so it survives cleanup.
for (const a of useEditor.getState().assets) {
if (!before.has(a.id)) tagChatAsset(a.id, chatId);
}
return {
added: t.name,
duration: roundT(t.duration),
parts: t.layers.length + t.audio.length + t.texts.length + t.cues.length,
};
},
save_template: (s, input) => {
if (!s.projectId) throw new ToolError("No project open.");
const name = String(input.name ?? "").trim();
if (!name) throw new ToolError("A template name is required.");
const ids = Array.isArray(input.item_ids) ? input.item_ids.map(String) : [];
if (ids.length === 0) throw new ToolError("item_ids is required — the timeline items to save.");
const sels = ids.map((id): NonNullable<Selection> => {
if (s.clips.some((c) => c.id === id)) return { kind: "clip", id };
if (s.audioClips.some((c) => c.id === id)) return { kind: "audio", id };
if (s.overlays.some((o) => o.id === id)) return { kind: "overlay", id };
if (s.subtitles.cues.some((c) => c.id === id)) return { kind: "cue", id };
throw new ToolError(`No timeline item with id ${id}. Call get_state for current ids.`);
});
// Build through the store's selection-template path — the same shape the
// user's Save-selection button produces — leaving the items selected.
s.select(sels[0]);
for (const sel of sels.slice(1)) s.toggleSelect(sel);
const built = useEditor.getState().selectionTemplate();
if (!built) throw new ToolError("Could not build a template from those items.");
const saved = useEditor.getState().addTemplate({ ...built, name });
return { id: saved.id, name: saved.name, duration: roundT(saved.duration) };
},
library_organize: async (_s, input) => {
// The library spans every shelf, so each id is resolved against the
// current listing to find the backend that owns it.
const lib = await fetchLibrary();
const folderShelf = (id: string) => lib.folders.find((f) => f.id === id)?.residency;
const itemShelf = (id: string) =>
lib.assets.find((a) => a.id === id)?.residency ??
lib.templates.find((t) => t.id === id)?.residency;
switch (String(input.action ?? "")) {
case "create_folder": {
const name = String(input.name ?? "").trim();
if (!name) throw new ToolError("A folder name is required.");
// Inside a parent, the folder lands on the parent's shelf.
const parentId =
typeof input.parent_id === "string" && input.parent_id ? input.parent_id : null;
const r = parentId ? folderShelf(parentId) : undefined;
if (parentId && !r) throw new ToolError(`No library folder with id ${parentId}.`);
const f = await createLibraryFolder(name, r, parentId);
return { folderId: f.id, name: f.name, ...(f.parentId ? { parentId: f.parentId } : {}) };
}
case "rename_folder": {
const name = String(input.name ?? "").trim();
if (!name) throw new ToolError("A folder name is required.");
const id = String(input.folder_id ?? "");
const r = folderShelf(id);
if (!r) throw new ToolError(`No library folder with id ${id}.`);
await updateLibraryFolder(r, id, { name });
return { renamed: true, name };
}
case "move_folder": {
const id = String(input.folder_id ?? "");
const r = folderShelf(id);
if (!r) throw new ToolError(`No library folder with id ${id}.`);
const parentId =
typeof input.parent_id === "string" && input.parent_id ? input.parent_id : null;
if (parentId && folderShelf(parentId) !== r) {
throw new ToolError("That folder is on a different library shelf.");
}
if (parentId && folderWithin(lib.folders, parentId, id)) {
throw new ToolError("A folder can't move into itself or a folder inside it.");
}
const moved = await updateLibraryFolder(r, id, { parentId });
return { moved: true, parentId: moved.parentId ?? null };
}
case "delete_folder": {
const id = String(input.folder_id ?? "");
const r = folderShelf(id);
if (!r) throw new ToolError(`No library folder with id ${id}.`);
const takes = folderDeleteTakes(lib, [{ id }]);
const notes = (await fetchNotes()).notes.filter((n) =>
[...takes.tree].some((f) => noteInLibraryFolder(n, f, r)),
).length;
forgetLinkedCopies(takes.assets);
await deleteLibraryFolder(r, id);
const phone = takes.assets.filter((a) => !!a.origin).length;
return {
deleted: true,
items: takes.assets.length + takes.templates.length,
...(notes > 0 ? { notes } : {}),
...(phone > 0 ? { removedFromPhone: phone } : {}),
note: "Everything in it — folders, items and notes — was deleted too. A camera clip filed there stays in Camera Roll.",
};
}
case "move_asset": {
const folderId =
typeof input.folder_id === "string" && input.folder_id ? input.folder_id : null;
const id = String(input.id ?? "");
const r = itemShelf(id);
if (!r) throw new ToolError(`No library item with id ${id}.`);
if (folderId && folderShelf(folderId) !== r) {
throw new ToolError("That folder is on a different library shelf.");
}
await moveLibraryItem(r, id, folderId);
return { moved: true, folderId };
}
case "rename_asset": {
const id = String(input.id ?? "");
const asset = lib.assets.find((a) => a.id === id);
if (!asset) throw new ToolError(`No library asset with id ${id}.`);
if (!String(input.name ?? "").trim()) throw new ToolError("A name is required.");
return { renamed: true, name: await renameLibraryFile(asset, String(input.name), lib.assets) };
}
case "rename_template": {
const id = String(input.id ?? "");
const r = lib.templates.find((t) => t.id === id)?.residency;
if (!r) throw new ToolError(`No library template with id ${id}.`);
if (!String(input.name ?? "").trim()) throw new ToolError("A name is required.");
const name = itemName(input.name);
await renameTemplate(r, id, name);
return { renamed: true, name };
}
case "delete_asset": {
const id = String(input.id ?? "");
const r = lib.assets.find((a) => a.id === id)?.residency;
if (!r) throw new ToolError(`No library asset with id ${id}.`);
await deleteFromLibrary(r, id);
return { deleted: true };
}
case "delete_template": {
const id = String(input.id ?? "");
const r = lib.templates.find((t) => t.id === id)?.residency;
if (!r) throw new ToolError(`No library template with id ${id}.`);
await deleteTemplate(r, id);
return { deleted: true };
}
default:
throw new ToolError(`Unknown action "${String(input.action)}".`);
}
},
file_asset: async (s, input) => {
const asset = requireItem(s.assets, input.asset_id, "project asset");
if (input.to === "media") {
s.updateAsset(asset.id, { origin: undefined, chatId: undefined });
return { filed: "media", name: asset.name };
}
if (input.to === "library") {
const projectId = s.projectId;
if (!projectId) throw new ToolError("No project open.");
const saved = await saveAssetToLibrary(projectId, asset);
return { filed: "library", libraryId: saved.id, name: saved.name };
}
throw new ToolError('`to` must be "media" or "library".');
},
media_organize: (s, input) => {
const folderOf = (id: string) => {
const f = s.mediaFolders.find((x) => x.id === id);
if (!f) throw new ToolError(`No Media folder with id ${id}.`);
return f;
};
const assetIds = () => {
const ids = Array.isArray(input.asset_ids) ? input.asset_ids.map(String) : [];
for (const id of ids) requireItem(s.assets, id, "project asset");
return ids;
};
switch (String(input.action ?? "")) {
case "create_folder": {
const name = String(input.name ?? "").trim();
if (!name) throw new ToolError("A folder name is required.");
const ids = assetIds();
const folderId = s.addMediaFolder(name, ids);
return { folderId, name, ...(ids.length > 0 ? { filed: ids.length } : {}) };
}
case "rename_folder": {
const name = String(input.name ?? "").trim();
if (!name) throw new ToolError("A folder name is required.");
const f = folderOf(String(input.folder_id ?? ""));
s.renameMediaFolder(f.id, name);
return { renamed: true, name };
}
case "delete_folder": {
const f = folderOf(String(input.folder_id ?? ""));
const files = s.assets.filter((a) => a.folderId === f.id).length;
s.removeMediaFolder(f.id);
return {
deleted: true,
files,
note: "Its files were removed from the project, with the timeline clips made from them.",
};
}
case "rename_asset": {
const asset = requireItem(s.assets, input.asset_id, "project asset");
if (!String(input.name ?? "").trim()) throw new ToolError("A name is required.");
s.renameAsset(asset.id, String(input.name));
return { renamed: true, name: useEditor.getState().assets.find((a) => a.id === asset.id)?.name };
}
case "move_asset": {
const folderId =
typeof input.folder_id === "string" && input.folder_id
? folderOf(input.folder_id).id
: null;
const ids = assetIds();
if (ids.length === 0)
throw new ToolError("asset_ids is required — the media to file.");
s.moveAssetsToMediaFolder(ids, folderId);
return { moved: ids.length, folderId };
}
default:
throw new ToolError(`Unknown action "${String(input.action)}".`);
}
},
convert_media: async (s, input) => {
const projectId = s.projectId;
if (!projectId) throw new ToolError("No project open.");
const ids = Array.isArray(input.asset_ids) ? input.asset_ids.map((v) => String(v)) : [];
if (ids.length === 0) throw new ToolError("Pass the asset ids to convert.");
const maxHeight = isNum(input.max_height) ? Math.round(input.max_height) : undefined;
const mode = convertModeIn(input.mode);
if (!mode) throw new ToolError("mode is fit or reencode.");
// Named `assets` so each converted file renders as its own card in the
// thread (ToolOutputAssets keys off assetId) — the user drops files on
// the chat and takes the MP4s back from the same place.
const converted: Record<string, unknown>[] = [];
const failed: { assetId: string; name?: string; error: string }[] = [];
for (const id of ids) {
// Read live: each conversion rewrites the asset it just finished.
const asset = useEditor.getState().assets.find((a) => a.id === id);
if (!asset) {
failed.push({ assetId: id, error: `No project asset with id ${id}.` });
continue;
}
try {
const out = await convertAssetToMp4(projectId, asset, { maxHeight, mode });
converted.push({
assetId: out.assetId,
// The card now reads `name`; `from` is what the user dropped.
name: out.name,
...(out.name !== asset.name ? { from: asset.name } : {}),
file: out.fileName,
// False means the packets were copied — same picture, new container.
reencoded: out.reencoded,
...(out.unchanged ? { unchanged: true } : {}),
duration: roundT(out.duration),
...(out.width !== undefined ? { width: out.width, height: out.height } : {}),
// The file stayed where it already lived: a chat attachment on its
// card in this thread, an import in the Media panel.
where: asset.origin === "chat" ? "chat card" : asset.origin ?? "media panel",
});
} catch (e) {
failed.push({
assetId: id,
name: asset.name,
error: e instanceof Error ? e.message : "Could not convert that file.",
});
}
}
if (converted.length === 0) throw new ToolError(failed[0]?.error ?? "Nothing was converted.");
const untouched = converted.every((c) => c.unchanged);
return {
assets: converted,
...(failed.length > 0 ? { failed } : {}),
...(untouched
? { note: "These were already MP4 with H.264 picture and AAC sound, so they were left as they are — say so." }
: {}),
};
},
delete_asset: (s, input) => {
// The sweep: every asset no timeline uses, open or parked — of the
// ones this chat can see: another thread's unplaced media and the
// project's fonts and LUTs stay.
const listed = Array.isArray(input.asset_ids) && input.asset_ids.length > 0;
if (input.unused === true || listed) {
let gone: MediaAsset[];
let held = 0;
if (input.unused === true) {
const used = assetIdsOnAnyTimeline(s);
const chatId = chatOwner();
const spare = s.assets.filter((a) => !used.has(a.id) && !isLinkedAssetType(a.type));
gone = spare.filter((a) => !hiddenFromChat(a, chatId, used));
held = spare.length - gone.length;
} else {
const want = [...new Set((input.asset_ids as unknown[]).filter((v): v is string => typeof v === "string"))];
gone = want.map((id) => requireItem(s.assets, id, "project asset"));
}
const uses = assetClipUses(s, new Set(gone.map((a) => a.id)));
for (const a of gone) useEditor.getState().removeAsset(a.id);
return {
removed: gone.length,
names: gone.slice(0, 30).map((a) => a.name),
...(gone.length > 30 ? { namesTruncated: true } : {}),
clipsRemoved: uses,
...(held > 0 ? { heldByOtherChats: held, note: OTHER_CHATS_MEDIA_NOTE } : {}),
};
}
const asset = requireItem(s.assets, input.asset_id, "project asset");
const uses = assetClipUses(s, new Set([asset.id]));
s.removeAsset(asset.id);
return { removed: asset.name, clipsRemoved: uses };
},
subtitles_generate: async (_s, input) => {
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.");
const made = laneCues(cur.subtitles, lane);
if (made.length > 0 && cur.timelineH < 276) cur.setTimelineH(276);
// The cues ride the result — the model's next move is usually editing
// them, and the ids are what update_cue/delete_cue/merge_cue take.
return {
status: cur.subtitleStatus,
track: lane,
count: made.length,
cues: made
.slice(0, 60)
.map((q) => ({ id: q.id, start: roundT(q.start), end: roundT(q.end), text: q.text })),
...(made.length > 60 ? { cuesTruncated: true } : {}),
note:
cur.subtitleStatus === "empty"
? "No speech found — no subtitles were added to the video."
: undefined,
};
},
captions_generate: async (_s, input) => {
const raw = typeof input.style === "string" ? input.style : "hook";
const style = (["clean", "hook", "punchy"].includes(raw) ? raw : "hook") as
| "clean"
| "hook"
| "punchy";
const lane = targetSubtitleTrack(input);
await useEditor.getState().generateCaptions(style);
const cur = useEditor.getState();
if (cur.subtitleStatus === "error")
throw new ToolError(cur.subtitleError ?? "Captions failed.");
const made = laneCues(cur.subtitles, lane).length;
if (made > 0 && cur.timelineH < 276) cur.setTimelineH(276);
return {
status: cur.subtitleStatus,
track: lane,
cues: made,
style: cur.subtitles.style,
note:
cur.subtitleStatus === "empty"
? "No speech found — no captions were added to the video."
: undefined,
};
},
subtitles_from_visuals: async (_s, input) => {
const lane = targetSubtitleTrack(input);
if (typeof input.locale === "string" && input.locale)
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.");
const made = laneCues(cur.subtitles, lane).length;
if (made > 0 && cur.timelineH < 276) cur.setTimelineH(276);
return { status: cur.subtitleStatus, track: lane, cues: made };
},
subtitles_add_track: (s, input) => {
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 };
},
subtitles_remove_track: (s, input) => {
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) {
// The editor always keeps one lane, so removing the only track
// empties it instead.
const cleared = laneCues(s.subtitles, 0).length;
s.removeSubtitleTrack(0);
return { track: 0, tracks: 1, clearedCues: cleared };
}
s.removeSubtitleTrack(lane);
return { removed: lane, tracks: count - 1 };
},
subtitles_translate_track: async (s, input) => {
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,
};
},
credit_prices: async () => {
// Read live, so a quote follows the same rates the charge uses.
const [prices, balance] = await Promise.all([
hostedFetch("/api/credits/prices", { cache: "no-store" }),
hostedFetch("/api/credits/balance", { cache: "no-store" }),
]);
for (const res of [prices, balance]) {
if (!res.ok) {
throw new ToolError((await readHostedFailure(res, new UserError("sign_in_to_see_prices", "Sign in to Donkey to see credit prices."), new UserError("credit_prices_read_failed", "Could not read credit prices."))).message);
}
}
const sheet = (await prices.json()) as CreditPriceSheet;
const { balance: dollars } = (await balance.json()) as { balance: string };
return { ...creditPriceQuote(sheet), balance: creditsFromDollars(dollars, "down") };
},
list_voices: () => {
// Gemini's prebuilt voice catalog is fixed and ships hardcoded.
return {
voices: SPEECH_VOICES.map((v) => ({ name: v.name, style: v.style })),
total: SPEECH_VOICES.length,
};
},
voiceover_generate: (s, input) => {
if (typeof input.script !== "string" || !input.script.trim())
throw new ToolError("script is required.");
const start = isNum(input.start) ? Math.max(0, input.start) : playheadAt();
// Label with the spoken line (capped) so its preview fills across the row.
const lead = input.script.replace(/\s+/g, " ").trim().slice(0, 200);
const place = wantsTimeline(input, "start");
return synthesizeVoiceover(
[{ text: input.script, at: 0 }],
`AI voice — ${lead}`,
start,
input,
place
);
},
generate_music: async (s, input) => {
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;
// References ("match this audio", "the tone of this video"): the music
// model reads only text, so a multimodal pass listens to/looks at each
// reference and folds a description of its sound into the prompt. A failed
// compose falls back to the raw prompt so the render still happens. Keep
// the user's own words as the track name — the composed prompt is verbose.
const refs = resolveRefAssets(input.reference_asset_ids);
let sent = prompt;
if (refs.length > 0) {
const composed = await composeMusicPrompt(prompt, refs);
if (composed) sent = composed;
}
// 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, sent, {
variant,
instrumental,
...(sent !== prompt ? { name: prompt } : {}),
});
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) {
// Stamp chat ownership before persisting — the render outlived the open
// project, but it still belongs to the thread that asked, exactly as the
// still-open path tags it (and as generate.ts persists chat renders).
applyOwnership(asset, chatId);
void stockAssetInDoc(projectId, asset).catch(() => {});
return {
assetId: asset.id,
name: asset.name,
duration: roundT(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: roundT(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) : playheadAt();
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, 3) : 0.4;
const sel = useEditor.getState().selection;
const clipId = sel?.kind === "audio" ? sel.id : null;
if (clipId) useEditor.getState().updateAudio(clipId, { volume });
// Report where the clip actually landed: addAudioFromAsset slides it to the
// next free slot on the soundtrack when the requested start overlaps
// existing audio, so `start` is not necessarily where it sits.
const placed = clipId
? useEditor.getState().audioClips.find((c) => c.id === clipId)
: undefined;
const placedStart = placed?.start ?? start;
return {
assetId: asset.id,
name: asset.name,
audioClipId: clipId,
start: roundT(placedStart),
duration: roundT(asset.duration),
volume,
addedToTimeline: true,
};
},
read_subtitles_aloud: async (s, input) => {
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 = await resolveVoiceAsk(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.
const out = await generateSubtitlesReadout(voice, {
direction:
typeof input.direction === "string" && input.direction.trim()
? input.direction.trim()
: undefined,
language: typeof input.language === "string" ? input.language : undefined,
duck: isNum(input.duck) ? clamp(input.duck, 0, 1) : undefined,
});
const sel = useEditor.getState().selection;
return {
assetId: out.asset.id,
name: out.asset.name,
audioClipId: sel?.kind === "audio" ? sel.id : null,
voice,
start: roundT(out.start),
duration: roundT(out.asset.duration),
duck: out.duck,
lines: out.lines,
};
},
subtitles_set_view: (s, input) => {
const patch: { showOnVideo?: boolean; showOnTimeline?: boolean } = {};
if (typeof input.showOnVideo === "boolean") patch.showOnVideo = input.showOnVideo;
if (typeof input.showOnTimeline === "boolean") patch.showOnTimeline = input.showOnTimeline;
s.setSubtitlesView(patch);
if (patch.showOnTimeline && s.subtitles.cues.length > 0 && s.timelineH < 276) s.setTimelineH(276);
return patch;
},
update_cue: (s, input) => {
const cue = requireItem(s.subtitles.cues, input.id, "subtitle cue");
const clearPos = input.follow_track === true || input.x === null || input.y === null;
if (clearPos && (isNum(input.x) || isNum(input.y)))
throw new ToolError("Pass x/y for the caption's own spot, or follow_track to drop it — not both.");
if (typeof input.text === "string") s.setCueText(cue.id, input.text);
if (isNum(input.start) || isNum(input.end)) {
const start = isNum(input.start) ? Math.max(0, input.start) : cue.start;
const end = isNum(input.end) ? input.end : cue.end;
if (end - start < 0.15) throw new ToolError("Cue must stay at least 0.15s long.");
s.setCueTiming(cue.id, start, end);
}
if (clearPos || isNum(input.x) || isNum(input.y)) {
const st = useEditor.getState();
const live = st.subtitles.cues.find((c) => c.id === cue.id);
if (live) {
// One side given keeps the other where the caption already sits.
const at = cueSpot(st.subtitles, live);
st.pushHistory();
st.setCuePosition(
cue.id,
clearPos
? null
: {
x: clamp(isNum(input.x) ? input.x : at.x, 0.02, 0.98),
y: clamp(isNum(input.y) ? input.y : at.y, 0.02, 0.98),
}
);
}
}
const next = useEditor.getState().subtitles.cues.find((c) => c.id === cue.id);
return next
? {
id: next.id,
start: next.start,
end: next.end,
text: next.text,
...(next.x !== undefined && next.y !== undefined ? { x: round2(next.x), y: round2(next.y) } : {}),
}
: { deleted: cue.id };
},
delete_cue: (s, input) => {
const cue = requireItem(s.subtitles.cues, input.id, "subtitle cue");
s.deleteCue(cue.id);
return { deleted: cue.id };
},
set_publish: (s, input) => {
const patch: Record<string, string> = {};
for (const k of ["caption", "tags", "soundTitle", "handle"] as const) {
if (typeof input[k] === "string") patch[k] = input[k] as string;
}
if (Object.keys(patch).length === 0) throw new ToolError("Nothing to change.");
s.setPublish(patch);
return patch;
},
set_project_notes: (s, input) => {
const strings = (v: unknown, k: string) => {
if (!Array.isArray(v) || !v.every((x) => typeof x === "string")) throw new ToolError(`${k} must be a list of strings.`);
return (v as string[]).map((x) => x.trim()).filter(Boolean);
};
const patch: Partial<{ text: string; publishedAt: string; links: string[] }> = {};
let links = input.links !== undefined ? strings(input.links, "links") : undefined;
if (input.add_links !== undefined) {
const base = links ?? s.notes.links.filter(Boolean);
links = [...new Set([...base, ...strings(input.add_links, "add_links")])];
}
if (links) patch.links = links;
if (typeof input.text === "string") patch.text = input.text;
if (typeof input.published_at === "string") {
if (input.published_at && !/^\d{4}-\d{2}-\d{2}$/.test(input.published_at)) throw new ToolError("published_at is a date as yyyy-mm-dd.");
patch.publishedAt = input.published_at;
}
if (Object.keys(patch).length === 0) throw new ToolError("Nothing to change.");
s.setNotes(patch);
return useEditor.getState().notes;
},
copy_from_timeline: (s, input) => {
if (!isTimelineId(input.timeline))
throw new ToolError(`timeline must be one of ${TIMELINE_IDS.join(", ")}.`);
const ids = Array.isArray(input.ids) ? input.ids.filter((id): id is string => typeof id === "string") : [];
if (ids.length === 0) throw new ToolError("Name the items to copy in ids.");
const source = input.timeline === s.timeline ? s : parkedTimeline(s, input.timeline);
// Each id is found in whichever item list holds it on the source.
const found = ids.map((id) => {
const kind = ITEM_KIND_IDS.find((k) => timelineItem(source, { kind: k, id } as NonNullable<Selection>));
return kind ? ({ kind, id } as NonNullable<Selection>) : null;
});
const missing = ids.filter((_, i) => !found[i]);
if (missing.length > 0)
throw new ToolError(`${TIMELINE_LABELS[input.timeline]} has no item ${missing.join(", ")}; get_state with timeline "${input.timeline}" lists its items.`);
if (input.lane !== undefined && (!isNum(input.lane) || !Number.isInteger(input.lane) || input.lane < 0)) {
throw new ToolError("lane must be a non-negative integer.");
}
const copies = timelineCopies(source, found);
const items = isNum(input.lane) ? copiesOnLane(copies, input.lane) : copies;
const at = isNum(input.at) ? Math.max(0, input.at) : Math.min(...items.map((cb) => cb.item.start));
// What holds each copy's row at the asked time, read before the paste
// slides the copies past it.
const asked = at - Math.min(...items.map((cb) => cb.item.start));
const blockers = items.map((cb) => timelineBlocker(s, cb, asked));
const landed = s.pasteCopies(items, at);
if (!landed) throw new ToolError("Nothing could be copied onto this timeline.");
const now = useEditor.getState();
return {
timeline: now.timeline,
copied: landed.map((sel, i) => {
const item = timelineItem(now, sel)!;
const start = roundT(item.start);
const askedStart = roundT(items[i].item.start + asked);
if (start === askedStart) {
return { kind: sel.kind, id: sel.id, start };
}
// A slid copy names what took its spot, or the copy it kept its spacing with.
const blocker = blockers[i];
const why = blocker
? `${blocker.kind} ${blocker.id} holds lane ${blocker.lane} from ${roundT(blocker.start)} to ${roundT(blocker.end)} s`
: "kept its spacing with a copy that slid past a taken spot";
return { kind: sel.kind, id: sel.id, start, askedStart, why };
}),
};
},
switch_timeline: async (_s, input) => {
if (!isTimelineId(input.timeline))
throw new ToolError(`timeline must be one of ${TIMELINE_IDS.join(", ")}.`);
const blocked = await switchTimeline(input.timeline);
if (blocked) throw new ToolError(blocked);
const s = useEditor.getState();
return {
timeline: s.timeline,
duration: roundT(projectDuration(s)),
clips: s.clips.length,
audioClips: s.audioClips.length,
overlays: s.overlays.length,
};
},
set_view: (s, input) => {
const out: Record<string, number> = {};
if (input.fit) {
const el = document.querySelector<HTMLElement>(".tl-scroll");
const dur = projectDuration(s);
if (el && dur > 0) {
s.setPxPerSec((el.clientWidth - 60) / dur);
el.scrollLeft = 0;
}
out.pxPerSec = useEditor.getState().pxPerSec;
} else if (isNum(input.pxPerSec)) {
s.setPxPerSec(input.pxPerSec);
out.pxPerSec = useEditor.getState().pxPerSec;
}
if (isNum(input.timelineH)) {
s.setTimelineH(input.timelineH);
out.timelineH = useEditor.getState().timelineH;
}
return out;
},
copy_selection: (s) => {
if (!s.copySelection()) throw new ToolError("Select timeline items to copy.");
return { copied: s.copiedItems().length };
},
paste_selection: (s, input) => {
if (input.at !== undefined && !isNum(input.at)) throw new ToolError("at must be finite timeline seconds.");
if (!s.paste(isNum(input.at) ? input.at : undefined)) throw new ToolError("Copy timeline items before pasting.");
return { selection: useEditor.getState().multiSelection };
},
undo: (s) => {
const before = useEditor.getState();
const step = s.undoStep();
if (!step) throw new ToolError("Nothing to undo.");
return { reverted: stepName(step.label), changes: historyChanges(before, useEditor.getState()) };
},
redo: (s) => {
const before = useEditor.getState();
const step = s.redoStep();
if (!step) throw new ToolError("Nothing to redo.");
return { restored: stepName(step.label), changes: historyChanges(before, useEditor.getState()) };
},
open_export: (s) => {
if (!(projectDuration(s) > 0))
throw new ToolError("Add something to the timeline first.");
s.setExportOpen(true);
return { open: true };
},
set_speed: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
refuseStillRetime(s, clip);
const reverse = typeof input.reverse === "boolean" ? input.reverse : undefined;
const smooth = typeof input.smooth === "boolean" ? input.smooth : undefined;
if (!isNum(input.speed) && reverse === undefined && smooth === undefined)
throw new ToolError("speed (e.g. 1.5), reverse, or smooth is required.");
const before = clipLen(clip);
if (isNum(input.speed)) s.setClipSpeed(clip.id, input.speed);
if (reverse !== undefined) s.setClipReverse(clip.id, reverse);
if (smooth !== undefined) s.setClipSmoothSlow(clip.id, smooth);
const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;
return {
id: next.id,
speed: next.speed ?? 1,
...(next.reverse ? { reverse: true } : {}),
...(next.smoothSlow ? { smooth: true } : {}),
lenBefore: roundT(before),
lenAfter: roundT(clipLen(next)),
...tracksAfter(),
};
},
set_speed_curve: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
refuseStillRetime(s, clip);
const before = clipLen(clip);
if (typeof input.preset === "string") {
if (Array.isArray(input.nodes) && input.nodes.length > 0)
throw new ToolError(
"Pass either `preset` or `nodes`, not both — a preset lays its own nodes over the clip."
);
if (!SPEED_CURVE_PRESET_IDS.includes(input.preset))
throw new ToolError(
`Unknown preset "${input.preset}". One of: ${SPEED_CURVE_PRESET_IDS.join(", ")}.`
);
s.setClipSpeedPreset(clip.id, input.preset);
} else {
const raw = input.nodes;
if (!Array.isArray(raw))
throw new ToolError("nodes must be a list (empty clears the curve), or pass a preset.");
if (raw.length === 0) {
s.setClipSpeedCurve(clip.id, undefined);
} else {
const nodes: SpeedNode[] = (raw as Record<string, unknown>[]).map((n) => {
if (!isNum(n.at) || !isNum(n.speed))
throw new ToolError("Every node needs `at` (source seconds) and `speed`.");
if (n.at < clip.in - 1e-6 || n.at > clip.out + 1e-6)
throw new ToolError(
`Node at ${round2(n.at)}s is outside the clip's trim [${round2(clip.in)}, ${round2(clip.out)}] (source seconds).`
);
return [n.at, clamp(n.speed, SPEED_CURVE_MIN, SPEED_CURVE_MAX)];
});
s.setClipSpeedCurve(clip.id, nodes);
}
}
// After the curve, so a rejected curve leaves the flag alone too.
if (typeof input.smooth === "boolean") s.setClipSmoothSlow(clip.id, input.smooth);
const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;
const curve = speedCurveOf(next);
return {
id: next.id,
speed: round2(retimeOf(next).rate),
...(next.smoothSlow ? { smooth: true } : {}),
nodes: curve ? curve.map(([at, speed]) => ({ at: roundT(at), speed: round2(speed) })) : [],
lenBefore: roundT(before),
lenAfter: roundT(clipLen(next)),
...tracksAfter(),
};
},
set_color_grade: async (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
// reset and auto rebuild the manual layer; the preset and LUT stay.
let grade: ColorGrade =
input.reset === true ? { preset: clip.grade?.preset, lut: clip.grade?.lut } : { ...clip.grade };
if (input.auto === true) {
const raw = await clipRawFrame(s, clip, 96, 54);
const kept: ColorGrade = { preset: clip.grade?.preset, lut: clip.grade?.lut };
const lutId = lutIdOf(kept);
const userLut = lutId ? await loadLibraryLut(lutId) : undefined;
grade = { ...autoGrade(raw.px, { ...raw.recipe, grade: kept }, userLut), ...kept };
}
for (const k of GRADE_KEYS) if (isNum(input[k])) grade[k] = input[k];
s.updateClip(clip.id, { grade: normalizeGrade(grade) });
const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;
return { id: next.id, grade: next.grade ?? "neutral" };
},
set_color_preset: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
const id = typeof input.preset === "string" ? input.preset : "";
if (id !== "none" && !GRADE_PRESETS[id])
throw new ToolError(`No color preset "${id}" — pass one of the catalog ids or "none".`);
const preset =
id === "none"
? undefined
: {
id,
amount: isNum(input.amount) ? Math.max(0, Math.min(1, input.amount)) : undefined,
skin: input.protect_skin === true || undefined,
};
s.updateClip(clip.id, { grade: normalizeGrade({ ...clip.grade, preset }) });
const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;
return {
id: next.id,
preset: next.grade?.preset ?? "none",
...(preset ? { label: GRADE_PRESETS[id].label } : {}),
...(preset && next.grade?.preset?.amount === 0
? { note: "amount 0 holds the preset at neutral — raise it for the look to show." }
: {}),
};
},
set_color_curves: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
const curves: GradeCurves = input.reset === true ? {} : { ...clip.grade?.curves };
const channels = [
["m", input.master],
["r", input.red],
["g", input.green],
["b", input.blue],
] as const;
for (const [ch, pts] of channels) {
if (!Array.isArray(pts)) continue;
if (pts.length === 0) delete curves[ch];
else curves[ch] = pts as CurvePoint[];
}
if (isNum(input.curve_contrast)) {
const master = semanticMasterCurve(input.curve_contrast, 0);
if (master) curves.m = master;
else delete curves.m;
}
s.updateClip(clip.id, { grade: normalizeGrade({ ...clip.grade, curves }) });
const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;
return { id: next.id, curves: next.grade?.curves ?? "neutral" };
},
set_color_wheels: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
const wheels = input.reset === true ? {} : { ...clip.grade?.wheels };
// The wheels by their labels (lift, gamma, gain, offset); the older
// names a thread may still carry map onto the first three.
const zones = WHEEL_ZONES.map((z) => [z, input[WHEEL_LABELS[z].toLowerCase()]] as const);
const legacy = { s: input.shadows, m: input.midtones, h: input.highlights } as const;
for (const [zone, given] of zones) {
const w = given ?? (legacy as Partial<Record<string, unknown>>)[zone];
if (!w || typeof w !== "object") continue;
const t = w as { dx?: number; dy?: number; luma?: number };
wheels[zone] = [t.dx ?? 0, t.dy ?? 0, t.luma ?? 0] as WheelTuple;
}
s.updateClip(clip.id, { grade: normalizeGrade({ ...clip.grade, wheels }) });
const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;
return { id: next.id, wheels: next.grade?.wheels ?? "neutral" };
},
set_color_hsl: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
const hsl = input.reset_all === true ? {} : { ...clip.grade?.hsl };
const band = typeof input.band === "string" ? (input.band as HslBand) : undefined;
if (band) {
if (!HSL_BANDS.some((b) => b.id === band))
throw new ToolError(`band must be one of ${HSL_BANDS.map((b) => b.id).join(", ")}.`);
hsl[band] = [
isNum(input.hue) ? input.hue : 0,
isNum(input.sat) ? input.sat : 0,
isNum(input.luma) ? input.luma : 0,
];
} else if (input.reset_all !== true) {
throw new ToolError("Pass a band to adjust, or reset_all to clear every band.");
}
s.updateClip(clip.id, { grade: normalizeGrade({ ...clip.grade, hsl }) });
const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;
return { id: next.id, hsl: next.grade?.hsl ?? "neutral" };
},
read_color_stats: async (s, input) => {
const stats = await colorStatsForRef(s, {
clipId: typeof input.clipId === "string" ? input.clipId : undefined,
assetId: typeof input.assetId === "string" ? input.assetId : undefined,
graded: input.graded === true,
});
return statsReport(stats);
},
set_color_lut: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
const lut = typeof input.lut === "string" ? input.lut.trim() : "";
const amount = isNum(input.amount) ? Math.max(0, Math.min(1, input.amount)) : clip.grade?.lut?.amount;
const grade: ColorGrade = { ...clip.grade };
if (lut === "none") {
delete grade.lut;
} else {
if (!lutLabel(lut))
throw new ToolError(`No LUT "${lut}" — pass one of editor_state.luts, or "none".`);
grade.lut = { id: lut, amount };
}
s.updateClip(clip.id, { grade: normalizeGrade(grade) });
const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;
return { id: next.id, lut: next.grade?.lut ?? "none" };
},
copy_color_grade: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
const ids = clipTargets(s, input, clip.id);
if (ids.length === 0)
throw new ToolError("Pass ids for the clips to copy onto, or all_clips for every clip.");
const grade = normalizeGrade(clip.grade);
s.beginHistoryBatch();
const landed: string[] = [];
const failed: { id: string; error: string }[] = [];
try {
for (const id of ids) {
const target = useEditor.getState().clips.find((c) => c.id === id);
if (!target) {
failed.push({ id, error: `No video clip "${id}".` });
continue;
}
useEditor.getState().updateClip(id, { grade });
landed.push(id);
}
} finally {
s.endHistoryBatch();
}
if (landed.length === 0)
throw new ToolError(`None of those ${ids.length} landed: ${failed.map((f) => f.error).join("; ")}`);
return { from: clip.id, ids: landed, grade: grade ?? "neutral", ...(failed.length ? { failed } : {}) };
},
set_source_color: (s, input) => {
const profile = typeof input.profile === "string" ? input.profile : "";
if (profile !== "auto" && !SOURCE_PROFILES.some((p) => p.id === profile))
throw new ToolError(`profile must be one of ${SOURCE_PROFILES.map((p) => p.id).join(", ")}, or "auto".`);
let assetId = typeof input.assetId === "string" ? input.assetId : "";
if (!assetId && typeof input.clipId === "string")
assetId = requireItem(s.clips, input.clipId, "video clip").assetId;
const asset = requireItem(s.assets, assetId, "project asset");
if (asset.type !== "video" && asset.type !== "image")
throw new ToolError("Source color is a picture's setting — pass a video or image asset.");
const detected = asset.color?.detected ?? "rec709";
s.setAssetColorProfile(
asset.id,
profile === "auto" || profile === detected ? undefined : (profile as SourceProfile)
);
const next = useEditor.getState().assets.find((a) => a.id === asset.id)!;
return {
id: next.id,
profile: sourceProfileOf(next),
detected,
clips: useEditor.getState().clips.filter((c) => c.assetId === next.id).map((c) => c.id),
};
},
save_color_grade: async (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
const name = typeof input.name === "string" ? input.name.trim() : "";
if (!name) throw new ToolError("name is required.");
if (!normalizeGrade(clip.grade)) throw new ToolError("That clip's grade is neutral; grade it first.");
if (!s.projectId) throw new ToolError("No open project.");
const saved = await saveGradePreset(s.projectId, name, clip.grade);
if (!saved) throw new ToolError("The grade could not be saved.");
return { id: saved.id, name: saved.name, residency: saved.residency, grade: saved.grade };
},
apply_saved_grade: async (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
const wanted = typeof input.preset_id === "string" ? input.preset_id.trim() : "";
if (!wanted) throw new ToolError("preset_id is required.");
const saved = (await listSavedGrades()).find(
(p) => p.id === wanted || p.name.toLowerCase() === wanted.toLowerCase()
);
if (!saved) throw new ToolError(`No saved grade called "${wanted}" — editor_state.savedGrades lists them.`);
s.updateClip(clip.id, { grade: saved.grade });
const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;
return { id: next.id, preset: { id: saved.id, name: saved.name }, grade: next.grade ?? "neutral" };
},
match_color_grade: async (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
// The reference reads as it shows — a clip through its own grade — and
// the fit renders this clip's code values through its real recipe for
// every grade it tries.
const reference = await colorStatsForRef(s, {
clipId: typeof input.ref_clip_id === "string" ? input.ref_clip_id : undefined,
assetId: typeof input.ref_asset_id === "string" ? input.ref_asset_id : undefined,
at: isNum(input.ref_at) ? input.ref_at : undefined,
graded: true,
});
const raw = await clipRawFrame(s, clip, 192, 108);
const strength = isNum(input.strength) ? input.strength : 1;
const grade = await matchGrade(recipeStatsRender(raw.px, raw.recipe), reference, strength);
// The frames already agree, or strength 0 asked for none of the match:
// the clip's own grade stays as it is.
if (!grade)
return {
id: clip.id,
grade: clip.grade ?? "neutral",
note: strength <= 0 ? "strength 0 takes none of the match — nothing changed." : "The footage already matches the reference — nothing changed.",
};
// The computed curves carry the whole look, so the match replaces the
// clip's grade — a preset left underneath would double the move.
s.updateClip(clip.id, { grade });
const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;
return {
id: next.id,
grade: next.grade ?? "already matched (no change needed)",
note: "Verify with read_color_stats graded:true on the clip and capture_frame, then refine with the grading tools.",
};
},
merge_cue: (s, input) => {
const cue = requireItem(s.subtitles.cues, input.id, "subtitle cue");
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" };
},
set_aspect: (s, input) => {
const a = typeof input.aspect === "string" ? normalizeAspect(input.aspect) : null;
if (!a)
throw new ToolError(
'aspect must be "W:H" up to an 8:1 shape — whole or decimal sides, e.g. "9:16", "1:1", "9:2", "2.39:1".'
);
s.setAspect(a);
const f = frameOf(a);
return { aspect: a, frame: `${f.w}x${f.h}` };
},
set_guides: (s, input) => {
if (!Array.isArray(input.show)) throw new ToolError("show must be a list of guide ids.");
const bad = input.show.filter((id) => !isGuideId(id));
if (bad.length)
throw new ToolError(`Unknown guide ${bad.join(", ")} — pick from ${GUIDE_IDS.join(", ")}.`);
const show = input.show as GuideId[];
const unfit = show.filter((id) => !guideFits(id, s.aspect));
if (unfit.length)
throw new ToolError(
`${unfit.map((id) => guidePreset(id).name).join(", ")} fits portrait frames only; this project is ${s.aspect}. Turn it on after set_aspect to a portrait shape, or place by project.safeZones.margins.`
);
if (input.lines !== undefined) {
s.setGuideLines(sanitizeGuideLines(input.lines));
if (!show.includes("custom")) show.push("custom");
}
s.setGuides(show);
s.setGuidesHidden(false);
const after = useEditor.getState();
return {
guides: after.guides,
...(after.guides.includes("custom") ? { customLines: after.guideLines } : {}),
};
},
set_background: (s, input) => {
const raw = typeof input.color === "string" ? input.color : "";
const hex = projectBackground(raw);
// projectBackground falls back rather than throwing, so a color it could
// not read would silently paint the frame black. Say so instead.
if (raw.trim() && hex === DEFAULT_BACKGROUND && !/^#?(000|000000)$/i.test(raw.trim()))
throw new ToolError(`Could not read ${raw} as a color — pass a hex like #FFFFFF.`);
s.setBackground(hex);
return { background: useEditor.getState().background };
},
set_project_name: (s, input) => {
if (typeof input.name !== "string" || !input.name.trim())
throw new ToolError("name is required.");
s.setProjectName(input.name.trim());
return { name: input.name.trim() };
},
set_project_color: (s, input) => {
const space = OUTPUT_SPACES.find((o) => o.id === input.space);
if (!space)
throw new ToolError(`Unknown color space ${String(input.space)} — pick from ${OUTPUT_SPACES.map((o) => o.id).join(", ")}.`);
s.setColorSpace(space.id);
return { colorSpace: useEditor.getState().colorSpace };
},
};
class ToolError extends Error {}
/** Tools that decode or rasterize media — frame grabs, audio scans, image
* decodes, the transcription mixdown. A page has those primitives and a
* headless process installs them; a process that installed neither refuses
* these with a typed error rather than a stray "document is not defined". */
/** The stock candidates an editor searching for `query` would want, best
* first: one judged fit per candidate, in chunks, kept above the setting's
* floor. */
async function rankStock<T extends { id: string; kind: string; category: string; prompt: string; persona?: string; tags: string[] }>(
query: string,
candidates: T[],
): Promise<T[]> {
if (candidates.length === 0) return [];
const post = (payload: Record<string, unknown>, signal?: AbortSignal) =>
hostedPost("/api/inference/judge", payload, signal);
const byKey = new Map<string, T>(candidates.map((c, i) => [`fit::${i}`, c]));
const questions = Object.fromEntries(
candidates.map((_, i) => [
`fit::${i}`,
noul(`Would an editor searching the stock catalog for \`query\` want candidate ${i} in \`candidates\`?`, {
true: "The candidate is what the search describes, or serves its purpose well.",
false: "The candidate is unrelated to the search, or only shares a word with it.",
}),
]),
);
const state = (keys: string[]) => ({
query,
candidates: keys.map((k) => {
const c = byKey.get(k)!;
return {
i: Number(k.slice("fit::".length)),
kind: c.kind,
category: c.category,
prompt: c.prompt.slice(0, 240),
...(c.persona ? { persona: c.persona.slice(0, 160) } : {}),
tags: c.tags.slice(0, 8),
};
}),
});
let answers: Record<string, { type: string; noul?: number }>;
try {
answers = (await askJudgeChunked(post, state, questions, STOCK_JUDGE_CHUNK)) as Record<string, { type: string; noul?: number }>;
} catch (e) {
throw new ToolError(`Stock search is unavailable: ${e instanceof Error ? e.message : String(e)}`);
}
const floor = CUT_JUDGE.stockFit;
return candidates
.map((c, i) => ({ c, p: answers[`fit::${i}`]?.noul ?? 0 }))
.filter((x) => x.p >= floor)
.sort((a, b) => b.p - a.p)
.map((x) => x.c);
}
/** Filler words this close together are cut as one span. */
const WORD_GAP = 0.12;
const STOCK_JUDGE_CHUNK = 50;
const FILLER_JUDGE_CHUNK = 60;
export const MEDIA_RUNTIME_TOOLS: ReadonlySet<string> = new Set([
"convert_media",
"watch_video",
"listen_audio",
"measure_level",
"detect_silence",
"detect_beats",
"refine_speech_cuts",
"sync_audio",
"capture_frame",
"compare_to_source",
"find_picture",
"detect_cuts",
"sample_color",
"track_element",
"track_camera",
"suggest_font",
"render_preview",
"freeze_frame",
"create_sticker",
"subtitles_generate",
"captions_generate",
"subtitles_from_visuals",
"sync_lyrics",
"align_to_audio",
"stock_add",
"read_color_stats",
"match_color_grade",
]);
/** Tools that need the editor page itself: motion tracking runs MediaPipe's
* landmark models, which load into a browser and nowhere else. A headless
* session answers these with a refusal that sends the person to the tab. */
export const PAGE_ONLY_TOOLS: ReadonlySet<string> = new Set(["track_motion"]);
export async function runAiTool(
name: string,
input: Record<string, unknown>
): Promise<unknown> {
try {
return await dispatchTool(useEditor.getState(), name, input);
} catch (err) {
// A call the connection dropped passes with the connection: the model
// waits for it and runs the call again.
if (!droppedByConnection(err)) {
throw err;
}
const message = err instanceof Error ? err.message : String(err);
throw new ToolError(
`${message} The connection dropped while this ran. Call wait_for_uploads, which waits for the connection and the uploads, then run this call again.`,
{ cause: err }
);
}
}
/** Whether a tool failed on the connection: a dropped request anywhere in its
* causes, or, while offline, anything besides the tool turning its input
* down (a ToolError of its own, with no failure underneath). */
function droppedByConnection(err: unknown): boolean {
const dropped = (e: unknown): boolean =>
e instanceof ConnectionLostError || fetchDropped(e) || (e instanceof Error && e.cause !== undefined && dropped(e.cause));
if (dropped(err)) {
return true;
}
return isOffline() && !(err instanceof ToolError && err.cause === undefined);
}
async function dispatchTool(s: Editor, name: string, raw: Record<string, unknown>, operation?: ProjectOperation): Promise<unknown> {
// Every call is its own undo step, named for the tool, however many writes
// it makes: inside a chat turn's batch it is a step the chat's undo takes
// back alone; outside one it is an ordinary history entry. Undo and redo
// step the history themselves.
if (name === "undo" || name === "redo") return dispatchRun(s, name, raw, operation);
const step = s.beginHistoryStep(name);
try {
return await dispatchRun(s, name, raw, operation);
} finally {
s.endHistoryStep(step);
}
}
/** What an undo or redo moved across, for its result: the tool call the step
* was, or what kind of edit it was when no tool made it. */
function stepName(label: string | null): string {
if (label === CHAT_TURN_LABEL) return "an earlier chat turn, all of its edits at once";
return label ?? "an edit made in the editor";
}
/** How a history step changed the timeline, by kind: what came, went or
* changed, so an undo's result says what it took back. */
function historyChanges(before: Editor, after: Editor): string {
const kinds: [string, { id: string }[], { id: string }[]][] = [
["video clip", before.clips, after.clips],
["sound clip", before.audioClips, after.audioClips],
["element", before.overlays, after.overlays],
["caption", before.subtitles.cues, after.subtitles.cues],
["transition", before.transitions, after.transitions],
];
const parts: string[] = [];
const count = (n: number, what: string, how: string) => {
if (n > 0) parts.push(`${n} ${what}${n === 1 ? "" : "s"} ${how}`);
};
for (const [what, was, now] of kinds) {
const old = new Map(was.map((x) => [x.id, x]));
const ids = new Set(now.map((x) => x.id));
count(was.filter((x) => !ids.has(x.id)).length, what, "removed");
count(now.filter((x) => !old.has(x.id)).length, what, "back");
count(now.filter((x) => old.has(x.id) && JSON.stringify(old.get(x.id)) !== JSON.stringify(x)).length, what, "changed");
}
return parts.length > 0 ? parts.join(", ") : "no timeline item changed";
}
async function dispatchRun(s: Editor, name: string, raw: Record<string, unknown>, operation?: ProjectOperation): Promise<unknown> {
const input = snapSeconds(raw) as Record<string, unknown>;
// "update_title" stays as an alias so older threads keep working.
const key = name === "update_title" ? "update_overlay" : name;
const run = (toolRuns as Partial<Record<string, ToolRun>>)[key];
if (!run) throw new ToolError(`Unknown tool: ${name}`);
const field = SWEEP_TARGETS[key];
const ids = field ? sweepIds(s, key, field, input) : null;
if (!ids) return run(s, input, operation);
// A sweep's apply: the same write over every id, as one undo step, with
// the live state re-read each time because a write can move or remove the
// items after it. A failure on one item is reported and the rest still land.
const rest = Object.fromEntries(Object.entries(input).filter(([k]) => k !== "ids" && k !== "all_clips"));
s.beginHistoryBatch();
const landed: string[] = [];
const ran: unknown[] = [];
const failed: { id: string; error: string }[] = [];
try {
for (const id of ids) {
try {
ran.push(await run(useEditor.getState(), { ...rest, [field]: id }, operation));
landed.push(id);
} catch (e) {
failed.push({ id, error: e instanceof Error ? e.message : String(e) });
}
}
} finally {
s.endHistoryBatch();
}
if (ran.length === 0)
throw new ToolError(`None of those ${ids.length} landed: ${failed.map((f) => f.error).join("; ")}`);
// `ids` and `failed` sit at the top level: the turn ledger reads both, so
// the closing reply is grounded in what actually changed.
return { ran: ran.length, ids: landed, results: ran, ...(failed.length > 0 ? { failed } : {}) };
}
/** The ids a fan-out writes, or null for a one-item call. Every sweepable
* tool takes one target or a list, and a call carrying neither reaches no
* item at all, so it is refused here rather than in each handler. */
function sweepIds(s: Editor, name: string, field: string, input: Record<string, unknown>): string[] | null {
// `all_clips` is the whole video timeline, every track, as the id list.
if (input.all_clips === true && field === "clipId") {
const all = s.clips.map((c) => c.id);
if (all.length === 0) throw new ToolError("The timeline has no clips.");
return all;
}
const list = Array.isArray(input.ids)
? input.ids.filter((x): x is string => typeof x === "string" && x.length > 0)
: null;
const one = typeof input[field] === "string" && (input[field] as string).length > 0;
if (list && list.length > 0) {
if (one) throw new ToolError(`${name} takes ${field} or ids, not both.`);
return list;
}
if (!one) throw new ToolError(`${name} needs ${field}, or ids for several at once (select_items finds them).`);
return null;
}
/** The clips a copy lands on: every other clip for all_clips, else the ids
* given, the source itself left out. */
function clipTargets(s: Editor, input: Record<string, unknown>, source: string): string[] {
if (input.all_clips === true) return s.clips.filter((c) => c.id !== source).map((c) => c.id);
return Array.isArray(input.ids)
? input.ids.filter((x): x is string => typeof x === "string" && x.length > 0 && x !== source)
: [];
}
/** Used inside the existing serialized engine session or isolated cloud worker.
* The caller supplies a hydrated project; deterministic commands invoke no model. */
export async function runProjectCommand(
operation: ProjectOperation,
name: string,
input: Record<string, unknown>
): Promise<unknown> {
const state = useEditor.getState();
assertProjectCommand(operation, state.projectId, name, projectRevision(operation.projectId));
if (!state.loaded) throw new ToolError("The project is still opening.");
const result = await dispatchTool(state, name, input, operation);
if (useEditor.getState().projectId !== operation.projectId)
throw new ToolError("The project changed while the command was running.");
return result;
}
/** Synthesize speech segments with hosted Gemini voices (the user's Donkey
* sign-in and credits), register the media, and drop one soundtrack clip
* (voiceovers duck other audio by default). Shared by voiceover_generate and
* read_subtitles_aloud. */
async function synthesizeVoiceover(
segments: { text: string; at: number }[],
name: string,
start: number,
input: Record<string, unknown>,
place: boolean
) {
const projectId = useEditor.getState().projectId;
if (!projectId) throw new ToolError("No project open.");
const voice = await resolveVoiceAsk(typeof input.voice === "string" ? input.voice : undefined);
const direction =
typeof input.direction === "string" && input.direction.trim()
? input.direction.trim()
: undefined;
const duck = isNum(input.duck) ? clamp(input.duck, 0, 1) : DUCK_DEFAULT;
// Captured before synthesis: the audio files under the chat that asked,
// even if the user switches threads while it renders.
const chatId = chatOwner();
const { asset, offset } = await synthesizeSpeech(projectId, segments, {
voice,
direction,
language: typeof input.language === "string" ? input.language : undefined,
name,
});
const cur = useEditor.getState();
cur.addAsset(asset);
tagChatAsset(asset.id, chatId);
void enrichAsset(asset);
if (!place) {
return {
assetId: asset.id,
name: asset.name,
voice,
duration: roundT(asset.duration),
addedToTimeline: false,
note: "The voiceover 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.",
};
}
// A single script lands at `start`; a multi-line readout is pre-offset to its
// first cue, so it lands at that offset.
const at = segments.length === 1 ? start : offset;
cur.addAudioFromAsset(asset.id, at, { duck: duck < 1 ? duck : undefined });
const sel = useEditor.getState().selection;
return {
assetId: asset.id,
name: asset.name,
audioClipId: sel?.kind === "audio" ? sel.id : null,
voice,
start: roundT(at),
duration: roundT(asset.duration),
duck: duck < 1 ? duck : null,
addedToTimeline: true,
};
}
/** Resolve a watch/listen target: a timeline clip (its source plus trim and
* placement) or a bare project asset. */
/** The words a caption track carries, on the timeline clock: the
* transcriber's own word times where it left them, and an even split of each
* cue's span where it did not. */
/** An alignment pass as the model reads it. The audio declining to testify is
* a result of its own, never a silent success: a caller told "0 moved" without
* `evidence` would report a mix it could not read as captions already in sync. */
function syncResult(
report: SyncReport<{ id: string; text: string; start: number; end: number }>,
items: { id: string; text: string }[],
only: ReadonlySet<string> | null
) {
if (!report.evidence)
return {
evidence: false,
moved: 0,
note:
"The mix has no readable speech edges over these times — digital silence, a bed of music that never lets up, " +
"or speech that does not line up with them at all. Nothing moved, and nothing was confirmed either: check by ear with listen_audio.",
};
const moved = report.moved.filter((m) => !only || only.has(report.items[m.index].id));
const sizes = moved.map((m) => Math.abs(m.shift)).sort((a, b) => a - b);
const median = sizes.length > 0 ? sizes[Math.floor(sizes.length / 2)] : 0;
const worst = sizes.length > 0 ? sizes[sizes.length - 1] : 0;
return {
evidence: true,
moved: moved.length,
medianShift: median,
maxShift: worst,
items: moved.slice(0, 40).map((m) => ({
id: report.items[m.index].id,
text: items.find((i) => i.id === report.items[m.index].id)?.text,
start: m.start,
end: m.end,
shift: m.shift,
})),
...(moved.length > 40 ? { itemsTruncated: true } : {}),
note:
moved.length === 0
? "Every edge was already on the speech; nothing needed moving."
: `${moved.length} moved onto the speech in the mix itself (median ${median}s, farthest ${worst}s). Times sitting inside continuous speech, where nothing audible marks a boundary, kept what they had.`,
};
}
/** Several rows' passes read as one. Indexes are rebased onto the concatenated
* item list the caller reports from. */
function mergeReports<T extends { id: string; text: string; start: number; end: number }>(
reports: SyncReport<T>[]
): SyncReport<T> {
const items: T[] = [];
const moved: SyncReport<T>["moved"] = [];
let evidence = false;
for (const r of reports) {
const base = items.length;
items.push(...r.items);
moved.push(...r.moved.map((m) => ({ ...m, index: base + m.index })));
evidence ||= r.evidence;
}
const sizes = moved.map((m) => Math.abs(m.shift)).sort((a, b) => a - b);
return {
items,
evidence,
moved,
medianShift: sizes.length > 0 ? sizes[Math.floor(sizes.length / 2)] : 0,
maxShift: sizes.length > 0 ? sizes[sizes.length - 1] : 0,
};
}
/** Whether dressing the project in this look repaints the frame color. A look
* that keeps the frame only repaints it when the caller asked for it in so
* many words — adding words to a cut is not a reason to recolor it. */
function paintsFrame(look: TextLook, background: unknown): boolean {
if (typeof background === "boolean") return background;
return look.keepsFrame !== true;
}
/** The lines a text sequence should place: the ones passed in, or the caption
* track read as a running order. */
function textSequenceLines(
s: ReturnType<typeof useEditor.getState>,
input: Record<string, unknown>
): ComposeLine[] {
if (input.from_captions === true || isNum(input.from_captions)) {
const lane = isNum(input.from_captions) ? Math.max(0, Math.round(input.from_captions)) : 0;
return laneCues(s.subtitles, lane).map((c) => ({
text: c.text,
start: c.start,
end: Math.max(c.end, c.start + CLIP_MIN_SECONDS),
}));
}
const raw = Array.isArray(input.lines) ? input.lines : [];
const lines = raw
.filter((l): l is Record<string, unknown> => typeof l === "object" && l !== null)
.map((l) => ({
text: typeof l.text === "string" ? l.text.replace(/\\n/g, "\n").trim() : "",
start: isNum(l.start) ? Math.max(0, l.start) : NaN,
end: isNum(l.end) ? l.end : NaN,
...(typeof l.color === "string" ? { color: l.color } : {}),
...(isNum(l.size) ? { size: clamp(Math.round(l.size), TEXT_SIZE_MIN, TEXT_SIZE_MAX) } : {}),
...(l.emphasis === "whisper" || l.emphasis === "hero" || l.emphasis === "normal"
? { emphasis: l.emphasis }
: {}),
...(typeof l.section === "string" && l.section ? { section: l.section } : {}),
...(typeof l.font === "string" ? { font: l.font } : {}),
...(isNum(l.x) ? { x: clampOverlayPos(l.x) } : {}),
...(isNum(l.y) ? { y: clampOverlayPos(l.y) } : {}),
...(isNum(l.rotation) ? { rotation: clamp(l.rotation, -45, 45) } : {}),
...(typeof l.in_style === "string" ? { inStyle: l.in_style as OverlayAnimStyle } : {}),
...(typeof l.move === "string" && TEXT_MOVE_IDS.includes(l.move as TextMoveId)
? { move: l.move as TextMoveId }
: {}),
}))
.filter((l) => l.text.length > 0);
// A line with no times follows the one before it; the first starts at the
// playhead. Every line gets a real span, so nothing lands on top of
// anything. Times stay on the frames they were given (the input snap put
// them there): a label per shot holds that shot's frames, one or more.
let cursor = playheadAt();
return lines.map((l, i) => {
const start = Number.isNaN(l.start) ? cursor : l.start;
const nextStart = lines[i + 1]?.start ?? NaN;
const fallbackEnd = Number.isNaN(nextStart) ? start + 2 : nextStart;
// Every line lands at least one frame long, whichever way its end was
// decided — a following line that starts earlier cannot invert it.
const end = Math.max(Number.isNaN(l.end) ? fallbackEnd : l.end, start + CLIP_MIN_SECONDS);
cursor = end;
return { ...l, start, end } as ComposeLine;
});
}
/** Spans watched this session that nobody has written down yet, by asset id.
* Contact sheets fall out of the conversation as it grows, so the record has
* to be written while the frames are still on screen; a second look at the
* same source asks for the first look's reading before it spends a call. */
const unwritten = new Map<string, { from: number; to: number }>();
/** The moments detect_cuts measured in each source, by asset id: the middle
* of every shot and the frame every change inside one settles on. */
const shotMoments = new Map<string, number[]>();
/** A span counts as written down once notes describe all but a sliver of it. */
function spanIsNoted(watch: AssetWatch | undefined, span: { from: number; to: number }): boolean {
let cursor = span.from;
for (const n of [...(watch?.notes ?? [])].sort((a, b) => a.from - b.from)) {
if (n.to <= cursor) continue;
if (n.from > cursor + 2) break;
cursor = Math.max(cursor, n.to);
}
return cursor >= span.to - 2;
}
/** What has been written about a stretch of a source: the notes overlapping
* it, oldest span first. */
function notesIn(
watch: AssetWatch | undefined,
from: number,
to: number
): { from: number; to: number; text: string }[] {
return (watch?.notes ?? [])
.filter((n) => n.to > from && n.from < to)
.map((n) => ({ from: roundT(n.from), to: roundT(n.to), text: n.text }));
}
/** A clip volume as decibels of gain; silence reads as the quiet floor. */
const gainDb = (volume: number) => (volume > 0 ? 20 * Math.log10(volume) : -100);
/** A source's loudness and true peak moved by a clip's volume. */
function playedLoudness(
loudness: LoudnessMeasure | null,
volume: number
): { integratedLufs: number | null; truePeakDbtp: number | null } {
if (!loudness) return { integratedLufs: null, truePeakDbtp: null };
const r = roundedLoudness(loudness);
const gain = gainDb(volume);
return {
integratedLufs: r.integratedLufs === null ? null : round2(r.integratedLufs + gain),
truePeakDbtp: r.truePeakDbtp === null ? null : round2(r.truePeakDbtp + gain),
};
}
/** The whole mix as an unmastered export hears it: the same offline mix, at
* the export's 48 kHz stereo, measured to BS.1770. */
async function measureMix(s: ReturnType<typeof useEditor.getState>) {
const whole = await renderMix(mixSpecFor(renderDoc(s), (a) => a.url), {
sampleRate: 48000,
channels: 2,
resolve: (file) => file,
});
if (!whole) return { silent: true, note: "Nothing in the cut makes a sound." };
const channels = Array.from({ length: whole.numberOfChannels }, (_, c) => whole.getChannelData(c));
return { ...roundedLoudness(await measureLoudnessSliced(channels, whole.sampleRate)), seconds: roundT(whole.duration) };
}
function resolveWatchTarget(
s: ReturnType<typeof useEditor.getState>,
input: Record<string, unknown>
): {
asset: MediaAsset;
clip: { id: string; start: number; in: number; out: number; speed?: number; speedCurve?: SpeedNode[]; reverse?: boolean; smoothSlow?: boolean } | null;
} {
if (input.clip_id !== undefined && input.clip_id !== null) {
const id = String(input.clip_id);
const clip =
s.clips.find((c) => c.id === id) ??
s.audioClips.find((c) => c.id === id);
if (!clip) throw new ToolError(`No clip with id ${id}. Call get_state for current ids.`);
const asset = s.assets.find((a) => a.id === clip.assetId);
if (!asset) throw new ToolError("That clip's media asset is missing.");
return { asset, clip };
}
if (input.asset_id !== undefined && input.asset_id !== null) {
return { asset: requireItem(s.assets, input.asset_id, "project asset"), clip: null };
}
throw new ToolError("Pass clip_id or asset_id — see videoTrack and media in the editor state.");
}
/** The shared preamble for the source-reading tools (watch_video, detect_silence):
* require an open project, resolve the target asset/clip, and derive the source
* range to scan. Each tool then does its own media-type check and API call. */
function resolveWatchRange(
s: ReturnType<typeof useEditor.getState>,
input: Record<string, unknown>,
): {
projectId: string;
asset: MediaAsset;
clip: { id: string; start: number; in: number; out: number; speed?: number; speedCurve?: SpeedNode[]; reverse?: boolean; smoothSlow?: boolean } | null;
speed: number;
from: number;
to: number | undefined;
} {
const projectId = s.projectId;
if (!projectId) throw new ToolError("No project open.");
const { asset, clip } = resolveWatchTarget(s, input);
const speed = clip ? retimeOf(clip).rate : 1;
const dur = asset.duration > 0 ? asset.duration : Infinity;
const from = clamp(isNum(input.from) ? input.from : clip ? clip.in : 0, 0, dur);
// An unknown duration leaves `to` for the engine to probe.
const to = isNum(input.to)
? clamp(input.to, 0, dur)
: clip
? clip.out
: Number.isFinite(dur)
? dur
: undefined;
if (to !== undefined && to <= from)
throw new ToolError("from/to describe an empty range of the source.");
return { projectId, asset, clip, speed, from, to };
}
/** What a source can still be asked for, from what is already known. A steer
* that names a tool the source refuses spends a round on an error: an image
* has no sound, a music asset has no picture, and a video's sound is proven by
* its transcript or by having been played. */
function soundOf(asset: MediaAsset): "yes" | "none" | "unknown" {
if (asset.type === "image") return "none";
if (asset.type === "audio") return "yes";
if (asset.watch?.heard?.length) return "yes";
if (asset.speech) return asset.speech.noSpeech ? "none" : "yes";
return "unknown";
}
/** What a comparison says when the cut plays nothing and the reference may
* have sound: the frames can match while the cut is still mute. */
function silenceNote(s: Editor, asset: MediaAsset): string {
const sound = soundOf(asset);
if (sound === "none" || s.audioClips.length > 0) {
return "";
}
const voiced = s.clips.some((c) => !c.muted && s.assets.find((a) => a.id === c.assetId)?.type === "video");
if (voiced) {
return "";
}
return sound === "yes"
? `The cut plays no sound and "${asset.name}" has a soundtrack: import_url with audio_only on the link it came from brings that track in as an audio file of its own, and add_clip at 0 lines it up with the picture while the reference stays off every timeline (detach_audio with its assetId when it came without a link). `
: `The cut plays no sound. listen_audio on "${asset.name}" says whether it has a soundtrack to lay down. `;
}
/** How every source-reading tool names the source it read. `type` and `sound`
* say which tools it can answer at all, so nothing downstream asks a music
* file for its picture or a silent take for its sound. */
function sourceRef(asset: MediaAsset) {
return {
assetId: asset.id,
name: asset.name,
duration: roundT(asset.duration),
type: asset.type,
sound: soundOf(asset),
};
}
/** What is said over a stretch of a source, on the source's own clock.
* Project captions win where they cover it — their cue times are timeline
* seconds, mapped back through the clip's retime — and the asset's own
* transcript, already source time, covers the rest. The range decides: a
* caption lane holding cues for one clip leaves every other clip to its
* source's transcript. */
function sourceSpeech(
s: ReturnType<typeof useEditor.getState>,
asset: MediaAsset,
clip: { id: string; start: number; in: number; out: number; speed?: number; speedCurve?: SpeedNode[]; reverse?: boolean; smoothSlow?: boolean } | null,
from: number,
to: number,
): { start: number; end: number; text: string }[] {
const cues = clip
? laneCues(s.subtitles, s.subtitleLane).map((c) => ({
start: retimeOf(clip).srcAt(c.start - clip.start),
end: retimeOf(clip).srcAt(c.end - clip.start),
text: c.text,
}))
: [];
return speechOver(cues, asset.speech?.segments ?? [], from, to);
}
/** A reference link the model typed into a tool argument, opened. Every
* failure is the reader's own plain reason. */
async function openReferenceLink(raw: unknown): Promise<ReferenceProject> {
const link = parseProjectLink(String(raw ?? ""));
if (!link) throw new ToolError("Pass a Donkey Cut project link, share link, or project id.");
return openReference(link).catch((e) => {
throw new ToolError(e instanceof Error ? e.message : "Could not read that project.", { cause: e });
});
}
/** watch_video aimed at a reference project's source: the same target and
* span rules as the open project's, on the reference's document, with the
* file played from wherever the reference lives. */
async function resolveReferenceWatch(
input: Record<string, unknown>
): Promise<(ReturnType<typeof resolveWatchRange> & { ref: ReferenceProject }) | null> {
const raw = input.project_link;
if (raw === undefined || raw === null || String(raw).trim() === "") return null;
const ref = await openReferenceLink(raw);
const docAssets = ref.doc.assets ?? [];
let stored: StoredAsset | undefined;
let clip: ReturnType<typeof resolveWatchTarget>["clip"] = null;
if (input.clip_id !== undefined && input.clip_id !== null) {
const id = String(input.clip_id);
const c =
(ref.doc.clips ?? []).find((x) => x.id === id) ??
(ref.doc.audioClips ?? []).find((x) => x.id === id);
if (!c) throw new ToolError(`No clip with id ${id} in the reference. read_project lists its clips.`);
stored = docAssets.find((a) => a.id === c.assetId);
clip = c;
} else if (input.asset_id !== undefined && input.asset_id !== null) {
stored = docAssets.find((a) => a.id === String(input.asset_id));
if (!stored)
throw new ToolError(`No asset with id ${String(input.asset_id)} in the reference. read_project lists its media.`);
} else {
throw new ToolError("Pass clip_id or asset_id from the reference — see read_project's videoTrack and media.");
}
if (!stored) throw new ToolError("That reference clip's media asset is missing.");
const asset: MediaAsset = { ...stored, url: await referenceMediaUrl(ref, stored.fileName) };
const speed = clip ? retimeOf(clip).rate : 1;
const dur = asset.duration > 0 ? asset.duration : Infinity;
const from = clamp(isNum(input.from) ? input.from : clip ? clip.in : 0, 0, dur);
const to = isNum(input.to)
? clamp(input.to, 0, dur)
: clip
? clip.out
: Number.isFinite(dur)
? dur
: undefined;
if (to !== undefined && to <= from)
throw new ToolError("from/to describe an empty range of the source.");
return { projectId: ref.projectId, asset, clip, speed, from, to, ref };
}
/** The shared landing, with every failure a plain tool error. */
async function landReferenceAssets(
ref: ReferenceProject,
sources: StoredAsset[],
projectId: string,
chatId: string | null,
mapped?: ReadonlySet<string>
): Promise<LandedAsset[]> {
if (sources.length === 0) return [];
return landReferenceAssetsInto(ref, sources, projectId, { chatId, mapped }).catch((e) => {
throw new ToolError(e instanceof Error ? e.message : "Could not copy the reference's media.", { cause: e });
});
}
/** Scans, a few clips at a time. Each one opens a decoder over its own span of
* the source, and a recut hands this tool every clip it made. */
async function eachScanned<T>(items: T[], run: (item: T) => Promise<void>) {
const width = 3;
let next = 0;
await Promise.all(
Array.from({ length: Math.min(width, items.length) }, async () => {
while (next < items.length) await run(items[next++]);
})
);
}
/** Where the words are in a source range, in source seconds. One reader for
* every residency: the page decodes its own media whether the engine or the
* cloud is serving it, and the headless runner installs the same decoders.
* This is what refine_speech_cuts places its edges against — a fixed dB
* threshold cannot answer it, because a quiet room and a loud one disagree
* about what silence is and a cut placed on the wrong answer lands in a word. */
async function fetchSpeech(asset: MediaAsset, from: number, to: number) {
const heard = soundSpan(asset, from, to);
const scan = await scanSourceSpeech(heard.asset.url, { from: heard.from, to: heard.to }).catch((e) => {
throw new ToolError(e instanceof Error ? e.message : "Could not read the audio.", { cause: e });
});
return {
...scan,
from: heard.back(scan.from),
to: heard.back(scan.to),
segments: scan.segments.map((g) => ({ ...g, start: heard.back(g.start), end: heard.back(g.end) })),
};
}
/**
* Where a source range's sound is read. A video bound to a recording sounds
* from the recording: the range moves onto its clock and narrows to what it
* holds, and `back` carries a second on that file back to the video's source
* time, so every answer comes back in the seconds the caller asked in.
*/
function soundSpan(asset: MediaAsset, from: number, to: number | undefined) {
const src = soundSourceOf(asset, useEditor.getState().assets);
if (!src.bound) return { asset, from, to, back: (t: number) => t };
const lo = Math.max(0, from + src.offset);
const hi = Math.min(src.limit, (to ?? asset.duration) + src.offset);
if (!(hi - lo > 0.05))
throw new ToolError(`"${src.asset.name}", the sound bound to "${asset.name}", holds nothing of that stretch.`);
return { asset: src.asset, from: lo, to: hi as number | undefined, back: (t: number) => t - src.offset };
}
/** How loud a source range plays, read where its sound is. */
async function sourceLevel(asset: MediaAsset, from: number, to: number | undefined) {
const heard = soundSpan(asset, from, to);
const level = await measureSourceLevel(heard.asset.url, { from: heard.from, ...(heard.to !== undefined ? { to: heard.to } : {}) });
// A bound recording plays on its own clock; the peak is reported on the
// clip's.
return level.peakAt === undefined ? level : { ...level, peakAt: level.peakAt - (heard.from - from) };
}
/** Silent stretches of a source range, in source seconds — the engine's
* ffmpeg scan locally, the browser's RMS fold in cloud mode. Shared by
* detect_silence (the model's ears) and refine_speech_cuts (the mechanical
* re-trim). */
async function fetchSilences(
projectId: string,
asset: MediaAsset,
opts: { from: number; to?: number; thresholdDb?: number; minSilence?: number }
): Promise<{ start: number; end: number; duration: number }[]> {
// Same defaults and clamps as the engine's silence handler.
const thresholdDb = clamp(opts.thresholdDb ?? -30, -90, 0);
const minSilence = clamp(opts.minSilence ?? 0.35, 0.05, 10);
const heard = soundSpan(asset, opts.from, opts.to);
const back = (list: { start: number; end: number; duration: number }[]) =>
list.map((x) => ({ ...x, start: heard.back(x.start), end: heard.back(x.end) }));
if (getBackend().kind !== "local") {
return back(
await detectSilenceClientSide(heard.asset.url, {
from: heard.from,
...(heard.to !== undefined ? { to: heard.to } : {}),
thresholdDb,
minSilence,
}).catch((e) => {
throw new ToolError(e instanceof Error ? e.message : "Could not scan for silence.", { cause: e });
})
);
}
const res = await apiFetch(`/api/cut/projects/${projectId}/silence`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
file: heard.asset.fileName,
from: heard.from,
...(heard.to !== undefined ? { to: heard.to } : {}),
threshold_db: thresholdDb,
min_silence: minSilence,
}),
});
const body = await apiJson<{
silences: { start: number; end: number; duration: number }[];
error?: string;
}>(res);
if (!res.ok) throw new ToolError(body.error ?? "Could not scan for silence.");
return back(body.silences);
}
/** Pull a source's audio track off (video and audio alike) and inline it for
* the model; null when the range clears the inline cap. Local: the engine
* extracts mono AAC. Cloud: the browser renders the span to 16 kHz mono WAV. */
async function audioSpanBlob(
projectId: string,
asset: MediaAsset,
from: number,
to: number | undefined,
): Promise<Blob> {
if (getBackend().kind !== "local")
return renderAudioSpanWav(asset.url, from, to).catch((e) => {
throw new ToolError(e instanceof Error ? e.message : "Could not read the audio.", { cause: e });
});
const res = await apiFetch(`/api/cut/projects/${projectId}/audio`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ file: asset.fileName, from, ...(to !== undefined ? { to } : {}) }),
});
if (!res.ok) {
const body = await apiJson<{ error?: string }>(res).catch(() => ({ error: undefined }));
throw new ToolError(body.error ?? "Could not read the audio.");
}
return res.blob();
}
/** Bound the work per call the way a watch does; the caller listens on from
* coveredTo. */
const LISTEN_MAX_S = 600;
const LISTEN_MIN_S = 0.5;
/**
* A span's sound, shrunk to whatever the model can take at once. The two
* backends encode differently — the browser renders 16kHz mono WAV, the engine
* hands back AAC — so the seconds that fit the inline cap differ by an order
* of magnitude and neither is knowable up front. The bytes that come back say
* what a second of THIS source costs, which is what the retry sizes itself
* from. A stretch too long comes back as its opening, with the span it
* actually covered, rather than as a refusal the caller has to guess past.
*/
async function listenSpan(
projectId: string,
asset: MediaAsset,
askedFrom: number,
askedTo: number | undefined,
): Promise<{ inline: InlineImage; from: number; to: number }> {
// A bound recording is what is heard, from where it holds
// sound; the span reports back in the video's own seconds.
const heard = soundSpan(asset, askedFrom, askedTo ?? Math.min(asset.duration, askedFrom + LISTEN_MAX_S));
const from = heard.from;
const to = heard.to;
const end = Math.min(to ?? from + LISTEN_MAX_S, from + LISTEN_MAX_S);
let span = end - from;
// The asked stretch reads at any length; a stretch shrunk to fit stops at
// LISTEN_MIN_S, below which nothing worth hearing is left.
for (let attempt = 0; attempt < 3 && span > (attempt === 0 ? 0 : LISTEN_MIN_S); attempt++) {
const blob = await audioSpanBlob(projectId, heard.asset, from, round2(from + span));
const inline = await blobToInlineAudio(blob);
if (inline) return { inline, from: roundT(heard.back(from)), to: roundT(heard.back(from + span)) };
const perSecond = blob.size / span;
// Leave room for the base64 inflation the cap already accounts for.
const fits = (MAX_AUDIO_BYTES * 0.9) / perSecond;
span = Math.min(span * 0.9, fits);
}
throw new ToolError("Could not read a stretch of that audio short enough to listen to.");
}
/** One line per timeline item for a sweep to judge: what it is, when it
* plays, and the settings already on it. This is everything the finding
* reads, so an ask about what the footage shows or the audio holds is
* measured first and the measurement goes in the description. */
function sweepCandidates(s: Editor, kind: ItemKind): SweepCandidate[] {
const assetName = (id: string) => s.assets.find((a) => a.id === id)?.name ?? "media";
const span = (start: number, len: number) => `starts ${roundT(start)}s, ${roundT(len)}s long`;
if (kind === "clip")
return s.clips.map((c) => ({
id: c.id,
label: [
`"${c.name || assetName(c.assetId)}"`,
`video track ${c.track}`,
span(c.start, retimeOf(c).len),
c.muted ? "muted" : "",
c.hidden ? "hidden" : "",
c.speed && c.speed !== 1 ? `${round2(c.speed)}× speed` : "",
c.reverse ? "reversed" : "",
c.grade?.preset ? `${c.grade.preset.id} look` : "",
c.removal && !c.removal.off ? "cut out of its background" : "",
]
.filter(Boolean)
.join(", "),
}));
if (kind === "audio")
return s.audioClips.map((a) => ({
id: a.id,
label: [
`"${a.name || assetName(a.assetId)}"`,
span(a.start, retimeOf(a).len),
a.volume !== undefined && a.volume !== 1 ? `${Math.round(a.volume * 100)}% volume` : "",
a.duck !== undefined ? "ducks under speech" : "",
a.hidden ? "hidden" : "",
]
.filter(Boolean)
.join(", "),
}));
if (kind === "overlay")
return s.overlays.map((o) => ({
id: o.id,
label: [
isTextOverlay(o) ? `text "${o.text}"` : `${o.kind ?? "element"} "${o.name ?? o.kind ?? "element"}"`,
`${roundT(o.start)}s to ${roundT(o.end)}s`,
o.hidden ? "hidden" : "",
]
.filter(Boolean)
.join(", "),
}));
if (kind === "cue")
return s.subtitles.cues.map((c) => ({
id: c.id,
label: `caption "${c.text}", ${roundT(c.start)}s to ${roundT(c.end)}s`,
}));
return s.transitions.map((t) => ({
id: t.id,
label: `${t.style} transition, ${roundT(t.seconds)}s at ${roundT(t.start)}s${t.hidden ? ", switched off" : ""}`,
}));
}
/** The one-item argument each tool a sweep lands on takes, so `ids` runs the
* same write over a list of them. One entry point: the dispatcher fans the
* call out, and every handler stays a single-item write. */
const SWEEP_TARGETS: Readonly<Record<string, string>> = {
set_clip_muted: "clipId",
set_clip_effects: "clipId",
set_clip_hidden: "clipId",
set_clip_volume: "clipId",
set_split_edit: "clipId",
set_color_preset: "clipId",
set_color_grade: "clipId",
set_color_curves: "clipId",
set_color_wheels: "clipId",
set_color_hsl: "clipId",
set_color_lut: "clipId",
apply_saved_grade: "clipId",
set_speed: "clipId",
set_framing: "clipId",
set_camera_card: "clipId",
set_transition: "clipId",
delete_item: "id",
update_cue: "id",
delete_cue: "id",
update_audio: "id",
};
/** The clip a sound tool names — a video clip or a soundtrack clip, whichever
* carries the id — with its current treatment and the store write that
* lands a new one. */
function soundTarget(s: Editor, id: unknown) {
const key = typeof id === "string" ? id.trim() : "";
const clip = s.clips.find((c) => c.id === key);
if (clip) {
return {
id: clip.id,
kind: "clip" as const,
current: clip.sound,
write: (sound: ClipSound | undefined) => s.updateClip(clip.id, { sound }),
};
}
const audio = s.audioClips.find((a) => a.id === key);
if (audio) {
return {
id: audio.id,
kind: "audio" as const,
current: audio.sound,
write: (sound: ClipSound | undefined) => s.updateAudio(audio.id, { sound }),
};
}
throw new ToolError(`No video or soundtrack clip with id "${key}".`);
}
/** sync_audio's bind: line the recording up with the video and bind it, or
* refuse with the reason. The clip it was named by aims the match. */
async function syncVideoSound(s: Editor, video: MediaAsset, audioId: unknown, clip: VideoClip | undefined) {
const rec = requireItem(s.assets, audioId, "audio asset");
const bound = await bindRecording(video.id, rec.id, clip).catch((e: unknown) => {
throw new ToolError(e instanceof Error ? e.message : "Could not line the recording up.", { cause: e });
});
const { assetId, ...rest } = bound;
return {
id: assetId,
...rest,
note: `Every clip of "${video.name}" (${bound.clips} on the timeline) now plays "${rec.name}"; recording second = video second ${bound.offset < 0 ? "−" : "+"} ${Math.abs(bound.offset)}.${bound.refined ? "" : " Aligned to the nearest 20 ms; the waveforms had no sharp detail to place it closer."}`,
};
}
/** set_overlay_animation's caret fields, written onto the typewriter entrance
* in `anim` (which the call has already updated). */
function applyCaretInput(
o: { kind?: string },
anim: OverlayAnim,
input: Record<string, unknown>
): void {
const named =
typeof input.caret === "boolean" ||
typeof input.caret_blink === "boolean" ||
isNum(input.caret_blinks) ||
typeof input.caret_hide === "boolean" ||
typeof input.caret_color === "string";
if (!named) return;
const edge = anim.in;
if (input.caret === false) {
if (edge?.caret) {
const next = { ...edge };
delete next.caret;
anim.in = next;
}
return;
}
if ((o.kind ?? "text") !== "text" || !edge || !edgeMotion(edge)?.animate.typed)
throw new ToolError("A caret rides a typewriter entrance on a title: set in_style typewriter on a title first.");
const caret: OverlayCaret = { ...(edge.caret ?? { blink: true }) };
if (typeof input.caret_blink === "boolean") caret.blink = input.caret_blink;
if (isNum(input.caret_blinks)) {
const n = Math.round(clamp(input.caret_blinks, 0, CARET_BLINKS_MAX));
if (n > 0) caret.blinks = n;
else delete caret.blinks;
}
if (typeof input.caret_hide === "boolean") {
if (input.caret_hide) caret.hide = true;
else delete caret.hide;
}
if (typeof input.caret_color === "string") caret.color = hexColor(input.caret_color, "caret_color");
anim.in = { ...edge, caret };
}
/** set_overlay_animation's hit fields, written onto `anim`. A new hit takes
* the default length, darkens, and starts at the element's middle unless
* hit_at names the moment; the moment is held so the whole hit fits. */
function applyHitInput(
o: { start: number; end: number },
anim: OverlayAnim,
input: Record<string, unknown>
): void {
const raw = input.hit_style;
const named =
typeof raw === "string" ||
isNum(input.hit_at) ||
isNum(input.hit_seconds) ||
typeof input.hit_darken === "boolean";
if (!named) return;
if (raw === "none") {
delete anim.hit;
return;
}
if (typeof raw === "string" && !OVERLAY_HIT_STYLE_IDS.includes(raw))
throw new ToolError(`Unknown hit style: ${raw}. Use one of: ${OVERLAY_HIT_STYLE_IDS.join(", ")}.`);
const style = typeof raw === "string" ? raw : anim.hit?.style;
if (!style) throw new ToolError("Name hit_style to add a hit.");
const dur = Math.max(0.1, o.end - o.start);
const seconds = Math.min(
dur,
isNum(input.hit_seconds)
? clamp(input.hit_seconds, OVERLAY_HIT_MIN_SECONDS, OVERLAY_HIT_MAX_SECONDS)
: (anim.hit?.seconds ?? OVERLAY_HIT_DEFAULT_SECONDS)
);
const at = isNum(input.hit_at) ? input.hit_at : (anim.hit?.at ?? (dur - seconds) / 2);
anim.hit = {
style,
at: Math.round(clamp(at, 0, Math.max(0, dur - seconds)) * 1000) / 1000,
seconds,
darken: typeof input.hit_darken === "boolean" ? input.hit_darken : (anim.hit?.darken ?? true),
};
}
/** set_overlay_animation's font-cycle fields, written onto `anim`. A new
* cycle runs from the element's start to its end at the default rate; an
* empty face list removes it. Only font ids the registry knows are kept, so
* the cycle never shows a face the user could not pick. Switch times or a
* clip's beat grid time the faces instead: each face holds from one switch
* to the next. */
function applyFontCycleInput(
s: Editor,
o: { kind?: string; start: number; end: number },
anim: OverlayAnim,
input: Record<string, unknown>
): void {
const raw = input.font_cycle;
const named =
raw !== undefined ||
isNum(input.font_cycle_at) ||
isNum(input.font_cycle_seconds) ||
isNum(input.font_cycle_rate) ||
input.font_cycle_switches !== undefined ||
input.font_cycle_beats !== undefined;
if (!named) return;
// An empty list clears the cycle.
if (Array.isArray(raw) && raw.length === 0) {
delete anim.fonts;
return;
}
if ((o.kind ?? "text") !== "text") throw new ToolError("A font cycle changes a title's face; it needs a title.");
if (raw !== undefined && !Array.isArray(raw)) throw new ToolError("font_cycle must be a list of faces.");
const faces = Array.isArray(raw) ? raw.slice(0, FONT_CYCLE_FACES_MAX).map(cycleFaceOf) : anim.fonts?.faces;
if (!faces) throw new ToolError("Name font_cycle to add a font cycle.");
// Timing: held inside the element, with the rate in its supported range.
const dur = Math.max(0.1, o.end - o.start);
const at = onFrame(clamp(isNum(input.font_cycle_at) ? input.font_cycle_at : (anim.fonts?.at ?? 0), 0, dur - 0.05));
const seconds = onFrame(
clamp(isNum(input.font_cycle_seconds) ? input.font_cycle_seconds : (anim.fonts?.seconds ?? dur - at), 0.05, dur - at)
);
const rate = isNum(input.font_cycle_rate)
? clamp(input.font_cycle_rate, FONT_CYCLE_RATE_MIN, FONT_CYCLE_RATE_MAX)
: (anim.fonts?.rate ?? FONT_CYCLE_RATE);
// To the microsecond, so a run that starts on a frame stays on it.
const round = (v: number) => onFrame(Math.round(v * 1e6) / 1e6);
// Switch times (passed, or the beats of the music's clip) give each face
// its own hold, the faces repeating in order to fill them.
const edges = cycleSwitchesOf(s, o, input, at, seconds);
if (edges) {
anim.fonts = timedFontCycle(faces, edges, rate, round);
return;
}
anim.fonts = { faces, at: round(at), seconds: round(seconds), rate };
}
/** The face-change times of a timed font cycle, in seconds from the element's
* start, first to last: font_cycle_switches as passed, or the stored beat
* grid of the font_cycle_beats clip inside the cycle's run [at, at+seconds].
* Null when neither is named. */
function cycleSwitchesOf(
s: Editor,
o: { start: number; end: number },
input: Record<string, unknown>,
at: number,
seconds: number
): number[] | null {
const dur = o.end - o.start;
let edges: number[];
if (input.font_cycle_switches !== undefined) {
if (!Array.isArray(input.font_cycle_switches)) throw new ToolError("font_cycle_switches must be a list of timeline seconds.");
edges = input.font_cycle_switches.filter(isNum).map((t) => t - o.start);
} else if (input.font_cycle_beats !== undefined) {
edges = beatSwitchesOf(s, String(input.font_cycle_beats), input, o.start, at, at + seconds);
} else {
return null;
}
// Inside the element, in order; a switch under a face's shortest hold
// after the one before it merges into it, the run's end kept.
edges = tidySwitches(edges, dur);
const problem = switchProblem(edges);
if (problem?.kind === "few")
throw new ToolError("A timed font cycle needs at least two switch times inside the title: the first face's start and the last face's end.");
if (problem?.kind === "many")
throw new ToolError(
`That run changes face ${problem.faces} times; one cycle holds ${FONT_CYCLE_FACES_MAX}. Pass font_cycle_beat_step 2 (every other beat), or shorten the run with font_cycle_seconds.`
);
if (problem?.kind === "long")
throw new ToolError(`One face would hold ${round2(problem.seconds)}s; a face holds at most ${CYCLE_HOLD_MAX}s. Add a switch inside that gap.`);
return edges;
}
/** Face changes on a clip's beat grid, seconds from the element's start: the
* beats (every `step`th, or each split into 1/step parts) that land inside
* the run, closed by the next one or the run's end. */
function beatSwitchesOf(
s: Editor,
clipId: string,
input: Record<string, unknown>,
elementStart: number,
from: number,
to: number
): number[] {
const clip = s.clips.find((c) => c.id === clipId) ?? s.audioClips.find((c) => c.id === clipId);
if (!clip) throw new ToolError(`No clip with id ${clipId}. font_cycle_beats takes the clip that plays the music.`);
const asset = s.assets.find((a) => a.id === clip.assetId);
const grid = asset?.beats?.beats ?? [];
if (grid.length < 2)
throw new ToolError(`"${asset?.name ?? clipId}" has no beat grid yet. Call detect_beats with clip_id ${clipId} first, then time the cycle to it.`);
// The beats the clip plays, on the element's clock, in play order.
const beats = clipBeatTimes(clip, asset).map((t) => t - elementStart);
const step = isNum(input.font_cycle_beat_step) && input.font_cycle_beat_step > 0 ? input.font_cycle_beat_step : 1;
if (!validBeatStep(step))
throw new ToolError("font_cycle_beat_step is a whole number of beats (1, 2, 4) or a split of one (0.5, 0.25).");
const switches = beatSwitches(beats, step, from, to);
if (switches.length === 0) throw new ToolError("No beat of that clip lands inside the cycle's run.");
return switches;
}
/** A font id the registry knows, or a refusal naming the one it does not. */
function knownFont(v: unknown): FontId {
if (typeof v !== "string" || !allFonts().some((f) => f.id === v)) {
throw new ToolError(`Unknown font id "${String(v)}".`);
}
return v as FontId;
}
/** One font_cycle entry as a stored face, checked against the registry. */
function cycleFaceOf(raw: unknown): CycleFace {
const f = (raw ?? {}) as Record<string, unknown>;
if (typeof f.font !== "string" || !allFonts().some((x) => x.id === f.font))
throw new ToolError(`Unknown font id "${String(f.font)}".`);
if (f.weight !== undefined && !isTextWeight(f.weight))
throw new ToolError(`A face's weight is one of ${TEXT_WEIGHTS.join(", ")}.`);
return {
font: f.font,
...(isTextWeight(f.weight) ? { weight: f.weight } : {}),
...(isNum(f.scale) && f.scale !== 1 ? { scale: clamp(f.scale, CYCLE_SCALE_MIN, CYCLE_SCALE_MAX) } : {}),
...(isNum(f.tracking) ? { tracking: clamp(f.tracking, -0.05, 0.5) } : {}),
...(typeof f.italic === "boolean" ? { italic: f.italic } : {}),
...(isNum(f.hold) && f.hold > 0 ? { hold: onFrame(clamp(f.hold, CYCLE_HOLD_MIN, CYCLE_HOLD_MAX)) } : {}),
};
}
function requireItem<T extends { id: string }>(pool: T[], id: unknown, label: string): T {
const item = pool.find((x) => x.id === String(id ?? ""));
if (!item) throw new ToolError(`No ${label} with id ${String(id)}. Call get_state for current ids.`);
return item;
}
/** A still holds one frame for as long as its clip runs, so a rate over it
* means nothing — what a "faster" or "shorter" ask wants there is a trim. */
function refuseStillRetime(s: Editor, clip: VideoClip): void {
const asset = s.assets.find((a) => a.id === clip.assetId);
if (asset?.type !== "image") return;
throw new ToolError(
`"${asset.name}" is a still — it has no motion to retime. Change how long it holds with trim_clip.`
);
}
/** 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 asset refs. Any media resolves:
* images and video frames ride as pictures; audio rides to the compose pass,
* which folds what it hears (speech, sound) into the prompt. An id may carry
* a pinned moment as "<assetId>@<seconds>" — the model forwards a user's pin
* this way, and the ref then reads from that moment (its frame capture, its
* audio segment) instead of the default spot. */
function resolveRefAssets(ids: unknown): AssetRef[] {
if (ids === undefined || ids === null) return [];
const s = useEditor.getState();
return (Array.isArray(ids) ? ids : [ids]).map((raw) => {
const token = String(raw);
const at = token.lastIndexOf("@");
const suffix = at > 0 ? Number(token.slice(at + 1)) : NaN;
const pinned = Number.isFinite(suffix) && suffix >= 0;
const id = pinned ? token.slice(0, at) : token;
// The whole token wins over the split when both name an asset — an id
// that happens to contain "@" is still addressable.
const asset = s.assets.find((a) => a.id === token) ?? (pinned ? s.assets.find((a) => a.id === id) : undefined);
if (!asset)
throw new ToolError(`No project asset with id ${token} — see media in the editor state.`);
return pinned && asset.id === id ? { ...refFromAsset(asset), t: suffix } : 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<VideoClip> {
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 };
}
/** How far a layer's box runs past each side of the frame, in frame
* fractions — the part the frame crops. Null when the box sits inside. A box
* set past the frame on purpose (a screen that spills off) reads the same;
* the chat checks the sides against what it meant.
* e.g. centre 0.875 at width 0.75 → { right: 0.25 } */
function frameOverhang(r: { x: number; y: number; w: number; h: number }): Record<string, number> | null {
const sides = {
left: -r.x,
right: r.x + r.w - 1,
top: -r.y,
bottom: r.y + r.h - 1,
};
const past = Object.entries(sides).filter(([, v]) => v > OVERHANG_EPS);
return past.length > 0 ? Object.fromEntries(past.map(([k, v]) => [k, Math.round(v * 1000) / 1000])) : null;
}
// Under a pixel of a 1080 frame: a box flush with an edge is not past it.
const OVERHANG_EPS = 0.001;
// How close another clip's edge sits for set_animation to name it as the
// clip that took the bar: a frame at 50 fps.
const ANIM_TOUCH_SECONDS = 0.02;
/** The model asked for timeline placement — explicitly, or implicitly by
* giving a position. Otherwise generated media stays on its chat card. */
function wantsTimeline(input: Record<string, unknown>, positionKey: "index" | "start"): boolean {
return input.add_to_timeline === true || isNum(input[positionKey]);
}
const NOT_PLACED = { added: false, clipId: null, index: null };
/** Place a project asset on the timeline like a drag: video/image onto track 0
* (an `index` insert, a free-positioned `start`, or appended at the end),
* audio onto the soundtrack. Returns the created clip's summary. */
/** The lowest soundtrack lane with room for `len` seconds at `start` itself,
* leaving `skip` (the clip being moved) out of the count. */
function lowestFreeAudioLane(clips: AudioClip[], start: number, len: number, skip?: string): number {
for (let lane = 0; ; lane++) {
const taken = footprints(clips.filter((c) => c.id !== skip && (c.lane ?? 0) === lane));
if (nextFreeStart(taken, start, len) < start + 1e-3) return lane;
}
}
/** When a soundtrack clip sits on a higher lane than its span needs, the lane
* it fits on, so a soundtrack built a sound at a time stays packed. */
function audioPackHint(id: string): { freeLane?: number; note?: string } {
const all = useEditor.getState().audioClips;
const c = all.find((x) => x.id === id);
if (!c) return {};
const free = lowestFreeAudioLane(all, c.start, clipLen(c), c.id);
if (free >= (c.lane ?? 0)) return {};
return {
freeLane: free,
note: `Lane ${free} is free for this sound's whole span. Keep the soundtrack packed: move it there with update_audio lane ${free} unless it is stacked on purpose.`,
};
}
/** Soundtrack and element copies moved onto `lane`, each kind keeping its rows'
* order: copies from lanes 2 and 3 asked onto lane 0 land on 0 and 1. Video
* clips keep their tracks. */
function copiesOnLane(items: TimelineClipboardItem[], lane: number): TimelineClipboardItem[] {
const lowest = { audio: Infinity, overlay: Infinity };
for (const cb of items) {
if (cb.kind === "audio" || cb.kind === "overlay") {
lowest[cb.kind] = Math.min(lowest[cb.kind], laneOf(cb.item));
}
}
// Each copy moves by the distance from its kind's lowest row to `lane`.
return items.map((cb) => {
if (cb.kind !== "audio" && cb.kind !== "overlay") {
return cb;
}
return { ...cb, item: { ...cb.item, lane: lane + laneOf(cb.item) - lowest[cb.kind] } } as TimelineClipboardItem;
});
}
function audioLaneInput(value: unknown): number {
if (!isNum(value) || !Number.isInteger(value) || value < 0)
throw new ToolError("Audio lane must be a non-negative integer.");
return value;
}
/** A colour the model passed, as the document stores it. A value that is not
* a colour is named: silently falling back paints a shot the reference never
* had while the reply says the backdrop landed. */
function hexColor(raw: unknown, what: string): string {
const v = typeof raw === "string" ? raw.trim() : "";
const short = /^#([0-9a-fA-F]{3})$/.exec(v);
if (short) return `#${[...short[1]].map((c) => c + c).join("")}`;
if (/^#[0-9a-fA-F]{6}$/.test(v)) return v;
throw new ToolError(`${what} has to be a hex colour like #ff5a00 or #f50 — got ${JSON.stringify(raw)}.`);
}
/** Lay out shots that have no footage yet: one block per shot on track 0,
* each the length that shot runs, in one undo step. The blocks own no files,
* so this writes nothing to storage — and each one is an ordinary clip, so it
* trims, moves, takes a transition, and is replaced when the footage lands. */
function placeBlocks(s: Editor, raw: unknown[], input: Record<string, unknown>) {
const shots = raw
.filter((x): x is Record<string, unknown> => typeof x === "object" && x !== null)
.map((x) => ({
// A shot as detect_cuts reads it, from and to each on the frame it
// names, runs exactly between them; a length taken from two times
// written to the millisecond can be a millisecond off, and a run of
// them drifts a cut onto the frame after.
seconds: Math.min(
isNum(x.from) && isNum(x.to) ? x.to - x.from : isNum(x.seconds) ? x.seconds : 0,
BLOCK_MAX_SECONDS
),
label: typeof x.label === "string" ? x.label.trim() : "",
// The shot's own backdrop, so a cut waiting on its footage still shows
// the look it is standing in for.
...(x.color === undefined || x.color === null ? {} : { color: hexColor(x.color, "A block's color") }),
}))
.filter((x) => x.seconds > 0);
if (shots.length === 0)
throw new ToolError("Pass blocks: [{from, to, label}] (a shot as detect_cuts reads it) or [{seconds, label}] — one entry per shot, in order.");
if (shots.length > BLOCKOUT_MAX)
throw new ToolError(
`That is ${shots.length} shots — ${BLOCKOUT_MAX} is the most one call lays down. Pass the first ${BLOCKOUT_MAX} now, then the other ${shots.length - BLOCKOUT_MAX} in a second call with no start: they append right after the last block.`
);
// A block is at least one frame: the shortest clip any renderer plays.
const short = shots.findIndex((x) => x.seconds < BLOCK_MIN_SECONDS - 1e-9);
if (short >= 0)
throw new ToolError(
`Block ${short + 1} runs ${roundT(shots[short].seconds)}s, under one frame (${roundT(BLOCK_MIN_SECONDS)}s at 60 fps). Give it at least that, or fold it into the shot beside it.`
);
const frame = frameOf(s.aspect);
const made: { clipId: string; assetId: string; start: number; seconds: number; label: string }[] = [];
let at = isNum(input.start) ? Math.max(0, input.start) : undefined;
useEditor.getState().beginHistoryBatch();
try {
for (const [i, shot] of shots.entries()) {
const asset = blockAsset(shot, i, frame);
const cur = useEditor.getState();
cur.addAsset(asset);
// One at a time, each sized before the next goes down, so every block
// appends against a row whose end is already true and no two intersect.
const clipId = cur.addClipFromAsset(asset.id, at);
if (!clipId) continue;
useEditor.getState().updateClip(clipId, { out: shot.seconds });
const placed = useEditor.getState().clips.find((c) => c.id === clipId);
if (!placed) continue;
// The next block starts where this one ends, on the frame it names: a
// sum of frame lengths drifts off k/fps, and a start a hair late shows
// the shot before for one frame.
at = onFrame(placed.start + shot.seconds);
made.push({
clipId: placed.id,
assetId: asset.id,
start: roundT(placed.start),
seconds: roundT(shot.seconds),
label: asset.block?.label ?? "",
});
}
} finally {
useEditor.getState().endHistoryBatch();
}
return {
placed: made,
...tracksAfter(),
note: "Each block holds its shot's place on track 0. A block is filled by dropping footage on it — the footage takes its place and its length — or with replace_item; titles, sound and transitions go on top of the skeleton now.",
};
}
/** Several stretches of one source laid down in order, each trimmed to itself
* — a clip assembled from moments that were never next to each other, with
* everything between them left out. Placement and trimming both ride the
* store's own paths, so track 0 keeps its no-overlap invariant, and the whole
* run is one undo step. */
function placeAssetSpans(
asset: MediaAsset,
spans: { from: number; to: number }[],
input: Record<string, unknown>
) {
if (asset.type === "audio") throw new ToolError("spans cut a video source — audio lands whole.");
if (asset.type === "image") throw new ToolError("An image has no time axis to cut spans out of.");
const dur = asset.duration > 0 ? asset.duration : Infinity;
const cuts = spans
.map((sp) => ({
from: clamp(Math.min(sp.from, sp.to), 0, dur - CLIP_MIN_SECONDS),
to: clamp(Math.max(sp.from, sp.to), CLIP_MIN_SECONDS, dur),
}))
.filter((sp) => sp.to - sp.from >= CLIP_MIN_SECONDS - 1e-9)
.sort((a, b) => a.from - b.from);
if (cuts.length === 0) throw new ToolError("Every span was empty or outside the source.");
const s = useEditor.getState();
s.beginHistoryBatch();
const laid: { id: string; in: number; out: number }[] = [];
try {
let index = isNum(input.index) ? Math.round(input.index) : undefined;
for (const cut of cuts) {
let clipId: string | null;
if (index === undefined) {
// Appended, the way a drag to the end of the run would.
useEditor.getState().addClipFromAsset(asset.id);
const sel = useEditor.getState().selection;
clipId = sel?.kind === "clip" ? sel.id : null;
} else {
clipId = addVideoTrackClip(asset.id, index++).clipId;
}
if (!clipId) throw new ToolError("Could not create the clip.");
useEditor.getState().setClipTrim(clipId, cut.from, cut.to);
laid.push({ id: clipId, in: roundT(cut.from), out: roundT(cut.to) });
}
} finally {
useEditor.getState().endHistoryBatch();
}
const now = useEditor.getState().clips;
return {
clips: laid.map((c) => {
const live = now.find((x) => x.id === c.id);
return {
id: c.id,
in: c.in,
out: c.out,
start: roundT(live?.start ?? 0),
len: roundT(c.out - c.in),
};
}),
seconds: roundT(laid.reduce((n, c) => n + c.out - c.in, 0)),
};
}
function placeAssetOnTimeline(asset: MediaAsset, input: Record<string, unknown>) {
const s = useEditor.getState();
const start = isNum(input.start) ? Math.max(0, input.start) : undefined;
if (asset.type === "audio") {
// With no lane, a sound placed at a moment lands at that moment on the
// lowest lane free there, on its mark.
const lane =
input.lane !== undefined
? audioLaneInput(input.lane)
: start === undefined
? 0
: lowestFreeAudioLane(s.audioClips, start, Math.max(0.1, asset.duration));
s.addAudioFromAsset(asset.id, start, { lane });
const sel = useEditor.getState().selection;
const c =
sel?.kind === "audio"
? useEditor.getState().audioClips.find((x) => x.id === sel.id)
: undefined;
if (!c) throw new ToolError("Could not create the soundtrack clip.");
return { id: c.id, kind: asset.type, lane: c.lane ?? 0, start: roundT(c.start), len: roundT(c.out - c.in), ...audioPackHint(c.id) };
}
let clipId: string | null;
if (isNum(input.index)) {
clipId = addVideoTrackClip(asset.id, Math.round(input.index)).clipId;
} else {
s.addClipFromAsset(asset.id, start);
const sel = useEditor.getState().selection;
clipId = sel?.kind === "clip" ? sel.id : null;
}
const c = clipId ? useEditor.getState().clips.find((x) => x.id === clipId) : undefined;
if (!c) throw new ToolError("Could not create the clip.");
return {
id: c.id,
kind: asset.type,
index: track0Clips(useEditor.getState().clips).findIndex((x) => x.id === c.id),
start: roundT(c.start),
len: roundT(c.out - c.in),
};
}
const promptedIndex = (input: Record<string, unknown>): number | undefined =>
isNum(input.index) ? Math.round(input.index) : undefined;
/** Append a project asset to the video track, at `index` when given. Shared
* by add_clip, generate_image (inline), and the video renders' completion. */
function addVideoTrackClip(
assetId: string,
index?: number
): { added: boolean; clipId: string | null; index: number | null } {
const s = useEditor.getState();
if (!s.assets.some((a) => a.id === assetId)) return NOT_PLACED;
s.addClipFromAsset(assetId); // lands at the end, selected
const sel = useEditor.getState().selection;
const clipId = sel?.kind === "clip" ? sel.id : null;
const count = useEditor.getState().clips.length;
const at = index === undefined ? count - 1 : clamp(Math.round(index), 0, count - 1);
if (clipId && at !== count - 1) s.moveClip(clipId, at);
return { added: true, clipId, index: at };
}
/** Start a video render — the shared shape of generate_video and
* generate_character_video: one job (and one chat card) spans the ladder's
* fallback rungs, the landed asset files under the asking chat, and it goes
* onto the timeline only when the model asked.
*
* Awaits the submission, not the render: it returns started:true only once the
* backend actually accepted the render, so the model can say it is underway. An
* instant reject — bad credentials, no credits, a bad request — settles the
* submit in well under a second and comes back started:false with the reason,
* so the model reports the failure instead of narrating a clip that never
* started. `success.note` overrides the default "rendering" line; `success.extra`
* merges caller facts (the designed still, the character) into either outcome. */
async function launchVideoJob(
projectId: string,
input: Record<string, unknown>,
attempts: VideoAttempt[],
success?: { note?: string; extra?: Record<string, unknown> }
) {
const addToTimeline = wantsTimeline(input, "index");
const index = promptedIndex(input);
// Captured now: the render must file under the chat that asked, even if
// the user switches threads before it lands. Ownership rides the job from
// creation, so neither the job row nor the landed asset ever touches the
// Video panel — including a render that errors and lands no asset.
const chatId = chatOwner();
const { jobId, submitted } = useGenerate.getState().generateVideoLadder(projectId, attempts, {
...(chatId ? { chatId } : {}),
onDone: (asset) => {
if (addToTimeline) addVideoTrackClip(asset.id, index);
},
});
const extra = success?.extra ?? {};
const outcome = await submitted;
if (!outcome.ok) {
return {
kind: "video",
started: false,
jobId,
...extra,
error: outcome.error,
note: `The render didn't start — ${outcome.error} Tell the user it failed; don't say it's rendering.`,
};
}
return {
kind: "video",
started: true,
jobId,
addToTimeline,
...extra,
note:
success?.note ??
("Rendering — it previews in this chat when it lands, in a minute or two" +
(addToTimeline
? ", and goes onto the timeline."
: ". It stays in the chat until the user places it.")),
};
}
/** Sanitize an overlay-element patch from tool input: shared fields (timing,
* position, rotation, opacity, hidden) plus the target kind's own fields.
* Outline width is em for text (scales with the type) and design px for
* shapes, so the interpretation follows the element being patched. */
/** A shutter from a call: `shutter` (0 or less turns it off), or
* `motion_blur` true for the current one or the default, false for off;
* neither keeps `current`. */
function shutterInput(input: Record<string, unknown>, current: number | undefined): number | undefined {
if (isNum(input.shutter)) return input.shutter > 0 ? clamp(input.shutter, SHUTTER_MIN, SHUTTER_MAX) : undefined;
if (input.motion_blur === true) return current ?? CUT_MOTION.motionBlur;
if (input.motion_blur === false) return undefined;
return current;
}
/** A key's ease from a call: a known curve, or linear (no ease) for
* "linear" and anything else. */
function easeInput(v: unknown) {
if (!isEaseId(v)) throw new ToolError("ease must be one of the listed curves.");
return v === "linear" ? undefined : v;
}
/** A shadow from a call, or null when the call leaves it alone: `shadow`
* false turns it off (as `off`), true turns it on, and any shadow_* field
* lands on top of the current one. Example: shadow_color "#00E5FF" with
* shadow_y 0 is a cyan glow. */
function shadowInput(
input: Record<string, unknown>,
current: boolean | ShadowSpec | undefined,
off: false | undefined
): { value: boolean | ShadowSpec | undefined } | null {
if (input.shadow === false) {
return { value: off };
}
const tuned =
typeof input.shadow_color === "string" || isNum(input.shadow_blur) || isNum(input.shadow_opacity) || isNum(input.shadow_y);
if (!tuned) {
return input.shadow === true ? { value: current || true } : null;
}
// Tuning starts from the current spec, or the default look when it is off.
const spec: ShadowSpec = typeof current === "object" ? { ...current } : {};
if (typeof input.shadow_color === "string") {
if (!HEX_COLOR.test(input.shadow_color)) {
throw new ToolError("shadow_color is a hex color like #00E5FF.");
}
spec.color = input.shadow_color;
}
if (isNum(input.shadow_blur)) {
spec.blur = clamp(input.shadow_blur, 0, SHADOW_BLUR_MAX);
}
if (isNum(input.shadow_opacity)) {
spec.opacity = clamp(input.shadow_opacity, 0, 1);
}
if (isNum(input.shadow_y)) {
spec.offsetY = clamp(input.shadow_y, -SHADOW_OFFSET_MAX, SHADOW_OFFSET_MAX);
}
return { value: spec };
}
/** Six-digit hex, the form a shadow color is stored in. */
const HEX_COLOR = /^#[0-9a-fA-F]{6}$/;
/** A shape's pattern from a call, or null when the call leaves it alone:
* "none" clears it, a kind or any pattern_* field lands on the current one. */
function patternInput(
input: Record<string, unknown>,
current: PatternSpec | undefined
): { value: PatternSpec | undefined } | null {
if (input.pattern === "none") {
return { value: undefined };
}
if (input.pattern !== undefined && !(PATTERN_KINDS as readonly unknown[]).includes(input.pattern)) {
throw new ToolError(`pattern is one of ${[...PATTERN_KINDS, "none"].join(", ")}.`);
}
const tuned = isNum(input.pattern_width) || isNum(input.pattern_gap) || isNum(input.pattern_angle);
if (input.pattern === undefined && !tuned) {
return null;
}
// Stripes are the one kind today; fields land on the current pattern.
const spec: PatternSpec = { ...(current ?? STRIPES_DEFAULT) };
if (isNum(input.pattern_width)) {
spec.width = clamp(input.pattern_width, STRIPE_LINE_MIN, STRIPE_LINE_MAX);
}
if (isNum(input.pattern_gap)) {
spec.gap = clamp(input.pattern_gap, 0, STRIPE_GAP_MAX);
}
if (isNum(input.pattern_angle)) {
spec.angle = Math.round(clamp(input.pattern_angle, -90, 90)) || undefined;
}
return { value: spec };
}
/**
* The settings an effect of this kind takes from a tool call: a light leak's
* course, a glitch's pinned kind, a flash's tone, strobe rate, rhythm and
* fade. Only the keys the call names come back, each as the value to store
* (undefined clears it back to the default); a setting the effect doesn't
* take is skipped. Shared by add_effect and update_overlay.
*/
function effectSettings(effect: EffectId, input: Record<string, unknown>): Partial<EffectOverlay> {
const patch: Partial<EffectOverlay> = {};
// A light leak's course: drift is the default and stores as absence.
if (effect === "lightleak" && input.leak !== undefined) {
if (!(LEAK_COURSES as readonly unknown[]).includes(input.leak))
throw new ToolError(`leak is one of ${LEAK_COURSES.join(", ")}.`);
patch.leak = input.leak === "drift" ? undefined : (input.leak as LeakCourse);
}
// A glitch pinned to one kind; the random mix stores as absence.
if (effect === "glitch" && input.glitch !== undefined) {
if (!(GLITCH_KINDS as readonly unknown[]).includes(input.glitch)) {
throw new ToolError(`glitch is one of ${GLITCH_KINDS.join(", ")}.`);
}
patch.glitch = input.glitch as GlitchKind;
}
// A negative strobes at a rate; none flips the whole element.
if (effect === "negative" && isNum(input.rate)) patch.rate = input.rate > 0 ? clamp(input.rate, FLASH_RATE_MIN, FLASH_RATE_MAX) : undefined;
if (effect !== "flash") return patch;
// A flash's tone and strobe: white and a single pop store as absence.
if (input.tone !== undefined) {
if (!(FLASH_TONES as readonly unknown[]).includes(input.tone)) {
throw new ToolError(`tone is one of ${FLASH_TONES.join(", ")}.`);
}
patch.tone = input.tone === "black" ? "black" : undefined;
}
if (isNum(input.rate)) patch.rate = input.rate > 0 ? clamp(input.rate, FLASH_RATE_MIN, FLASH_RATE_MAX) : undefined;
if (input.rhythm !== undefined) patch.rhythm = flashRhythm(input.rhythm);
// A fade of none is the pop again, and stores as absence.
if (input.fade !== undefined) {
if (!(FLASH_FADE_CHOICES as readonly unknown[]).includes(input.fade)) {
throw new ToolError(`fade is one of ${FLASH_FADE_CHOICES.join(", ")}.`);
}
patch.fade = input.fade === FLASH_FADE_NONE ? undefined : (input.fade as FlashFade);
}
if (input.fade_ease !== undefined) patch.fadeEase = fadeEaseOf(input.fade_ease);
return patch;
}
function overlayPatch(
input: Record<string, unknown>,
kind: "text" | "shape" | "sticker" | "effect",
place?: { groupId?: string; shadow?: boolean | ShadowSpec; pattern?: PatternSpec }
) {
const patch: Record<string, unknown> = {};
if (isNum(input.start)) patch.start = onFrame(Math.max(0, input.start));
if (isNum(input.end)) patch.end = onFrame(input.end);
if (isNum(input.lane)) patch.lane = Math.max(0, Math.round(input.lane));
if (isNum(input.x)) patch.x = clampOverlayPos(input.x, place);
if (isNum(input.y)) patch.y = clampOverlayPos(input.y, place);
if (isNum(input.rotation))
patch.rotation = degInput(input.rotation) || undefined;
if (isNum(input.opacity))
patch.opacity = input.opacity >= 0.995 ? undefined : clamp(input.opacity, 0, 1);
if (kind !== "effect") {
if (isNum(input.blur)) patch.blur = input.blur <= 0.05 ? undefined : clamp(input.blur, 0, ELEMENT_BLUR_MAX);
if (isNum(input.shutter) || typeof input.motion_blur === "boolean") patch.motionBlur = shutterInput(input, undefined);
}
if (typeof input.hidden === "boolean") patch.hidden = input.hidden || undefined;
if (typeof input.name === "string") patch.name = input.name.trim().slice(0, 60) || undefined;
if (kind === "text") {
// A literal backslash-n in the call is always a meant newline — models
// double-escape multi-line titles.
if (typeof input.text === "string" && input.text.trim())
patch.text = input.text.replace(/\\n/g, "\n");
if (isNum(input.size)) patch.size = clamp(Math.round(input.size), TEXT_SIZE_MIN, TEXT_SIZE_MAX);
if (typeof input.color === "string") patch.color = input.color;
// Only ids the registry knows: an unknown one is refused, since it would
// render the default face and leave the Inspector's font menu blank.
if (input.font !== undefined) {
patch.font = knownFont(input.font);
}
if (isTextWeight(input.weight)) patch.weight = input.weight;
if (typeof input.italic === "boolean") patch.italic = input.italic || undefined;
if (["left", "center", "right"].includes(String(input.align)))
patch.align = input.align === "center" ? undefined : input.align;
if (isNum(input.letter_spacing))
patch.letterSpacing = Math.abs(input.letter_spacing) < 0.0025 ? undefined : clamp(input.letter_spacing, LETTER_SPACING_MIN, LETTER_SPACING_MAX);
if (isNum(input.line_height))
patch.lineHeight = Math.abs(input.line_height - 1.25) < 0.01 ? undefined : clamp(input.line_height, 0.7, 2.5);
if (isNum(input.wrap_width))
patch.wrapWidth = input.wrap_width <= 0 ? undefined : clamp(input.wrap_width, 0.01, 2);
const shadow = shadowInput(input, place?.shadow, false);
if (shadow) {
patch.shadow = shadow.value;
}
if (typeof input.plate === "boolean") patch.plate = input.plate;
// A texture names one of the kit's grains; "none" stores as absence.
if (input.texture === "none") {
patch.texture = undefined;
} else if ((TEXT_TEXTURES as readonly unknown[]).includes(input.texture)) {
patch.texture = input.texture;
} else if (input.texture !== undefined) {
throw new ToolError(`texture is one of ${[...TEXT_TEXTURES, "none"].join(", ")}.`);
}
if (isNum(input.plateRadius)) patch.plateRadius = clamp(input.plateRadius, 0, 1);
if (typeof input.stroke_color === "string" || isNum(input.stroke_width)) {
const width = isNum(input.stroke_width) ? clamp(input.stroke_width, 0, 0.3) : 0.04;
patch.stroke =
width > 0
? { color: typeof input.stroke_color === "string" ? input.stroke_color : "#111114", width }
: undefined;
}
return patch;
}
if (kind === "shape") {
if (isNum(input.w)) patch.w = clamp(input.w, 0.01, 2);
if (isNum(input.h)) patch.h = clamp(input.h, 0.002, 2);
if (typeof input.fill === "string") patch.fill = input.fill;
if (isNum(input.fill_opacity))
patch.fillOpacity = input.fill_opacity >= 0.995 ? undefined : clamp(input.fill_opacity, 0, 1);
if (isNum(input.radius)) patch.radius = clamp(input.radius, 0, 200) || undefined;
if (typeof input.stroke_color === "string" || isNum(input.stroke_width)) {
const width = isNum(input.stroke_width) ? clamp(input.stroke_width, 0, 60) : 6;
patch.stroke =
width > 0
? { color: typeof input.stroke_color === "string" ? input.stroke_color : "#111114", width }
: undefined;
}
const pattern = patternInput(input, place?.pattern);
if (pattern) {
patch.pattern = pattern.value;
}
// A doodle's inks replace the list whole; an empty list leaves the fill
// as its one paint.
if (input.inks !== undefined) {
const inks = cleanInks(input.inks);
patch.inks = inks.length > 0 ? inks : undefined;
}
const shadow = shadowInput(input, place?.shadow, undefined);
if (shadow) {
patch.shadow = shadow.value;
}
return patch;
}
if (kind === "effect") {
if (isNum(input.amount)) patch.amount = clamp(input.amount, 0.05, 1);
return patch;
}
if (isNum(input.w)) patch.w = clamp(input.w, STICKER_W_MIN, 1.5);
// A sticker's height is its own once set; 0 hands it back to the source's
// aspect.
if (isNum(input.h)) patch.h = input.h > 0 ? clamp(input.h, STICKER_W_MIN, 1.5) : undefined;
return patch;
}