fablecut 1.17.0 → 1.19.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
@@ -50,8 +50,8 @@ const ROOT = APP_DIR;
50
50
  ensureDirs();
51
51
  const PORT = process.env.FABLECUT_PORT || 7777;
52
52
  const BASE = `http://localhost:${PORT}`;
53
- // Requests go to the address the server binds: on Node 18, "localhost" can
54
- // resolve to ::1 first and is not retried on 127.0.0.1.
53
+ // Requests go to the address the server binds rather than "localhost", which
54
+ // can resolve to ::1 first; this does not rely on a fallback to 127.0.0.1.
55
55
  const API = `http://${process.env.HOST === "::1" ? "[::1]" : "127.0.0.1"}:${PORT}`;
56
56
 
57
57
  /* MCP initialize must echo a version we actually speak. Echoing an unknown
@@ -231,6 +231,22 @@ const TOOLS = [
231
231
  required: ["path"],
232
232
  },
233
233
  },
234
+ {
235
+ name: "fablecut_files",
236
+ description: "The project's files on disk, inside ./media/ (the folder fablecut_import_media copies into): list a folder, make folders, move or rename files and folders, and throw away what isn't needed. Nothing is deleted: trash moves a file into media/.trash/ and restore puts it back. A move repoints every project's media entries at the new place, so no clip goes offline, and the file keeps its transcript. Trash refuses a file a project still uses (removeMedia it first, or force:true to trash it anyway: it goes offline there until restored). The media bin's folders (folderId) are separate: they organize entries, these are the real folders. Paths are relative to media/ ('b-roll/day 1/a.mp4') or /media/… srcs. Move, rename and trash only when the user asked for it.",
237
+ inputSchema: {
238
+ type: "object",
239
+ properties: {
240
+ action: { type: "string", enum: ["list", "mkdir", "move", "trash", "trash-list", "restore"], description: "list (default) · mkdir · move (also renames) · trash · trash-list · restore" },
241
+ dir: { type: "string", description: "list: the folder (default media/ itself) · mkdir: the folder to make (parents too)" },
242
+ from: { type: "string", description: "move: the file or folder" },
243
+ to: { type: "string", description: "move: an existing folder to move it into, or the new path (a rename)" },
244
+ paths: { type: "array", items: { type: "string" }, description: "trash: files or folders" },
245
+ force: { type: "boolean", description: "trash: even files a project still uses (they go offline until restored); move: even while a project can't be read (the file goes offline there)" },
246
+ id: { type: "string", description: "restore: a trashed item's id (trash-list shows them)" },
247
+ },
248
+ },
249
+ },
234
250
  {
235
251
  name: "fablecut_encode_profiles",
236
252
  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.",
@@ -291,6 +307,52 @@ const TOOLS = [
291
307
  required: ["clipIds"],
292
308
  },
293
309
  },
310
+ {
311
+ name: "fablecut_beats",
312
+ description: "The music's beat on the timeline, and cuts that land on it. Listens to a music clip (an audio clip, or a video's sound) and finds its tempo (BPM), a steady beat grid phased to the hits, and the drop — all in timeline seconds, through the clip's in point and speed. Then, in one revision: markers:true puts a cyan marker on every beat; snap:true rolls each cut on the video tracks (the targeted ones, or snap:{tracks}) to the nearest beat within half a beat (snap:{maxShift} seconds) — nothing else moves, linked stems follow; retime:{track?, every?, from?} lays the clips on a track (default the lowest video track with clips) back to back on the beat, `every` beats each (1, 2, 4, 8 or 16; default 2), from the first beat at or after `from` (default the music's start) — a clip whose footage runs out gets fewer beats, and the order is kept. Locked clips are left alone (snap) or refuse (retime) unless force:true. A version is saved before snap or retime (if that fails the edit still goes ahead and the reply warns). Without markers / snap / retime it only reports. The same as the Inspector's Beats section. Needs ffmpeg on PATH.",
313
+ inputSchema: {
314
+ type: "object",
315
+ properties: {
316
+ clipId: { type: "string", description: "The music clip to listen to" },
317
+ markers: { type: "boolean", description: "Put a cyan marker on every beat (other markers stay)" },
318
+ snap: { description: "true, or {tracks?:[…], maxShift?: seconds}: roll each cut on those video tracks to the nearest beat" },
319
+ retime: { description: "true, or {track?: 'V1', every?: 1|2|4|8|16, from?: seconds}: re-cut that track's clips to the beat, `every` beats each" },
320
+ every: { type: "number", description: "Beats per shot for retime (1, 2, 4, 8 or 16; default 2)" },
321
+ force: { type: "boolean", description: "Also move locked clips (only when the user asked)" },
322
+ },
323
+ required: ["clipId"],
324
+ },
325
+ },
326
+ {
327
+ name: "fablecut_reframe",
328
+ description: "Reframe for another shape, following the subject: a 16:9 edit made 9:16 (Reels, Shorts, TikTok), 1:1 or 4:5. With aspect, a copy of the open sequence is made on that canvas (the project's shorter side kept, e.g. 1920×1080 → 1080×1920) and opened, so the original cut stays as it was; without aspect, the open sequence is reframed on its own canvas. Each full-frame shot (a video or still that isn't moved, scaled, cropped or animated by hand) is fitted to cover the canvas, and its position follows what matters in it: frames are sampled 5 times a second, the subject is found by motion against the shot's own movement, detail and colour, and a virtual camera operator holds still until the subject leaves a dead zone, then eases after it no faster than a pan speed. The result is ordinary x (or y) keyframes, thinned to a few, or one steady position — edit them like any keys. Shots without a clear subject are centred. Titles, picture-in-picture, clips placed by hand and locked clips are left alone (listed in the reply) — check them with fablecut_frame on the new canvas. clipIds limits it to some clips; follow:false only fits and centres; smooth 0…1 (default 0.5) — higher holds longer and pans slower. A version is saved first. Needs ffmpeg on PATH.",
329
+ inputSchema: {
330
+ type: "object",
331
+ properties: {
332
+ aspect: { type: "string", enum: ["9:16", "1:1", "4:5", "16:9", "4:3", "2:3"], description: "Make a copy of the open sequence on this canvas shape and reframe it (default: reframe the open sequence as it is)" },
333
+ name: { type: "string", description: "With aspect: the new sequence's name (default: the open one's name and the shape)" },
334
+ clipIds: { type: "array", items: { type: "string" }, description: "Only these clips (default: every full-frame shot)" },
335
+ follow: { type: "boolean", description: "Follow the subject (default true); false only fits and centres" },
336
+ smooth: { type: "number", description: "0…1, default 0.5: higher holds longer and pans slower" },
337
+ force: { type: "boolean", description: "Also reframe locked clips (only when the user asked)" },
338
+ },
339
+ },
340
+ },
341
+ {
342
+ name: "fablecut_highlights",
343
+ description: "The best moments of long footage, cut into a short edit: a 30 s reel from a 20-minute vlog, a match, a talk, a day of B-roll. Looks at the video clips on the open timeline (or clipIds, or whole files with mediaIds) — frames twice a second and the sound — and scores every half second: movement, sound louder than around it (a cheer, a laugh, a hit), a clear picture. Cuts already in the footage are found and never crossed. It takes the best moments of `shot` seconds (default: duration / 8, 1.5–4 s), apart from each other and spread over the shots, until the edit is `duration` seconds (default 30), and nudges each end to a quiet point so no word or hit is cut through. They go back to back on V1 of a new sequence, in story order, with their linked sound, and the sequence is opened; the timeline you started from is left as it was. aspect makes the new sequence 9:16, 1:1 or 4:5 (then fablecut_reframe {} fits the shots and follows the subject). The reply lists each moment (source, times, why it was picked). A version is saved first. Then: music under it and fablecut_beats {clipId, retime:{every:2}} cuts it on the beat. Needs ffmpeg on PATH.",
344
+ inputSchema: {
345
+ type: "object",
346
+ properties: {
347
+ duration: { type: "number", description: "Seconds of edit to make, 5…600 (default 30)" },
348
+ shot: { type: "number", description: "Seconds per moment, 0.5…20 (default: duration / 8, kept within 1.5–4)" },
349
+ clipIds: { type: "array", items: { type: "string" }, description: "Video clips to look through (default: every video clip on the open timeline)" },
350
+ mediaIds: { type: "array", items: { type: "string" }, description: "Instead of clips: whole video files from the project's media" },
351
+ name: { type: "string", description: "The new sequence's name (default: Highlights <duration> s)" },
352
+ aspect: { type: "string", enum: ["9:16", "1:1", "4:5", "16:9", "4:3", "2:3"], description: "The new sequence's shape (default: the open one's canvas)" },
353
+ },
354
+ },
355
+ },
294
356
  {
295
357
  name: "fablecut_transcribe",
296
358
  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.",
@@ -409,6 +471,7 @@ const TOOLS = [
409
471
  type: "object",
410
472
  properties: {
411
473
  range: { type: "string", enum: ["entire", "in-out"], description: "Whole timeline, or the project's inPoint→outPoint (default: in-out when either is set)" },
474
+ name: { type: "string", description: "The file's name, without the extension. Default: a delivery preset's filename pattern, which starts with the project's name (with an encoding profile, the project's name) — so name the file after what it is (e.g. 'salon-promo-15s') whenever the project holds more than this one video. The editor's own Export dialog asks the user for a name; this is that answer. Only the name changes: the preset, delivery or encoding profile the export uses stays the same. Not with outputs" },
412
475
  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'" },
413
476
  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" },
414
477
  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" }] } }] },
@@ -634,8 +697,7 @@ async function silenceTool(args) {
634
697
  let verWarn = "";
635
698
  try { createHistory({ projects: createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR }) }).beforeAgent("Before cutting silences"); }
636
699
  catch (e) { verWarn = ` Warning: no version was saved before the cut (${e.message}).`; }
637
- let diskRev = readRev;
638
- try { diskRev = readProject().revision || 0; } catch {}
700
+ const diskRev = readProject().revision || 0; // a failed read stops it: never write over what we can't see
639
701
  if (diskRev !== readRev) throw new Error(`the project changed while cutting (revision ${readRev} → ${diskRev}) — nothing cut; run fablecut_silence again`);
640
702
  proj.revision = readRev + 1;
641
703
  writeProject(proj);
@@ -643,6 +705,224 @@ async function silenceTool(args) {
643
705
  return `Cut ${head} — timeline ${fmtDur(before)} → ${fmtDur(end(proj))} (revision ${proj.revision}). UI hot-reloaded.` +
644
706
  (verWarn || ` The project as it was is kept as a version (fablecut_versions lists it; restore undoes the cut).`);
645
707
  }
708
+ /* fablecut_beats: beats.js on the music clip's sound, then its ops (markers, snap, retime). */
709
+ const BEATS_MAX_SECS = 20 * 60;
710
+ async function beatsTool(args) {
711
+ const Bt = require("./beats.js");
712
+ const doc = readProject();
713
+ const readRev = doc.revision || 0;
714
+ const clip = doc.clips.find((c) => c.id === String(args.clipId || ""));
715
+ if (!clip) throw new Error("`clipId` must name the music clip on the timeline (fablecut_get_project {compact:true} lists them)");
716
+ if (clip.kind !== "audio" && clip.kind !== "video") throw new Error(`clip ${clip.id} is ${clip.kind} — no sound to find a beat in`);
717
+ if (Bt.ramped(clip)) throw new Error(`clip ${clip.id} has a speed ramp — beats follow music playing at a steady speed`);
718
+ const sp = Math.min(8, Math.max(0.1, +clip.props?.speed || 1));
719
+ if (clip.duration * sp > BEATS_MAX_SECS) throw new Error(`clip ${clip.id} is longer than ${BEATS_MAX_SECS / 60} minutes of music — split it, or find the beat on a part of it`);
720
+ const parts = [];
721
+ const nCh = await streamClipAudio(doc, clip, () => true, (chs) => parts.push(Bt.mono(chs)));
722
+ if (!nCh) throw new Error(`clip ${clip.id} has no audio stream — nothing to listen to`);
723
+ const len = parts.reduce((n, p) => n + p.length, 0), all = new Float32Array(len);
724
+ let at = 0;
725
+ for (const p of parts) { all.set(p, at); at += p.length; }
726
+ const a = Bt.analyze(Bt.resample(all, NORM_SR));
727
+ const src0 = clip.in || 0;
728
+ const abs = { beats: a.beats.map((t) => t + src0), bpm: a.bpm, drop: a.drop != null ? a.drop + src0 : null };
729
+ const acts = { markers: args.markers === true, snap: args.snap || false, retime: args.retime || false, every: args.every, force: args.force === true };
730
+ const r = Bt.plan(doc, clip, abs, acts);
731
+ if (!r.ops.length) return Bt.describe(r);
732
+ const proj = readProject();
733
+ if ((proj.revision || 0) !== readRev)
734
+ throw new Error(`the project changed while listening (revision ${readRev} → ${proj.revision}) — nothing changed; run fablecut_beats again`);
735
+ ProjectOps.applyPatch(proj, r.ops, { savedItems });
736
+ let verWarn = "";
737
+ if (acts.snap || acts.retime) {
738
+ try { createHistory({ projects: createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR }) }).beforeAgent(acts.retime ? "Before re-cutting to the beat" : "Before snapping cuts to the beat"); }
739
+ catch (e) { verWarn = ` Warning: no version was saved first (${e.message}).`; }
740
+ }
741
+ const diskRev = readProject().revision || 0; // a failed read stops it: never write over what we can't see
742
+ if (diskRev !== readRev) throw new Error(`the project changed meanwhile (revision ${readRev} → ${diskRev}) — nothing changed; run fablecut_beats again`);
743
+ proj.revision = readRev + 1;
744
+ writeProject(proj);
745
+ lastReadRevision = proj.revision;
746
+ return Bt.describe(r, { applied: true }) + ` (revision ${proj.revision}; UI hot-reloaded.)` +
747
+ (acts.snap || acts.retime ? verWarn || " The project as it was is kept as a version (fablecut_versions; restore undoes it)." : "");
748
+ }
749
+ /* fablecut_reframe: a new sequence on the canvas asked for (or the open one), then reframe.js on frames
750
+ ffmpeg samples from each full-frame shot's window. */
751
+ const REFRAME_MAX_SECS = 15 * 60;
752
+ function sampleFrames(file, c, w, h) {
753
+ const R = require("./reframe.js");
754
+ const sp = Math.min(8, Math.max(0.1, +c.props?.speed || 1));
755
+ const len = Math.max(0.1, Math.min(REFRAME_MAX_SECS, c.duration * sp));
756
+ const args = c.kind === "image"
757
+ ? ["-v", "error", "-i", file, "-frames:v", "1", "-vf", `scale=${w}:${h}`, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"]
758
+ : ["-v", "error", "-ss", String(Math.max(0, +c.in || 0)), "-t", String(len), "-i", file, "-an",
759
+ "-vf", `fps=${R.SAMPLE_FPS},scale=${w}:${h}`, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"];
760
+ const r = require("child_process").spawnSync("ffmpeg", args, { maxBuffer: 1 << 29, timeout: Math.max(120000, len * 2000) });
761
+ if (r.error?.code === "ENOENT") throw new Error("ffmpeg not found on PATH — needed to look at the footage");
762
+ if (r.error) throw new Error(`ffmpeg couldn't read ${c.id}: ${r.error.code === "ETIMEDOUT" ? "it took too long" : r.error.message}`);
763
+ if (r.status !== 0) throw new Error(`ffmpeg couldn't read ${c.id}: ${String(r.stderr).trim().split("\n").pop()}`);
764
+ const fb = w * h * 3, frames = [];
765
+ for (let o = 0; o + fb <= r.stdout.length; o += fb) frames.push(r.stdout.subarray(o, o + fb));
766
+ return frames;
767
+ }
768
+ async function reframeTool(args) {
769
+ const R = require("./reframe.js");
770
+ const doc = readProject();
771
+ const readRev = doc.revision || 0;
772
+ const smooth = args.smooth == null ? 0.5 : +args.smooth;
773
+ if (!(smooth >= 0 && smooth <= 1)) throw new Error("smooth must be 0…1");
774
+ const ids = Array.isArray(args.clipIds) && args.clipIds.length ? args.clipIds.map(String) : null;
775
+ const ops = [];
776
+ // the sequence as it will be: a copy on the new canvas, opened — or the open one
777
+ let work = doc, made = "";
778
+ if (args.aspect) {
779
+ const canvas = R.canvasFor(args.aspect, doc.width, doc.height);
780
+ const open = (doc.sequences || []).find((s) => s.id === doc.sequence);
781
+ const seqName = String(args.name || `${open?.name || "Main"} ${args.aspect}`).slice(0, 80);
782
+ const add = { op: "addSequence", from: "open", name: seqName, width: canvas.width, height: canvas.height, open: true };
783
+ work = JSON.parse(JSON.stringify(doc));
784
+ ProjectOps.applyPatch(work, [add], { savedItems });
785
+ ops.push(add);
786
+ made = `New sequence "${seqName}" ${canvas.width}×${canvas.height}, opened. `;
787
+ }
788
+ const canvas = { width: work.width, height: work.height };
789
+ const { take, skip } = R.targets(work, { ids, force: args.force === true });
790
+ if (!take.length) throw new Error("no full-frame shots to reframe" + (skip.length ? ` (${skip.map((x) => `${x.id}: ${x.why}`).join("; ")})` : ""));
791
+ const lines = [];
792
+ for (const c of take) {
793
+ const m = work.media.find((x) => x.id === c.mediaId);
794
+ const file = m && mediaFile(m.src);
795
+ if (!file) { skip.push({ id: c.id, why: "media file not found" }); continue; }
796
+ let src = m.width > 0 && m.height > 0 ? { width: m.width, height: m.height } : null;
797
+ if (!src) {
798
+ const pr = require("child_process").spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", file], { timeout: 10000 });
799
+ const [w, h] = String(pr.stdout).trim().split(",").map(Number);
800
+ if (w > 0 && h > 0) src = { width: w, height: h };
801
+ }
802
+ if (!src) { skip.push({ id: c.id, why: "couldn't read its size" }); continue; }
803
+ let samples = null;
804
+ const cover = R.coverRect(src.width, src.height, canvas.width, canvas.height, 1);
805
+ if (args.follow !== false && Math.max(cover.maxX, cover.maxY) > 0.5) { // no room to pan: nothing to look at
806
+ const w = R.SAMPLE_W, h = Math.max(8, Math.round(w * src.height / src.width / 2) * 2);
807
+ try { samples = R.subjectTrack(sampleFrames(file, c, w, h), w, h); }
808
+ catch (e) { skip.push({ id: c.id, why: e.message }); continue; }
809
+ }
810
+ const p = R.clipPlan(c, samples, src, canvas, { smooth, fps: work.fps || 30, follow: args.follow !== false });
811
+ ops.push({ op: "updateClip", id: c.id, set: p.set, ...(args.force === true ? { force: true } : {}) });
812
+ lines.push(` ${c.id}: ${p.note}`);
813
+ }
814
+ if (!lines.length) throw new Error("nothing could be reframed: " + skip.map((x) => `${x.id}: ${x.why}`).join("; "));
815
+ const proj = readProject();
816
+ if ((proj.revision || 0) !== readRev)
817
+ throw new Error(`the project changed while looking at the footage (revision ${readRev} → ${proj.revision}) — nothing changed; run fablecut_reframe again`);
818
+ let verWarn = "";
819
+ try { createHistory({ projects: createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR }) }).beforeAgent("Before reframing"); }
820
+ catch (e) { verWarn = ` Warning: no version was saved first (${e.message}).`; }
821
+ const diskRev = readProject().revision || 0; // a failed read stops it: never write over what we can't see
822
+ if (diskRev !== readRev) throw new Error(`the project changed meanwhile (revision ${readRev} → ${diskRev}) — nothing changed; run fablecut_reframe again`);
823
+ ProjectOps.applyPatch(proj, ops, { savedItems });
824
+ proj.revision = readRev + 1;
825
+ writeProject(proj);
826
+ lastReadRevision = proj.revision;
827
+ return `${made}Reframed ${lines.length} shot${lines.length === 1 ? "" : "s"} for ${canvas.width}×${canvas.height} (revision ${proj.revision}):\n` + lines.join("\n") +
828
+ (skip.length ? `\nLeft as they were: ${skip.map((x) => `${x.id} (${x.why})`).join(", ")} — check them on the new canvas with fablecut_frame {time}.` : "") +
829
+ (verWarn || "\nThe project as it was is kept as a version (fablecut_versions; restore undoes it).");
830
+ }
831
+ /* fablecut_highlights: highlights.js on the frames and sound ffmpeg streams from each source
832
+ (frame by frame, without holding the server), then a new sequence holding the best moments. */
833
+ function streamPicture(file, from, len, w, h, push) {
834
+ const H = require("./highlights.js");
835
+ return new Promise((resolve, reject) => {
836
+ const proc = spawn("ffmpeg", ["-v", "error", "-ss", String(Math.max(0, from)), "-t", String(Math.max(0.1, len)), "-i", file, "-an",
837
+ "-vf", `fps=${H.PIC_FPS},scale=${w}:${h}`, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"]);
838
+ const fb = w * h * 3;
839
+ let rest = Buffer.alloc(0), err = "", n = 0;
840
+ const tm = setTimeout(() => { proc.kill(); reject(new Error("ffmpeg took too long reading the footage")); }, Math.max(120000, len * 1000));
841
+ proc.stdout.on("data", (chunk) => {
842
+ const buf = rest.length ? Buffer.concat([rest, chunk]) : chunk;
843
+ let o = 0;
844
+ for (; o + fb <= buf.length; o += fb) { push(buf.subarray(o, o + fb)); n++; }
845
+ rest = Buffer.from(buf.subarray(o));
846
+ });
847
+ proc.stderr.on("data", (d) => { err += d; });
848
+ proc.on("error", (e) => { clearTimeout(tm); reject(new Error(e.code === "ENOENT" ? "ffmpeg not found on PATH — needed to look at the footage" : e.message)); });
849
+ proc.on("close", (code) => { clearTimeout(tm); if (code === 0) resolve(n); else reject(new Error(`ffmpeg couldn't read the footage: ${err.trim().split("\n").pop() || code}`)); });
850
+ });
851
+ }
852
+ async function highlightsTool(args) {
853
+ const H = require("./highlights.js"), Bt = require("./beats.js");
854
+ const opts = H.options(args);
855
+ const doc = readProject();
856
+ const readRev = doc.revision || 0;
857
+ const canvas = args.aspect ? require("./reframe.js").canvasFor(args.aspect, doc.width, doc.height) : {}; // a bad shape refuses before any reading
858
+ const srcs = [];
859
+ let skip = [];
860
+ if (Array.isArray(args.mediaIds) && args.mediaIds.length) {
861
+ for (const id of args.mediaIds.map(String)) {
862
+ const m = (doc.media || []).find((x) => x.id === id);
863
+ if (!m) throw new Error(`no media ${id}`);
864
+ if (m.kind !== "video") throw new Error(`media ${id} is ${m.kind} — highlights are cut from video`);
865
+ if (!(m.duration > 0)) throw new Error(`media ${id}: its length isn't known yet — open the editor so it probes the file, then call again`);
866
+ srcs.push({ id: "media:" + id, clip: { id: "media:" + id, mediaId: id, kind: "video", in: 0, duration: m.duration, props: {} }, media: m });
867
+ }
868
+ } else {
869
+ const ids = Array.isArray(args.clipIds) && args.clipIds.length ? args.clipIds.map(String) : null;
870
+ const r = H.sourcesOf(doc, ids);
871
+ skip = r.skip;
872
+ for (const c of r.take) {
873
+ const m = (doc.media || []).find((x) => x.id === c.mediaId);
874
+ if (m) srcs.push({ id: c.id, clip: c, media: m });
875
+ else skip.push({ id: c.id, why: "its media isn't in the project" });
876
+ }
877
+ }
878
+ const why = () => skip.map((x) => `${x.id} (${x.why})`).join(", ");
879
+ if (!srcs.length) throw new Error("no video to make highlights from" + (skip.length ? `: ${why()}` : "") + " — put footage on the timeline, or pass mediaIds");
880
+ const total = srcs.reduce((n, s) => n + clipSourceLen(s.clip), 0);
881
+ if (total > H.MAX_SOURCE_SECS)
882
+ throw new Error(`that's ${Math.round(total / 60)} minutes of footage — up to ${H.MAX_SOURCE_SECS / 60} at a time; pass clipIds or mediaIds`);
883
+ const sources = [];
884
+ for (const s of srcs) {
885
+ const file = mediaFile(s.media.src);
886
+ if (!file) { skip.push({ id: s.id, why: "media file not found" }); continue; }
887
+ let mw = s.media.width, mh = s.media.height;
888
+ if (!(mw > 0 && mh > 0)) {
889
+ const pr = spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", file], { timeout: 10000 });
890
+ [mw, mh] = String(pr.stdout || "").trim().split(",").map(Number);
891
+ }
892
+ const w = H.SAMPLE_W, h = Math.max(8, Math.round((w * (mw > 0 && mh > 0 ? mh / mw : 9 / 16)) / 2) * 2);
893
+ const len = clipSourceLen(s.clip), pic = H.picture(w, h);
894
+ try { await streamPicture(file, s.clip.in || 0, len, w, h, (f) => pic.push(f)); }
895
+ catch (e) { skip.push({ id: s.id, why: e.message }); continue; }
896
+ if (pic.motion.length < 2) { skip.push({ id: s.id, why: "too short to look at" }); continue; }
897
+ let aud = H.sound(NORM_SR);
898
+ try { if (!(await streamClipAudio(doc, s.clip, () => true, (chs) => aud.push(Bt.mono(chs))))) aud = null; }
899
+ catch { aud = null; } // no sound to read: the picture alone decides
900
+ sources.push({ id: s.id, len, pic, aud, speed: Math.min(8, Math.max(0.1, +s.clip.props?.speed || 1)) });
901
+ }
902
+ if (!sources.length) throw new Error("none of the footage could be read: " + why());
903
+ const picks = H.pick(sources, opts);
904
+ if (!picks.length) throw new Error("no moments long enough to use — try a shorter shot");
905
+ const seqName = String(args.name || `Highlights ${opts.duration} s`).slice(0, 80);
906
+ const ops = H.ops(doc, picks, { name: seqName, ...canvas });
907
+ const proj = readProject();
908
+ if ((proj.revision || 0) !== readRev)
909
+ throw new Error(`the project changed while looking at the footage (revision ${readRev} → ${proj.revision}) — nothing changed; run fablecut_highlights again`);
910
+ let verWarn = "";
911
+ try { createHistory({ projects: createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR }) }).beforeAgent("Before making highlights"); }
912
+ catch (e) { verWarn = ` Warning: no version was saved first (${e.message}).`; }
913
+ const diskRev = readProject().revision || 0; // a failed read stops it: never write over what we can't see
914
+ if (diskRev !== readRev) throw new Error(`the project changed meanwhile (revision ${readRev} → ${diskRev}) — nothing changed; run fablecut_highlights again`);
915
+ ProjectOps.applyPatch(proj, ops, { savedItems });
916
+ proj.revision = readRev + 1;
917
+ writeProject(proj);
918
+ lastReadRevision = proj.revision;
919
+ const reshaped = canvas.width && canvas.width * doc.height !== canvas.height * doc.width;
920
+ return H.describe(picks, { duration: opts.duration, seqName, made: true }) + `\n(revision ${proj.revision}; UI hot-reloaded.)` +
921
+ (skip.length ? `\nNot looked at: ${why()}.` : "") +
922
+ (reshaped ? "\nThe shots are letterboxed on the new canvas: fablecut_reframe {} fits them and follows the subject." : "") +
923
+ "\nCheck a moment with fablecut_frame {time}; with music under it, fablecut_beats {clipId, retime:{every:2}} cuts it on the beat." +
924
+ (verWarn || "\nThe project as it was is kept as a version (fablecut_versions; restore undoes it).");
925
+ }
646
926
  /** What words are placed by and cuts land on: where each clip sits and plays from, the track
647
927
  * switches and the frame rate. An editor saving probed media details while a transcription runs
648
928
  * doesn't change it; a moved, trimmed or cut clip does. */
