ropetide-runner 0.0.0-stage → 0.3.5

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.
Files changed (49) hide show
  1. package/README.md +145 -2
  2. package/dist/apps/runner/src/agents.js +36 -0
  3. package/dist/apps/runner/src/browser.js +386 -0
  4. package/dist/apps/runner/src/browserProxy.js +120 -0
  5. package/dist/apps/runner/src/cli.js +449 -0
  6. package/dist/apps/runner/src/commands/redact.js +45 -0
  7. package/dist/apps/runner/src/commands/sandbox.js +61 -0
  8. package/dist/apps/runner/src/commands/shell.js +279 -0
  9. package/dist/apps/runner/src/extension.js +159 -0
  10. package/dist/apps/runner/src/files.js +163 -0
  11. package/dist/apps/runner/src/folderChoice.js +40 -0
  12. package/dist/apps/runner/src/main.js +351 -0
  13. package/dist/apps/runner/src/mcp/connectors.js +161 -0
  14. package/dist/apps/runner/src/pairCrypto.js +80 -0
  15. package/dist/apps/runner/src/planUsage.js +189 -0
  16. package/dist/apps/runner/src/power.js +11 -0
  17. package/dist/apps/runner/src/projects/access.js +337 -0
  18. package/dist/apps/runner/src/projects/http.js +74 -0
  19. package/dist/apps/runner/src/projects/prompt.js +19 -0
  20. package/dist/apps/runner/src/projects/rules.js +45 -0
  21. package/dist/apps/runner/src/projects/shares.js +192 -0
  22. package/dist/apps/runner/src/room.js +154 -0
  23. package/dist/apps/runner/src/run.js +182 -0
  24. package/dist/apps/runner/src/server.js +627 -0
  25. package/dist/apps/runner/src/skills.js +94 -0
  26. package/dist/apps/runner/src/tui.js +189 -0
  27. package/dist/apps/runner/src/video/analyse.js +95 -0
  28. package/dist/apps/runner/src/video/exec.js +32 -0
  29. package/dist/apps/runner/src/video/http.js +60 -0
  30. package/dist/apps/runner/src/video/probe.js +52 -0
  31. package/dist/apps/runner/src/video/render.js +322 -0
  32. package/dist/apps/runner/src/video/studio.js +329 -0
  33. package/dist/apps/runner/src/video/tools.js +24 -0
  34. package/dist/apps/runner/src/video.js +444 -0
  35. package/dist/supabase/functions/_shared/effort.js +16 -0
  36. package/dist/supabase/functions/_shared/folder-rules.js +129 -0
  37. package/dist/supabase/functions/_shared/github.js +319 -0
  38. package/dist/supabase/functions/_shared/localVideo.js +24 -0
  39. package/dist/supabase/functions/_shared/modelLimits.js +47 -0
  40. package/dist/supabase/functions/_shared/modelPrices.js +28 -0
  41. package/dist/supabase/functions/_shared/roles.js +18 -0
  42. package/dist/supabase/functions/_shared/room-command.js +70 -0
  43. package/dist/supabase/functions/_shared/roomBudget.js +60 -0
  44. package/dist/supabase/functions/_shared/video-plan.js +567 -0
  45. package/dist/supabase/functions/_shared/workspace.js +21 -0
  46. package/dist/supabase/functions/_shared/workspaceMeter.js +40 -0
  47. package/dist/supabase/functions/room-turn/context.js +154 -0
  48. package/dist/supabase/functions/room-turn/turn.js +750 -0
  49. package/package.json +36 -4
