fablecut 1.15.0 → 1.17.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
@@ -28,12 +28,15 @@ const FX = require("./audio-fx");
28
28
  const EditOps = require("./edit-ops");
29
29
  const ProjectOps = require("./project-ops");
30
30
  const Denoise = require("./denoise");
31
+ const { createProjects } = require("./projects");
32
+ const { createHistory } = require("./history");
31
33
  const Color = require("./color");
32
34
  const FrameStats = require("./frame-stats");
33
35
  const Mask = require("./mask");
34
36
  const Tracker = require("./tracker");
35
37
  const Motion = require("./motion");
36
38
  const CompLib = require("./comp");
39
+ const SeqLib = require("./sequences");
37
40
  const Templates = require("./templates");
38
41
  const Delivery = require("./delivery");
39
42
  const { probeFile, infoForEntry } = require("./media-probe");
@@ -157,7 +160,7 @@ const TOOLS = [
157
160
  },
158
161
  {
159
162
  name: "fablecut_patch_project",
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.",
163
+ 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). SEQUENCES (several timelines in one project — e.g. a 16:9 cut and a 9:16 cut sharing the media and comps; the open one is the top level of the document, which every op, export and the compact view use): {op:'addSequence', name?, from?:'empty'|'open'|<sequence id> (empty takes the open one's canvas and frame rate; a copy takes its whole timeline), width?, height?, fps?, open?:true} · {op:'openSequence', id} (changes what the user's editor shows — only when asked, or to work on it) · {op:'updateSequence', id, set:{name?, index?}} · {op:'removeSequence', id} (only when the user asked) · {op:'inSequence', sequence, ops:[…]} (run any clip, timeline, track or setProject op on a sequence without opening it). 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.",
161
164
  inputSchema: {
162
165
  type: "object",
163
166
  properties: {
@@ -271,6 +274,70 @@ const TOOLS = [
271
274
  required: ["clipIds"],
272
275
  },
273
276
  },
277
+ {
278
+ name: "fablecut_silence",
279
+ description: "Find the silences in speech and, with cut:true, cut them out. Listens to the given clips (a video's linked audio stems, after channel routing, gain and volume) and reports every stretch where none of them is above `threshold` for at least `minSilence` seconds, keeping `padding` seconds of quiet beside each phrase so words aren't clipped. Gaps between clips are left alone. With cut:true each silence is removed with an `extract` on the targeted tracks (or `tracks`), last first, in one revision: later material moves up, linked stems stay in sync, locked tracks and clips stay put — lock the music bed first if it should keep running. A version is saved before the cut. Without cut it only reports, so check the spans (and fablecut_frame them) first. The same as the inspector's Silence section. Needs ffmpeg + ffprobe on PATH.",
280
+ inputSchema: {
281
+ type: "object",
282
+ properties: {
283
+ clipIds: { type: "array", items: { type: "string" }, description: "The speech clips to listen to (a video clip brings its linked stems)" },
284
+ threshold: { type: "number", description: "Below this level (dBFS) counts as silence, -80…-10 (default -40; raise it toward -30 for a noisy room)" },
285
+ minSilence: { type: "number", description: "Shortest silence to report or cut, seconds 0.1…10 (default 0.5)" },
286
+ padding: { type: "number", description: "Quiet kept beside each phrase, seconds 0…2 (default 0.15)" },
287
+ cut: { type: "boolean", description: "Cut the silences out (default false: only report them)" },
288
+ tracks: { type: "array", items: { type: "string" }, description: "cut: the lanes to cut on (default: the targeted tracks)" },
289
+ force: { type: "boolean", description: "cut: also cut through locked clips (only when the user asked)" },
290
+ },
291
+ required: ["clipIds"],
292
+ },
293
+ },
294
+ {
295
+ name: "fablecut_transcribe",
296
+ description: "What is said, word by word, with times — and text-based editing. Transcribes the clips' speech with Whisper in the editor (an open tab, else headless Chrome / Edge; the speech model downloads once, the audio never leaves the machine), keeps one transcript per file (analysis/transcripts/), and answers with the timeline's words as timed lines (timeline seconds), so you can read an interview, pick the good takes, or find where something is said. find:\"phrase\" (or a list) reports every place it is said — case, punctuation and spacing ignored, whole words only — with the exact span; cut:true then extracts each of them on the targeted tracks (or `tracks`), the words and the pause after them, last first, in one revision: later material moves up, linked stems stay in sync, locked clips stay put (lock the music bed first). A version is saved before a cut. Files already transcribed aren't done again unless again:true. Default clips: every video / audio clip with sound on the open timeline. mediaIds reads whole files instead (file seconds; no cut). The same as the editor's Transcript tab.",
297
+ inputSchema: {
298
+ type: "object",
299
+ properties: {
300
+ clipIds: { type: "array", items: { type: "string" }, description: "Clips to transcribe and read (a video brings its linked stems). Default: every clip with sound on the timeline" },
301
+ mediaIds: { type: "array", items: { type: "string" }, description: "Instead of clips: whole files, read in file seconds (find works, cut doesn't)" },
302
+ model: { type: "string", enum: ["base", "small"], description: "Whisper model: base (default, 77 MB, quick) or small (250 MB, more accurate, slower)" },
303
+ language: { type: "string", description: "The spoken language as a Whisper code (en, es, hi, ja, …) or auto (default: detected)" },
304
+ again: { type: "boolean", description: "Transcribe again even when a transcript exists (another model or language)" },
305
+ find: { anyOf: [{ type: "string" }, { type: "array", items: { type: "string" } }], description: "A word or phrase (or several) to find; matches are reported with their timeline spans" },
306
+ from: { type: "number", description: "Only words from this time on (timeline seconds; file seconds with mediaIds)" },
307
+ to: { type: "number", description: "Only words before this time" },
308
+ cut: { type: "boolean", description: "Cut every match of `find` out (default false: only report)" },
309
+ tracks: { type: "array", items: { type: "string" }, description: "cut: the lanes to cut on (default: the targeted tracks)" },
310
+ force: { type: "boolean", description: "cut: also cut through locked clips (only when the user asked)" },
311
+ where: { type: "string", enum: ["auto", "tab", "headless"], description: "Where to transcribe: auto (default): an open editor tab, else headless · tab · headless" },
312
+ timeout: { type: "number", description: "Seconds to wait for the transcription (default 1800)" },
313
+ },
314
+ },
315
+ },
316
+ {
317
+ name: "fablecut_captions",
318
+ description: "Captions from what is said: makes caption clips on the timeline from the clips' transcripts (transcribing first when there is none, like fablecut_transcribe), each one a text clip with `wordTimes` so its words follow the speech. Captions are cut at pauses and sentences, one or two lines as wide as the canvas allows. Styles: subtitle (plain, on a dark bar), karaoke (words light up as they are said), highlight (bold, the word being said in a colour — the reel look), pop (one to three big words at a time, each popping in). They go on the lane captions are already on, else the top video lane, else a new lane above it, and replace the captions there (replace:false keeps them). export:\"srt\"|\"vtt\" writes the timeline's captions to a subtitle file in exports/; import: a path to an SRT / WebVTT file (or its text) places its captions instead of the transcript's. remove:true deletes the captions. Captions are text clips: restyle them with updateClip, and make them after the cutting is done (a cut through a caption doesn't re-time its words — run this again). The same as the Transcript tab's Captions row.",
319
+ inputSchema: {
320
+ type: "object",
321
+ properties: {
322
+ style: { type: "string", enum: ["subtitle", "karaoke", "highlight", "pop"], description: "The look (default subtitle)" },
323
+ clipIds: { type: "array", items: { type: "string" }, description: "Caption only these clips' speech (default: every clip with sound)" },
324
+ from: { type: "number", description: "Only speech from this time on (timeline seconds)" },
325
+ to: { type: "number", description: "Only speech before this time" },
326
+ lines: { type: "number", description: "Lines per caption, 1–3 (default: the style's)" },
327
+ words: { type: "number", description: "At most this many words per caption (pop and highlight have their own default)" },
328
+ size: { type: "number", description: "Scale the style's text size, e.g. 1.2 (default 1)" },
329
+ track: { type: "string", description: "The video lane to put them on (default: chosen as described)" },
330
+ replace: { type: "boolean", description: "Remove the captions already on the timeline first (default true)" },
331
+ export: { type: "string", enum: ["srt", "vtt"], description: "Write the timeline's captions to exports/ as SubRip or WebVTT, and change nothing" },
332
+ import: { type: "string", description: "An SRT or WebVTT file (absolute path, or a /media/… src) or its text: place its captions" },
333
+ remove: { type: "boolean", description: "Delete every caption clip" },
334
+ force: { type: "boolean", description: "Also replace or remove locked captions (only when the user asked)" },
335
+ model: { type: "string", enum: ["base", "small"], description: "Transcribing first: the Whisper model (see fablecut_transcribe)" },
336
+ language: { type: "string", description: "Transcribing first: the spoken language (default: detected)" },
337
+ where: { type: "string", enum: ["auto", "tab", "headless"], description: "Transcribing first: where (see fablecut_transcribe)" },
338
+ },
339
+ },
340
+ },
274
341
  {
275
342
  name: "fablecut_denoise",
276
343
  description: "Reduce background noise (hiss, hum, room tone) on audio clips: ffmpeg's FFT denoiser renders a cleaned FLAC of each clip's whole source file into media/, and the clip — with its linked stems — switches to it (the picture keeps its own file, so links and timing stay intact). The same as the inspector's Noise control. amount 'off' switches back to the original. Re-running reuses a file already rendered. Needs ffmpeg + ffprobe on PATH. Refuses locked clips unless force:true.",
@@ -284,6 +351,42 @@ const TOOLS = [
284
351
  required: ["clipIds"],
285
352
  },
286
353
  },
354
+ {
355
+ name: "fablecut_projects",
356
+ description: "Several projects in one FableCut: the projects dashboard. ./project.json (what every other tool reads and edits) is always the OPEN project; the others are stored beside it and share media/, exports/ and the library, so a duplicate or a template copies no footage. Actions: list (default; archived:'only'|'all' to see archived ones) · open {id} — switches the editor to that project (the open one is saved first; editor tabs reload; your next fablecut_get_project reads the new one) · new {name, template?, fps?, width?, height?, notes?, tags?, open?:true} — template is a built-in canvas (landscape-1080 default, vertical-1080, square-1080, portrait-1350, uhd-4k, landscape-720) or a saved template id · duplicate {id, name?, open?:false} · update {id, name?, notes?, tags?} · archive / unarchive {id} · delete {id} (archived projects only) · templates · save_template {id, name} (the project's canvas, tracks, clips and media references) · delete_template {template}. Opening another project changes what the user sees — only open, archive or delete when the user asked for it.",
357
+ inputSchema: {
358
+ type: "object",
359
+ properties: {
360
+ action: { type: "string", enum: ["list", "open", "new", "duplicate", "update", "archive", "unarchive", "delete", "templates", "save_template", "delete_template"], description: "What to do (default list)" },
361
+ id: { type: "string", description: "The project (p_…), from list" },
362
+ name: { type: "string", description: "new / duplicate / update: the project's name · save_template: the template's name" },
363
+ template: { type: "string", description: "new: the template to start from · delete_template: the saved template's id" },
364
+ fps: { type: "number", description: "new: frame rate (default: the template's)" },
365
+ width: { type: "integer", description: "new: canvas width (default: the template's)" },
366
+ height: { type: "integer", description: "new: canvas height (default: the template's)" },
367
+ notes: { type: "string", description: "new / update: free-text notes (brief, client, deadline …)" },
368
+ tags: { type: "array", items: { type: "string" }, description: "new / update: labels (replaces the list)" },
369
+ open: { type: "boolean", description: "new (default true) / duplicate (default false): open it afterwards" },
370
+ archived: { type: "string", enum: ["exclude", "only", "all"], description: "list: archived projects too, or only them" },
371
+ },
372
+ },
373
+ },
374
+ {
375
+ name: "fablecut_versions",
376
+ description: "A project's version history: saved copies you can go back to, never destructive. Actions: list (default) · save {name?, note?, final?} — keep the project as it is now (do this before big or risky edits, and when the user is happy with a cut) · diff {version, to?} — what changed from that version to now (or to another version): clips added / removed / changed, length, media, settings · restore {version} — put that version back; the current state is saved as a version first, so a restore can itself be undone · update {version, name?, note?, final?} — rename, annotate, or mark the one final cut · delete {version}. project defaults to the open one (fablecut_projects lists ids). Versions are also made on their own: every 10 minutes while the project changes, and before an agent's first edit of a session or a fablecut_set_project rewrite. Restoring changes what the user sees: only when they asked.",
377
+ inputSchema: {
378
+ type: "object",
379
+ properties: {
380
+ action: { type: "string", enum: ["list", "save", "diff", "restore", "update", "delete"], description: "What to do (default list)" },
381
+ project: { type: "string", description: "The project (p_…); default the open one" },
382
+ version: { description: "The version: its number (3) or \"v3\"", anyOf: [{ type: "integer" }, { type: "string" }] },
383
+ to: { description: "diff: compare to this version instead of the current project", anyOf: [{ type: "integer" }, { type: "string" }] },
384
+ name: { type: "string", description: "save / update: the version's name (default \"Version NN\")" },
385
+ note: { type: "string", description: "save / update: what this version is (\"client cut, shorter intro\")" },
386
+ final: { type: "boolean", description: "save / update: mark it the final cut (one per project)" },
387
+ },
388
+ },
389
+ },
287
390
  {
288
391
  name: "fablecut_proxy",
289
392
  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.",
@@ -454,19 +557,314 @@ async function measureClipGroup(proj, clips) {
454
557
  return meter ? meter.result() : null;
455
558
  }
456
559
  /** Timeline spans with sound on these voice clips (ducking.js pipeline). */
457
- async function voiceRegions(proj, voices, threshold) {
560
+ async function voiceRegions(proj, voices, threshold, minLen, heard) {
458
561
  const L = require("./loudness.js"), D = require("./ducking.js");
459
562
  const lists = [];
460
563
  for (const v of voices) {
461
564
  let env = null;
462
565
  await streamClipAudio(proj, v, (nCh) => { env = new D.EnvelopeMeter(nCh, NORM_SR); },
463
566
  (chs) => env.push(L.routeChannels(chs, v.props || {})));
464
- if (!env) continue;
567
+ if (!env) continue; // no audio stream
568
+ if (heard) heard.add(v.id);
465
569
  const sp = Math.min(8, Math.max(0.1, +v.props?.speed || 1));
466
570
  const gain = Math.pow(10, (+v.props?.gain || 0) / 20) * Math.min(2, Math.max(0, +(v.props?.volume ?? 1)));
467
- lists.push(D.activeRegions(env.result(), { t0: v.start, speed: sp, gain, threshold }));
571
+ lists.push(D.activeRegions(env.result(), { t0: v.start, speed: sp, gain, threshold, ...(minLen != null ? { minLen } : {}) }));
572
+ }
573
+ return D.mergeRegions(lists, minLen != null ? 0 : undefined);
574
+ }
575
+ /** The clips that carry a selection's sound, one list per linked group: its
576
+ * audio stems, else the clip itself (audio, or a video without stems). */
577
+ function speechGroups(proj, ids) {
578
+ const groups = new Map();
579
+ for (const id of ids) {
580
+ const c = proj.clips.find((x) => x.id === id);
581
+ if (!c) throw new Error("no clip " + id);
582
+ if (c.kind !== "audio" && c.kind !== "video") throw new Error(`clip ${id} is ${c.kind} — no sound to listen to`);
583
+ const key = c.linkGroup || c.id;
584
+ if (groups.has(key)) continue;
585
+ const members = c.linkGroup ? proj.clips.filter((x) => x.linkGroup === c.linkGroup) : [c];
586
+ const stems = members.filter((x) => x.kind === "audio");
587
+ groups.set(key, stems.length ? stems : [c]);
588
+ }
589
+ return [...groups.values()];
590
+ }
591
+ const fmtClock = (s) => `${Math.floor(s / 60)}:${(s % 60).toFixed(2).padStart(5, "0")}`;
592
+ const fmtDur = (s) => { const t = Math.round(s); return `${Math.floor(t / 60)}:${String(t % 60).padStart(2, "0")}`; };
593
+ /* fablecut_silence: silence.js on the clips' sound, then (cut:true) its extract ops. */
594
+ async function silenceTool(args) {
595
+ const S = require("./silence.js");
596
+ const ids = Array.isArray(args.clipIds) ? args.clipIds.map(String) : [];
597
+ if (!ids.length) throw new Error("`clipIds` must list the speech clip(s) to listen to");
598
+ const opts = S.options(args);
599
+ const doc = readProject();
600
+ const readRev = doc.revision || 0;
601
+ const groups = speechGroups(doc, ids);
602
+ const disabled = new Set(Array.isArray(doc.disabledTracks) ? doc.disabledTracks : []);
603
+ const enabled = groups.map((g) => g.filter((x) => !disabled.has(x.track) && x.disabled !== true)).filter((g) => g.length);
604
+ if (!enabled.length) throw new Error("those clips are disabled (or on disabled tracks) — nothing to listen to");
605
+ // a speed ramp moves the sound along the timeline unevenly: those clips are left alone
606
+ const live = enabled.filter((g) => !g.some(S.ramped));
607
+ const rampedN = enabled.length - live.length;
608
+ if (!live.length) throw new Error("those clips have a speed ramp (speed keyframes) — silence removal works on clips at a steady speed");
609
+ const heard = new Set();
610
+ const sound = await voiceRegions(doc, live.flat(), opts.threshold, S.MIN_SOUND, heard);
611
+ // only time that was actually listened to can be silent: a clip with no audio stream is left alone
612
+ const usable = live.filter((g) => g.every((x) => heard.has(x.id)));
613
+ if (!usable.length) throw new Error("those clips have no audio stream — nothing to listen to");
614
+ const ranges = usable.map((g) => [Math.min(...g.map((x) => x.start)), Math.max(...g.map((x) => x.start + x.duration))]);
615
+ const spans = S.silentSpans(sound, ranges, { ...opts, fps: doc.fps });
616
+ const listen = S.union(ranges).reduce((n, [a, b]) => n + b - a, 0);
617
+ const head = `${spans.length} silence${spans.length === 1 ? "" : "s"}, ${S.total(spans).toFixed(1)} s of ${fmtDur(listen)} ` +
618
+ `(threshold ${opts.threshold} dBFS, at least ${opts.minSilence} s, ${opts.padding} s kept beside speech` +
619
+ (usable.length < live.length ? `; ${live.length - usable.length} clip(s) with no audio stream left alone` : "") +
620
+ (rampedN ? `; ${rampedN} clip(s) with a speed ramp left alone` : "") + ")";
621
+ const list = spans.slice(0, 60).map((s) => ` ${fmtClock(s.from)} → ${fmtClock(s.to)} (${(s.to - s.from).toFixed(2)} s)`)
622
+ .concat(spans.length > 60 ? [` … +${spans.length - 60} more`] : []);
623
+ if (args.cut !== true) return [head + (spans.length ? ":" : "."), ...list,
624
+ ...(spans.length ? ["Nothing cut yet: call again with cut:true to remove them (lock the music bed first if it should keep running)."] : [])].join("\n");
625
+ if (!spans.length) return head + " — nothing to cut.";
626
+ // the timeline must be the one that was listened to
627
+ const proj = readProject();
628
+ if ((proj.revision || 0) !== readRev)
629
+ throw new Error(`the project changed while listening (revision ${readRev} → ${proj.revision}) — nothing cut; run fablecut_silence again`);
630
+ const end = (p) => p.clips.reduce((m, c) => Math.max(m, c.start + c.duration), 0);
631
+ const before = end(proj);
632
+ ProjectOps.applyPatch(proj, S.cutOps(spans, { tracks: args.tracks, force: args.force === true }), { savedItems });
633
+ // a cut this size always keeps the project as it was, not once per session like other edits
634
+ let verWarn = "";
635
+ try { createHistory({ projects: createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR }) }).beforeAgent("Before cutting silences"); }
636
+ catch (e) { verWarn = ` Warning: no version was saved before the cut (${e.message}).`; }
637
+ let diskRev = readRev;
638
+ try { diskRev = readProject().revision || 0; } catch {}
639
+ if (diskRev !== readRev) throw new Error(`the project changed while cutting (revision ${readRev} → ${diskRev}) — nothing cut; run fablecut_silence again`);
640
+ proj.revision = readRev + 1;
641
+ writeProject(proj);
642
+ lastReadRevision = proj.revision;
643
+ return `Cut ${head} — timeline ${fmtDur(before)} → ${fmtDur(end(proj))} (revision ${proj.revision}). UI hot-reloaded.` +
644
+ (verWarn || ` The project as it was is kept as a version (fablecut_versions lists it; restore undoes the cut).`);
645
+ }
646
+ /** What words are placed by and cuts land on: where each clip sits and plays from, the track
647
+ * switches and the frame rate. An editor saving probed media details while a transcription runs
648
+ * doesn't change it; a moved, trimmed or cut clip does. */
649
+ function timelineSig(doc) {
650
+ return JSON.stringify([doc.fps, doc.lockedTracks || [], doc.untargetedTracks || [], doc.disabledTracks || [],
651
+ (doc.clips || []).map((c) => [c.id, c.track, c.start, c.in, c.duration, c.mediaId, c.props?.speed ?? 1, c.keyframes?.speed ?? null, !!c.locked, !!c.disabled])]);
652
+ }
653
+ /* The words said on the timeline (or in whole files, mediaIds): transcribes what has no
654
+ transcript yet as a job in an open tab, else headless, then lays the words out. Shared by
655
+ fablecut_transcribe and fablecut_captions. */
656
+ async function speechWords(args, fileMode) {
657
+ const T = require("./transcribe.js");
658
+ const model = T.model(args.model), language = T.language(args.language);
659
+ const doc = readProject();
660
+ const readRev = doc.revision || 0;
661
+ const mediaById = new Map((doc.media || []).map((m) => [m.id, m]));
662
+ const disabled = new Set(Array.isArray(doc.disabledTracks) ? doc.disabledTracks : []);
663
+ let entries = [], files = [], rampedN = 0;
664
+ if (fileMode) {
665
+ for (const id of args.mediaIds.map(String)) {
666
+ const m = mediaById.get(id);
667
+ if (!m) throw new Error("no media " + id);
668
+ if (m.kind !== "audio" && m.kind !== "video") throw new Error(`media ${id} is ${m.kind} — no sound to transcribe`);
669
+ files.push(m);
670
+ }
671
+ } else {
672
+ const ids = Array.isArray(args.clipIds) && args.clipIds.length ? args.clipIds.map(String)
673
+ : doc.clips.filter((c) => (c.kind === "audio" || c.kind === "video") && mediaById.get(c.mediaId) && mediaById.get(c.mediaId).audioChannels !== 0
674
+ // a picture whose sound is on linked stems (they are read instead), or one with its sound off
675
+ && !(c.kind === "video" && (c.linkGroup ? doc.clips.some((x) => x.linkGroup === c.linkGroup && x.kind === "audio") : +(c.props?.volume ?? 1) === 0))).map((c) => c.id);
676
+ if (!ids.length) throw new Error("the timeline has no clips with sound — add some, or pass mediaIds");
677
+ const groups = speechGroups(doc, ids).map((g) => g.filter((x) => !disabled.has(x.track) && x.disabled !== true)).filter((g) => g.length);
678
+ if (!groups.length) throw new Error("those clips are disabled (or on disabled tracks) — nothing to read");
679
+ for (const g of groups) {
680
+ if (g.some(T.ramped)) { rampedN++; continue; }
681
+ const m = mediaById.get(g[0].mediaId);
682
+ if (m) entries.push({ clip: g[0], media: m });
683
+ }
684
+ if (!entries.length) throw new Error("those clips have a speed ramp (speed keyframes) — their words can't be placed on the timeline");
685
+ files = [...new Map(entries.map((e) => [e.media.src, e.media])).values()];
686
+ }
687
+ if (!(await ensureUIServer())) throw new Error(`the editor server is not running and could not be started on port ${PORT}`);
688
+ const srcs = files.map((m) => m.src);
689
+ const st = await apiJSON("POST", "/api/transcript/status", { srcs });
690
+ if (st.status !== 200) throw new Error(st.body?.error || "could not read the transcripts");
691
+ const gone = srcs.filter((s) => st.body.status[s] === null);
692
+ if (gone.length) throw new Error("these files are missing (offline): " + gone.join(", "));
693
+ const todo = args.again === true ? srcs : srcs.filter((s) => !st.body.status[s]);
694
+ let note = "";
695
+ if (todo.length) {
696
+ const r = await apiJSON("POST", "/api/transcribe/request", { where: args.where || "auto", transcribe: { srcs: todo, model, language, again: args.again === true } });
697
+ if (r.status !== 200) throw new Error(r.body?.error || `transcribe request failed (${r.status})`);
698
+ let job = r.body;
699
+ const deadline = Date.now() + 1000 * (Number.isFinite(args.timeout) && args.timeout > 0 ? args.timeout : 1800);
700
+ while (job.status === "pending" || job.status === "running") {
701
+ if (Date.now() > deadline) {
702
+ await apiJSON("POST", "/api/export/job/cancel?id=" + encodeURIComponent(job.id));
703
+ throw new Error("timed out waiting for the transcription — try fewer clips, or a larger timeout");
704
+ }
705
+ await sleep(1000);
706
+ const q = await apiJSON("GET", "/api/export/job?id=" + encodeURIComponent(job.id));
707
+ if (q.status !== 200) throw new Error(q.body?.error || "lost track of the transcription job");
708
+ job = q.body;
709
+ }
710
+ if (job.status !== "done") throw new Error(`transcription ${job.status}: ${job.error || "no reason given"}`);
711
+ const res = job.result || {};
712
+ note = `Transcribed ${(res.done || []).length} file${(res.done || []).length === 1 ? "" : "s"} (${model}${language ? ", " + language : ""}, in ${job.via === "headless" ? "a headless browser" : "the open editor tab"})` +
713
+ ((res.failed || []).length ? `; failed: ${res.failed.map((f) => `${f.src} (${f.error})`).join(", ")}` : "") + ".\n";
714
+ }
715
+ const docs = new Map();
716
+ for (const src of srcs) {
717
+ const g = await apiJSON("GET", "/api/transcript?src=" + encodeURIComponent(src));
718
+ if (g.status === 200 && g.body?.transcript) docs.set(src, T.validate(g.body.transcript));
719
+ }
720
+ const langs = [...new Set([...docs.values()].map((d) => d.language === "auto" ? "detected" : d.language).filter(Boolean))];
721
+ const without = srcs.filter((s) => !docs.has(s));
722
+ let words, scope;
723
+ if (fileMode) {
724
+ // file seconds, one file after another
725
+ words = [];
726
+ for (const m of files) { const d = docs.get(m.src); if (d) words.push(...d.words.map(([w, s, e]) => ({ w, s, e, clip: m.id, r: [0, d.duration || e] }))); }
727
+ scope = `${files.length} file${files.length === 1 ? "" : "s"} (file seconds)`;
728
+ } else {
729
+ words = T.layout(entries.filter((e) => docs.has(e.media.src)).map((e) => ({ clip: e.clip, words: docs.get(e.media.src).words })));
730
+ scope = `${entries.length} clip${entries.length === 1 ? "" : "s"} on the timeline (timeline seconds)`;
731
+ }
732
+ return { doc, readRev, sig: timelineSig(doc), words, scope, note, langs, without, rampedN };
733
+ }
734
+ /* fablecut_transcribe: transcripts from the editor (a job), read on the timeline, found, cut. */
735
+ async function transcribeTool(args) {
736
+ const T = require("./transcribe.js");
737
+ const model = T.model(args.model), language = T.language(args.language);
738
+ const finds = (args.find == null ? [] : Array.isArray(args.find) ? args.find : [args.find]).map(String).filter((q) => T.norm(q));
739
+ if (args.find != null && !finds.length) throw new Error("find needs a word or phrase with letters or digits in it");
740
+ const fileMode = Array.isArray(args.mediaIds) && args.mediaIds.length;
741
+ if (args.cut === true && !finds.length) throw new Error("cut:true needs find — the words or phrases to cut");
742
+ if (args.cut === true && fileMode) throw new Error("cut works on the timeline — pass clipIds (or nothing), not mediaIds");
743
+ const { doc, sig, words, scope, note, langs, without, rampedN } = await speechWords(args, fileMode);
744
+ const fmtT = (x) => fmtClock(Math.max(0, x));
745
+ const lo = Number.isFinite(args.from) ? args.from : -Infinity, hi = Number.isFinite(args.to) ? args.to : Infinity;
746
+ const inWin = (w) => w.e >= lo && w.s <= hi;
747
+ const head = note + `${words.filter(inWin).length} words, ${scope}` + (langs.length ? `, language ${langs.join("/")}` : "") +
748
+ (without.length ? `; no transcript for ${without.join(", ")}` : "") + (rampedN ? `; ${rampedN} clip(s) with a speed ramp left out` : "");
749
+ if (!finds.length) {
750
+ const segs = T.segments(words).filter((sg) => sg.to >= lo && sg.from <= hi);
751
+ const MAX = 300;
752
+ const lines = segs.slice(0, MAX).map((sg) => `[${fmtT(sg.from)}] ${sg.text}`);
753
+ return [head + (segs.length ? ":" : "."), ...lines,
754
+ ...(segs.length > MAX ? [`… ${segs.length - MAX} more lines — pass from (e.g. ${segs[MAX].from.toFixed(1)}) to read on`] : []),
755
+ ...(segs.length ? ["find:\"…\" locates a phrase; with cut:true it is cut out."] : [])].join("\n");
468
756
  }
469
- return D.mergeRegions(lists);
757
+ // find (and cut)
758
+ const runs = [], report = [];
759
+ for (const q of finds) {
760
+ const hits = T.find(words, q).filter((r) => inWin(words[r.i]) && inWin(words[r.j]));
761
+ const spans = T.cutSpans(words, hits, { fps: doc.fps });
762
+ report.push(`"${q}": ${hits.length} match${hits.length === 1 ? "" : "es"}` + (hits.length ? ":" : ""));
763
+ for (const r of hits.slice(0, 50)) {
764
+ const ctx = `${T.text(words, Math.max(0, r.i - 4), r.i - 1)} «${T.text(words, r.i, r.j)}» ${T.text(words, r.j + 1, Math.min(words.length - 1, r.j + 4))}`.trim();
765
+ report.push(` ${fmtT(words[r.i].s)} → ${fmtT(words[r.j].e)} ${ctx}`);
766
+ }
767
+ if (hits.length > 50) report.push(` … +${hits.length - 50} more`);
768
+ runs.push(...hits);
769
+ if (!spans.length && hits.length) report.push(" (each is too short to cut on its own)");
770
+ }
771
+ const spans = T.cutSpans(words, runs, { fps: doc.fps });
772
+ if (args.cut !== true) return [head + ".", ...report,
773
+ ...(spans.length && !fileMode ? [`Cutting them would remove ${spans.length} span${spans.length === 1 ? "" : "s"}, ${T.total(spans).toFixed(1)} s (the words and the pause after each): call again with cut:true.`] : [])].join("\n");
774
+ if (!spans.length) return [head + ".", ...report, "Nothing to cut."].join("\n");
775
+ const proj = readProject(), readRev = proj.revision || 0;
776
+ if (timelineSig(proj) !== sig)
777
+ throw new Error("the timeline changed while transcribing (a clip was moved, trimmed or cut) — nothing cut; run fablecut_transcribe again");
778
+ const end = (p) => p.clips.reduce((m, c) => Math.max(m, c.start + c.duration), 0);
779
+ const before = end(proj);
780
+ ProjectOps.applyPatch(proj, T.cutOps(spans, { tracks: args.tracks, force: args.force === true }), { savedItems });
781
+ let verWarn = "";
782
+ try { createHistory({ projects: createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR }) }).beforeAgent("Before cutting words"); }
783
+ catch (e) { verWarn = ` Warning: no version was saved before the cut (${e.message}).`; }
784
+ let diskRev = readRev;
785
+ try { diskRev = readProject().revision || 0; } catch {}
786
+ if (diskRev !== readRev) throw new Error(`the project changed while cutting (revision ${readRev} → ${diskRev}) — nothing cut; run fablecut_transcribe again`);
787
+ proj.revision = readRev + 1;
788
+ writeProject(proj);
789
+ lastReadRevision = proj.revision;
790
+ return [head + ".", ...report,
791
+ `Cut ${spans.length} span${spans.length === 1 ? "" : "s"}, ${T.total(spans).toFixed(1)} s — timeline ${fmtDur(before)} → ${fmtDur(end(proj))} (revision ${proj.revision}). UI hot-reloaded.` +
792
+ (verWarn || " The project as it was is kept as a version (fablecut_versions lists it; restore undoes the cut).")].join("\n");
793
+ }
794
+ /* fablecut_captions: caption clips from the transcripts (captions.js), subtitle files out and in. */
795
+ async function captionsTool(args) {
796
+ const C = require("./captions.js");
797
+ const st = C.style(args.style);
798
+ const ownLocks = (proj, c) => c.locked === true || (Array.isArray(proj.lockedTracks) && proj.lockedTracks.includes(c.track));
799
+ if (args.export != null) {
800
+ if (args.export !== "srt" && args.export !== "vtt") throw new Error("export must be srt or vtt");
801
+ const proj = readProject(), list = C.fromClips(proj.clips, proj.disabledTracks);
802
+ if (!list.length) throw new Error("there are no captions on the timeline to export — make them first (fablecut_captions {})");
803
+ fs.mkdirSync(EXPORTS_DIR, { recursive: true });
804
+ const base = String(proj.name || "captions").replace(/[^\w\- ]+/g, "_").trim().slice(0, 80) || "captions";
805
+ let file = path.join(EXPORTS_DIR, `${base}.${args.export}`);
806
+ for (let n = 2; fs.existsSync(file); n++) file = path.join(EXPORTS_DIR, `${base} ${n}.${args.export}`);
807
+ fs.writeFileSync(file, args.export === "srt" ? C.toSRT(list) : C.toVTT(list));
808
+ return `Wrote ${list.length} caption${list.length === 1 ? "" : "s"} to ${file} (${args.export === "srt" ? "SubRip" : "WebVTT"}, ${fmtClock(list[0].start)} → ${fmtClock(list[list.length - 1].end)}).`;
809
+ }
810
+ if (args.remove === true) {
811
+ const proj = readProject(), caps = proj.clips.filter(C.isCaption);
812
+ if (!caps.length) return "There are no captions on the timeline.";
813
+ const locked = caps.filter((c) => ownLocks(proj, c));
814
+ if (locked.length && args.force !== true) throw new Error(`${locked.length} caption(s) are locked — nothing removed (pass force:true only if the user asked)`);
815
+ ProjectOps.applyPatch(proj, caps.map((c) => ({ op: "removeClip", id: c.id, ...(args.force === true ? { force: true } : {}) })), { savedItems });
816
+ proj.revision = (proj.revision || 0) + 1;
817
+ writeProject(proj);
818
+ lastReadRevision = proj.revision;
819
+ return `Removed ${caps.length} caption${caps.length === 1 ? "" : "s"} (revision ${proj.revision}). UI hot-reloaded.`;
820
+ }
821
+ let list, note = "", sig;
822
+ const first = readProject();
823
+ const m = C.metrics(st, first.width || 1920, first.height || 1080, { lines: args.lines, words: args.words, scale: args.size });
824
+ if (args.import != null) {
825
+ let text = String(args.import);
826
+ const asFile = text.length < 1024 && !text.includes("-->");
827
+ if (asFile) {
828
+ const file = text.startsWith("/media/") ? path.join(MEDIA_DIR, decodeURIComponent(text.slice(7))) : path.resolve(text);
829
+ if (!fs.existsSync(file)) throw new Error("no such subtitle file: " + text);
830
+ text = fs.readFileSync(file, "utf8");
831
+ }
832
+ list = C.fit(C.parse(text), m.chars, m.lines);
833
+ sig = timelineSig(first);
834
+ note = `Read ${list.length} caption${list.length === 1 ? "" : "s"} from the ${/^WEBVTT/m.test(text) ? "WebVTT" : "SubRip"} file.\n`;
835
+ } else {
836
+ const r = await speechWords(args, false);
837
+ const lo = Number.isFinite(args.from) ? args.from : -Infinity, hi = Number.isFinite(args.to) ? args.to : Infinity;
838
+ const words = r.words.filter((w) => w.s >= lo && w.e <= hi);
839
+ if (!words.length) throw new Error("no words to caption" + (r.without.length ? ` — no transcript for ${r.without.join(", ")}` : " in that stretch"));
840
+ list = C.cues(words, { chars: m.chars, lines: m.lines, words: m.words, maxDur: m.maxDur, fps: r.doc.fps });
841
+ sig = r.sig;
842
+ note = r.note;
843
+ }
844
+ const proj = readProject(), readRev = proj.revision || 0;
845
+ if (timelineSig(proj) !== sig)
846
+ throw new Error("the timeline changed while transcribing (a clip was moved, trimmed or cut) — nothing added; run fablecut_captions again");
847
+ const old = args.replace === false ? [] : proj.clips.filter(C.isCaption);
848
+ const lockedOld = old.filter((c) => ownLocks(proj, c));
849
+ if (lockedOld.length && args.force !== true) throw new Error(`${lockedOld.length} existing caption(s) are locked — nothing changed (pass replace:false to keep them, or force:true if the user asked)`);
850
+ const from = list[0].start, to = list[list.length - 1].end;
851
+ let lane = args.track ? { track: String(args.track), add: false } : C.trackFor(old.length ? proj : { ...proj, clips: proj.clips.filter((c) => !C.isCaption(c)) }, from, to);
852
+ if (!/^V\d+$/.test(lane.track)) throw new Error("track must be a video lane such as V3");
853
+ if (args.track && !(proj.tracks || C.DEFAULT_TRACKS).some((t) => t.id === lane.track)) lane.add = true;
854
+ if (Array.isArray(proj.lockedTracks) && proj.lockedTracks.includes(lane.track) && args.force !== true) throw new Error(`${lane.track} is locked — pick another track, or unlock it`);
855
+ if (lane.add) proj.tracks = [{ id: lane.track, kind: "video" }, ...(Array.isArray(proj.tracks) && proj.tracks.length ? proj.tracks : C.DEFAULT_TRACKS)];
856
+ const ops = [
857
+ ...old.map((c) => ({ op: "removeClip", id: c.id, ...(args.force === true ? { force: true } : {}) })),
858
+ ...list.map((cue) => ({ op: "addClip", clip: C.clip(cue, { style: st, width: proj.width, height: proj.height, track: lane.track, scale: args.size }), ...(args.force === true ? { force: true } : {}) })),
859
+ ];
860
+ ProjectOps.applyPatch(proj, ops, { savedItems });
861
+ proj.revision = readRev + 1;
862
+ writeProject(proj);
863
+ lastReadRevision = proj.revision;
864
+ const sample = list.slice(0, 3).map((c) => ` [${fmtClock(c.start)}] ${c.text.replace(/\n/g, " / ")}`);
865
+ return note + `Added ${list.length} caption${list.length === 1 ? "" : "s"} (${C.STYLES[st].label}, ${m.fontSize} px) on ${lane.track}${lane.add ? " (a new lane)" : ""}, ${fmtClock(from)} → ${fmtClock(to)}` +
866
+ (old.length ? `, replacing ${old.length}` : "") + ` (revision ${proj.revision}). UI hot-reloaded.\n` + sample.join("\n") +
867
+ (list.length > 3 ? `\n … ${list.length - 3} more` : "") + "\nfablecut_frame {time} shows how one looks; export:\"srt\" writes a subtitle file.";
470
868
  }
