fablecut 1.13.0 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/mcp-server.js CHANGED
@@ -7,11 +7,11 @@
7
7
  or, from a clone:
8
8
  claude mcp add -s user fablecut -- node "<path-to>/fablecut/mcp-server.js"
9
9
 
10
- Tools: fablecut_status, fablecut_docs, fablecut_get_project,
11
- fablecut_set_project, fablecut_patch_project, fablecut_import_media,
12
- fablecut_analyze_reference, fablecut_encode_profiles,
13
- fablecut_normalize_audio, fablecut_auto_duck, fablecut_export,
14
- fablecut_scopes
10
+ Tools: fablecut_status, fablecut_docs, fablecut_get_project,
11
+ fablecut_set_project, fablecut_patch_project, fablecut_import_media,
12
+ fablecut_analyze_reference, fablecut_frame, fablecut_encode_profiles,
13
+ fablecut_normalize_audio, fablecut_auto_duck, fablecut_export,
14
+ fablecut_scopes
15
15
  ═══════════════════════════════════════════════════════════════════════════ */
16
16
  "use strict";
17
17
  const fs = require("fs");
@@ -21,15 +21,25 @@ const { spawn, spawnSync } = require("child_process");
21
21
  const { loadEncodeProfiles, listProfilesPublic, resolveProfile, profileSummary } = require("./encode-profiles");
22
22
 
23
23
  const {
24
- APP_DIR, DATA_DIR, MEDIA_DIR, EXPORTS_DIR, ANALYSIS_DIR, LIBRARY_DIR, PROJECT_FILE, ensureDirs,
24
+ APP_DIR, DATA_DIR, MEDIA_DIR, EXPORTS_DIR, ANALYSIS_DIR, LIBRARY_DIR, PROJECT_FILE, PROXIES_DIR, ensureDirs, readSaved, writeSaved,
25
25
  } = require("./paths");
26
26
  const { downloadImportUrl, kindFromName, maybeFaststart } = require("./import-url");
27
27
  const FX = require("./audio-fx");
28
28
  const EditOps = require("./edit-ops");
29
+ const ProjectOps = require("./project-ops");
29
30
  const Denoise = require("./denoise");
30
31
  const Color = require("./color");
32
+ const FrameStats = require("./frame-stats");
31
33
  const Mask = require("./mask");
32
34
  const Tracker = require("./tracker");
35
+ const Motion = require("./motion");
36
+ const CompLib = require("./comp");
37
+ const Templates = require("./templates");
38
+ const Delivery = require("./delivery");
39
+ const { probeFile, infoForEntry } = require("./media-probe");
40
+ const { findProxies } = require("./proxy");
41
+ /** The user's saved presets / templates (library/presets, library/templates), validated; bad files skipped. */
42
+ const savedItems = (kind) => readSaved(kind).map((x) => (kind === "presets" ? Templates.normalizePreset(x.data) : Templates.normalizeTemplate(x.data))).filter(Boolean);
33
43
 
34
44
  /* ROOT is where the code lives (server.js, CLAUDE.md); the user's timeline and
35
45
  media live under DATA_DIR. Identical unless FABLECUT_DATA_DIR is set. */
@@ -72,10 +82,11 @@ function httpOk(url) {
72
82
  req.setTimeout(1200, () => { req.destroy(); resolve(false); });
73
83
  });
74
84
  }