@@ -781,8 +1061,7 @@ async function transcribeTool(args) {
781
1061
  let verWarn = "";
782
1062
  try { createHistory({ projects: createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR }) }).beforeAgent("Before cutting words"); }
783
1063
  catch (e) { verWarn = ` Warning: no version was saved before the cut (${e.message}).`; }
784
- let diskRev = readRev;
785
- try { diskRev = readProject().revision || 0; } catch {}
1064
+ const diskRev = readProject().revision || 0; // a failed read stops it: never write over what we can't see
786
1065
  if (diskRev !== readRev) throw new Error(`the project changed while cutting (revision ${readRev} → ${diskRev}) — nothing cut; run fablecut_transcribe again`);
787
1066
  proj.revision = readRev + 1;
788
1067
  writeProject(proj);
@@ -1083,6 +1362,51 @@ async function proxyTool(args) {
1083
1362
  };
1084
1363
  return list.map(line).join("\n") + (busy() ? "\nStill working — call fablecut_proxy again (without create) to check." : "");
1085
1364
  }
1365
+ /* ── Files in media/ (fablecut_files) ── */
1366
+ async function filesTool(args) {
1367
+ if (!(await ensureUIServer())) throw new Error(`the editor server is not running and could not be started on port ${PORT}`);
1368
+ const action = args.action || "list";
1369
+ const body = { action, dir: args.dir, from: args.from, to: args.to, paths: args.paths, force: args.force, id: args.id };
1370
+ const r = await apiJSON("POST", "/api/files", body);
1371
+ const name = (src) => { try { return decodeURIComponent(String(src).replace(/^\/media\//, "")); } catch { return src; } };
1372
+ const restoreWith = (t) => `Trashed ${name(t.src)} (id ${t.id} — restore with {action:"restore", id:"${t.id}"})${t.warning ? ` — ${t.warning}` : ""}`;
1373
+ if (r.status !== 200) {
1374
+ // a trash that stopped part-way: the ones that went still need their ids
1375
+ if (r.body?.trashed?.length) throw new Error(r.body.error + "\n" + r.body.trashed.map(restoreWith).join("\n"));
1376
+ throw new Error(r.body?.error || `files request failed (${r.status})`);
1377
+ }
1378
+ const b = r.body;
1379
+ const kb = (n) => n >= 1048576 ? (n / 1048576).toFixed(1) + " MB" : Math.max(1, Math.round(n / 1024)) + " KB";
1380
+ if (action === "list") {
1381
+ const lines = [`media/${b.dir ? b.dir + "/" : ""} — ${b.folders.length} folder${b.folders.length === 1 ? "" : "s"}, ${b.files.length} file${b.files.length === 1 ? "" : "s"}`];
1382
+ for (const f of b.folders) lines.push(` ${f}/`);
1383
+ for (const f of b.files) lines.push(` ${f.name} ${kb(f.size)} ${f.src}`);
1384
+ return lines.join("\n");
1385
+ }
1386
+ if (action === "mkdir") return `Made media/${b.dir}/`;
1387
+ if (action === "move") {
1388
+ if (b.from === b.to) return "Nothing moved (it is already there).";
1389
+ if (!b.moved.length) return `Moved ${name(b.from)}/ → ${name(b.to)}/ (an empty folder)`;
1390
+ const lines = [`Moved ${b.moved.length} file${b.moved.length === 1 ? "" : "s"}:`, ...b.moved.slice(0, 20).map((m) => ` ${name(m.from)} → ${name(m.to)}`)];
1391
+ if (b.moved.length > 20) lines.push(` … +${b.moved.length - 20} more`);
1392
+ lines.push(b.repointed.length ? "Media entries repointed: " + b.repointed.map((x) => `${x.media} in ${x.open ? "the open project" : `"${x.project}"`}`).join(", ") : "No project used them.");
1393
+ if (b.warning) lines.push("Warning: " + b.warning);
1394
+ return lines.join("\n");
1395
+ }
1396
+ if (action === "trash") {
1397
+ const lines = b.trashed.map(restoreWith);
1398
+ if (b.stillThere?.length) lines.push("Still playing (part of the original stayed): " + b.stillThere.map((u) => `"${u.name}"`).join(", "));
1399
+ if (b.offline.length) lines.push("Now OFFLINE: " + b.offline.map((u) => `"${u.name}" in ${u.open ? "the open project" : `"${u.project}"`}`).join(", "));
1400
+ return lines.join("\n");
1401
+ }
1402
+ if (action === "trash-list") {
1403
+ if (!b.items.length) return "The trash is empty.";
1404
+ return b.items.map((t) => `${t.id} ${name(t.src)}${t.kind === "folder" ? `/ (${t.size} files)` : " " + kb(t.size)} trashed ${t.trashed}`).join("\n");
1405
+ }
1406
+ if (action === "restore") return `Restored ${name(b.restored.src)}` + (b.restored.warning ? ` — ${b.restored.warning}` : "");
1407
+ return JSON.stringify(b);
1408
+ }
1409
+
1086
1410
  async function exportTool(args) {
1087
1411
  if (!(await ensureUIServer())) throw new Error(`the editor server is not running and could not be started on port ${PORT}`);
1088
1412
  let startNote = "";
@@ -1097,7 +1421,10 @@ async function exportTool(args) {
1097
1421
  if (r.status !== 200) throw new Error(r.body?.error || "no such export job");
1098
1422
  job = r.body;
1099
1423
  } else {
1100
- 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" });
1424
+ if (args.name != null && typeof args.name !== "string") throw new Error("name is a string: the file's name, without the extension");
1425
+ const name = args.name?.trim() || undefined;
1426
+ if (name && args.outputs) throw new Error("name goes with one file, not with outputs (give each output its own filename)");
1427
+ const r = await apiJSON("POST", "/api/export/request", { range: args.range, profile: args.profile, preset: args.preset, delivery: args.delivery, outputs: args.outputs, name, where: args.where || "auto" });
1101
1428
  if (r.status !== 200) throw new Error(r.body?.error || `export request failed (${r.status})`);
1102
1429
  job = r.body;
1103
1430
  if (job.notes && job.notes.length) startNote = `Settings adjusted: ${job.notes.join("; ")}\n`;
@@ -1320,6 +1647,12 @@ async function callTool(name, args, attempt = 0) {
1320
1647
  return frameTool(args);
1321
1648
  case "fablecut_silence":
1322
1649
  return silenceTool(args);
1650
+ case "fablecut_beats":
1651
+ return beatsTool(args);
1652
+ case "fablecut_reframe":
1653
+ return reframeTool(args);
1654
+ case "fablecut_highlights":
1655
+ return highlightsTool(args);
1323
1656
  case "fablecut_transcribe":
1324
1657
  return transcribeTool(args);
1325
1658
  case "fablecut_captions":
@@ -1443,8 +1776,7 @@ async function callTool(name, args, attempt = 0) {
1443
1776
  const verWarn = versionBeforeAgent(false);
1444
1777
  // Someone else saved while the ops ran: writing now would drop their change.
1445
1778
  // Without a baseRevision the ops just re-apply on the newer document.
1446
- let diskRev = readRev;
1447
- try { diskRev = readProject().revision || 0; } catch {}
1779
+ const diskRev = readProject().revision || 0; // a failed read stops it: never write over what we can't see
1448
1780
  if (diskRev !== readRev) {
1449
1781
  if (base == null && attempt < 3) return callTool(name, args, attempt + 1);
1450
1782
  throw conflict(diskRev);
@@ -1644,6 +1976,8 @@ async function callTool(name, args, attempt = 0) {
1644
1976
  `REMAKE RECIPE: 1) set project width/height/fps to ${bp.width}x${bp.height} @ ${bp.fps} — 2) write beats[] into project markers — 3) extracted music on A1 — 4) one clip per shots[] entry at the same start/duration on V1 (hard cuts; footage energy should track each shot's energy value) — 5) biggest moment on drop (${bp.drop}s)${bp.bpm ? ` — tempo ${bp.bpm} BPM` : ""}. Full recipe: fablecut_docs → "Remake a reference video".`,
1645
1977
  ].join("\n");
1646
1978
  }
1979
+ case "fablecut_files":
1980
+ return filesTool(args);
1647
1981
  case "fablecut_import_media": {
1648
1982
  const src = args.path;
1649
1983
  if (!src) throw new Error("path is required");
@@ -1746,7 +2080,7 @@ async function handle(msg) {
1746
2080
  result: {
1747
2081
  protocolVersion: negotiateProtocolVersion(params?.protocolVersion),
1748
2082
  capabilities: { tools: {} },
1749
- serverInfo: { name: "fablecut", version: "1.17.0" },
2083
+ serverInfo: { name: "fablecut", version: "1.19.0" },
1750
2084
  },
1751
2085
  });
1752
2086
  }