@@ -0,0 +1,322 @@
1
+ /**
2
+ * Turns a checked edit plan into ffmpeg commands. Plain calculation: nothing here runs anything.
3
+ *
4
+ * Each clip is first made on its own, at the new size and frame rate, then the pieces are joined and
5
+ * the overlays, titles and music added. The commands are argument lists, never a shell line. No name
6
+ * or word from a plan is put into them: files are reached by paths Runner chose, words arrive as
7
+ * pictures, and everything else is a number or a choice from a fixed list. Every input has its format
8
+ * forced and may only be read from disk, so an uploaded file can't make ffmpeg open anything else.
9
+ */
10
+ import { timeline, videoKey } from "../../../../supabase/functions/_shared/video-plan.js";
11
+ const FPS = 30;
12
+ const FADE = 0.4;
13
+ /** The most clips joined in one run. Each open file costs memory: forty at once took about 4 GB. */
14
+ const JOIN_AT_ONCE = 8;
15
+ /** The joined video before its loudness is evened. */
16
+ const MIX = 'mix.mkv';
17
+ const PLAYS_ANYWHERE = ['-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart'];
18
+ const START = ['-hide_banner', '-nostdin', '-y', '-loglevel', 'error', '-progress', 'pipe:1', '-nostats'];
19
+ const num = (n) => String(Math.round(n * 10_000) / 10_000);
20
+ const at = (seconds) => seconds.toFixed(3);
21
+ const even = (n) => Math.max(2, Math.round(n / 2) * 2);
22
+ const input = (format, path, before = []) => [...before, '-protocol_whitelist', 'file', '-f', format, '-i', path];
23
+ const clipFile = (i) => `clip${i}.mkv`;
24
+ /** atempo changes speed without changing pitch, at most doubling or halving at a time. */
25
+ export function atempo(speed) {
26
+ const steps = [];
27
+ let left = speed;
28
+ while (left > 2) {
29
+ steps.push(2);
30
+ left /= 2;
31
+ }
32
+ while (left < 0.5) {
33
+ steps.push(0.5);
34
+ left *= 2;
35
+ }
36
+ if (Math.abs(left - 1) > 1e-6)
37
+ steps.push(left);
38
+ return steps.map((s) => `atempo=${num(s)}`);
39
+ }
40
+ const PRESETS = {
41
+ warm: ['colorbalance=rs=0.08:bs=-0.08:rm=0.05:bm=-0.05'],
42
+ cool: ['colorbalance=rs=-0.07:bs=0.09:rm=-0.04:bm=0.05'],
43
+ cinematic: ['colorbalance=rs=-0.08:bs=0.1:rh=0.08:bh=-0.08', 'eq=contrast=1.08:saturation=0.92'],
44
+ vivid: ['eq=contrast=1.08:saturation=1.35'],
45
+ muted: ['eq=contrast=0.95:saturation=0.7:brightness=0.02'],
46
+ mono: ['hue=s=0', 'eq=contrast=1.05'],
47
+ vintage: ['curves=preset=vintage'],
48
+ bright: ['eq=brightness=0.06:saturation=1.05'],
49
+ };
50
+ function grade(look) {
51
+ if (!look)
52
+ return [];
53
+ const eq = ['brightness', 'contrast', 'saturation'].flatMap((key) => (look[key] === undefined ? [] : [`${key}=${num(look[key])}`]));
54
+ const w = look.warmth;
55
+ return [
56
+ ...(look.preset ? PRESETS[look.preset] : []),
57
+ ...(eq.length ? [`eq=${eq.join(':')}`] : []),
58
+ ...(w ? [`colorbalance=rs=${num(w * 0.15)}:bs=${num(-w * 0.15)}:rm=${num(w * 0.1)}:bm=${num(-w * 0.1)}`] : []),
59
+ ...(look.vignette ? ['vignette'] : []),
60
+ ...(look.sharpen ? ['unsharp=5:5:0.8'] : []),
61
+ ];
62
+ }
63
+ /** Scales a source into the new frame: filling it and cropping, or whole with bars. */
64
+ function fit({ width, height, fit: how, keep }) {
65
+ if (how === 'bars')
66
+ return [`scale=${width}:${height}:force_original_aspect_ratio=decrease:force_divisible_by=2`, `pad=${width}:${height}:(ow-iw)/2:(oh-ih)/2:black`];
67
+ const x = keep === 'left' ? '0' : keep === 'right' ? 'iw-ow' : '(iw-ow)/2';
68
+ const y = keep === 'top' ? '0' : keep === 'bottom' ? 'ih-oh' : '(ih-oh)/2';
69
+ return [`scale=${width}:${height}:force_original_aspect_ratio=increase`, `crop=${width}:${height}:${x}:${y}`];
70
+ }
71
+ /** A slow push in or out. The picture is doubled first, so the movement doesn't shake. */
72
+ function zoom(clip, frames, width, height, fps) {
73
+ if (!clip.zoom)
74
+ return [];
75
+ const { from, to } = clip.zoom;
76
+ const z = `${num(from)}+${num(to - from)}*min(on/${Math.max(1, frames - 1)},1)`;
77
+ return [`scale=${width * 2}:${height * 2}`, `zoompan=z='${z}':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d=1:s=${width}x${height}:fps=${fps}`];
78
+ }
79
+ function encoder(capabilities, width, height, fps, finished) {
80
+ if (capabilities.encoder === 'libx264')
81
+ return ['-c:v', 'libx264', '-preset', finished ? 'medium' : 'veryfast', '-crf', finished ? '20' : '14'];
82
+ return ['-c:v', 'h264_videotoolbox', '-b:v', String(Math.round(width * height * fps * (finished ? 0.12 : 0.25)))];
83
+ }
84
+ function clipSteps(job, piece, i, fps) {
85
+ const { plan, capabilities } = job;
86
+ const { clip, source, frames, length } = piece;
87
+ const { width, height } = plan.frame;
88
+ const took = clip.to - clip.from;
89
+ const read = input(source.format, source.path, ['-ss', at(clip.from), '-t', at(took)]);
90
+ const shake = plan.stabilize ? (capabilities.stabilizer === 'vidstab' ? [`vidstabtransform=input=clip${i}.trf:smoothing=15`] : ['deshake']) : [];
91
+ const video = [
92
+ 'setpts=PTS-STARTPTS',
93
+ ...shake,
94
+ ...fit(plan.frame),
95
+ ...(clip.reverse ? ['reverse'] : []),
96
+ ...(clip.speed !== 1 ? [`setpts=(PTS-STARTPTS)/${num(clip.speed)}`] : []),
97
+ `fps=${fps}`,
98
+ ...zoom(clip, frames, width, height, fps),
99
+ ...grade(plan.look),
100
+ 'setsar=1',
101
+ 'format=yuv420p',
102
+ // Holds the last picture if the source runs a frame short, so every piece is exactly its length.
103
+ 'tpad=stop_mode=clone:stop_duration=1',
104
+ `trim=duration=${at(length)}`,
105
+ 'setpts=PTS-STARTPTS',
106
+ ];
107
+ const silent = clip.mute || !source.hasAudio;
108
+ const sound = silent ? [`atrim=duration=${at(length)}`] : [
109
+ 'asetpts=PTS-STARTPTS',
110
+ ...(clip.reverse ? ['areverse'] : []),
111
+ ...atempo(clip.speed),
112
+ ...(plan.sound?.denoise ? ['afftdn=nf=-25'] : []),
113
+ ...(clip.volume !== undefined ? [`volume=${num(clip.volume)}`] : []),
114
+ 'aresample=48000',
115
+ 'aformat=sample_fmts=fltp:channel_layouts=stereo',
116
+ 'apad',
117
+ `atrim=duration=${at(length)}`,
118
+ ];
119
+ const make = {
120
+ label: `Clip ${i + 1} of ${plan.clips.length}`,
121
+ seconds: length,
122
+ args: [
123
+ ...START, ...read,
124
+ ...(silent ? ['-f', 'lavfi', '-i', 'anullsrc=r=48000:cl=stereo'] : []),
125
+ '-filter_complex', `[0:v:0]${video.join(',')}[v];[${silent ? '1:a' : '0:a:0'}]${sound.join(',')}[a]`,
126
+ '-map', '[v]', '-map', '[a]',
127
+ ...encoder(capabilities, width, height, fps, false),
128
+ '-c:a', 'pcm_s16le', '-f', 'matroska', clipFile(i),
129
+ ],
130
+ };
131
+ if (!plan.stabilize || capabilities.stabilizer !== 'vidstab')
132
+ return [make];
133
+ return [{
134
+ label: `Studying shake in clip ${i + 1}`,
135
+ seconds: took,
136
+ args: [...START, ...read, '-vf', `vidstabdetect=result=clip${i}.trf:shakiness=6`, '-an', '-f', 'null', '-'],
137
+ }, make];
138
+ }
139
+ const CORNER = {
140
+ 'top-left': (m) => `x=${m}:y=${m}`,
141
+ 'top-right': (m) => `x=W-w-${m}:y=${m}`,
142
+ 'bottom-left': (m) => `x=${m}:y=H-h-${m}`,
143
+ 'bottom-right': (m) => `x=W-w-${m}:y=H-h-${m}`,
144
+ center: () => 'x=(W-w)/2:y=(H-h)/2',
145
+ };
146
+ /** A still picture held for the whole video. */
147
+ const held = (fps, total) => ['loop=loop=-1:size=1:start=0', `fps=${fps}`, `trim=duration=${at(total)}`, 'setpts=PTS-STARTPTS'];
148
+ const during = (from, to) => `enable='between(t,${at(from)},${at(to)})'`;
149
+ function titleMotion(t) {
150
+ if (!t.animation)
151
+ return { filters: [], position: 'x=0:y=0' };
152
+ const length = Math.min(FADE, (t.to - t.from) / 2);
153
+ const filters = [`fade=t=in:st=${at(t.from)}:d=${at(length)}:alpha=1`, `fade=t=out:st=${at(t.to - length)}:d=${at(length)}:alpha=1`];
154
+ const left = `max(0,1-(t-${at(t.from)})/${at(length)})`;
155
+ const position = t.animation === 'slide' ? `x='-W*0.25*${left}':y=0` : t.animation === 'rise' ? `x=0:y='H*0.06*${left}'` : 'x=0:y=0';
156
+ return { filters, position };
157
+ }
158
+ /** The inputs and filters that play parts one after another, each arriving as its first clip asks. */
159
+ function chain(parts, fps) {
160
+ const inputs = parts.flatMap((p) => input('matroska', p.file));
161
+ const graph = parts.flatMap((_, i) => [`[${i}:v]settb=AVTB,fps=${fps}[cv${i}]`, `[${i}:a]aresample=48000[ca${i}]`]);
162
+ let video = 'cv0';
163
+ let audio = 'ca0';
164
+ let total = parts[0]?.length ?? 0;
165
+ for (const [i, part] of parts.entries()) {
166
+ if (!i)
167
+ continue;
168
+ const { transition } = part;
169
+ if (transition) {
170
+ const length = Math.max(1, Math.round(transition.seconds * fps)) / fps;
171
+ graph.push(`[${video}][cv${i}]xfade=transition=${transition.type}:duration=${at(length)}:offset=${at(total - length)}[jv${i}]`);
172
+ graph.push(`[${audio}][ca${i}]acrossfade=d=${at(length)}[ja${i}]`);
173
+ total += part.length - length;
174
+ }
175
+ else {
176
+ graph.push(`[${video}][cv${i}]concat=n=2:v=1:a=0,settb=AVTB,fps=${fps}[jv${i}]`);
177
+ graph.push(`[${audio}][ca${i}]concat=n=2:v=0:a=1[ja${i}]`);
178
+ total += part.length;
179
+ }
180
+ video = `jv${i}`;
181
+ audio = `ja${i}`;
182
+ }
183
+ return { inputs, graph, video, audio, total };
184
+ }
185
+ /** Joins neighbours in groups until few enough are left for the last run. */
186
+ function joinInGroups(job, parts, fps) {
187
+ const { width, height } = job.plan.frame;
188
+ const steps = [];
189
+ const made = [];
190
+ let left = parts;
191
+ while (left.length > JOIN_AT_ONCE) {
192
+ const next = [];
193
+ for (let i = 0; i < left.length; i += JOIN_AT_ONCE) {
194
+ const group = left.slice(i, i + JOIN_AT_ONCE);
195
+ const [first] = group;
196
+ const last = group.at(-1);
197
+ if (!first || !last || group.length === 1) {
198
+ next.push(...group);
199
+ continue;
200
+ }
201
+ const { inputs, graph, video, audio, total } = chain(group, fps);
202
+ const file = `join${made.length}.mkv`;
203
+ made.push(file);
204
+ steps.push({
205
+ label: `Joining clips ${first.clips[0]} to ${last.clips[1]}`,
206
+ seconds: total,
207
+ args: [
208
+ ...START, ...inputs,
209
+ '-filter_complex', [...graph, `[${video}]format=yuv420p[vout]`, `[${audio}]anull[aout]`].join(';'),
210
+ '-map', '[vout]', '-map', '[aout]',
211
+ ...encoder(job.capabilities, width, height, fps, false),
212
+ '-c:a', 'pcm_s16le', '-f', 'matroska', file,
213
+ ],
214
+ });
215
+ next.push({ file, length: total, clips: [first.clips[0], last.clips[1]], ...(first.transition ? { transition: first.transition } : {}) });
216
+ }
217
+ left = next;
218
+ }
219
+ return { parts: left, steps, made };
220
+ }
221
+ function finishStep(job, parts, layers, music, fps) {
222
+ const { plan, capabilities } = job;
223
+ const { width, height } = plan.frame;
224
+ const joined = chain(parts, fps);
225
+ const { inputs, graph, total } = joined;
226
+ let { video, audio } = joined;
227
+ let next = parts.length;
228
+ if (music && plan.music) {
229
+ const index = next++;
230
+ // A track shorter than the video starts again.
231
+ inputs.push(...input(music.format, music.path, ['-stream_loop', '-1', '-ss', at(plan.music.from)]));
232
+ const fade = Math.min(1.5, total / 2);
233
+ graph.push(`[${index}:a:0]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,atrim=duration=${at(total)},asetpts=PTS-STARTPTS,volume=${num(plan.music.volume)},afade=t=out:st=${at(total - fade)}:d=${at(fade)}[music]`);
234
+ if (plan.music.duck) {
235
+ graph.push(`[${audio}]asplit=2[voice][key]`, '[music][key]sidechaincompress=threshold=0.03:ratio=8:attack=20:release=400[bed]', '[voice][bed]amix=inputs=2:duration=first:normalize=0[mixed]');
236
+ }
237
+ else {
238
+ graph.push(`[${audio}][music]amix=inputs=2:duration=first:normalize=0[mixed]`);
239
+ }
240
+ audio = 'mixed';
241
+ }
242
+ for (const [k, { layer, source }] of layers.entries()) {
243
+ const index = next++;
244
+ inputs.push(...input(source.format, source.path));
245
+ const look = [`scale=${even(layer.size * width)}:-2`, 'format=rgba', ...(layer.opacity < 1 ? [`colorchannelmixer=aa=${num(layer.opacity)}`] : [])];
246
+ const timing = layer.kind === 'image' ? held(fps, total) : [`fps=${fps}`, `trim=duration=${at(layer.to - layer.from)}`, `setpts=PTS-STARTPTS+${at(layer.from)}/TB`];
247
+ const start = layer.kind === 'image' ? [] : ['setpts=PTS-STARTPTS'];
248
+ graph.push(`[${index}:v:0]${[...start, ...look, ...timing].join(',')}[layer${k}]`);
249
+ graph.push(`[${video}][layer${k}]overlay=${CORNER[layer.corner](Math.round(width * 0.04))}:eof_action=pass:${during(layer.from, layer.to)}[ov${k}]`);
250
+ video = `ov${k}`;
251
+ }
252
+ for (const [k, words] of plan.text.entries()) {
253
+ const index = next++;
254
+ inputs.push(...input('png_pipe', job.textImages[k] ?? ''));
255
+ const motion = titleMotion(words);
256
+ graph.push(`[${index}:v:0]${[`scale=${width}:${height}`, 'format=rgba', ...held(fps, total), ...motion.filters].join(',')}[words${k}]`);
257
+ graph.push(`[${video}][words${k}]overlay=${motion.position}:eof_action=pass:${during(words.from, words.to)}[tx${k}]`);
258
+ video = `tx${k}`;
259
+ }
260
+ const evened = !!plan.sound?.normalize;
261
+ graph.push(`[${video}]format=yuv420p[vout]`, `[${audio}]${music ? 'alimiter=limit=0.95' : 'anull'}[aout]`);
262
+ return {
263
+ label: 'Putting it together',
264
+ seconds: total,
265
+ args: [
266
+ ...START, ...inputs,
267
+ '-filter_complex', graph.join(';'),
268
+ '-map', '[vout]', '-map', '[aout]',
269
+ ...encoder(capabilities, width, height, fps, true),
270
+ '-pix_fmt', 'yuv420p',
271
+ ...(evened ? ['-c:a', 'pcm_s16le', '-t', at(total), '-f', 'matroska', MIX] : [...PLAYS_ANYWHERE, '-t', at(total), '-f', 'mp4', job.output]),
272
+ ],
273
+ };
274
+ }
275
+ /** Loudness is evened on its own, so ffmpeg isn't holding pictures back while it listens ahead. */
276
+ function loudnessStep(job, seconds) {
277
+ return {
278
+ label: 'Evening the loudness',
279
+ seconds,
280
+ args: [
281
+ ...START, ...input('matroska', MIX),
282
+ '-filter_complex', '[0:a:0]loudnorm=I=-16:TP=-1.5:LRA=11,aresample=48000,aformat=channel_layouts=stereo[aout]',
283
+ '-map', '0:v:0', '-map', '[aout]', '-c:v', 'copy', ...PLAYS_ANYWHERE,
284
+ '-t', at(seconds), '-f', 'mp4', job.output,
285
+ ],
286
+ };
287
+ }
288
+ export function renderSteps(job) {
289
+ const { plan } = job;
290
+ const fps = plan.fps ?? FPS;
291
+ const byName = new Map(job.sources.map((s) => [videoKey(s.name), s]));
292
+ const gone = (name) => ({ ok: false, reason: `“${name}” is no longer attached.` });
293
+ if (job.textImages.length !== plan.text.length)
294
+ return { ok: false, reason: 'The pictures of the titles didn’t arrive. Try again.' };
295
+ const pieces = [];
296
+ for (const { clip, length } of timeline(plan)) {
297
+ const source = byName.get(videoKey(clip.video));
298
+ if (!source)
299
+ return gone(clip.video);
300
+ const frames = Math.max(1, Math.round(length * fps));
301
+ pieces.push({ clip, source, frames, length: frames / fps });
302
+ }
303
+ const layers = [];
304
+ for (const layer of plan.overlays ?? []) {
305
+ const source = byName.get(videoKey(layer.file));
306
+ if (!source)
307
+ return gone(layer.file);
308
+ layers.push({ layer, source });
309
+ }
310
+ const music = plan.music ? byName.get(videoKey(plan.music.file)) : undefined;
311
+ if (plan.music && !music)
312
+ return gone(plan.music.file);
313
+ const clips = pieces.map((p, i) => ({ file: clipFile(i), length: p.length, clips: [i + 1, i + 1], ...(p.clip.transition ? { transition: p.clip.transition } : {}) }));
314
+ const groups = joinInGroups(job, clips, fps);
315
+ const finish = finishStep(job, groups.parts, layers, music, fps);
316
+ const evened = !!plan.sound?.normalize;
317
+ return {
318
+ ok: true,
319
+ steps: [...pieces.flatMap((piece, i) => clipSteps(job, piece, i, fps)), ...groups.steps, finish, ...(evened ? [loudnessStep(job, finish.seconds)] : [])],
320
+ scratch: [...pieces.flatMap((_, i) => [clipFile(i), `clip${i}.trf`]), ...groups.made, ...(evened ? [MIX] : [])],
321
+ };
322
+ }
@@ -0,0 +1,329 @@
1
+ /**
2
+ * The video editor Runner runs for a paired browser: it keeps the files attached to a room, shows
3
+ * agents stills of them, and makes the new video from an edit plan with the ffmpeg on this computer.
4
+ *
5
+ * Files stay in Runner's own folder and belong to the browser that sent them. They are removed when
6
+ * that browser removes them or disconnects, after twelve idle hours, and when Runner stops or next
7
+ * starts.
8
+ */
9
+ import { randomBytes } from 'node:crypto';
10
+ import { open, mkdir, readFile, rename, rm, stat, statfs, writeFile } from 'node:fs/promises';
11
+ import path from 'node:path';
12
+ import { parseEditPlan, proGuide, readVideoName, videoKey, videoLimits } from "../../../../supabase/functions/_shared/video-plan.js";
13
+ import { study } from "./analyse.js";
14
+ import { readProbe, sniff } from "./probe.js";
15
+ import { renderSteps } from "./render.js";
16
+ import { findTools } from "./tools.js";
17
+ export const studioLimits = { fileBytes: videoLimits.bytes, totalBytes: 12 * 1024 ** 3, files: 30, attached: 10, titleBytes: 3 * 1024 ** 2, jobs: 3, idleMs: 12 * 3_600_000 };
18
+ const SPARE_BYTES = 500 * 1024 ** 2;
19
+ /** How long a turn waits for stills before going ahead without them. */
20
+ const STUDY_WAIT_MS = 90_000;
21
+ const STEP_TIMEOUT_MS = 60 * 60_000;
22
+ const TOOLS_TTL_MS = 60_000;
23
+ const refuse = (status, reason) => ({ ok: false, status, reason });
24
+ const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
25
+ const info = ({ name, kind, duration, width, height, hasAudio }) => ({ name, ...(kind ? { kind } : {}), duration, width, height, hasAudio });
26
+ export function videoStudio(options) {
27
+ const { dir, exec, now } = options;
28
+ const log = options.log ?? (() => { });
29
+ const freeBytes = options.freeBytes ?? (async (at) => { const s = await statfs(at); return s.bavail * s.bsize; });
30
+ const files = new Map();
31
+ const jobs = new Map();
32
+ const closing = new AbortController();
33
+ /** Uploads still arriving, counted against the limits. */
34
+ let arriving = 0;
35
+ let arrivingBytes = 0;
36
+ // Whatever an earlier run left behind belongs to nobody now. Cleared on first use, so a second
37
+ // Runner that fails to start (the port is taken) never touches the running one's files.
38
+ let cleared;
39
+ const ready = () => (cleared ??= rm(dir, { recursive: true, force: true }).then(() => mkdir(dir, { recursive: true, mode: 0o700 })));
40
+ // Files are studied one at a time, so a handful attached together don't swamp the computer.
41
+ let studying = Promise.resolve();
42
+ let found;
43
+ const tools = () => {
44
+ // A computer without ffmpeg is checked again after a minute, so installing it needs no restart.
45
+ if (!found || now() - found.at > TOOLS_TTL_MS)
46
+ found = { at: now(), tools: findTools(options.env, exec) };
47
+ return found.tools;
48
+ };
49
+ const own = (owner, id) => { const f = files.get(id); return f?.owner === owner ? f : undefined; };
50
+ const ownJob = (owner, id) => { const j = jobs.get(id); return j?.owner === owner ? j : undefined; };
51
+ const pick = (owner, ids) => {
52
+ if (!ids.length || ids.length > studioLimits.attached)
53
+ return undefined;
54
+ const kept = ids.flatMap((id) => own(owner, id) ?? []);
55
+ if (kept.length !== ids.length)
56
+ return undefined;
57
+ for (const f of kept)
58
+ f.used = now();
59
+ return kept;
60
+ };
61
+ async function dropFile(id) {
62
+ const kept = files.get(id);
63
+ if (!kept)
64
+ return;
65
+ files.delete(id);
66
+ await kept.quit();
67
+ await rm(kept.folder, { recursive: true, force: true });
68
+ }
69
+ async function dropJob(id) {
70
+ const running = jobs.get(id);
71
+ if (!running)
72
+ return;
73
+ running.stop.abort();
74
+ jobs.delete(id);
75
+ await running.done;
76
+ await rm(running.folder, { recursive: true, force: true });
77
+ }
78
+ async function receive(target, body, length) {
79
+ const handle = await open(target, 'wx', 0o600);
80
+ let size = 0;
81
+ try {
82
+ for await (const chunk of body) {
83
+ size += chunk.length;
84
+ if (size > length)
85
+ return false;
86
+ await handle.write(chunk);
87
+ }
88
+ return size === length;
89
+ }
90
+ catch {
91
+ return false;
92
+ }
93
+ finally {
94
+ await handle.close();
95
+ }
96
+ }
97
+ async function add(owner, rawName, body, length) {
98
+ await ready();
99
+ const found = await tools();
100
+ if (!found.ok)
101
+ return refuse(503, found.reason);
102
+ const name = readVideoName(rawName);
103
+ if (!name)
104
+ return refuse(400, 'That file needs a name.');
105
+ if (!Number.isSafeInteger(length) || length <= 0)
106
+ return refuse(411, 'That file arrived empty.');
107
+ if (length > studioLimits.fileBytes)
108
+ return refuse(413, 'Files can be at most 2 GB each.');
109
+ const kept = [...files.values()];
110
+ if (kept.length + arriving >= studioLimits.files || kept.reduce((n, f) => n + f.bytes, arrivingBytes) + length > studioLimits.totalBytes)
111
+ return refuse(507, 'Runner is holding as many files as it can. Remove one and try again.');
112
+ arriving++;
113
+ arrivingBytes += length;
114
+ const id = randomBytes(16).toString('hex');
115
+ const folder = path.join(dir, 'files', id);
116
+ let stored = false;
117
+ try {
118
+ await mkdir(folder, { recursive: true, mode: 0o700 });
119
+ if ((await freeBytes(folder)) < length + SPARE_BYTES)
120
+ return refuse(507, 'This computer doesn’t have enough free space for that file.');
121
+ const partial = path.join(folder, 'incoming');
122
+ if (!(await receive(partial, body, length)))
123
+ return refuse(400, 'The file didn’t arrive whole. Try again.');
124
+ const handle = await open(partial, 'r');
125
+ const head = Buffer.alloc(32);
126
+ try {
127
+ await handle.read(head, 0, head.length, 0);
128
+ }
129
+ finally {
130
+ await handle.close();
131
+ }
132
+ const format = sniff(head);
133
+ const unusable = () => refuse(415, 'Ropetide can’t read that file. Use MP4, MOV, WebM, MKV, AVI, MP3, WAV, M4A, AAC, FLAC, OGG, PNG, JPEG or WebP.');
134
+ if (!format)
135
+ return unusable();
136
+ const target = path.join(folder, `${id}.${format.extension}`);
137
+ await rename(partial, target);
138
+ const probe = await exec(found.ffprobe, ['-v', 'error', '-protocol_whitelist', 'file', '-f', format.format, '-of', 'json', '-show_format', '-show_streams', target], { timeoutMs: 30_000, signal: closing.signal });
139
+ let parsed = null;
140
+ if (probe.ok)
141
+ try {
142
+ parsed = JSON.parse(probe.stdout);
143
+ }
144
+ catch {
145
+ parsed = null;
146
+ }
147
+ const probed = readProbe(parsed, format.kind);
148
+ if (!probed)
149
+ return unusable();
150
+ // A second file of the same name takes the first one's place in a room.
151
+ const source = { name, ...probed, path: target, format: format.format };
152
+ const stop = new AbortController();
153
+ const signal = AbortSignal.any([stop.signal, closing.signal]);
154
+ let active;
155
+ const seen = studying.then(() => {
156
+ // A file removed while it waited its turn is not touched again.
157
+ if (signal.aborted)
158
+ return {};
159
+ active = study(source, folder, found.ffmpeg, exec, signal);
160
+ return active;
161
+ }).catch(() => ({}));
162
+ studying = seen;
163
+ const quit = async () => { stop.abort(); await active?.catch(() => { }); };
164
+ files.set(id, { owner, used: now(), bytes: length, folder, source, seen, quit });
165
+ stored = true;
166
+ return { ok: true, file: { id, ...info(source) } };
167
+ }
168
+ finally {
169
+ arriving--;
170
+ arrivingBytes -= length;
171
+ if (!stored)
172
+ await rm(folder, { recursive: true, force: true });
173
+ }
174
+ }
175
+ /** What agents are told about these files, and the stills to put beside it. */
176
+ async function context(owner, ids) {
177
+ const kept = pick(owner, ids);
178
+ if (!kept)
179
+ return { ok: false };
180
+ let timer;
181
+ const late = new Promise((resolve) => { timer = setTimeout(() => resolve(undefined), STUDY_WAIT_MS); });
182
+ const seen = {};
183
+ const images = [];
184
+ try {
185
+ for (const [i, file] of kept.entries()) {
186
+ const found = await Promise.race([file.seen, late]);
187
+ if (!found)
188
+ continue;
189
+ const { sheet, ...rest } = found;
190
+ const bytes = sheet ? await readFile(sheet).catch(() => undefined) : undefined;
191
+ // Named by number, so a file's name never becomes a path.
192
+ const at = `video-snapshots/${i + 1}.jpg`;
193
+ if (bytes)
194
+ images.push({ path: at, bytes });
195
+ seen[file.source.name] = { ...rest, ...(bytes ? { sheet: at } : {}) };
196
+ }
197
+ }
198
+ finally {
199
+ clearTimeout(timer);
200
+ }
201
+ return { ok: true, guide: proGuide(kept.map((f) => info(f.source)), seen), images };
202
+ }
203
+ async function run(running, steps, ffmpeg, output) {
204
+ const total = steps.reduce((n, s) => n + s.seconds, 0);
205
+ let before = 0;
206
+ for (const step of steps) {
207
+ running.job = { state: 'working', progress: Math.min(0.99, before / total), step: step.label };
208
+ const r = await exec(ffmpeg, step.args, {
209
+ cwd: running.folder,
210
+ timeoutMs: STEP_TIMEOUT_MS,
211
+ signal: AbortSignal.any([running.stop.signal, closing.signal]),
212
+ onStdout: (text) => {
213
+ const at = [...text.matchAll(/out_time_us=(\d+)/g)].at(-1)?.[1];
214
+ if (at === undefined)
215
+ return;
216
+ running.job = { state: 'working', progress: Math.min(0.99, (before + Math.min(step.seconds, Number(at) / 1e6)) / total), step: step.label };
217
+ },
218
+ });
219
+ if (!r.ok) {
220
+ if (r.code !== 'stopped')
221
+ log(`Video edit failed while ${step.label.toLowerCase()}: ${r.stderr.trim().split('\n').slice(-3).join(' | ') || r.code}`);
222
+ running.job = { state: 'failed', reason: r.code === 'stopped' ? 'Stopped.' : r.code === 'timeout' ? 'Making the video took too long, so Runner stopped it.' : `ffmpeg couldn’t make this video (while ${step.label.toLowerCase()}). The Runner window shows why.` };
223
+ return;
224
+ }
225
+ before += step.seconds;
226
+ }
227
+ const made = await stat(output).catch(() => undefined);
228
+ running.job = made?.size ? { state: 'done', progress: 1, bytes: made.size } : { state: 'failed', reason: 'ffmpeg finished without writing a video.' };
229
+ }
230
+ async function render(owner, planText, ids, titles) {
231
+ await ready();
232
+ const found = await tools();
233
+ if (!found.ok)
234
+ return refuse(503, found.reason);
235
+ const kept = pick(owner, ids);
236
+ if (!kept)
237
+ return refuse(404, 'Runner no longer has those files. Add them to the room again.');
238
+ // Later files replace earlier ones of the same name.
239
+ const byName = [...new Map(kept.map((f) => [videoKey(f.source.name), f])).values()];
240
+ const parsed = parseEditPlan(planText, byName.map((f) => info(f.source)));
241
+ if (!parsed.ok)
242
+ return refuse(400, parsed.reason);
243
+ const pictures = titles.map((t) => Buffer.from(t, 'base64'));
244
+ if (pictures.length !== parsed.plan.text.length || pictures.some((p) => !p.subarray(0, PNG.length).equals(PNG)) || pictures.reduce((n, p) => n + p.length, 0) > studioLimits.titleBytes * 4)
245
+ return refuse(400, 'The pictures of the titles didn’t arrive. Try again.');
246
+ if ([...jobs.values()].some((j) => j.job.state === 'working'))
247
+ return refuse(429, 'Runner is already making a video. Wait for it or stop it first.');
248
+ const id = randomBytes(16).toString('hex');
249
+ const folder = path.join(dir, 'jobs', id);
250
+ const output = path.join(folder, `${id}.mp4`);
251
+ const textImages = pictures.map((_, i) => path.join(folder, `title${i}.png`));
252
+ const made = renderSteps({ plan: parsed.plan, sources: byName.map((f) => f.source), textImages, capabilities: found.capabilities, output });
253
+ if (!made.ok)
254
+ return refuse(400, made.reason);
255
+ const running = { owner, used: now(), folder, name: `${parsed.plan.name}.mp4`, job: { state: 'working', progress: 0, step: 'Starting' }, stop: new AbortController(), done: Promise.resolve() };
256
+ // Taken before any waiting, so a second request can't also start.
257
+ jobs.set(id, running);
258
+ running.done = (async () => {
259
+ try {
260
+ await mkdir(folder, { recursive: true, mode: 0o700 });
261
+ for (const [i, picture] of pictures.entries())
262
+ await writeFile(textImages[i] ?? '', picture, { mode: 0o600 });
263
+ await run(running, made.steps, found.ffmpeg, output);
264
+ }
265
+ catch (err) {
266
+ log(`Video edit failed: ${err instanceof Error ? err.message : 'unknown error'}`);
267
+ running.job = { state: 'failed', reason: 'Runner couldn’t make this video. The Runner window shows why.' };
268
+ }
269
+ finally {
270
+ const keep = running.job.state === 'done';
271
+ // Only the finished video is worth keeping.
272
+ await Promise.all([...made.scratch, ...textImages.map((p) => path.basename(p)), ...(keep ? [] : [`${id}.mp4`])].map((f) => rm(path.join(folder, f), { force: true }))).catch(() => { });
273
+ }
274
+ })();
275
+ // Older finished videos make room.
276
+ const mine = [...jobs].filter(([, j]) => j.owner === owner);
277
+ await Promise.all(mine.slice(0, Math.max(0, mine.length - studioLimits.jobs)).map(([old]) => dropJob(old)));
278
+ return { ok: true, id };
279
+ }
280
+ return {
281
+ async status() {
282
+ await ready();
283
+ const found = await tools();
284
+ return found.ok ? { ready: true } : { ready: false, reason: found.reason };
285
+ },
286
+ add,
287
+ context,
288
+ render,
289
+ async remove(owner, id) {
290
+ if (own(owner, id))
291
+ await dropFile(id);
292
+ },
293
+ job(owner, id) {
294
+ const running = ownJob(owner, id);
295
+ if (running)
296
+ running.used = now();
297
+ return running?.job;
298
+ },
299
+ cancel(owner, id) {
300
+ ownJob(owner, id)?.stop.abort();
301
+ },
302
+ output(owner, id) {
303
+ const running = ownJob(owner, id);
304
+ if (running?.job.state !== 'done')
305
+ return undefined;
306
+ running.used = now();
307
+ return { path: path.join(running.folder, `${id}.mp4`), bytes: running.job.bytes, name: running.name };
308
+ },
309
+ async forget(owner) {
310
+ await Promise.all([...jobs].filter(([, j]) => j.owner === owner).map(([id]) => dropJob(id)));
311
+ await Promise.all([...files].filter(([, f]) => f.owner === owner).map(([id]) => dropFile(id)));
312
+ },
313
+ async sweep() {
314
+ const old = (used) => now() - used > studioLimits.idleMs;
315
+ await Promise.all([...jobs].filter(([, j]) => j.job.state !== 'working' && old(j.used)).map(([id]) => dropJob(id)));
316
+ // A file a render is reading is kept until it finishes.
317
+ if (![...jobs.values()].some((j) => j.job.state === 'working'))
318
+ await Promise.all([...files].filter(([, f]) => old(f.used)).map(([id]) => dropFile(id)));
319
+ },
320
+ async close() {
321
+ closing.abort();
322
+ await ready();
323
+ await Promise.all([...jobs.keys()].map(dropJob));
324
+ await studying;
325
+ files.clear();
326
+ await rm(dir, { recursive: true, force: true });
327
+ },
328
+ };
329
+ }