471
869
  /** The clips that sound for a selection: a linked group's audio stems, else the clip. */
472
870
  function normalizeGroups(proj, ids) {
@@ -567,6 +965,85 @@ function describeExportJob(j) {
567
965
  `Check again with fablecut_export {job:"${j.id}"}, or stop it with {cancel:"${j.id}"}.`;
568
966
  }
569
967
  /* fablecut_proxy: the server makes proxies (proxy.js); this asks it, and waits. */
968
+ /* fablecut_projects: through the editor server, so it is the only process that
969
+ switches ./project.json and its tabs hear about it at once. */
970
+ function describeProject(p) {
971
+ const dur = p.duration == null ? "?" : `${Math.floor(p.duration / 60)}:${String(Math.round(p.duration % 60)).padStart(2, "0")}`;
972
+ return `${p.id} "${p.name}"${p.active ? " (OPEN)" : ""}${p.archived ? " [archived]" : ""} — ` +
973
+ (p.unreadable ? "project file unreadable" : `${p.width}x${p.height}@${p.fps} ${dur}, ${p.clips} clip(s), ${p.media} media`) +
974
+ (p.modified ? `, modified ${p.modified.slice(0, 16).replace("T", " ")}` : "") +
975
+ (p.tags?.length ? " " + p.tags.map((t) => "#" + t).join(" ") : "") +
976
+ (p.notes ? `\n notes: ${p.notes.length > 300 ? p.notes.slice(0, 300) + "…" : p.notes}` : "");
977
+ }
978
+ const describeTemplate = (t) => `${t.id} "${t.name}" ${t.width}x${t.height}@${t.fps}${t.builtin ? " (built-in)" : ` — ${t.clips} clip(s)`}`;
979
+ async function projectsTool(args) {
980
+ if (!(await ensureUIServer())) throw new Error(`the editor server is not running and could not be started on port ${PORT}`);
981
+ const action = args.action || "list";
982
+ if (action === "list") {
983
+ const r = await apiJSON("GET", "/api/projects?archived=" + encodeURIComponent(args.archived || "exclude"));
984
+ if (r.status !== 200) throw new Error(r.body?.error || `projects request failed (${r.status})`);
985
+ const { projects, templates } = r.body;
986
+ return [`${projects.length} project(s):`, ...projects.map(describeProject),
987
+ `Templates (action:"new", template): ${templates.map((t) => t.id).join(", ")}`].join("\n");
988
+ }
989
+ const r = await apiJSON("POST", "/api/projects", { ...args, action });
990
+ if (r.status !== 200) throw new Error(r.body?.error || `projects request failed (${r.status})`);
991
+ const out = r.body;
992
+ if (action === "templates") return out.templates.map(describeTemplate).join("\n");
993
+ if (action === "save_template") return `Saved template ${describeTemplate(out.template)}. Start a project from it: {action:"new", template:"${out.template.id}", name}.`;
994
+ if (action === "delete_template") return `Deleted template ${out.template}.`;
995
+ if (action === "delete") return `Deleted project ${out.id} (its media stay in media/).`;
996
+ if (out.already) return `${describeProject(out.project)}\nAlready open.`;
997
+ if (out.from) return `Opened ${describeProject(out.project)}\nThe editor switched to it (${out.from} was saved first). Read it with fablecut_get_project {compact:true} before editing.`;
998
+ return describeProject(out.project);
999
+ }
1000
+ /* fablecut_versions: through the editor server, like fablecut_projects. */
1001
+ const KIND_LABEL = { manual: "", auto: " (auto)", agent: " (before agent edits)", restore: " (before a restore)" };
1002
+ function describeVersion(e) {
1003
+ const when = e.created ? e.created.slice(0, 16).replace("T", " ") : "?";
1004
+ return `v${e.v}${e.final ? " FINAL" : ""} "${e.name}"${KIND_LABEL[e.kind] || ""} — ${when}, ${e.clips} clip(s), ` +
1005
+ `${Math.floor(Math.round(e.duration) / 60)}:${String(Math.round(e.duration) % 60).padStart(2, "0")}, revision ${e.revision}` +
1006
+ (e.note ? `\n note: ${e.note.length > 300 ? e.note.slice(0, 300) + "…" : e.note}` : "");
1007
+ }
1008
+ async function versionsTool(args) {
1009
+ if (!(await ensureUIServer())) throw new Error(`the editor server is not running and could not be started on port ${PORT}`);
1010
+ const action = args.action || "list";
1011
+ const r = action === "list"
1012
+ ? await apiJSON("GET", "/api/versions" + (args.project ? "?project=" + encodeURIComponent(args.project) : ""))
1013
+ : await apiJSON("POST", "/api/versions", { ...args, action });
1014
+ if (r.status !== 200) throw new Error(r.body?.error || `versions request failed (${r.status})`);
1015
+ const out = r.body;
1016
+ if (action === "list") return out.versions.length
1017
+ ? [`${out.versions.length} version(s) of ${out.project}, newest first:`, ...out.versions.map(describeVersion)].join("\n")
1018
+ : `No versions of ${out.project} yet. {action:"save", name, note} keeps one.`;
1019
+ if (action === "save") return `Saved ${describeVersion(out.version)}`;
1020
+ if (action === "update") return describeVersion(out.version);
1021
+ if (action === "delete") return `Deleted v${out.deleted}.`;
1022
+ if (action === "restore") return `Restored v${out.restored.v} "${out.restored.name}". What was there is kept as v${out.saved.v} "${out.saved.name}" (restore it to undo). ` +
1023
+ (out.open === false
1024
+ ? `${out.project} is not the open project, so the editor didn't change; open it (fablecut_projects {action:"open", id:"${out.project}"}) before reading or editing it.`
1025
+ : `The editor reloaded; re-read the project (fablecut_get_project {compact:true}) before editing.`);
1026
+ if (action === "diff") return out.same
1027
+ ? `No difference between ${out.from === "current" ? "now" : "v" + String(out.from).replace(/^v/, "")} and ${out.to === "current" ? "now" : "v" + String(out.to).replace(/^v/, "")}.`
1028
+ : [`From v${String(out.from).replace(/^v/, "")} to ${out.to === "current" ? "now" : "v" + String(out.to).replace(/^v/, "")}:`, ...out.lines.map((l) => "- " + l)].join("\n");
1029
+ return JSON.stringify(out);
1030
+ }
1031
+ /* Before an agent changes the project: a version to go back to. Once per session start
1032
+ (or after 10 quiet minutes), and before every whole-document rewrite. */
1033
+ let lastAgentVersion = 0;
1034
+ /** "" when the version was kept (or wasn't due), else a warning for the tool's answer:
1035
+ * a version is a safety net, so the edit itself goes ahead either way. */
1036
+ function versionBeforeAgent(rewrite) {
1037
+ if (!rewrite && Date.now() - lastAgentVersion < 10 * 60_000) return "";
1038
+ try {
1039
+ const pj = createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR });
1040
+ createHistory({ projects: pj }).beforeAgent(rewrite ? "Before an agent rewrote the project" : "Before agent edits");
1041
+ lastAgentVersion = Date.now();
1042
+ return "";
1043
+ } catch (e) {
1044
+ return ` Warning: no version was saved before this edit (${e.message}) — fablecut_versions {action:"save"} keeps one.`;
1045
+ }
1046
+ }
570
1047
  async function proxyTool(args) {
571
1048
  if (!(await ensureUIServer())) throw new Error(`the editor server is not running and could not be started on port ${PORT}`);
572
1049
  const proj = readProject();
@@ -841,10 +1318,20 @@ async function callTool(name, args, attempt = 0) {
841
1318
  return scopesTool(args);
842
1319
  case "fablecut_frame":
843
1320
  return frameTool(args);
1321
+ case "fablecut_silence":
1322
+ return silenceTool(args);
1323
+ case "fablecut_transcribe":
1324
+ return transcribeTool(args);
1325
+ case "fablecut_captions":
1326
+ return captionsTool(args);
844
1327
  case "fablecut_denoise":
845
1328
  return denoiseTool(args);
846
1329
  case "fablecut_proxy":
847
1330
  return proxyTool(args);
1331
+ case "fablecut_projects":
1332
+ return projectsTool(args);
1333
+ case "fablecut_versions":
1334
+ return versionsTool(args);
848
1335
  case "fablecut_status": {
849
1336
  const up = await ensureUIServer();
850
1337
  const proj = readProject();
@@ -889,6 +1376,7 @@ async function callTool(name, args, attempt = 0) {
889
1376
  return [
890
1377
  `Editor server: ${up ? "RUNNING — open " + BASE + " in a browser to watch edits live" : "FAILED TO START (check node / port " + PORT + ")"}`,
891
1378
  `Project: "${proj.name}" — ${proj.width}x${proj.height} @ ${proj.fps}fps, ${proj.clips.length} clip(s), ${dur.toFixed(2)}s, revision ${proj.revision}`,
1379
+ ...(SeqLib.entries(proj).length > 1 ? [`Sequences (${SeqLib.entries(proj).length}; the numbers above are the open one's): ${SeqLib.list(proj).map(SeqLib.describe).join(" · ")}`] : []),
892
1380
  encLine,
893
1381
  `Registered media: ${cap(proj.media.map((m) => `${m.id} (${m.kind}, ${m.name}${m.duration ? ", " + m.duration + "s" : ""})`), 25).join("; ") || "none"}`,
894
1382
  ...(() => {
@@ -897,6 +1385,15 @@ async function callTool(name, args, attempt = 0) {
897
1385
  })(),
898
1386
  `Files in media/: ${cap(files, 25).join(", ") || "none"}`,
899
1387
  `Library assets (./library): ${libSummary}`,
1388
+ ...(() => {
1389
+ try {
1390
+ const pj = createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR });
1391
+ if (!pj.peekActive()) return [];
1392
+ const { projects: all } = pj.list();
1393
+ const nv = createHistory({ projects: pj }).list(pj.peekActive()).versions.length;
1394
+ return [`Projects: ${all.length} (fablecut_projects lists, opens and creates them; this one is ${pj.peekActive()}, with ${nv} saved version(s): fablecut_versions)`];
1395
+ } catch { return []; }
1396
+ })(),
900
1397
  `Project file: ${PROJECT_FILE}`,
901
1398
  `Tips: fablecut_docs (use \`section\`) for the schema · fablecut_get_project {compact:true} to see the timeline · fablecut_patch_project for edits (cheapest) · fablecut_encode_profiles for export presets.`,
902
1399
  ].join("\n");
@@ -942,6 +1439,8 @@ async function callTool(name, args, attempt = 0) {
942
1439
  deliveryPresets: savedDeliveryPresets(),
943
1440
  mediaInfo: (src) => { const f = mediaFile(src); return f ? probeFile(f) : null; },
944
1441
  });
1442
+ // a version of the project as it was, kept before the last check so the write follows that check at once
1443
+ const verWarn = versionBeforeAgent(false);
945
1444
  // Someone else saved while the ops ran: writing now would drop their change.
946
1445
  // Without a baseRevision the ops just re-apply on the newer document.
947
1446
  let diskRev = readRev;
@@ -954,7 +1453,7 @@ async function callTool(name, args, attempt = 0) {
954
1453
  writeProject(proj);
955
1454
  lastReadRevision = proj.revision;
956
1455
  for (const [kind, item] of toSave) writeSaved(kind, item.id, item);
957
- return `Patched (revision ${proj.revision}): ${notes.join(" ")}. Now ${proj.clips.length} clip(s), ${proj.media.length} media. UI hot-reloaded.`;
1456
+ return `Patched (revision ${proj.revision}): ${notes.join(" ")}. Now ${proj.clips.length} clip(s), ${proj.media.length} media. UI hot-reloaded.${verWarn}`;
958
1457
  }
959
1458
  case "fablecut_set_project": {
960
1459
  const doc = args.project;
@@ -962,6 +1461,7 @@ async function callTool(name, args, attempt = 0) {
962
1461
  if (!Array.isArray(doc.clips) || !Array.isArray(doc.media))
963
1462
  throw new Error("project must contain `clips` and `media` arrays");
964
1463
  ProjectOps.checkProject(doc);
1464
+ const verWarn = versionBeforeAgent(true); // before the conflict check, so the write follows it at once
965
1465
  let cur = { revision: 0 };
966
1466
  try { cur = readProject(); } catch {}
967
1467
  const curRev = cur.revision || 0;
@@ -984,7 +1484,7 @@ async function callTool(name, args, attempt = 0) {
984
1484
  if (!(doc.panSchema >= 1) && (cur.panSchema >= 1)) doc.panSchema = 1;
985
1485
  writeProject(doc);
986
1486
  lastReadRevision = doc.revision;
987
- return `Saved (revision ${doc.revision}). ${doc.clips.length} clip(s). The editor UI (if open at ${BASE}) has hot-reloaded.`;
1487
+ return `Saved (revision ${doc.revision}). ${doc.clips.length} clip(s). The editor UI (if open at ${BASE}) has hot-reloaded.${verWarn}`;
988
1488
  }
989
1489
  case "fablecut_normalize_audio": {
990
1490
  const ids = Array.isArray(args.clipIds) ? args.clipIds.map(String) : [];
@@ -1246,7 +1746,7 @@ async function handle(msg) {
1246
1746
  result: {
1247
1747
  protocolVersion: negotiateProtocolVersion(params?.protocolVersion),
1248
1748
  capabilities: { tools: {} },
1249
- serverInfo: { name: "fablecut", version: "1.15.0" },
1749
+ serverInfo: { name: "fablecut", version: "1.17.0" },
1250
1750
  },
1251
1751
  });
1252
1752
  }