75
- /** JSON request to the editor server → {status, body}. */
76
- function apiJSON(method, urlPath, payload) {
85
+ /** JSON request to the editor server → {status, body}. Extra headers are for
86
+ * endpoints that gate on them — /api/frame?path= needs X-FableCut-Client. */
87
+ function apiJSON(method, urlPath, payload, headers) {
77
88
  return new Promise((resolve, reject) => {
78
- const req = http.request(API + urlPath, { method, headers: { "Content-Type": "application/json" } }, (r) => {
89
+ const req = http.request(API + urlPath, { method, headers: { "Content-Type": "application/json", ...headers } }, (r) => {
79
90
  let data = "";
80
91
  r.setEncoding("utf8");
81
92
  r.on("data", (d) => { data += d; });
@@ -92,6 +103,11 @@ function apiJSON(method, urlPath, payload) {
92
103
  }
93
104
  async function ensureUIServer() {
94
105
  if (await httpOk(API + "/api/project")) return true;
106
+ /* Tests (and nothing else) may set FABLECUT_NO_AUTOSTART=1: the auto-start
107
+ below spawns a detached server.js the test harness cannot stop — it
108
+ inherits the test's port and data dir and keeps running after the test.
109
+ With the flag set, report the missing server instead of starting one. */
110
+ if (process.env.FABLECUT_NO_AUTOSTART === "1") return false;
95
111
  spawn(process.execPath, [path.join(ROOT, "server.js")],
96
112
  { cwd: ROOT, detached: true, stdio: "ignore" }).unref();
97
113
  for (let i = 0; i < 12; i++) {
@@ -141,7 +157,7 @@ const TOOLS = [
141
157
  },
142
158
  {
143
159
  name: "fablecut_patch_project",
144
- description: "Apply targeted edits to the FableCut project WITHOUT round-tripping the whole document — PREFER THIS over get+set for every edit (it is ~10-100x cheaper in tokens and merge-safe by design: it re-reads the latest document from disk, applies your ops in order, bumps revision once, saves atomically). Ops: {op:'addClip', clip:{…}} (id auto-generated if omitted) · {op:'updateClip', id, set:{…}} · {op:'removeClip', id} · {op:'addMedia', media:{…}} · {op:'removeMedia', id} · {op:'setProject', set:{name|width|height|fps|background|markers|disabledTracks|lockedTracks|untargetedTracks|encodeProfile|master}} (markers = the full list [{t, label?, color?}], color: gold|red|orange|green|cyan|blue|purple|pink; master = {gain}, the master fader in dB) · {op:'setTrack', id:'A1', set:{gain?, pan?, out?}} (audio-track fader in dB −60…+12, pan −1…1, out = a submix bus id or 'master'; null or 0 resets) · {op:'setBus', id:'B1', set:{name?, gain?, pan?, mute?}} (submix bus, created if missing; route tracks into it with setTrack out) · {op:'removeBus', id} · {op:'setFx', target:'clip'|'track'|'bus'|'master', id?, preset?:'podcast'|… OR fx:[{type,…params}], append?:true} (audio effects — validated; presets: clean-voice, podcast, radio, deep-voice, telephone, cinematic, wide, muffled; fx:null clears; on a clip it applies to its linked stems too) · {op:'setFxKeys', target, id?, index?|type?, param, keys:[{t, v, ease?}]|null} (automate one effect parameter: t is clip-local for a clip's effects, timeline seconds otherwise; see the 'Audio mix' docs section) · {op:'setGrade', id | ids:[…], grade:{exposure?, temp?, tint?, lift?, gamma?, gain?, offset?, contrast?, pivot?, blacks?, shadows?, midtones?, highlights?, whites?, lowSoft?, highSoft?, saturation?, curves?:{y?, r?, g?, b?}, hueHue?, hueSat?, hueLuma?, satLuma?, layers?:[…], on?}, replace?:true} (color grade on video / image / svg / adjust clips — wheels are [r, g, b, master]; curves are [[x, y], …] point lists on 0…1 and merge per channel; hue curves are [[hue°, value], …] — one point = a ±40° band; layers replaces the whole layer list; merges key by key, null resets a key, replace:true starts from neutral, grade:null clears; see the 'Color' docs section; measure the result with fablecut_scopes) · {op:'setGradeLayer', id | ids, layer: index | 'name', set:{name?, on?, qualifier?:{hue?:[centre°, width°, soft°], sat?:[lo, hi, soft], luma?:[lo, hi, soft], invert?}, mask?:{shape:'ellipse'|'rect'|'poly', x, y, w, h, rotation?, feather?, invert?, points?, keys?:[{t, x?, y?, …}]}, …any grade key}, replace?:true, remove?:true} (a secondary: a grade applied only where the qualifier × mask select; a new name or index = length adds a layer; qualifier and mask merge key by key; check what it selects with fablecut_scopes matte:{clip, layer}) · {op:'setMask', id | ids, mask?: index | 'name', set:{shape?:'rect'|'ellipse'|'bezier'|'freehand', mode?:'add'|'subtract'|'intersect'|'difference', invert?, opacity?, feather? (px), expand? (px, − shrinks), x?, y? (centre, 0…1 of the clip's picture), w?, h?, scale?, rotation?, points?:[[dx, dy, inX?, inY?, outX?, outY?], …] (bezier, around x, y), stroke?:[[u, v], …] (freehand: fitted into a bezier), keys?:[{t, ease?, x?, y?, w?, h?, scale?, rotation?, feather?, expand?, opacity?, points?}], name?, on?}, replace?:true, remove?:true} (clip masks on video / image / svg / text / adjust clips: the clip shows only where its masks combine to, bottom-up; mask left out, an unknown name or index = length adds one — a new mask needs shape; set merges key by key; masks follow the clip's transform; check with fablecut_scopes mask:{clip}) · {op:'removeMask', id, mask} · {op:'setMaskKeys', id, mask, keys:[…]|null} (animate a mask; t = seconds from the clip's start) · {op:'setMatte', id | ids, matte:'alpha'|'alpha-inverted'|'luma'|'luma-inverted'|null, track?:'V3'|null} (track matte: the picture on the video track directly above — or track — cuts the clip by its alpha or its brightness, inverted or not; that track stops drawing while it is a matte; null clears). · {op:'removeTrack', id, track: name | index} (delete a motion track stored by fablecut_track; what follows it keeps its keys). props.blend: normal · multiply · screen · overlay · darken · lighten · color-dodge · color-burn · hard-light · soft-light · difference · exclusion · hue · saturation · color · luminosity · lighter. TIMELINE EDITS — the editor's own split / ripple / trim code, so linked stems, track targeting (untargetedTracks) and locks behave exactly as in the UI; times in seconds: {op:'split', at, ids?} (no ids: every targeted track) · {op:'rippleDelete', ids} (later clips close the hole) · {op:'closeGap', at} · {op:'lift'|'extract', from?, to?} (remove a range; extract closes it; default = project inPoint/outPoint, which then clear) · {op:'insert'|'overwrite', mediaId, at, in?, duration?} (three-point edit: insert pushes later clips right, overwrite replaces what is there; a video brings one audio stem per channel) · {op:'rippleTrim'|'roll', id, side:'in'|'out', delta} · {op:'slip'|'slide', id, delta} (clamped to the media; the note says what was applied) · {op:'crossfade', ids? | at, duration?} (constant-power audio crossfade, borrowing handles from both sides). Any of these takes tracks:[…] to target lanes for that op only. setProject also takes inPoint / outPoint. updateClip merge rules: top-level keys are replaced (keyframes/transitionIn/transitionOut wholesale), `props` merges key-by-key, and setting any key to null deletes it. LOCKS: the user can lock clips (`locked:true`) and tracks (`lockedTracks`); updateClip / removeClip on a locked clip — or on a clip linked to one — and addClip onto a locked track are refused. Leave locked material alone; only if the user asked you to change it, pass force:true on that op (or unlock first: updateClip set:{locked:null}, which is always allowed). All-or-nothing: an invalid op aborts the whole patch unsaved. Optional baseRevision: the revision your ops were planned against (from fablecut_get_project, fablecut_status or the previous patch result) — if the project has moved past it (e.g. the user edited in the UI meanwhile), the patch is refused with CONFLICT and the current revision, nothing saved; re-check the clips you touch, then retry with the new revision. Omit it to apply on top of whatever is latest.",
160
+ description: "Apply targeted edits to the FableCut project WITHOUT round-tripping the whole document — PREFER THIS over get+set for every edit (it is ~10-100x cheaper in tokens and merge-safe by design: it re-reads the latest document from disk, applies your ops in order, bumps revision once, saves atomically). Ops: {op:'addClip', clip:{…}} (id auto-generated if omitted) · {op:'updateClip', id, set:{…}} · {op:'removeClip', id} · {op:'addMedia', media:{…}} · {op:'removeMedia', id} · MEDIA BIN: {op:'updateMedia', id | ids, set:{name?, favorite?:true|false, tags?:[…], folderId?}, addTags?:[…], removeTags?:[…]} (organize media; fps, codec, audio channels and size are probed from the file and read-only) · {op:'setCollection', id?, name?, media?:[…ids] (replaces), add?:[…], remove?:[…]} (a collection groups media across folders; a new id or name creates it) · {op:'removeCollection', id} · {op:'relinkMedia', id, src:'/media/…'} (the same footage found elsewhere — an OFFLINE file in the compact view; clips keep their In points) · {op:'replaceMedia', id, src, name?} (a different file behind the media — every clip using it switches, keeping its timing, trimmed to fit a shorter file; import the new file first with fablecut_import_media) · {op:'setProject', set:{name|width|height|fps|background|markers|disabledTracks|lockedTracks|untargetedTracks|encodeProfile|delivery|outputs|master}} (markers = the full list [{t, label?, color?}], color: gold|red|orange|green|cyan|blue|purple|pink; master = {gain}, the master fader in dB; delivery = a delivery preset id or spec — see fablecut_export — that exports use by default; outputs = the batch list, [preset id | spec, …] up to 16, exported together by fablecut_export {outputs:true}) · {op:'setTrack', id:'A1', set:{gain?, pan?, out?}} (audio-track fader in dB −60…+12, pan −1…1, out = a submix bus id or 'master'; null or 0 resets) · {op:'setBus', id:'B1', set:{name?, gain?, pan?, mute?}} (submix bus, created if missing; route tracks into it with setTrack out) · {op:'removeBus', id} · {op:'setFx', target:'clip'|'track'|'bus'|'master', id?, preset?:'podcast'|… OR fx:[{type,…params}], append?:true} (audio effects — validated; presets: clean-voice, podcast, radio, deep-voice, telephone, cinematic, wide, muffled; fx:null clears; on a clip it applies to its linked stems too) · {op:'setFxKeys', target, id?, index?|type?, param, keys:[{t, v, ease?}]|null} (automate one effect parameter: t is clip-local for a clip's effects, timeline seconds otherwise; see the 'Audio mix' docs section) · {op:'setGrade', id | ids:[…], grade:{exposure?, temp?, tint?, lift?, gamma?, gain?, offset?, contrast?, pivot?, blacks?, shadows?, midtones?, highlights?, whites?, lowSoft?, highSoft?, saturation?, curves?:{y?, r?, g?, b?}, hueHue?, hueSat?, hueLuma?, satLuma?, layers?:[…], on?}, replace?:true} (color grade on video / image / svg / adjust clips — wheels are [r, g, b, master]; curves are [[x, y], …] point lists on 0…1 and merge per channel; hue curves are [[hue°, value], …] — one point = a ±40° band; layers replaces the whole layer list; merges key by key, null resets a key, replace:true starts from neutral, grade:null clears; see the 'Color' docs section; measure the result with fablecut_scopes) · {op:'setGradeLayer', id | ids, layer: index | 'name', set:{name?, on?, qualifier?:{hue?:[centre°, width°, soft°], sat?:[lo, hi, soft], luma?:[lo, hi, soft], invert?}, mask?:{shape:'ellipse'|'rect'|'poly', x, y, w, h, rotation?, feather?, invert?, points?, keys?:[{t, x?, y?, …}]}, …any grade key}, replace?:true, remove?:true} (a secondary: a grade applied only where the qualifier × mask select; a new name or index = length adds a layer; qualifier and mask merge key by key; check what it selects with fablecut_scopes matte:{clip, layer}) · {op:'setMask', id | ids, mask?: index | 'name', set:{shape?:'rect'|'ellipse'|'bezier'|'freehand', mode?:'add'|'subtract'|'intersect'|'difference', invert?, opacity?, feather? (px), expand? (px, − shrinks), x?, y? (centre, 0…1 of the clip's picture), w?, h?, scale?, rotation?, points?:[[dx, dy, inX?, inY?, outX?, outY?], …] (bezier, around x, y), stroke?:[[u, v], …] (freehand: fitted into a bezier), keys?:[{t, ease?, x?, y?, w?, h?, scale?, rotation?, feather?, expand?, opacity?, points?}], name?, on?}, replace?:true, remove?:true} (clip masks on video / image / svg / text / adjust clips: the clip shows only where its masks combine to, bottom-up; mask left out, an unknown name or index = length adds one — a new mask needs shape; set merges key by key; masks follow the clip's transform; check with fablecut_scopes mask:{clip}) · {op:'removeMask', id, mask} · {op:'setMaskKeys', id, mask, keys:[…]|null} (animate a mask; t = seconds from the clip's start) · {op:'setMatte', id | ids, matte:'alpha'|'alpha-inverted'|'luma'|'luma-inverted'|null, track?:'V3'|null} (track matte: the picture on the video track directly above — or track — cuts the clip by its alpha or its brightness, inverted or not; that track stops drawing while it is a matte; null clears). · {op:'removeTrack', id, track: name | index} (delete a motion track stored by fablecut_track; what follows it keeps its keys). MOTION GRAPHICS: a shape layer is addClip {kind:'shape', track, start, duration, props:{shapes:[…]}} (no mediaId); a null is addClip {kind:'null', …} — invisible, a parent for other clips. {op:'setShape', id | ids, shape?: index | 'name' | '2.0' (path into a group), set:{type?:'rect'|'ellipse'|'polygon'|'star'|'line'|'path'|'group', name?, on?, x?, y? (px from the layer's origin), rotation?, scale?, opacity?, w?, h?, radius? (rect corners), sides?, inner? (star 0.05…1), points?:[[x, y, inX?, inY?, outX?, outY?], …] (line: 2, path: 2…128, px around x, y), closed? (path), fill?, stroke? ('#rrggbb' | '#rrggbbaa' | 'none'), strokeWidth?, lineCap?, lineJoin?, dash?:[on, off…], trimStart?, trimEnd? (0…100 — a draw-on), trimOffset?, items?:[…] (group), keys?:[{t, ease?, …any of x y rotation scale opacity w h radius inner strokeWidth trimStart trimEnd trimOffset fill stroke points}]}, replace?:true, remove?:true} (shape left out, an unknown name or index = length adds one — a new shape needs type; set merges key by key) · {op:'removeShape', id, shape} · {op:'setParent', id | ids, parent: clip id | null, keep?: true, at?} (the clip moves, turns and scales with its parent; keep:true — the default — keeps it where it is at time at, default its start; opacity and effects are not inherited). COMPOSITIONS (nested sequences): project.comps = [{id, name, width, height, duration, background?, tracks?, clips:[…]}]; a clip {kind:'comp', compId, start, in, duration} places one (draws like a picture of the comp's size — transform, masks, grade, blend, blur all apply — and its media plays and exports). {op:'addComp', comp:{id?, name, duration, width?, height?, background?, clips?:[…]}} · {op:'updateComp', id, set:{name?, width?, height?, duration?, background?, tracks?}} · {op:'removeComp', id} (refused while used) · {op:'precompose', ids:[…], name?, id?} (the clips move into a new comp; a comp clip takes their place) · {op:'inComp', comp, ops:[…]} (run clip and timeline ops on the comp's own clips — addClip, updateClip, setShape, split, …; nests). PRESETS AND TEMPLATES: {op:'applyPreset', id | ids, preset, length?, at?} keys a named animation onto visual clips, relative to where they sit (in: fade-in, pop-in, slide-up-in, slide-down-in, slide-left-in, slide-right-in, drop-in, zoom-in, spin-in, whip-in, rise-blur, draw-on · out: fade-out, pop-out, slide-up-out, slide-down-out, slide-left-out, slide-right-out, zoom-out, spin-out, whip-out, sink-blur, draw-off · at (an emphasis at timeline time at): pulse, shake, wobble, bounce, flash · loop (the whole clip): float, breathe, sway, spin, wiggle — or a saved one, or an inline {anchor:'in'|'out'|'at'|'whole', length, keys:{channel:[{t, v, ease?}]}} where scale / opacity multiply and the rest add). {op:'addTemplate', template, start?, track?, duration?, fields?:{key: value}, id?, compId?, name?} places a template as its own comp + a comp clip (lower-third-bar, lower-third-underline, lower-third-boxes [name, title, accent…] · logo-ring, logo-slam, logo-lines [logo = a media id, brand / tagline, accent] · social-story 1080x1920, social-quote 1080x1080, social-end-card [text fields, accent, background]); {op:'setTemplate', id: its clip or comp, fields?, duration?} changes the fields or the length (the exit keeps its timing). {op:'savePreset', id, name, anchor?} / {op:'saveTemplate', comp, name?, fields?} save to library/presets and library/templates for every project.MOTION PATHS: x and y keyed at the same time are a position key; curve handles pin / pout (px) on those x and y keys bend the path between keys ({op:'setMotionPath', id | ids, path:'smooth'|'straight', autoOrient?:bool} sets them for you; props.autoOrient turns the clip along its path). props.motionBlur = shutter angle 0…720 (180 = film look), props.motionBlurSamples 2…32. TEXT ON A PATH: {op:'setTextPath', id | ids, path:'line'|'arc'|'circle'|'wave'|{type:'path'|'line'|'ellipse'|'rect'|'polygon'|'star', …shape item geometry, keys?}|null, offset? (% along, keyable as pathOffset), align?:'start'|'center'|'end'} — the title runs along the path (more lines on parallel curves below it), every textAnim plays along it. Every visual clip also has props.anchorX / anchorY (px from its picture's centre: the point x / y place and rotation / scale turn around) and shape clips props.trimStart / trimEnd / trimOffset (trim every path in the layer) — all keyframable. props.blend: normal · multiply · screen · overlay · darken · lighten · color-dodge · color-burn · hard-light · soft-light · difference · exclusion · hue · saturation · color · luminosity · lighter. TIMELINE EDITS — the editor's own split / ripple / trim code, so linked stems, track targeting (untargetedTracks) and locks behave exactly as in the UI; times in seconds: {op:'split', at, ids?} (no ids: every targeted track) · {op:'rippleDelete', ids} (later clips close the hole) · {op:'closeGap', at} · {op:'lift'|'extract', from?, to?} (remove a range; extract closes it; default = project inPoint/outPoint, which then clear) · {op:'insert'|'overwrite', mediaId, at, in?, duration?} (three-point edit: insert pushes later clips right, overwrite replaces what is there; a video brings one audio stem per channel) · {op:'rippleTrim'|'roll', id, side:'in'|'out', delta} · {op:'slip'|'slide', id, delta} (clamped to the media; the note says what was applied) · {op:'crossfade', ids? | at, duration?} (constant-power audio crossfade, borrowing handles from both sides). Any of these takes tracks:[…] to target lanes for that op only. setProject also takes inPoint / outPoint. updateClip merge rules: top-level keys are replaced (keyframes/transitionIn/transitionOut wholesale), `props` merges key-by-key, and setting any key to null deletes it. LOCKS: the user can lock clips (`locked:true`) and tracks (`lockedTracks`); updateClip / removeClip on a locked clip — or on a clip linked to one — and addClip onto a locked track are refused. Leave locked material alone; only if the user asked you to change it, pass force:true on that op (or unlock first: updateClip set:{locked:null}, which is always allowed). All-or-nothing: an invalid op aborts the whole patch unsaved. Optional baseRevision: the revision your ops were planned against (from fablecut_get_project, fablecut_status or the previous patch result) — if the project has moved past it (e.g. the user edited in the UI meanwhile), the patch is refused with CONFLICT and the current revision, nothing saved; re-check the clips you touch, then retry with the new revision. Omit it to apply on top of whatever is latest.",
145
161
  inputSchema: {
146
162
  type: "object",
147
163
  properties: {
@@ -170,6 +186,26 @@ const TOOLS = [
170
186
  required: ["project"],
171
187
  },
172
188
  },
189
+ {
190
+ name: "fablecut_frame",
191
+ description: "LOOK at the footage — returns an actual image, not just numbers. REQUIRES A VISION-CAPABLE MODEL: if you cannot read images, pass `text:true` instead (or skip this tool and use fablecut_analyze_reference). Three modes. (1) One frame of a source clip: pass `path` (an absolute file path, or a '/media/…' src — read where it lies, never copied) and `t` in seconds. (2) A contact sheet: pass `frames` (2–60) for one grid image with that many moments spread across the clip (`from`/`to` to survey part of it) — the cheap way to see what a whole clip holds. (3) With no `path`, `time` renders the COMPOSED TIMELINE at that moment through the editor's own compositor, graded and multi-track, exactly as export would. Use it before choosing a clip's `in` point, or to pick footage matching a blueprint's shots[] energy — seeing beats guessing. Needs ffmpeg on PATH (timeline mode runs in the open editor tab, else a headless browser).",
192
+ inputSchema: {
193
+ type: "object",
194
+ properties: {
195
+ path: { type: "string", description: "Source clip to look at: an absolute file path or a '/media/…' src. Read in place — nothing is copied into media/. Omit to render the timeline instead." },
196
+ t: { type: "number", description: "Seconds into the source clip (default 0). Ignored when `frames` is passed." },
197
+ time: { type: "number", description: "TIMELINE seconds to render, when `path` is omitted (default: the editor's playhead)" },
198
+ frames: { type: "number", description: "Contact-sheet mode: number of moments to sample across the clip, 2–60 (default 12)" },
199
+ cols: { type: "number", description: "Contact-sheet columns (omit for the squarest layout — 6 frames give 3×2, 12 give 4×3)" },
200
+ from: { type: "number", description: "Contact sheet: start of the range to survey (default 0)" },
201
+ to: { type: "number", description: "Contact sheet: end of the range (default: the clip's duration)" },
202
+ width: { type: "number", description: "Pixel width of the returned image (default 768 for one frame, 320 per cell for a sheet)" },
203
+ text: { type: "boolean", description: "Return TEXT measurements instead of the image, for a client or model that cannot see one: brightness and luma levels, dominant named colours with their share, texture (detail within the frame, 0–100), and for a contact sheet a per-cell line with change-since-the-previous-cell. Measurements, NOT a caption — they say what the picture is made of, never what is in it. Use when you have no vision." },
204
+ where: { type: "string", enum: ["auto", "tab", "headless"], description: "Timeline mode only: auto (default): an open editor tab, else headless · tab · headless" },
205
+ timeout: { type: "number", description: "Timeline mode: seconds to wait for the render (default 60)" },
206
+ },
207
+ },
208
+ },
173
209
  {
174
210
  name: "fablecut_analyze_reference",
175
211
  description: "Analyze a reference video into an EDIT BLUEPRINT so a similar edit can be rebuilt with different footage over the same music. Returns: shot boundaries (cuts) with per-shot audio energy, music beats + BPM, a loudness curve, the detected drop, and extracts the reference's music track into media/ (registered in the project, ready to place on A1). Remake recipe: copy the reference's width/height/fps to the project, write `beats` into project `markers`, lay the extracted music on A1, then place one clip per blueprint `shot` at the same start/duration — pick calm footage for low-energy shots and action for high-energy ones, and make the biggest moment land on `drop`. See the 'Remake a reference video' section of fablecut_docs.",
@@ -194,12 +230,13 @@ const TOOLS = [
194
230
  },
195
231
  {
196
232
  name: "fablecut_encode_profiles",
197
- description: "List ffmpeg encoding profiles for Fast export (from encoding-profiles.json). Each profile is a raw ffmpeg argument list plus jpegQuality, extension, and optional color (output matrix/range — default BT.709 tv). Use to pick a profile id for project.encodeProfile. Edit encoding-profiles.json on disk to add custom profiles — anything the local ffmpeg supports works, and the server hot-reloads the file. Profiles are dry-run against ffmpeg when an export starts, so a bad argument is rejected before rendering.",
233
+ description: "List what fablecut_export can make. DELIVERY PRESETS (structured settings, the Export dialog's Preset list): youtube, youtube-shorts, instagram-reels, tiktok, x, linkedin, master (project size), broadcast (ProRes 422 HQ), web (720p), archive (lossless FFV1), custom — plus presets the user saved — each a spec of resolution, fps, codec (h264, hevc, av1, vp9, prores, dnxhr, mpeg2 XDCAM, ffv1), rate control (crf / vbr / cbr), keyframe interval, pixel format, color, container, audio, a file-name template and metadata. {preset:'youtube'} returns one preset's full spec; the encoders this ffmpeg can use are listed (hardware ones only when they work on this machine). ENCODING PROFILES (encoding-profiles.json): raw ffmpeg argument lists plus jpegQuality, extension and color, for anything the presets do not cover; edit the file on disk (hot-reloaded); {profile:'hq'} returns one, detail:true includes every args array. Both are dry-run against ffmpeg when an export starts, so bad settings are refused before rendering.",
198
234
  inputSchema: {
199
235
  type: "object",
200
236
  properties: {
201
- detail: { type: "boolean", description: "Include the full ffmpeg args array per profile (default: a truncated summary)" },
202
- profile: { type: "string", description: "Return one profile by id instead of the full list" },
237
+ detail: { type: "boolean", description: "Include the full ffmpeg args array per encoding profile (default: a truncated summary)" },
238
+ profile: { type: "string", description: "Return one encoding profile by id instead of the full list" },
239
+ preset: { type: "string", description: "Return one delivery preset's full spec (youtube, broadcast, a saved preset id …)" },
203
240
  },
204
241
  },
205
242
  },
@@ -247,6 +284,21 @@ const TOOLS = [
247
284
  required: ["clipIds"],
248
285
  },
249
286
  },
287
+ {
288
+ name: "fablecut_proxy",
289
+ description: "Proxies: light H.264 copies (540p by default, 720p or 1080p; never larger than the source) of heavy footage — 4K, HEVC, ProRes, long phone clips — that the editor plays while the user edits, so playback and scrubbing stay smooth. Export, fablecut_frame, fablecut_scopes and every measurement always read the original, so a proxy never changes the result. Without create or delete it reports each video's proxy (ready, being made with its progress, failed, none). create:true makes them (one at a time, in the background on the server) and waits until they are done unless wait:false; delete:true removes them. mediaIds defaults to every video in the project. The user turns proxy playback on or off with the monitor's Proxy button. Needs ffmpeg on PATH.",
290
+ inputSchema: {
291
+ type: "object",
292
+ properties: {
293
+ mediaIds: { type: "array", items: { type: "string" }, description: "Video media ids (default: all video media)" },
294
+ create: { type: "boolean", description: "Make proxies for these files" },
295
+ delete: { type: "boolean", description: "Delete their proxies" },
296
+ height: { type: "number", enum: [540, 720, 1080], description: "Proxy height in pixels (default 540)" },
297
+ wait: { type: "boolean", description: "With create: wait until every proxy is done (default true)" },
298
+ timeout: { type: "number", description: "Seconds to wait with create (default 900)" },
299
+ },
300
+ },
301
+ },
250
302
  {
251
303
  name: "fablecut_export",
252
304
  description: "Render the timeline to a video file in exports/ — the editor's own Fast export (same compositor, audio mix and encoding profile as the Export button), so the file matches what the user sees. It runs in a browser: an open editor tab takes the job (the user sees the progress bar), or with no tab open the server starts headless Chrome / Edge (set FABLECUT_CHROME to pick one) and closes it afterwards. Waits for the file by default and returns its path. Range: the project's inPoint→outPoint when set, else the whole timeline (or pass range). Needs ffmpeg on PATH. One export at a time. Long edits: pass wait:false, then poll with {job}; {cancel:job} stops one.",
@@ -254,7 +306,10 @@ const TOOLS = [
254
306
  type: "object",
255
307
  properties: {
256
308
  range: { type: "string", enum: ["entire", "in-out"], description: "Whole timeline, or the project's inPoint→outPoint (default: in-out when either is set)" },
257
- profile: { type: "string", description: "Encoding profile id (fablecut_encode_profiles); default: project.encodeProfile, else the server default" },
309
+ preset: { type: "string", description: "Delivery preset: youtube, youtube-shorts, instagram-reels, tiktok, x, linkedin, master, broadcast, web, archive, custom, or a saved preset's id (fablecut_encode_profiles lists them). The output is reframed to the preset's size — cropped from the middle (or from the project's exportFrame), or padded with reframe:'fit'" },
310
+ delivery: { type: "object", description: "Delivery settings over the preset (or over custom): {width, height (null = the picture's size), fps (null = the project's), reframe:'fill'|'fit'|'stretch', container:'mp4'|'mov'|'mkv'|'webm'|'mxf', video:{codec:'h264'|'hevc'|'av1'|'vp9'|'prores'|'dnxhr'|'mpeg2'|'ffv1', encoder?, rate:'crf'|'vbr'|'cbr', crf, bitrate (kb/s), maxrate (kb/s), keyint (s), pixFmt, speed:'fast'|'balanced'|'best', profile (prores: proxy|lt|standard|hq|4444|4444xq · dnxhr: lb|sq|hq|hqx|444)}, audio:{codec:'aac'|'opus'|'mp3'|'pcm16'|'pcm24'|'flac'|'none', bitrate (kb/s), sampleRate, channels, loudness (LUFS target: -14 streaming/social, -16 podcast, -23 EBU R128, -24 ATSC; null = as mixed), truePeak (dBTP ceiling, default -1)}, color:'bt709'|'bt709-full'|'bt601-625'|'bt601-525', filename:'{project}_{preset}_{res}' (tokens {project} {preset} {res} {w} {h} {fps} {codec} {date} {time} {range} {n}), metadata:{title, artist, description, copyright, date, keywords}}. Anything left out comes from the preset; impossible combinations are corrected and the reply says how. Every finished file is checked against what was asked (size, fps, frames, codecs, length, loudness, true peak, file size) and the reply lists the checks" },
311
+ outputs: { description: "Several files, rendered once per frame rate (up to 8 outputs per render): true = the project's checked batch outputs (project.outputs, set with setProject {outputs:[…]}), or a list like [{preset:'master'}, {preset:'youtube'}, {preset:'instagram-reels'}, {preset:'custom', width:1080, height:1080, filename:'{project}_square_{res}'}, {preset:'web', filename:'{project}_preview_{res}'}]. Outputs with the same fps share one render; the reply lists every file", anyOf: [{ type: "boolean" }, { type: "array", items: { anyOf: [{ type: "string" }, { type: "object" }] } }] },
312
+ profile: { type: "string", description: "Encoding profile id (raw ffmpeg args, fablecut_encode_profiles) instead of a preset. With neither: project.delivery, else project.encodeProfile, else the server's default profile" },
258
313
  where: { type: "string", enum: ["auto", "tab", "headless"], description: "auto (default): an open editor tab, else headless · tab: only an open tab · headless: always a background browser, leaving the user's tab alone" },
259
314
  wait: { type: "boolean", description: "Block until the file is written (default true)" },
260
315
  timeout: { type: "number", description: "Seconds to wait before returning the job's status instead (default 900); the export keeps running" },
@@ -429,114 +484,6 @@ function normalizeGroups(proj, ids) {
429
484
  return [...groups.values()];
430
485
  }
431
486
 
432
- /* ── Timeline edits (patch ops split … crossfade) ──
433
- The editor's own edit code (edit-ops.js) run against the document, so an
434
- agent gets the same targeting (untargetedTracks, or the op's `tracks`), the
435
- same sync lock (linked partners ride along) and the same lock rules as the
436
- keyboard shortcuts. Returns a short note; throws to abort the patch. */
437
- const relinkedDocs = new WeakSet();
438
- function timelineEdit(proj, op, refuseLocked, lockReason) {
439
- const name = op.op;
440
- const E = EditOps.forDoc(proj, { tracks: op.tracks, force: op.force === true, uid: () => uid() });
441
- // Links are rebuilt from timing on every editor load; do the same once per
442
- // patch so clips an agent added (without linkGroup) ride along with their stems.
443
- if (!relinkedDocs.has(proj)) { E.relinkClips(); relinkedDocs.add(proj); }
444
- const r3 = (n) => Math.round(n * 1000) / 1000;
445
- const signed = (n) => (n > 0 ? "+" : "") + r3(n);
446
- const num = (v, what) => {
447
- if (typeof v !== "number" || !Number.isFinite(v)) throw new Error(`${name}: ${what} must be a number (seconds)`);
448
- return v;
449
- };
450
- const clipOf = (id) => {
451
- const c = proj.clips.find((x) => x.id === id);
452
- if (!c) throw new Error(`${name}: no clip ${id}`);
453
- return c;
454
- };
455
- const named = () => {
456
- if (!Array.isArray(op.ids) || !op.ids.length) throw new Error(`${name}: ids must list at least one clip`);
457
- const clips = op.ids.map(String).map(clipOf);
458
- for (const c of clips) refuseLocked(name, lockReason(c), op);
459
- return clips;
460
- };
461
- const refused = (why) => new Error(`${name}: ${why}` +
462
- (/locked/i.test(why) ? " — the user locked it; pass force:true only if they asked" : ""));
463
- const trimmed = (c, r, extra = "") => {
464
- if (typeof r === "string") throw refused(r);
465
- const asked = num(op.delta, "delta");
466
- return `${name} ${c.id}${extra} ${signed(r)}s` + (Math.abs(r - asked) > 1e-6 ? ` (asked ${signed(asked)}, clamped)` : "");
467
- };
468
- switch (name) {
469
- case "split": {
470
- const at = num(op.at, "at");
471
- const r = E.splitAt(at, op.ids ? named() : null);
472
- if (!r.split) throw refused(r.blocked ? "only locked clips under that time — left whole" : `no clip runs across ${at}s on the ${op.ids ? "given clips" : "targeted tracks"}`);
473
- return `split@${at} +${r.rights.map((x) => x.id).join("+")}` + (r.blocked ? " (locked clips left whole)" : "");
474
- }
475
- case "rippleDelete": {
476
- const r = E.rippleDelete(named());
477
- return `-${r.removed.map((x) => x.id).join("-")} (rippled)`;
478
- }
479
- case "closeGap": {
480
- const G = E.closeGapAt(num(op.at, "at"));
481
- if (typeof G === "string") throw refused(G.replace("at playhead", `at ${op.at}s`).replace("move the playhead", "pick another time"));
482
- return `closed ${r3(G)}s gap @${op.at}`;
483
- }
484
- case "lift": case "extract": {
485
- const usePoints = op.from == null && op.to == null;
486
- const t0 = op.from == null ? proj.inPoint : num(op.from, "from");
487
- const t1 = op.to == null ? proj.outPoint : num(op.to, "to");
488
- if (t0 == null || t1 == null) throw refused("give from and to (seconds), or set the project's inPoint and outPoint");
489
- const why = E.liftRange(t0, t1, name === "extract");
490
- if (why) throw refused(why.replace("Set IN and OUT first (I / O) to", "from→to must span more than a frame to"));
491
- if (usePoints) { delete proj.inPoint; delete proj.outPoint; } // as in the editor
492
- return `${name} ${r3(t0)}→${r3(t1)}s`;
493
- }
494
- case "rippleTrim": case "roll": {
495
- const c = clipOf(String(op.id));
496
- if (op.side !== "in" && op.side !== "out") throw new Error(`${name}: side must be "in" (head) or "out" (tail)`);
497
- const fn = name === "roll" ? E.rollEdit : E.rippleTrim;
498
- return trimmed(c, fn(c, op.side, num(op.delta, "delta")), "." + op.side);
499
- }
500
- case "slip": case "slide": {
501
- const c = clipOf(String(op.id));
502
- const fn = name === "slip" ? E.slipClip : E.slideClip;
503
- return trimmed(c, fn(c, num(op.delta, "delta")));
504
- }
505
- case "insert": case "overwrite": {
506
- const m = proj.media.find((x) => x.id === op.mediaId);
507
- if (!m) throw new Error(`${name}: unknown mediaId ${op.mediaId}`);
508
- const timed = m.kind === "video" || m.kind === "audio";
509
- const inn = op.in == null ? 0 : num(op.in, "in");
510
- if (inn < 0) throw new Error(`${name}: in must be ≥ 0`);
511
- const dur = op.duration != null ? num(op.duration, "duration")
512
- : timed && m.duration > 0 ? m.duration - inn : null;
513
- if (dur == null) throw new Error(`${name}: duration is required for ${timed ? "media with no known duration yet" : m.kind}`);
514
- if (!(dur >= EditOps.MIN_DUR)) throw new Error(`${name}: duration must be at least ${EditOps.MIN_DUR}s`);
515
- if (timed && m.duration > 0 && inn + dur > m.duration + 1e-3)
516
- throw new Error(`${name}: in + duration (${r3(inn + dur)}s) runs past the end of ${m.id} (${m.duration}s)`);
517
- let stems = 2;
518
- if (m.kind === "video") {
519
- try { const f = mediaFile(m.src); if (f) stems = probeChannels(f) || 0; } catch { /* no ffprobe: assume stereo */ }
520
- }
521
- const r = (name === "insert" ? E.insertAt : E.overwriteAt)(m, timed ? inn : 0, dur, num(op.at, "at"), stems);
522
- if (typeof r === "string") throw refused(r.replace(" — click a track name to target it (and unlock it)", " — every lane for it is untargeted or locked (pass tracks:[…])"));
523
- const placed = r.clip ? (r.clip.linkGroup ? proj.clips.filter((x) => x.linkGroup === r.clip.linkGroup) : [r.clip]) : [];
524
- return `${name}@${r3(r.at)} ` + placed.map((x) => `+${x.id}(${x.track})`).join("") + (name === "insert" ? ` · later clips moved +${r3(dur)}s` : "");
525
- }
526
- case "crossfade": {
527
- const dur = op.duration == null ? EditOps.CROSSFADE_DUR : num(op.duration, "duration");
528
- if (dur < EditOps.MIN_TRANS_DUR) throw new Error(`${name}: duration must be at least ${EditOps.MIN_TRANS_DUR}s`);
529
- const pairs = op.ids ? E.crossfadeCuts(E.withLinked(named())) : E.crossfadeCutsNear(num(op.at, "at"));
530
- if (!pairs.length) throw refused(op.ids ? "no audio cut next to those clips — they must touch or overlap on one track"
531
- : `no audio cut within 0.5s of ${op.at}s on the targeted audio tracks`);
532
- const { done, why } = E.crossfadePairs(pairs, dur);
533
- if (!done) throw refused(why.join(", "));
534
- return `crossfaded ${done} cut${done === 1 ? "" : "s"}` + (why.length ? ` (skipped: ${why.join(", ")})` : "");
535
- }
536
- }
537
- throw new Error("Unknown edit op " + name);
538
- }
539
-
540
487
  /* ── Noise reduction (fablecut_denoise) — denoise.js, as the editor's Noise control ── */
541
488
  async function denoiseTool(args) {
542
489
  const ids = Array.isArray(args.clipIds) ? args.clipIds.map(String) : [];
@@ -597,20 +544,71 @@ async function denoiseTool(args) {
597
544
  }
598
545
 
599
546
  /* ── Export (fablecut_export) ── */
547
+ /** Saved delivery presets (library/delivery/), as the server lists them. */
548
+ function savedDeliveryPresets() { return Delivery.savedPresets(readSaved("delivery")); }
600
549
  function describeExportJob(j) {
601
550
  const pct = Math.round((j.progress || 0) * 100);
602
551
  if (j.status === "done") {
603
552
  const file = path.join(EXPORTS_DIR, path.basename(decodeURIComponent(j.src || "")));
604
553
  let size = "";
605
554
  try { size = ` (${(fs.statSync(file).size / 1048576).toFixed(1)} MB)`; } catch {}
606
- return `Export ${j.id} done → ${file}${size}\nServed at ${BASE}${j.src}`;
555
+ const outs = j.result && Array.isArray(j.result.outputs) ? j.result.outputs : null;
556
+ if (outs && outs.length > 1) {
557
+ return `Export ${j.id} done — ${outs.filter((o) => o.ok).length} of ${outs.length} files:\n` + outs.map((o) => o.ok
558
+ ? `✓ ${path.join(EXPORTS_DIR, o.file)}${o.summary ? ` — ${o.summary}` : ""}${o.report ? `\n ${o.report.ok ? "checks passed" : "CHECK"}: ${o.report.line}` : ""}`
559
+ : `✗ ${o.file}: ${o.error}`).join("\n");
560
+ }
561
+ const rep = outs && outs[0] && outs[0].report;
562
+ return `Export ${j.id} done → ${file}${size}${j.result && j.result.summary ? `\n${j.result.summary}` : ""}` +
563
+ `${rep ? `\n${rep.ok ? "Checks passed" : "CHECK"}: ${rep.line}` : ""}\nServed at ${BASE}${j.src}`;
607
564
  }
608
565
  if (j.status === "failed" || j.status === "cancelled") return `Export ${j.id} ${j.status}: ${j.error || "no reason given"}`;
609
566
  return `Export ${j.id} ${j.status}${j.status === "running" ? ` — ${pct}%` : ""} (in ${j.via === "headless" ? "a headless browser" : "the open editor tab"}). ` +
610
567
  `Check again with fablecut_export {job:"${j.id}"}, or stop it with {cancel:"${j.id}"}.`;
611
568
  }
569
+ /* fablecut_proxy: the server makes proxies (proxy.js); this asks it, and waits. */
570
+ async function proxyTool(args) {
571
+ if (!(await ensureUIServer())) throw new Error(`the editor server is not running and could not be started on port ${PORT}`);
572
+ const proj = readProject();
573
+ const ids = Array.isArray(args.mediaIds) && args.mediaIds.length ? args.mediaIds : proj.media.filter((m) => m.kind === "video").map((m) => m.id);
574
+ const list = ids.map((id) => {
575
+ const m = proj.media.find((x) => x.id === id);
576
+ if (!m) throw new Error(`no media ${id}`);
577
+ if (m.kind !== "video") throw new Error(`${id} is ${m.kind === "audio" || m.kind === "image" ? "an" : "a"} ${m.kind} — only video gets a proxy`);
578
+ return m;
579
+ });
580
+ if (!list.length) return "No video in the project.";
581
+ const srcs = list.map((m) => m.src);
582
+ if (args.delete) {
583
+ const r = await apiJSON("POST", "/api/proxy/delete", { srcs });
584
+ if (r.status !== 200) throw new Error(r.body?.error || "delete failed");
585
+ return list.map((m) => `${m.id} "${m.name}": ${r.body.deleted[m.src] ? "proxy deleted" : "had no proxy"}`).join("\n");
586
+ }
587
+ let r = await apiJSON("POST", args.create ? "/api/proxy" : "/api/proxy/status", { srcs, height: args.height });
588
+ if (r.status !== 200) throw new Error(r.body?.error || `proxy request failed (${r.status})`);
589
+ let status = r.body.status;
590
+ const busy = () => Object.values(status).some((s) => s && (s.state === "queued" || s.state === "running"));
591
+ if (args.create && args.wait !== false) {
592
+ const deadline = Date.now() + 1000 * (Number.isFinite(args.timeout) && args.timeout > 0 ? args.timeout : 900);
593
+ while (busy() && Date.now() < deadline) {
594
+ await sleep(1000);
595
+ r = await apiJSON("POST", "/api/proxy/status", { srcs });
596
+ if (r.status === 200) status = r.body.status;
597
+ }
598
+ }
599
+ const line = (m) => {
600
+ const s = status[m.src];
601
+ if (!s) return `${m.id} "${m.name}": OFFLINE — the file is missing`;
602
+ if (s.state === "ready") return `${m.id} "${m.name}": proxy ready — ${s.width ? s.width + "×" + s.height : s.height + "p"}, ${(s.size / 1048576).toFixed(1)} MB (${s.src})`;
603
+ if (s.state === "running" || s.state === "queued") return `${m.id} "${m.name}": proxy ${s.state}${s.state === "running" ? ` ${Math.round(s.progress * 100)}%` : ""} (${s.height}p)`;
604
+ if (s.state === "failed") return `${m.id} "${m.name}": proxy FAILED — ${s.error}`;
605
+ return `${m.id} "${m.name}": no proxy${m.height ? ` (source ${m.width}×${m.height})` : ""}`;
606
+ };
607
+ return list.map(line).join("\n") + (busy() ? "\nStill working — call fablecut_proxy again (without create) to check." : "");
608
+ }
612
609
  async function exportTool(args) {
613
610
  if (!(await ensureUIServer())) throw new Error(`the editor server is not running and could not be started on port ${PORT}`);
611
+ let startNote = "";
614
612
  if (args.cancel) {
615
613
  const r = await apiJSON("POST", "/api/export/job/cancel?id=" + encodeURIComponent(args.cancel));
616
614
  if (r.status !== 200) throw new Error(r.body?.error || "cancel failed");
@@ -622,10 +620,11 @@ async function exportTool(args) {
622
620
  if (r.status !== 200) throw new Error(r.body?.error || "no such export job");
623
621
  job = r.body;
624
622
  } else {
625
- const r = await apiJSON("POST", "/api/export/request", { range: args.range, profile: args.profile, where: args.where || "auto" });
623
+ const r = await apiJSON("POST", "/api/export/request", { range: args.range, profile: args.profile, preset: args.preset, delivery: args.delivery, outputs: args.outputs, where: args.where || "auto" });
626
624
  if (r.status !== 200) throw new Error(r.body?.error || `export request failed (${r.status})`);
627
625
  job = r.body;
628
- if (args.wait === false) return describeExportJob(job);
626
+ if (job.notes && job.notes.length) startNote = `Settings adjusted: ${job.notes.join("; ")}\n`;
627
+ if (args.wait === false) return (job.delivery ? `Output: ${job.delivery}\n` : "") + startNote + describeExportJob(job);
629
628
  }
630
629
  const deadline = Date.now() + 1000 * (Number.isFinite(args.timeout) && args.timeout > 0 ? args.timeout : 900);
631
630
  while (job.status === "pending" || job.status === "running") {
@@ -636,32 +635,148 @@ async function exportTool(args) {
636
635
  if (r.status !== 200) throw new Error(r.body?.error || "lost track of the export job");
637
636
  job = r.body;
638
637
  }
639
- return describeExportJob(job);
638
+ return startNote + describeExportJob(job);
640
639
  }
641
640
 
642
- /* ── Scopes (fablecut_scopes): one graded still, measured in the editor ── */
643
- function describeScopes(j) {
644
- if (j.status !== "done") return `Scope reading ${j.id} ${j.status}${j.error ? ": " + j.error : ""}`;
645
- const r = j.result || {}, st = r.stats;
646
- if (!st) return `Frame at ${r.time}s is empty (nothing drawn).`;
647
- const L = st.luma, cast = st.cast;
648
- const lines = [
649
- `Frame at ${r.time}s (${r.frame?.w}x${r.frame?.h}):`,
650
- ` luma min ${L.min} · p1 ${L.p1} · median ${L.median} · mean ${L.mean} · p99 ${L.p99} · max ${L.max}`,
651
- ` clipped: black ${st.clipped.blackPct}% · white ${st.clipped.whitePct}%`,
652
- ` rgb mean [${st.rgbMean.join(", ")}] · saturation ${st.saturation}`,
653
- ` cast: ${cast.tone === "neutral" ? "neutral" : `${cast.tone} (hue ${cast.hue}°)`} · strength ${cast.strength}`,
654
- `On screen (bottom → top): ${(r.clips || []).map((c) => `${c.id} ${c.track} ${c.kind}${c.grade !== "neutral" ? " grade:" + c.grade : ""}${c.masks ? ` masks:[${c.masks}]` : ""}${c.matte ? ` matte:${c.matte}` : ""}${c.isMatte ? " (a matte — not drawn)" : ""}${c.blend ? " blend:" + c.blend : ""}`).join(" | ") || "nothing"}`,
655
- ];
656
- const m = r.matte;
657
- if (m) {
658
- lines.push(m.error ? `Matte ${m.clip} layer ${m.layer}: ${m.error}` : `Matte of ${m.clip} layer ${m.layer}: covers ${m.coverage}% of the clip's picture` +
659
- (m.selected ? ` · selected pixels: luma median ${m.selected.luma.median} (p1 ${m.selected.luma.p1}, p99 ${m.selected.luma.p99}) · rgb mean [${m.selected.rgbMean.join(", ")}] · saturation ${m.selected.saturation} · cast ${m.selected.cast.tone === "neutral" ? "neutral" : `${m.selected.cast.tone} (hue ${m.selected.cast.hue}°)`}` : " · nothing selected"));
641
+ /* ── Frames (fablecut_frame) ──
642
+ The tool is the only one that answers with an image, so it returns content
643
+ blocks rather than a string. Text comes FIRST: it carries the coordinates of
644
+ what is in the picture (src, timestamp, dimensions), which is the part an
645
+ agent would otherwise have to guess at, and it keeps the existing
646
+ content[0].text reading in the test harness valid. */
647
+
648
+ /** {mimeType, data:Buffer} → an MCP image content block. */
649
+ function imageBlock(mimeType, buf) {
650
+ return { type: "image", data: buf.toString("base64"), mimeType };
651
+ }
652
+ /** A data: URL from the compositor → an image content block, or null. */
653
+ function imageBlockFromDataUrl(url) {
654
+ const m = /^data:(image\/\w+);base64,(.+)$/.exec(String(url || ""));
655
+ return m ? { type: "image", data: m[2], mimeType: m[1] } : null;
656
+ }
657
+
658
+ /** Raw GET to the editor server → {status, headers, buffer}.
659
+ * Sends the MCP client header: /api/frame?path= only answers requests that
660
+ * carry it, so a web page in the user's browser can neither render frames of
661
+ * arbitrary files nor probe which ones exist. */
662
+ function apiBytes(urlPath) {
663
+ return new Promise((resolve, reject) => {
664
+ const req = http.request(API + urlPath, { method: "GET", headers: { "X-FableCut-Client": "mcp" } }, (r) => {
665
+ const chunks = [];
666
+ r.on("data", (c) => chunks.push(c));
667
+ r.on("end", () => resolve({ status: r.statusCode, headers: r.headers, body: Buffer.concat(chunks) }));
668
+ });
669
+ req.on("error", reject);
670
+ req.setTimeout(60_000, () => req.destroy(new Error("the editor server did not answer")));
671
+ req.end();
672
+ });
673
+ }
674
+
675
+ async function frameTool(args) {
676
+ /* Timeline mode: no path. The compositor lives in the browser, so this rides
677
+ the same job queue the scopes reading uses, with image:true. Text mode
678
+ needs no image at all here — the scopes reading already measures the frame,
679
+ and those numbers describe the composed picture. */
680
+ if (!args.path) {
681
+ if (!(await ensureUIServer())) throw new Error(`the editor server is not running and could not be started on port ${PORT}`);
682
+ const body = { where: args.where || "auto", image: true };
683
+ if (args.time != null) body.time = args.time;
684
+ const r = await apiJSON("POST", "/api/scopes/request", body);
685
+ if (r.status !== 200) throw new Error(r.body?.error || `frame request failed (${r.status})`);
686
+ let job = r.body;
687
+ const deadline = Date.now() + 1000 * (Number.isFinite(args.timeout) && args.timeout > 0 ? args.timeout : 60);
688
+ while (job.status === "pending" || job.status === "running") {
689
+ if (Date.now() > deadline) {
690
+ await apiJSON("POST", "/api/export/job/cancel?id=" + encodeURIComponent(job.id));
691
+ throw new Error("timed out waiting for the editor to render the frame");
692
+ }
693
+ await sleep(300);
694
+ const q = await apiJSON("GET", "/api/export/job?id=" + encodeURIComponent(job.id));
695
+ if (q.status !== 200) throw new Error(q.body?.error || "lost track of the frame render");
696
+ job = q.body;
697
+ }
698
+ if (job.status !== "done") throw new Error(`frame render ${job.status}: ${job.error || "no reason given"}`);
699
+ const res = job.result || {};
700
+ const onScreen = (res.clips || []).map((c) => `${c.id} ${c.track} ${c.kind}`).join(", ") || "nothing";
701
+ const head = `Timeline at ${res.time}s (${res.frame?.w}x${res.frame?.h}) — on screen: ${onScreen}`;
702
+
703
+ /* Text mode: the scopes reading measured this exact frame already, and its
704
+ numbers are the same family as the source-frame measurements — so a
705
+ text-only agent gets the composed picture described, not nothing. */
706
+ if (args.text) {
707
+ const st = res.stats, st_ = st ? describeScopeLines(st) : null;
708
+ return [{ type: "text", text: head + "\n" + (st_ || "The editor returned no measurements for this frame.") + "\n\n" + TEXT_ONLY_NOTE }];
709
+ }
710
+ const img = imageBlockFromDataUrl(res.image);
711
+ if (!img) throw new Error("the editor rendered the frame but could not encode it as an image (a cross-origin source taints the canvas)");
712
+ return [{ type: "text", text: head }, img];
713
+ }
714
+
715
+ /* Source mode: ffmpeg on the server. Looking must not have side effects, so
716
+ the file is read where it is — an absolute path is passed through as
717
+ `path`, and a /media/… or /library/… src is passed through as `src`. The
718
+ server never copies anything into media/ on our behalf. */
719
+ if (!(await ensureUIServer())) throw new Error(`the editor server is not running and could not be started on port ${PORT}`);
720
+ const raw = String(args.path);
721
+ const served = /^\/(media|library)\//i.test(raw);
722
+ // A served src is resolved by the server against its own data dir, which may
723
+ // be somewhere this process cannot see (FABLECUT_DATA_DIR) — so let it decide
724
+ // and report the 404. A filesystem path we can check ourselves is checked.
725
+ if (!served && (!fs.existsSync(raw) || !fs.statSync(raw).isFile()))
726
+ throw new Error("File not found: " + raw);
727
+
728
+ const q = new URLSearchParams(served ? { src: raw } : { path: path.resolve(raw) });
729
+ if (args.frames != null) {
730
+ q.set("frames", String(Math.round(Number(args.frames))));
731
+ // No cols → the server picks the squarest layout (6 frames give 3×2).
732
+ if (args.cols != null) q.set("cols", String(Math.round(Number(args.cols))));
733
+ if (args.from != null) q.set("from", String(args.from));
734
+ if (args.to != null) q.set("to", String(args.to));
735
+ q.set("w", String(args.width || 320));
736
+ } else {
737
+ q.set("t", String(Number.isFinite(args.t) ? args.t : 0));
738
+ q.set("w", String(args.width || 768));
739
+ }
740
+ if (args.quality != null) q.set("q", String(args.quality));
741
+
742
+ /* text mode asks the server for measurements instead of the picture, in the
743
+ one request — not the picture and then a second call for the numbers. */
744
+ if (args.text) {
745
+ q.set("text", "1");
746
+ const j = await apiJSON("GET", "/api/frame?" + q.toString(), undefined, { "X-FableCut-Client": "mcp" });
747
+ if (j.status !== 200) throw new Error(j.body?.error || `frame description failed (${j.status})`);
748
+ const st = j.body.stats, b = j.body;
749
+ const where = b.frames > 1
750
+ ? `${b.frames} moments across ${b.source || raw}, left→right then top→bottom, at ${(b.times || []).join("s, ")}s.`
751
+ : `Frame at ${(b.times || [])[0] ?? 0}s of ${b.source || raw}.`;
752
+ const body = !st
753
+ ? "The server returned no measurements for this frame (does it have a video track?)."
754
+ : b.frames > 1 ? FrameStats.gridLines(st).join("\n") : FrameStats.frameLines("Frame", st).join("\n");
755
+ return [{ type: "text", text: where + "\n" + body + "\n\n" + TEXT_ONLY_NOTE }];
660
756
  }
661
- const k = r.mask;
662
- if (k) lines.push(k.error ? `Masks of ${k.clip}: ${k.error}` : `Masks of ${k.clip} (${k.masks}): keep ${k.coverage}% of the clip's picture · the masked clip covers ${k.frameCoverage}% of the frame`);
663
- return lines.join("\n") + "\n" + JSON.stringify({ time: r.time, stats: st, ...(m ? { matte: m } : {}), ...(k ? { mask: k } : {}) });
757
+
758
+ const res = await apiBytes("/api/frame?" + q.toString());
759
+ if (res.status !== 200) {
760
+ let msg = `frame request failed (${res.status})`;
761
+ try { msg = JSON.parse(res.body.toString("utf8")).error || msg; } catch { /* not JSON */ }
762
+ throw new Error(msg);
763
+ }
764
+ const times = (res.headers["x-fablecut-frame-times"] || "").split(",").filter(Boolean);
765
+ const type = res.headers["content-type"] || "image/jpeg";
766
+ const source = decodeURI(res.headers["x-fablecut-frame-source"] || "") || raw;
767
+ const head = args.frames != null
768
+ ? `Contact sheet — ${times.length} moments across ${source}, left→right then top→bottom, at ${times.join("s, ")}s.`
769
+ : `Frame at ${times[0] ?? 0}s of ${source}.`;
770
+
771
+ if (res.body.length < 4 || res.body[0] !== 0xff || res.body[1] !== 0xd8)
772
+ throw new Error("the server did not return a JPEG");
773
+ return [{ type: "text", text: head }, imageBlock(type, res.body)];
664
774
  }
775
+
776
+ /* Appended to every text: true answer, because a measurement is not a caption:
777
+ it says what the picture is made of, never what is in it. */
778
+ const { TEXT_ONLY_NOTE, describeScopeLines, describeScopes } = ProjectOps;
779
+
665
780
  async function scopesTool(args) {
666
781
  if (!(await ensureUIServer())) throw new Error(`the editor server is not running and could not be started on port ${PORT}`);
667
782
  const body = { where: args.where || "auto" };
@@ -712,15 +827,7 @@ async function trackTool(args) {
712
827
  job = q.body;
713
828
  }
714
829
  if (job.status !== "done") throw new Error(`tracking ${job.status}: ${job.error || "no reason given"}`);
715
- const t = job.result || {};
716
- return [
717
- t.tracked ? `Tracked ${t.clip} "${t.track}" (${t.kind}) ${t.from}–${t.to} s: ${t.samples} samples, match quality min ${t.quality.min} · mean ${t.quality.mean}`
718
- : `Used the stored track "${t.track}" on ${t.clip} (${t.from}–${t.to} s, ${t.samples} samples)`,
719
- t.lostAt && t.lostAt.length ? `Lost the region at ${t.lostAt.join(", ")} s — the track stops there (pick a spot with more detail, or a larger region, and track on from there)` : "",
720
- t.cancelled ? "Cancelled — kept what was tracked so far." : "",
721
- t.applied ? `Applied → ${t.applied}` : "Stored only (apply it with apply:{mask} or apply:{clip}).",
722
- `Project revision ${t.revision}.`,
723
- ].filter(Boolean).join("\n");
830
+ return ProjectOps.describeTrack(job.result || {});
724
831
  }
725
832
 
726
833
  /* ── Tool implementations ── */
@@ -732,8 +839,12 @@ async function callTool(name, args, attempt = 0) {
732
839
  return exportTool(args);
733
840
  case "fablecut_scopes":
734
841
  return scopesTool(args);
842
+ case "fablecut_frame":
843
+ return frameTool(args);
735
844
  case "fablecut_denoise":
736
845
  return denoiseTool(args);
846
+ case "fablecut_proxy":
847
+ return proxyTool(args);
737
848
  case "fablecut_status": {
738
849
  const up = await ensureUIServer();
739
850
  const proj = readProject();
@@ -764,11 +875,26 @@ async function callTool(name, args, attempt = 0) {
764
875
  encLine = `Export profile: ${describe(pinned || cfg.default) || `server default "${cfg.default}"`}`;
765
876
  }
766
877
  } catch { encLine = "Export profile: (encoding-profiles.json unavailable)"; }
878
+ if (proj.delivery) {
879
+ try {
880
+ const { spec } = Delivery.normalize(proj.delivery, { presets: savedDeliveryPresets() });
881
+ encLine = `Export: project.delivery — ${spec.preset} · ${Delivery.describe(spec)} (fablecut_export uses it unless you pass profile or preset)`;
882
+ } catch { }
883
+ }
884
+ if (Array.isArray(proj.outputs) && proj.outputs.length) {
885
+ const on = proj.outputs.filter((o) => o.on !== false);
886
+ encLine += `\nBatch outputs (fablecut_export {outputs:true}): ${on.length} of ${proj.outputs.length} checked — ` +
887
+ on.map((o) => Delivery.projectFilename(o, proj)).join(", ");
888
+ }
767
889
  return [
768
890
  `Editor server: ${up ? "RUNNING — open " + BASE + " in a browser to watch edits live" : "FAILED TO START (check node / port " + PORT + ")"}`,
769
891
  `Project: "${proj.name}" — ${proj.width}x${proj.height} @ ${proj.fps}fps, ${proj.clips.length} clip(s), ${dur.toFixed(2)}s, revision ${proj.revision}`,
770
892
  encLine,
771
893
  `Registered media: ${cap(proj.media.map((m) => `${m.id} (${m.kind}, ${m.name}${m.duration ? ", " + m.duration + "s" : ""})`), 25).join("; ") || "none"}`,
894
+ ...(() => {
895
+ const off = proj.media.filter((m) => /^\/(media|library)\//.test(m.src || "") && !mediaFile(m.src));
896
+ return off.length ? [`OFFLINE media (file missing — find it and relinkMedia): ${cap(off.map((m) => `${m.id} ${m.src}`), 25).join("; ")}`] : [];
897
+ })(),
772
898
  `Files in media/: ${cap(files, 25).join(", ") || "none"}`,
773
899
  `Library assets (./library): ${libSummary}`,
774
900
  `Project file: ${PROJECT_FILE}`,
@@ -789,88 +915,10 @@ async function callTool(name, args, attempt = 0) {
789
915
  const doc = readProject();
790
916
  lastReadRevision = doc.revision || 0;
791
917
  if (!args.compact) return JSON.stringify(doc);
792
- // the UI persists default-valued props on every clip; hide them so the
793
- // compact view only shows what actually deviates
794
- const DEFAULTS = {
795
- x: 0, y: 0, scale: 1, rotation: 0, opacity: 1, volume: 1, pan: 0, speed: 1,
796
- gain: 0, channelMode: "stereo", duck: 0,
797
- blend: "normal", fit: "contain", cropL: 0, cropR: 0, cropT: 0, cropB: 0,
798
- cornerRadius: 0, flipH: false, flipV: false, filterPreset: "none",
799
- brightness: 100, contrast: 100, saturation: 100, hue: 0, temperature: 0,
800
- tint: 0, blur: 0, grayscale: 0, sepia: 0, invert: 0, vignette: 0,
801
- shake: 0, shakeSpeed: 8, rgbSplit: 0, grain: 0,
802
- chromaKey: "", chromaTolerance: 26, chromaSoftness: 12, bgRemove: false,
803
- text: "Title", fontSize: 72, color: "#ffffff", color2: "", font: "Segoe UI",
804
- bold: true, weight: 0, italic: false, uppercase: false, align: "center",
805
- letterSpacing: 0, lineHeight: 1.2, textShadow: 12, glow: 0, glowColor: "",
806
- strokeWidth: 0, strokeColor: "#000", bgColor: "#000", bgOpacity: 0,
807
- textAnim: "none", wordRate: 0.15, direction: "auto", boxW: 0, boxH: 0, boxFit: false, vAlign: "middle",
808
- };
809
- const hex = (v) => typeof v === "string" && /^#[0-9a-f]{3}$/i.test(v)
810
- ? "#" + [...v.slice(1)].map((c) => c + c).join("").toLowerCase()
811
- : (typeof v === "string" && /^#[0-9a-f]{6}$/i.test(v) ? v.toLowerCase() : v);
812
- const fmtProps = (o, kind) => {
813
- if (!o) return "";
814
- const kept = {};
815
- for (const [k, v] of Object.entries(o)) {
816
- if (kind !== "text" && k === "text" && v === "Title") continue;
817
- // Always keep pan on linked stems — pan:0 (center) is meaningful and
818
- // must not be stripped, or agents rebuilding from compact can lose it.
819
- if (k === "pan" && Number.isInteger(o.audioChannel) && o.audioChannel >= 0) {
820
- kept[k] = v;
821
- continue;
822
- }
823
- if (k === "masks" || k === "tracks") continue; // summarized below — point lists and samples are long
824
- if (hex(DEFAULTS[k]) !== hex(v)) kept[k] = v;
825
- }
826
- const masks = Mask.describe(Mask.normalizeMasks(o.masks)), tracks = Tracker.describe(Tracker.normalizeTracks(o.tracks));
827
- return (Object.keys(kept).length ? " " + JSON.stringify(kept) : "") + (masks ? ` [${masks}]` : "") + (tracks ? ` [tracks: ${tracks}]` : "");
828
- };
829
- // Mixer: only off-default faders / pans, so a fresh project adds no line.
830
- const signed = (v) => (v > 0 ? "+" : "") + v;
831
- const fxTag = (fx) => Array.isArray(fx) && fx.length ? ` fx:${FX.summarizeFx(fx)}` : "";
832
- const mixLine = (d) => {
833
- const parts = (Array.isArray(d.tracks) ? d.tracks : [])
834
- .filter((t) => t && (+t.gain || +t.pan || t.fx?.length || t.out))
835
- .map((t) => t.id + (t.out ? `→${t.out}` : "") + (+t.gain ? ` ${signed(+t.gain)}dB` : "") + (+t.pan ? ` pan:${+t.pan}` : "") + fxTag(t.fx));
836
- for (const b of Array.isArray(d.buses) ? d.buses : [])
837
- parts.push(`bus ${b.id}${b.name ? ` "${b.name}"` : ""}` + (+b.gain ? ` ${signed(+b.gain)}dB` : "") + (+b.pan ? ` pan:${+b.pan}` : "") +
838
- (b.mute ? " muted" : "") + fxTag(b.fx));
839
- if (d.master && (+d.master.gain || d.master.fx?.length))
840
- parts.push("master" + (+d.master.gain ? ` ${signed(+d.master.gain)}dB` : "") + fxTag(d.master.fx));
841
- return parts.length ? [`MIX: ${parts.join(" · ")}`] : [];
842
- };
843
- const lines = [
844
- `"${doc.name}" ${doc.width}x${doc.height}@${doc.fps} rev:${doc.revision}` +
845
- (doc.panSchema >= 1 ? " panSchema:1" : "") +
846
- (doc.background ? ` bg:${doc.background}` : "") +
847
- (doc.inPoint != null || doc.outPoint != null ? ` in/out:${doc.inPoint ?? "-"}→${doc.outPoint ?? "-"}` : "") +
848
- (doc.markers?.length ? ` markers:${doc.markers.length} [${doc.markers.slice(0, 12).map((m) => m.t).join(",")}${doc.markers.length > 12 ? ",…" : ""}]` : "") +
849
- (doc.lockedTracks?.length ? ` lockedTracks:[${doc.lockedTracks.join(",")}]` : "") +
850
- (doc.untargetedTracks?.length ? ` untargetedTracks:[${doc.untargetedTracks.join(",")}]` : "") +
851
- (doc.disabledTracks?.length ? ` disabledTracks:[${doc.disabledTracks.join(",")}]` : ""),
852
- ...mixLine(doc),
853
- `MEDIA (${doc.media.length}):`,
854
- ...doc.media.map((m) => ` ${m.id} ${m.kind} "${m.name}"${m.duration ? " " + m.duration + "s" : ""}` +
855
- (m.derivedFrom ? ` (${m.denoise ? "denoised " + m.denoise : "derived"} from ${m.derivedFrom})` : "")),
856
- `CLIPS (${doc.clips.length}), by track/time:`,
857
- ...doc.clips
858
- .slice()
859
- .sort((a, b) => (a.track === b.track ? a.start - b.start : String(a.track).localeCompare(b.track)))
860
- .map((c) => {
861
- const kf = c.keyframes ? " kf:" + Object.entries(c.keyframes).map(([k, v]) => `${k}(${v.length})`).join(",") : "";
862
- const tr = (c.transitionIn ? ` in:${c.transitionIn.type}/${c.transitionIn.duration}` : "") +
863
- (c.transitionOut ? ` out:${c.transitionOut.type}/${c.transitionOut.duration}` : "");
864
- const r3 = (n) => Math.round(n * 1000) / 1000;
865
- return ` ${c.id} ${c.track} ${r3(c.start)}s+${r3(c.duration)}s ${c.kind}` +
866
- (c.mediaId ? `(${c.mediaId}${c.in ? ` in:${r3(c.in)}` : ""})` : "") +
867
- (c.name ? ` "${c.name}"` : "") + fmtProps(c.props, c.kind) + kf + tr +
868
- (c.locked === true ? " [locked]" : "") + (c.disabled === true ? " [disabled]" : "") +
869
- (c.unlinked === true ? " [unlinked]" : "") + fxTag(c.fx);
870
- }),
871
- `(compact view — full JSON: fablecut_get_project without compact; edit via fablecut_patch_project)`,
872
- ];
873
- return lines.join("\n");
918
+ return ProjectOps.compactView(doc, {
919
+ offline: (m) => /^\/(media|library)\//.test(m.src || "") && !mediaFile(m.src),
920
+ proxy: (m) => { const f = mediaFile(m.src); const p = f && findProxies(PROXIES_DIR, f)[0]; return p ? p.height : null; },
921
+ });
874
922
  }
875
923
  case "fablecut_patch_project": {
876
924
  if (!Array.isArray(args.ops) || !args.ops.length) throw new Error("`ops` must be a non-empty array");
@@ -887,414 +935,13 @@ async function callTool(name, args, attempt = 0) {
887
935
  `Re-read the clips you touch (fablecut_get_project {compact:true}), then retry with baseRevision:${rev} — ` +
888
936
  `or omit baseRevision to apply on top of the latest anyway.`);
889
937
  if (base != null && readRev !== base) throw conflict(readRev);
890
- const notes = [];
891
- // Locks mirror the editor: a clip is locked by its own flag or its track,
892
- // and a linked A/V group with any locked member is locked as a whole.
893
- const lockedTracks = () => new Set(Array.isArray(proj.lockedTracks) ? proj.lockedTracks : []);
894
- const lockReason = (c) => {
895
- const group = c.linkGroup ? proj.clips.filter((x) => x.linkGroup === c.linkGroup) : [c];
896
- for (const x of group) {
897
- const who = x.id === c.id ? `clip ${c.id}` : `clip ${c.id} is linked to ${x.id}, which`;
898
- if (x.locked === true) return `${who} is locked`;
899
- if (lockedTracks().has(x.track)) return `${who} is on locked track ${x.track}`;
900
- }
901
- return null;
902
- };
903
- const refuseLocked = (opName, reason, op) => {
904
- if (reason && op.force !== true)
905
- throw new Error(`${opName}: ${reason} — the user locked it. Leave it alone, or pass force:true if they asked you to change it`);
906
- };
907
- /* The effect chain an op names: a clip (and its linked stems), an
908
- A-track, a submix bus or the master → {label, read(), write(list)}. */
909
- const fxTarget = (op, name) => {
910
- const target = op.target || (op.id && /^A\d+$/.test(op.id) ? "track" : op.id && /^B\d+$/.test(op.id) ? "bus" : op.id ? "clip" : "master");
911
- if (target === "clip") {
912
- const c = proj.clips.find((x) => x.id === op.id);
913
- if (!c) throw new Error(`${name}: no clip ${op.id}`);
914
- if (c.kind !== "audio") throw new Error(`${name}: clip ${op.id} is ${c.kind} — effects go on audio clips (a video's sound is on its linked A-track clips)`);
915
- refuseLocked(name, lockReason(c), op);
916
- const group = c.linkGroup ? proj.clips.filter((x) => x.linkGroup === c.linkGroup && x.kind === "audio") : [c];
917
- return { label: group.map((x) => x.id).join("+"), read: () => c.fx, write(next) {
918
- for (const x of group) { if (next.length) x.fx = next.map((e) => JSON.parse(JSON.stringify(e))); else delete x.fx; }
919
- } };
920
- }
921
- if (target === "track") {
922
- if (!/^A\d+$/.test(String(op.id || ""))) throw new Error(`${name}: track id must be an audio track (A1, A2, …)`);
923
- if (!Array.isArray(proj.tracks) || !proj.tracks.length) proj.tracks = DEFAULT_TRACKS.map((t) => ({ ...t }));
924
- let t = proj.tracks.find((x) => x.id === op.id);
925
- if (!t) { t = { id: op.id, kind: "audio" }; proj.tracks.push(t); }
926
- return { label: op.id, read: () => t.fx, write(next) { if (next.length) t.fx = next; else delete t.fx; } };
927
- }
928
- if (target === "bus") {
929
- const b = (proj.buses || []).find((x) => x.id === op.id);
930
- if (!b) throw new Error(`${name}: no bus ${JSON.stringify(op.id)} — create it with {op:"setBus", id:"B1"}`);
931
- return { label: op.id, read: () => b.fx, write(next) { if (next.length) b.fx = next; else delete b.fx; } };
932
- }
933
- if (target === "master") {
934
- return { label: "master", read: () => proj.master?.fx, write(next) {
935
- const m = proj.master && typeof proj.master === "object" ? proj.master : {};
936
- if (next.length) m.fx = next; else delete m.fx;
937
- if (Object.keys(m).length) proj.master = m; else delete proj.master;
938
- } };
939
- }
940
- throw new Error(`${name}: target must be clip, track, bus or master`);
941
- };
942
- const mergeInto = (target, set) => {
943
- for (const [k, v] of Object.entries(set || {})) {
944
- if (v === null) delete target[k];
945
- else if (k === "props" && target.props && typeof v === "object" && !Array.isArray(v)) {
946
- for (const [pk, pv] of Object.entries(v)) {
947
- if (pv === null) delete target.props[pk]; else target.props[pk] = pv;
948
- }
949
- } else target[k] = v;
950
- }
951
- };
952
- // props.masks written wholesale (addClip / updateClip) is validated like setMask
953
- const checkMasks = (c, label) => {
954
- if (!c.props || c.props.masks == null) return;
955
- if (c.kind === "audio") throw new Error(`${label}: masks go on video, image, svg, text or adjust clips`);
956
- let n;
957
- try { n = Mask.normalizeMasks(c.props.masks, true); } catch (err) { throw new Error(`${label}: props.${err.message}`); }
958
- if (n) c.props.masks = n; else delete c.props.masks;
959
- };
960
- // props.tracks written wholesale is validated too (the editor writes them; agents rarely should)
961
- const checkTracks = (c, label) => {
962
- if (!c.props || c.props.tracks == null) return;
963
- if (c.kind !== "video") throw new Error(`${label}: tracks belong to video clips`);
964
- let n;
965
- try { n = Tracker.normalizeTracks(c.props.tracks, true); } catch (err) { throw new Error(`${label}: props.${err.message}`); }
966
- if (n) c.props.tracks = n; else delete c.props.tracks;
967
- };
968
- // blend / matte / matteTrack: checked when the op writes them
969
- const videoTrackIds = () => {
970
- const ids = (Array.isArray(proj.tracks) && proj.tracks.length ? proj.tracks : DEFAULT_TRACKS).filter((t) => t.kind === "video").map((t) => t.id);
971
- for (const x of proj.clips) if (/^V\d+$/.test(x.track) && !ids.includes(x.track)) ids.push(x.track);
972
- return ids;
973
- };
974
- const checkCompositing = (c, label, props) => {
975
- if (!props || !["blend", "matte", "matteTrack"].some((k) => props[k] != null)) return;
976
- if (c.kind === "audio") throw new Error(`${label}: blend and track mattes go on video, image, svg, text or adjust clips`);
977
- try { Mask.checkCompositing(c.props, videoTrackIds(), c.track, true); } catch (err) { throw new Error(`${label}: props.${err.message}`); }
978
- if (!c.props.matte) delete c.props.matteTrack;
979
- };
980
- for (const op of ops) {
981
- switch (op.op) {
982
- case "addClip": {
983
- const c = op.clip;
984
- if (!c || !c.track || typeof c.start !== "number" || typeof c.duration !== "number")
985
- throw new Error("addClip needs clip{track, start, duration}");
986
- c.id = c.id || "c_" + uid();
987
- if (proj.clips.some((x) => x.id === c.id)) throw new Error("addClip: duplicate clip id " + c.id);
988
- refuseLocked("addClip", lockedTracks().has(c.track) ? `track ${c.track} is locked` : null, op);
989
- if (c.kind !== "text" && c.kind !== "adjust" && !proj.media.some((m) => m.id === c.mediaId))
990
- throw new Error(`addClip: unknown mediaId ${c.mediaId}`);
991
- checkMasks(c, "addClip");
992
- checkTracks(c, "addClip");
993
- checkCompositing(c, "addClip", c.props);
994
- proj.clips.push(c);
995
- notes.push("+" + c.id);
996
- break;
997
- }
998
- case "updateClip": {
999
- const c = proj.clips.find((x) => x.id === op.id);
1000
- if (!c) throw new Error("updateClip: no clip " + op.id);
1001
- // Toggling the lock itself is always allowed — that's how you unlock.
1002
- const onlyLock = Object.keys(op.set || {}).every((k) => k === "locked");
1003
- if (!onlyLock) {
1004
- refuseLocked("updateClip", lockReason(c), op);
1005
- if (op.set && op.set.track && lockedTracks().has(op.set.track))
1006
- refuseLocked("updateClip", `track ${op.set.track} is locked`, op);
1007
- }
1008
- mergeInto(c, op.set);
1009
- checkMasks(c, "updateClip");
1010
- if (op.set && op.set.props && "tracks" in op.set.props) checkTracks(c, "updateClip");
1011
- // a track move re-checks the matte too (a clip can't be its own matte)
1012
- checkCompositing(c, "updateClip", op.set && op.set.track ? c.props : op.set && op.set.props);
1013
- if (c.props && c.props.matteTrack && !c.props.matte) delete c.props.matteTrack; // matte:null clears its track too
1014
- notes.push("~" + op.id);
1015
- break;
1016
- }
1017
- case "removeClip": {
1018
- const doomed = proj.clips.find((x) => x.id === op.id);
1019
- if (doomed) refuseLocked("removeClip", lockReason(doomed), op);
1020
- const n = proj.clips.length;
1021
- proj.clips = proj.clips.filter((x) => x.id !== op.id);
1022
- if (proj.clips.length === n) throw new Error("removeClip: no clip " + op.id);
1023
- notes.push("-" + op.id);
1024
- break;
1025
- }
1026
- case "addMedia": {
1027
- const m = op.media;
1028
- if (!m || !m.src || !m.kind) throw new Error("addMedia needs media{src, kind}");
1029
- m.id = m.id || "m_" + uid();
1030
- if (proj.media.some((x) => x.id === m.id)) throw new Error("addMedia: duplicate media id " + m.id);
1031
- m.name = m.name || path.basename(decodeURIComponent(m.src));
1032
- proj.media.push(m);
1033
- notes.push("+" + m.id);
1034
- break;
1035
- }
1036
- case "removeMedia": {
1037
- const used = proj.clips.find((c) => c.mediaId === op.id);
1038
- if (used) throw new Error(`removeMedia: media ${op.id} is used by clip ${used.id}`);
1039
- const n = proj.media.length;
1040
- proj.media = proj.media.filter((x) => x.id !== op.id);
1041
- if (proj.media.length === n) throw new Error("removeMedia: no media " + op.id);
1042
- notes.push("-" + op.id);
1043
- break;
1044
- }
1045
- case "setFx": {
1046
- // {op:"setFx", target:"clip"|"track"|"bus"|"master", id?, fx?:[…] | preset?:"podcast", append?:true}
1047
- const t = fxTarget(op, "setFx");
1048
- let chain;
1049
- if (op.preset != null) chain = FX.presetChain(String(op.preset));
1050
- else if (op.fx === null) chain = [];
1051
- else chain = FX.normalizeFx(op.fx, true);
1052
- t.write(op.append ? [...FX.normalizeFx(t.read()), ...chain] : chain);
1053
- notes.push("~" + t.label + ".fx");
1054
- break;
1055
- }
1056
- case "setFxKeys": {
1057
- // {op:"setFxKeys", target, id?, index?|type?, param, keys:[{t, v, ease?}] | null}
1058
- const t = fxTarget(op, "setFxKeys");
1059
- const list = FX.normalizeFx(t.read()).map((e) => ({ ...e }));
1060
- let i = Number.isInteger(op.index) ? op.index : op.type != null ? list.findIndex((e) => e.type === op.type) : list.length === 1 ? 0 : -1;
1061
- if (!list[i]) throw new Error(`setFxKeys: pick the effect with index (0…${list.length - 1}) or type — ${t.label} has ${FX.summarizeFx(list) || "no effects"}`);
1062
- const e = list[i];
1063
- if (!FX.FX_DEFS[e.type].params[op.param]) throw new Error(`setFxKeys: ${e.type} has no parameter ${JSON.stringify(op.param)} (has: ${Object.keys(FX.FX_DEFS[e.type].params).join(", ")})`);
1064
- const keys = { ...(e.keys || {}) };
1065
- if (op.keys == null || (Array.isArray(op.keys) && !op.keys.length)) delete keys[op.param];
1066
- else Object.assign(keys, FX.normalizeKeys(e.type, { [op.param]: op.keys }, true) || {});
1067
- if (Object.keys(keys).length) e.keys = keys; else delete e.keys;
1068
- t.write(list);
1069
- notes.push(`~${t.label}.fx[${i}].${op.param}` + (keys[op.param] ? `(${keys[op.param].length} keys)` : "(keys cleared)"));
1070
- break;
1071
- }
1072
- case "setGrade": {
1073
- // {op:"setGrade", id | ids, grade:{…} | null, replace?:true}
1074
- const ids = Array.isArray(op.ids) ? op.ids : op.id != null ? [op.id] : [];
1075
- if (!ids.length) throw new Error("setGrade needs id or ids");
1076
- if (op.grade !== null && (typeof op.grade !== "object" || Array.isArray(op.grade)))
1077
- throw new Error("setGrade needs grade:{…} (or grade:null to clear)");
1078
- if (op.grade) Color.normalizeGrade(Object.fromEntries(Object.entries(op.grade).filter(([, v]) => v !== null)), true); // validate first
1079
- for (const id of ids) {
1080
- const c = proj.clips.find((x) => x.id === id);
1081
- if (!c) throw new Error("setGrade: no clip " + id);
1082
- if (!["video", "image", "svg", "adjust"].includes(c.kind)) throw new Error(`setGrade: ${id} is a ${c.kind} clip — grades go on video, image, svg or adjust clips`);
1083
- refuseLocked("setGrade", lockReason(c), op);
1084
- const next = op.grade === null ? null : Color.mergeGrade(op.replace ? null : c.props?.grade, op.grade, true);
1085
- c.props = c.props || {};
1086
- if (next) c.props.grade = next; else delete c.props.grade;
1087
- notes.push(`~${id}.grade(${Color.summarizeGrade(next)})`);
1088
- }
1089
- break;
1090
- }
1091
- case "setGradeLayer": {
1092
- // {op:"setGradeLayer", id | ids, layer: index | "name", set?:{…}, replace?:true, remove?:true}
1093
- const ids = Array.isArray(op.ids) ? op.ids : op.id != null ? [op.id] : [];
1094
- if (!ids.length) throw new Error("setGradeLayer needs id or ids");
1095
- const byName = typeof op.layer === "string" && op.layer.trim() !== "";
1096
- if (!byName && !(Number.isInteger(op.layer) && op.layer >= 0)) throw new Error("setGradeLayer needs layer: an index (0 = first) or a layer name");
1097
- if (!op.remove && (op.set == null || typeof op.set !== "object" || Array.isArray(op.set))) throw new Error("setGradeLayer needs set:{…} (or remove:true)");
1098
- for (const id of ids) {
1099
- const c = proj.clips.find((x) => x.id === id);
1100
- if (!c) throw new Error("setGradeLayer: no clip " + id);
1101
- if (!["video", "image", "svg", "adjust"].includes(c.kind)) throw new Error(`setGradeLayer: ${id} is a ${c.kind} clip — grades go on video, image, svg or adjust clips`);
1102
- refuseLocked("setGradeLayer", lockReason(c), op);
1103
- const layers = (c.props?.grade?.layers || []).map((l) => ({ ...l }));
1104
- let i = byName ? layers.findIndex((l) => l.name === op.layer.trim()) : op.layer;
1105
- if (op.remove) {
1106
- if (i < 0 || i >= layers.length) throw new Error(`setGradeLayer: ${id} has no layer ${JSON.stringify(op.layer)}`);
1107
- layers.splice(i, 1);
1108
- } else {
1109
- if (i < 0 || i === layers.length) { // a new layer
1110
- if (layers.length >= Color.MAX_LAYERS) throw new Error(`setGradeLayer: at most ${Color.MAX_LAYERS} layers`);
1111
- i = layers.length; layers.push({ name: byName ? op.layer.trim() : `Layer ${i + 1}` });
1112
- } else if (i > layers.length) throw new Error(`setGradeLayer: ${id} has ${layers.length} layer(s) — use layer:${layers.length} to add one`);
1113
- const base = op.replace ? { name: layers[i].name } : layers[i];
1114
- let next;
1115
- try { next = Color.mergeLayer(base, op.set, true); } catch (err) { throw new Error(`setGradeLayer: ${err.message.replace(/^grade\.layers\[0\]\.?/, "")}`); }
1116
- if (!next.name) next.name = layers[i].name || `Layer ${i + 1}`;
1117
- layers[i] = next;
1118
- }
1119
- const g = Color.mergeGrade(c.props?.grade, { layers: layers.length ? layers : null }, true);
1120
- c.props = c.props || {};
1121
- if (g) c.props.grade = g; else delete c.props.grade;
1122
- notes.push(`~${id}.grade(${Color.summarizeGrade(g)})`);
1123
- }
1124
- break;
1125
- }
1126
- case "setMask":
1127
- case "removeMask":
1128
- case "setMaskKeys": {
1129
- // {op:"setMask", id | ids, mask?: index | "name", set:{…}, replace?:true, remove?:true}
1130
- // {op:"removeMask", id | ids, mask} · {op:"setMaskKeys", id | ids, mask, keys:[…] | null}
1131
- const name = op.op;
1132
- const ids = Array.isArray(op.ids) ? op.ids : op.id != null ? [op.id] : [];
1133
- if (!ids.length) throw new Error(`${name} needs id or ids`);
1134
- const remove = name === "removeMask" || op.remove === true;
1135
- const byName = typeof op.mask === "string" && op.mask.trim() !== "";
1136
- if (op.mask != null && !byName && !(Number.isInteger(op.mask) && op.mask >= 0)) throw new Error(`${name}: mask is an index (0 = first) or a mask name`);
1137
- if ((remove || name === "setMaskKeys") && op.mask == null) throw new Error(`${name} needs mask: an index or a name`);
1138
- let set;
1139
- if (name === "setMaskKeys") {
1140
- if (op.keys !== null && !Array.isArray(op.keys)) throw new Error("setMaskKeys needs keys:[{t, x?, y?, …}] (or keys:null to stop animating)");
1141
- set = { keys: op.keys && op.keys.length ? op.keys : null };
1142
- } else if (!remove) {
1143
- if (op.set == null || typeof op.set !== "object" || Array.isArray(op.set)) throw new Error("setMask needs set:{shape?, x?, y?, …} (or remove:true)");
1144
- set = op.set;
1145
- }
1146
- for (const id of ids) {
1147
- const c = proj.clips.find((x) => x.id === id);
1148
- if (!c) throw new Error(`${name}: no clip ${id}`);
1149
- if (c.kind === "audio") throw new Error(`${name}: ${id} is an audio clip — masks go on video, image, svg, text or adjust clips`);
1150
- refuseLocked(name, lockReason(c), op);
1151
- const list = (Mask.normalizeMasks(c.props?.masks) || []).slice();
1152
- let i = op.mask == null ? list.length : byName ? list.findIndex((m) => m.name === op.mask.trim()) : op.mask;
1153
- const where = `${name}: ${id}`;
1154
- if (remove) {
1155
- if (i < 0 || i >= list.length) throw new Error(`${where} has no mask ${JSON.stringify(op.mask)}`);
1156
- list.splice(i, 1);
1157
- } else {
1158
- const adding = i < 0 || i === list.length;
1159
- if (adding && name === "setMaskKeys") throw new Error(`${where} has no mask ${JSON.stringify(op.mask)}`);
1160
- if (!adding && i > list.length) throw new Error(`${where} has ${list.length} mask(s) — use mask:${list.length} (or leave mask out) to add one`);
1161
- if (adding && list.length >= Mask.MAX_MASKS) throw new Error(`${where}: at most ${Mask.MAX_MASKS} masks`);
1162
- const base = adding ? (byName ? { name: op.mask.trim() } : null) : op.replace ? { name: list[i].name } : list[i];
1163
- if (adding && !set.shape && !(base && base.shape)) throw new Error(`${where}: a new mask needs set.shape (rect | ellipse | bezier | freehand)`);
1164
- let next;
1165
- try { next = Mask.mergeMask(base, set, true); }
1166
- catch (err) { throw new Error(`${where}: ${err.message.replace(/^mask\.?/, "mask.")}`); }
1167
- if (adding) { i = list.length; list.push(next); } else list[i] = next;
1168
- }
1169
- c.props = c.props || {};
1170
- if (list.length) c.props.masks = list; else delete c.props.masks;
1171
- notes.push(`~${id}.masks(${Mask.describe(list) || "none"})`);
1172
- }
1173
- break;
1174
- }
1175
- case "removeTrack": {
1176
- // {op:"removeTrack", id, track: "name" | index} — what follows it keeps its keys
1177
- const c = proj.clips.find((x) => x.id === op.id);
1178
- if (!c) throw new Error("removeTrack: no clip " + op.id);
1179
- refuseLocked("removeTrack", lockReason(c), op);
1180
- const list = Tracker.normalizeTracks(c.props?.tracks) || [];
1181
- const i = typeof op.track === "string" ? list.findIndex((t) => t.name === op.track) : op.track;
1182
- if (!list[i]) throw new Error(`removeTrack: ${op.id} has no track ${JSON.stringify(op.track)}${list.length ? ` (it has ${Tracker.describe(list)})` : ""}`);
1183
- list.splice(i, 1);
1184
- if (list.length) c.props.tracks = list; else delete c.props.tracks;
1185
- notes.push(`~${op.id}.tracks(${Tracker.describe(list) || "none"})`);
1186
- break;
1187
- }
1188
- case "setMatte": {
1189
- // {op:"setMatte", id | ids, matte:"alpha"|"alpha-inverted"|"luma"|"luma-inverted"|null, track?:"V3"|null}
1190
- const ids = Array.isArray(op.ids) ? op.ids : op.id != null ? [op.id] : [];
1191
- if (!ids.length) throw new Error("setMatte needs id or ids");
1192
- if (op.matte !== null && !Mask.MATTES.includes(op.matte)) throw new Error(`setMatte needs matte: ${Mask.MATTES.join(" | ")} (or null for none)`);
1193
- for (const id of ids) {
1194
- const c = proj.clips.find((x) => x.id === id);
1195
- if (!c) throw new Error("setMatte: no clip " + id);
1196
- if (c.kind === "audio") throw new Error(`setMatte: ${id} is an audio clip — track mattes go on video, image, svg, text or adjust clips`);
1197
- refuseLocked("setMatte", lockReason(c), op);
1198
- c.props = c.props || {};
1199
- if (op.matte === null) { delete c.props.matte; delete c.props.matteTrack; notes.push(`~${id}.matte(none)`); continue; }
1200
- c.props.matte = op.matte;
1201
- if (op.track === null) delete c.props.matteTrack;
1202
- else if (op.track != null) c.props.matteTrack = op.track;
1203
- try { Mask.checkCompositing(c.props, videoTrackIds(), c.track, true); } catch (err) { throw new Error(`setMatte: ${id}: ${err.message.replace(/^matteTrack/, "track")}`); }
1204
- const from = Mask.matteTrackFor(c, videoTrackIds());
1205
- if (!from) throw new Error(`setMatte: ${id} is on ${c.track} and there is no video track above it — pass track:"Vn" (or add a track)`);
1206
- notes.push(`~${id}.matte(${op.matte} from ${from})`);
1207
- }
1208
- break;
1209
- }
1210
- case "setTrack": {
1211
- // Mixer settings on one lane: {op:"setTrack", id:"A1", set:{gain:-6, pan:0.2}}.
1212
- if (!/^A\d+$/.test(String(op.id || ""))) throw new Error("setTrack: id must be an audio track (A1, A2, …)");
1213
- if (!Array.isArray(proj.tracks) || !proj.tracks.length) proj.tracks = DEFAULT_TRACKS.map((t) => ({ ...t }));
1214
- let t = proj.tracks.find((x) => x.id === op.id);
1215
- if (!t) { t = { id: op.id, kind: "audio" }; proj.tracks.push(t); }
1216
- for (const [k, v] of Object.entries(op.set || {})) {
1217
- if (k === "out") { // route into a submix bus, or back to the master
1218
- if (v == null || v === "master") { delete t.out; continue; }
1219
- if (!(proj.buses || []).some((b) => b.id === v)) throw new Error(`setTrack: no bus ${JSON.stringify(v)} — create it first with {op:"setBus", id:"B1"}`);
1220
- t.out = v;
1221
- continue;
1222
- }
1223
- const range = k === "gain" ? [-60, 12] : k === "pan" ? [-1, 1] : null;
1224
- if (!range) throw new Error(`setTrack: '${k}' not settable (gain, pan, out)`);
1225
- if (v === null || v === 0) { delete t[k]; continue; }
1226
- if (typeof v !== "number" || !Number.isFinite(v) || v < range[0] || v > range[1])
1227
- throw new Error(`setTrack: ${k} must be a number ${range[0]}…${range[1]}`);
1228
- t[k] = v;
1229
- }
1230
- notes.push("~" + op.id);
1231
- break;
1232
- }
1233
- case "setBus": {
1234
- // {op:"setBus", id:"B1", set:{name?, gain?, pan?, mute?}} — creates the bus if needed
1235
- if (!/^B\d+$/.test(String(op.id || ""))) throw new Error("setBus: id must be B1, B2, …");
1236
- proj.buses = Array.isArray(proj.buses) ? proj.buses : [];
1237
- let b = proj.buses.find((x) => x.id === op.id);
1238
- if (!b) {
1239
- if (proj.buses.length >= 8) throw new Error("setBus: up to 8 buses");
1240
- b = { id: op.id };
1241
- proj.buses.push(b);
1242
- proj.buses.sort((x, y) => parseInt(x.id.slice(1), 10) - parseInt(y.id.slice(1), 10));
1243
- }
1244
- for (const [k, v] of Object.entries(op.set || {})) {
1245
- if (k === "name") { if (v == null || v === "") delete b.name; else b.name = String(v).slice(0, 40); continue; }
1246
- if (k === "mute") { if (v === true) b.mute = true; else delete b.mute; continue; }
1247
- const range = k === "gain" ? [-60, 12] : k === "pan" ? [-1, 1] : null;
1248
- if (!range) throw new Error(`setBus: '${k}' not settable (name, gain, pan, mute; effects via setFx target:"bus")`);
1249
- if (v === null || v === 0) { delete b[k]; continue; }
1250
- if (typeof v !== "number" || !Number.isFinite(v) || v < range[0] || v > range[1])
1251
- throw new Error(`setBus: ${k} must be a number ${range[0]}…${range[1]}`);
1252
- b[k] = v;
1253
- }
1254
- notes.push("~" + op.id);
1255
- break;
1256
- }
1257
- case "removeBus": {
1258
- const n = (proj.buses || []).length;
1259
- proj.buses = (proj.buses || []).filter((b) => b.id !== op.id);
1260
- if (proj.buses.length === n) throw new Error("removeBus: no bus " + op.id);
1261
- if (!proj.buses.length) delete proj.buses;
1262
- for (const t of proj.tracks || []) if (t.out === op.id) delete t.out; // back to the master
1263
- notes.push("-" + op.id);
1264
- break;
1265
- }
1266
- case "setProject": {
1267
- const allowed = ["name", "width", "height", "fps", "background", "markers", "disabledTracks", "lockedTracks", "untargetedTracks", "exportFrame", "encodeProfile", "master", "inPoint", "outPoint"];
1268
- for (const [k, v] of Object.entries(op.set || {})) {
1269
- if (!allowed.includes(k)) throw new Error(`setProject: '${k}' not settable (allowed: ${allowed.join(", ")})`);
1270
- if ((k === "inPoint" || k === "outPoint") && v != null && (typeof v !== "number" || !Number.isFinite(v) || v < 0))
1271
- throw new Error(`setProject: ${k} must be seconds ≥ 0 (null clears it)`);
1272
- if (k === "encodeProfile" && v != null) {
1273
- resolveProfile(String(v)); // validate id exists
1274
- }
1275
- if (k === "master" && v != null) {
1276
- const g = v.gain;
1277
- if (typeof v !== "object" || Object.keys(v).some((x) => x !== "gain") ||
1278
- (g != null && (typeof g !== "number" || !Number.isFinite(g) || g < -60 || g > 12)))
1279
- throw new Error("setProject: master is {gain} — master fader in dB, -60…+12");
1280
- }
1281
- if (v === null) delete proj[k]; else proj[k] = v;
1282
- }
1283
- if (proj.inPoint != null && proj.outPoint != null && !(proj.outPoint > proj.inPoint))
1284
- throw new Error("setProject: outPoint must be after inPoint");
1285
- notes.push("~project");
1286
- break;
1287
- }
1288
- case "split": case "rippleDelete": case "closeGap": case "lift": case "extract":
1289
- case "rippleTrim": case "roll": case "slip": case "slide":
1290
- case "insert": case "overwrite": case "crossfade":
1291
- notes.push(timelineEdit(proj, op, refuseLocked, lockReason));
1292
- break;
1293
- default:
1294
- throw new Error("Unknown op: " + op.op + " (addClip|updateClip|removeClip|addMedia|removeMedia|setProject|setTrack|setBus|removeBus|setFx|setFxKeys|setGrade|setGradeLayer|setMask|removeMask|setMaskKeys|setMatte|removeTrack|" +
1295
- "split|rippleDelete|closeGap|lift|extract|rippleTrim|roll|slip|slide|insert|overwrite|crossfade)");
1296
- }
1297
- }
938
+ const { notes, toSave } = ProjectOps.applyPatch(proj, ops, {
939
+ savedItems,
940
+ audioChannels: (m) => { const f = mediaFile(m.src); return f ? probeChannels(f) || 0 : null; },
941
+ checkProfile: resolveProfile,
942
+ deliveryPresets: savedDeliveryPresets(),
943
+ mediaInfo: (src) => { const f = mediaFile(src); return f ? probeFile(f) : null; },
944
+ });
1298
945
  // Someone else saved while the ops ran: writing now would drop their change.
1299
946
  // Without a baseRevision the ops just re-apply on the newer document.
1300
947
  let diskRev = readRev;
@@ -1306,6 +953,7 @@ async function callTool(name, args, attempt = 0) {
1306
953
  proj.revision = readRev + 1;
1307
954
  writeProject(proj);
1308
955
  lastReadRevision = proj.revision;
956
+ for (const [kind, item] of toSave) writeSaved(kind, item.id, item);
1309
957
  return `Patched (revision ${proj.revision}): ${notes.join(" ")}. Now ${proj.clips.length} clip(s), ${proj.media.length} media. UI hot-reloaded.`;
1310
958
  }
1311
959
  case "fablecut_set_project": {
@@ -1313,12 +961,7 @@ async function callTool(name, args, attempt = 0) {
1313
961
  if (!doc || typeof doc !== "object") throw new Error("`project` must be an object");
1314
962
  if (!Array.isArray(doc.clips) || !Array.isArray(doc.media))
1315
963
  throw new Error("project must contain `clips` and `media` arrays");
1316
- for (const c of doc.clips) {
1317
- if (!c.id || !c.track || typeof c.start !== "number" || typeof c.duration !== "number")
1318
- throw new Error(`clip ${c.id || "?"} needs id, track, numeric start and duration`);
1319
- if (c.kind !== "text" && c.kind !== "adjust" && !doc.media.some((m) => m.id === c.mediaId))
1320
- throw new Error(`clip ${c.id} references unknown mediaId ${c.mediaId}`);
1321
- }
964
+ ProjectOps.checkProject(doc);
1322
965
  let cur = { revision: 0 };
1323
966
  try { cur = readProject(); } catch {}
1324
967
  const curRev = cur.revision || 0;
@@ -1533,6 +1176,7 @@ async function callTool(name, args, attempt = 0) {
1533
1176
  src: "/media/" + encodeURIComponent(path.basename(target)),
1534
1177
  duration: kind === "image" || kind === "svg" ? undefined : ffprobeDuration(target),
1535
1178
  };
1179
+ Object.assign(entry, infoForEntry(await probeFile(target), entry));
1536
1180
  const proj = readProject();
1537
1181
  // import only appends a media entry (never touches clips), so it merges
1538
1182
  // into the live document; keep lastReadRevision in step only if it
@@ -1548,6 +1192,14 @@ async function callTool(name, args, attempt = 0) {
1548
1192
  : "Ready to use in clips via mediaId.");
1549
1193
  }
1550
1194
  case "fablecut_encode_profiles": {
1195
+ if (args.preset) {
1196
+ const saved = savedDeliveryPresets();
1197
+ const id = String(args.preset);
1198
+ if (!Delivery.PRESETS[id] && !saved[id]) throw new Error(`no delivery preset "${id}" — built-in: ${Delivery.PRESET_IDS.join(", ")}${Object.keys(saved).length ? "; saved: " + Object.keys(saved).join(", ") : ""}`);
1199
+ const { spec } = Delivery.normalize(id, { presets: saved });
1200
+ const p = Delivery.PRESETS[id] || saved[id];
1201
+ return JSON.stringify({ preset: id, label: p.label, note: p.note || "", summary: Delivery.describe(spec), spec }, null, 2);
1202
+ }
1551
1203
  if (args.profile) {
1552
1204
  const p = resolveProfile(String(args.profile));
1553
1205
  return JSON.stringify({
@@ -1561,7 +1213,20 @@ async function callTool(name, args, attempt = 0) {
1561
1213
  args: p.args,
1562
1214
  }, null, 2);
1563
1215
  }
1564
- return JSON.stringify(listProfilesPublic(!!args.detail), null, 2);
1216
+ const saved = savedDeliveryPresets();
1217
+ let encoders = null;
1218
+ try { const r = await apiJSON("GET", "/api/export/presets"); if (r.status === 200) encoders = r.body.encoders; } catch {}
1219
+ const presets = {};
1220
+ for (const id of [...Delivery.PRESET_IDS, ...Object.keys(saved)]) {
1221
+ const p = Delivery.PRESETS[id] || saved[id];
1222
+ presets[id] = { label: p.label, ...(saved[id] ? { saved: true } : {}), summary: Delivery.describe(Delivery.normalize(id, { presets: saved }).spec) };
1223
+ }
1224
+ // the encoding-profile fields stay at the top level, as they always were
1225
+ return JSON.stringify({
1226
+ ...listProfilesPublic(!!args.detail),
1227
+ deliveryPresets: presets,
1228
+ encoders: encoders || "(start the editor server to list them)",
1229
+ }, null, 2);
1565
1230
  }
1566
1231
  default:
1567
1232
  throw new Error("Unknown tool: " + name);
@@ -1581,7 +1246,7 @@ async function handle(msg) {
1581
1246
  result: {
1582
1247
  protocolVersion: negotiateProtocolVersion(params?.protocolVersion),
1583
1248
  capabilities: { tools: {} },
1584
- serverInfo: { name: "fablecut", version: "1.13.0" },
1249
+ serverInfo: { name: "fablecut", version: "1.15.0" },
1585
1250
  },
1586
1251
  });
1587
1252
  }
@@ -1589,8 +1254,11 @@ async function handle(msg) {
1589
1254
  if (method === "tools/call") {
1590
1255
  pending++;
1591
1256
  try {
1592
- const text = await callTool(params.name, params.arguments || {});
1593
- send({ jsonrpc: "2.0", id, result: { content: [{ type: "text", text }] } });
1257
+ const out = await callTool(params.name, params.arguments || {});
1258
+ /* A tool may answer with ready-made content blocks (fablecut_frame
1259
+ returns an image); everything else answers with a string. */
1260
+ const content = Array.isArray(out) ? out : [{ type: "text", text: String(out) }];
1261
+ send({ jsonrpc: "2.0", id, result: { content } });
1594
1262
  } catch (e) {
1595
1263
  send({ jsonrpc: "2.0", id, result: { content: [{ type: "text", text: "Error: " + e.message }], isError: true } });
1596
1264
  } finally {