@open-take/runtime 0.2.7 → 0.2.9

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/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- import { captureTake, captureTakeCDP, ensureChrome, inspectPage, resolveChrome } from "./cdp-capture-DXTkPLLF.js";
1
+ import { captureTake, captureTakeCDP, ensureChrome, inspectPage, resolveChrome, resolveNavigateUrl } from "./cdp-capture-BA3qT1Tg.js";
2
2
  import { appendFile, copyFile, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
3
+ import { homedir, tmpdir } from "node:os";
4
4
  import { basename, dirname, extname, join, normalize, resolve } from "node:path";
5
5
  import { FINISH, LOOKS, MOTION, ZOOM_LEVELS, finishName, formatIssues, formatIssues as formatIssues$1, lookName, math, motionName, planComposition, renderTake, resolveFfmpeg, resolveFfprobe, validateComposition, validateComposition as validateComposition$1, zoomLevelName } from "@open-take/compositor";
6
6
  import { spawn } from "node:child_process";
7
- import { createReadStream, statSync } from "node:fs";
7
+ import { createReadStream, mkdirSync, statSync } from "node:fs";
8
8
  import { createServer } from "node:http";
9
9
  import { fileURLToPath } from "node:url";
10
10
 
@@ -217,61 +217,104 @@ async function annotateCaptureLog(log, videoPath, opts = {}) {
217
217
 
218
218
  //#endregion
219
219
  //#region src/take.ts
220
+ /** working-directory suffix: `demo.mp4` → `demo.take/` */
221
+ const TAKE_DIR_SUFFIX = ".take";
220
222
  async function isFile(p) {
221
223
  return (await stat(p).catch(() => null))?.isFile() ?? false;
222
224
  }
223
- /** Strip any known take suffix to get the shared base, then derive the family.
224
- * A directory picks the `*.composition.json` that has a sibling capture. */
225
- async function resolveTakePaths(input) {
226
- let p = resolve(input);
227
- const s = await stat(p).catch(() => null);
228
- if (s?.isDirectory()) {
229
- const comps = (await readdir(p)).filter((e) => /\.composition\.json$/i.test(e) && !/\.prev\.composition\.json$/i.test(e));
230
- if (comps.length === 0) throw new Error(`no *.composition.json found in ${p}`);
231
- let pick = comps[0];
232
- for (const c of comps) {
233
- const base$1 = join(p, c.replace(/\.composition\.json$/i, ""));
234
- if (await isFile(`${base$1}.capture.mp4`)) {
235
- pick = c;
236
- break;
237
- }
238
- }
239
- p = join(p, pick);
240
- }
241
- const base = p.replace(/\.dossier\.md$/i, "").replace(/\.prev\.composition\.json$/i, "").replace(/\.composition\.json$/i, "").replace(/\.capture\.json$/i, "").replace(/\.capture\.mp4$/i, "").replace(/\.review\.mp4$/i, "").replace(/\.draft\.mp4$/i, "").replace(/\.ab\.mp4$/i, "").replace(/\.prev\.mp4$/i, "").replace(/\.mp4$/i, "");
225
+ const stripDirSuffix = (p) => p.slice(0, -TAKE_DIR_SUFFIX.length);
226
+ /** Every member the flat layout used to write beside the master. A path that
227
+ * matches one AND EXISTS is a pre-`.take/` take (or a path from an old doc):
228
+ * worth an explanation rather than a resolve to a take called "demo.capture".
229
+ * Existence is what keeps this from stealing a legitimate name — `--out
230
+ * foo.draft.mp4` is a fine thing to call a video nobody has written yet. */
231
+ const LEGACY_MEMBER = /\.(composition\.json|capture\.mp4|capture\.json|review\.mp4|draft\.mp4|ab\.mp4|prev\.mp4|frames(\.beat\d+)?\.png|dossier\.md|notes\.md|notes\.cursor)$/i;
232
+ function legacyLayout(base) {
233
+ const name = basename(base);
234
+ const dir = `${name}${TAKE_DIR_SUFFIX}`;
235
+ return `${base}.* is the old flat take layout — a take's working files now live in ${dir}/ beside the mp4.\nMigrate it:\n (cd ${JSON.stringify(dirname(base))} && mkdir -p ${JSON.stringify(dir)} && for f in ${JSON.stringify(name)}.*.*; do mv "$f" ${JSON.stringify(dir)}/"\${f#${name}.}"; done)\n— or just re-make the take.`;
236
+ }
237
+ function fromBase(base) {
238
+ const dir = `${base}${TAKE_DIR_SUFFIX}`;
239
+ const inDir = (n) => join(dir, n);
242
240
  return {
243
241
  base,
244
242
  name: basename(base),
245
243
  mp4Path: `${base}.mp4`,
246
- compositionPath: `${base}.composition.json`,
247
- capturePath: `${base}.capture.mp4`,
248
- captureLogPath: `${base}.capture.json`,
249
- reviewPath: `${base}.review.mp4`,
250
- draftPath: `${base}.draft.mp4`,
251
- abPath: `${base}.ab.mp4`,
252
- prevPath: `${base}.prev.mp4`,
253
- dossierPath: `${base}.dossier.md`
244
+ dir,
245
+ compositionPath: inDir("composition.json"),
246
+ capturePath: inDir("capture.mp4"),
247
+ captureLogPath: inDir("capture.json"),
248
+ reviewPath: inDir("review.mp4"),
249
+ draftPath: inDir("draft.mp4"),
250
+ abPath: inDir("ab.mp4"),
251
+ prevPath: inDir("prev.mp4"),
252
+ prevCompositionPath: inDir("prev.composition.json"),
253
+ framesPath: inDir("frames.png"),
254
+ dossierPath: inDir("dossier.md"),
255
+ notesPath: inDir("notes.md"),
256
+ notesCursorPath: inDir("notes.cursor")
254
257
  };
255
258
  }
259
+ /** A path inside the take's working dir — the ffmpeg intermediates and the
260
+ * per-beat frame sheets, which are members by position, not by name. */
261
+ const takeFile = (take, name) => join(take.dir, name);
262
+ /** Point at any member and get the whole take. Resolution is a pure string
263
+ * transform except for a bare directory, which is scanned for `*.take/`.
264
+ * The master need not exist yet — `make --out` resolves before it writes. */
265
+ async function resolveTakePaths(input) {
266
+ const p = resolve(input);
267
+ const parent = dirname(p);
268
+ if (parent.endsWith(TAKE_DIR_SUFFIX)) return fromBase(stripDirSuffix(parent));
269
+ if (p.endsWith(TAKE_DIR_SUFFIX)) return fromBase(stripDirSuffix(p));
270
+ if (LEGACY_MEMBER.test(p) && await isFile(p)) throw new Error(legacyLayout(p.replace(LEGACY_MEMBER, "")));
271
+ if (/\.mp4$/i.test(p)) return fromBase(p.replace(/\.mp4$/i, ""));
272
+ const s = await stat(p).catch(() => null);
273
+ if (s?.isDirectory()) return fromBase(await pickTakeIn(p));
274
+ return fromBase(p);
275
+ }
276
+ /** A plain directory means "the take in here" — unambiguous only when it holds
277
+ * exactly one. Two takes in one folder is now visible (two `*.take/` dirs)
278
+ * instead of an alphabetical race between compositions. */
279
+ async function pickTakeIn(dir) {
280
+ const entries = await readdir(dir).catch(() => []);
281
+ const takes = entries.filter((e) => e.endsWith(TAKE_DIR_SUFFIX)).sort();
282
+ if (takes.length === 1) return join(dir, stripDirSuffix(takes[0]));
283
+ if (takes.length > 1) throw new Error(`${dir} holds ${takes.length} takes (${takes.map(stripDirSuffix).join(", ")}) — name the one you mean, e.g. ${stripDirSuffix(takes[0])}.mp4`);
284
+ const flat = entries.find((e) => /\.composition\.json$/i.test(e));
285
+ if (flat) throw new Error(legacyLayout(join(dir, flat.replace(/\.composition\.json$/i, ""))));
286
+ throw new Error(`no take in ${dir} — a take is an mp4 with a <name>${TAKE_DIR_SUFFIX}/ working dir beside it`);
287
+ }
288
+ /** Create the working dir (idempotent). Everything except the master is
289
+ * written inside it, so any verb that writes calls this first. */
290
+ async function ensureTakeDir(take) {
291
+ const s = await stat(take.dir).catch(() => null);
292
+ if (s && !s.isDirectory()) throw new Error(`${take.dir} exists but is not a directory — that is where this take's working files go; move it aside`);
293
+ await mkdir(take.dir, { recursive: true });
294
+ }
256
295
  /** Friendly preflight: verbs die with a clear message instead of a raw ffmpeg
257
296
  * ENOENT when a take is missing the files they need. Old takes (or cleaned
258
297
  * ones) may have a composition + mp4 but no kept capture — those can be
259
298
  * watched but not re-rendered. */
260
299
  async function requireTakeFiles(take, opts = {}) {
261
- if (!await isFile(take.compositionPath)) throw new Error(`missing ${take.compositionPath} — not a take produced by \`make\` (or the wrong path)`);
262
- if (opts.capture && !await isFile(take.capturePath)) throw new Error(`this take has no kept capture (${take.capturePath}) — re-rendering needs the frozen recording.\nTakes made before capture-keeping (or cleaned up) can't be re-rendered; run \`make\` again for a refinable take.`);
300
+ if (!await isFile(take.compositionPath)) {
301
+ if (await isFile(`${take.base}.composition.json`)) throw new Error(legacyLayout(take.base));
302
+ throw new Error(`missing ${take.compositionPath} — not a take produced by \`make\` (or the wrong path)`);
303
+ }
304
+ if (opts.capture && !await isFile(take.capturePath)) throw new Error(`this take has no kept capture (${take.capturePath}) — re-rendering needs the frozen recording.\nDelete the working dir and the master is all that is left; run \`make\` again for a refinable take.`);
263
305
  }
264
- /** Stage a copy of the current master so it becomes `<base>.prev.mp4` only
265
- * AFTER the next render succeeds. A refused (validator) or crashed render
266
- * must NOT clobber the existing revert point — that would make "keep the old
267
- * one" replay the wrong version. No-op when there is no master yet. This is
268
- * what makes "A" (keep the old one) a mechanical revert instead of a memory. */
306
+ /** Stage a copy of the current master so it becomes `prev.mp4` only AFTER the
307
+ * next render succeeds. A refused (validator) or crashed render must NOT
308
+ * clobber the existing revert point — that would make "keep the old one"
309
+ * replay the wrong version. No-op when there is no master yet. This is what
310
+ * makes "A" (keep the old one) a mechanical revert instead of a memory. */
269
311
  async function stagePrev(mp4Path, prevPath) {
270
312
  if (!await isFile(mp4Path)) return {
271
313
  commit: async () => {},
272
314
  abort: async () => {}
273
315
  };
274
316
  const pending = `${prevPath}.pending`;
317
+ await mkdir(dirname(pending), { recursive: true });
275
318
  await copyFile(mp4Path, pending);
276
319
  return {
277
320
  commit: () => rename(pending, prevPath),
@@ -294,6 +337,7 @@ const KIND_LABEL = {
294
337
  click: "click",
295
338
  type: "type",
296
339
  drag: "drag",
340
+ dropFiles: "drop",
297
341
  scroll: "scroll",
298
342
  hover: "hover",
299
343
  press: "key"
@@ -418,7 +462,7 @@ async function renderReview(take, opts = {}) {
418
462
  badges: buildBadges(comp)
419
463
  }
420
464
  };
421
- await renderTake({
465
+ const { warnings } = await renderTake({
422
466
  composition: decorated,
423
467
  videoPath: take.capturePath,
424
468
  outPath: take.reviewPath,
@@ -429,10 +473,11 @@ async function renderReview(take, opts = {}) {
429
473
  });
430
474
  return {
431
475
  reviewPath: take.reviewPath,
432
- sheet: buildBeatSheet(comp, take.name)
476
+ sheet: buildBeatSheet(comp, take.name),
477
+ warnings
433
478
  };
434
479
  }
435
- /** Draft-quality re-render of the CURRENT composition to `<base>.draft.mp4` —
480
+ /** Draft-quality re-render of the CURRENT composition to `draft.mp4` —
436
481
  * no badges, no watermark, and never the master's path, so a mid-refine
437
482
  * frame-check (edit → draft → `frames`) costs seconds without downgrading or
438
483
  * clobbering the postable mp4. Disposable like the review copy. */
@@ -441,7 +486,7 @@ async function renderDraft(take, opts = {}) {
441
486
  const comp = JSON.parse(await readFile(take.compositionPath, "utf8"));
442
487
  const captureLog = await loadLogSibling(take.capturePath);
443
488
  const chromePath = await ensureChrome(opts.chromePath);
444
- await renderTake({
489
+ const { warnings } = await renderTake({
445
490
  composition: toDraft(comp),
446
491
  videoPath: take.capturePath,
447
492
  outPath: take.draftPath,
@@ -450,7 +495,10 @@ async function renderDraft(take, opts = {}) {
450
495
  chromePath,
451
496
  writeCompositionSibling: false
452
497
  });
453
- return { draftPath: take.draftPath };
498
+ return {
499
+ draftPath: take.draftPath,
500
+ warnings
501
+ };
454
502
  }
455
503
  function parseSetFlag(set, beat) {
456
504
  const eq = set.indexOf("=");
@@ -670,7 +718,7 @@ async function renderAbReel(take, opts) {
670
718
  ...base,
671
719
  review: { label: `${v.letter} · ${v.desc}` }
672
720
  };
673
- const clip = `${take.base}.ab.${v.letter}.mp4`;
721
+ const clip = takeFile(take, `ab.${v.letter}.mp4`);
674
722
  if (opts.logProgress !== false) process.stderr.write(`variant ${v.letter} · ${v.desc}${rangeSec ? ` · window ${rangeSec[0].toFixed(1)}–${rangeSec[1].toFixed(1)}s` : ""}\n`);
675
723
  await renderTake({
676
724
  composition: decorated,
@@ -728,8 +776,8 @@ async function renderBeforeAfter(take, opts = {}) {
728
776
  args.push("-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p", "-an", out);
729
777
  await ffmpeg(args);
730
778
  };
731
- const before = `${take.base}.ab.before.mp4`;
732
- const after = `${take.base}.ab.after.mp4`;
779
+ const before = takeFile(take, "ab.before.mp4");
780
+ const after = takeFile(take, "ab.after.mp4");
733
781
  await cut(take.prevPath, before);
734
782
  await cut(take.mp4Path, after);
735
783
  await concatWithGaps([
@@ -863,6 +911,81 @@ function revealPath(p) {
863
911
  spawnOpener(getRevealCommand(abs), `at: ${abs}\n`);
864
912
  }
865
913
 
914
+ //#endregion
915
+ //#region src/auth.ts
916
+ /** The canonical profile dir for a named auth profile. Names are a single
917
+ * path segment — anything else ("../", "/", spaces-only) would escape or
918
+ * collide with other open-take state under ~/.open-take. */
919
+ function profileDir(name) {
920
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name) || name.includes("..")) throw new Error(`invalid profile name ${JSON.stringify(name)} — use letters/digits/dots/dashes/underscores`);
921
+ return join(homedir(), ".open-take", "profiles", name);
922
+ }
923
+ /**
924
+ * Open a headed Chrome on the persistent profile and resolve when the user is
925
+ * done (Enter on stdin, or the browser quits). The profile dir is returned so
926
+ * callers can print how to use it.
927
+ */
928
+ async function authProfile(opts) {
929
+ const dir = opts.dir ?? profileDir(opts.name);
930
+ mkdirSync(dir, { recursive: true });
931
+ const chrome = await ensureChrome(opts.chromePath);
932
+ const proc = spawn(chrome, [
933
+ `--user-data-dir=${dir}`,
934
+ "--no-first-run",
935
+ "--no-default-browser-check",
936
+ "--password-store=basic",
937
+ "--use-mock-keychain",
938
+ "--window-size=1280,900",
939
+ opts.url ?? "about:blank"
940
+ ], {
941
+ stdio: [
942
+ "ignore",
943
+ "ignore",
944
+ "ignore"
945
+ ],
946
+ detached: false
947
+ });
948
+ let spawnErr;
949
+ await new Promise((resolveWait) => {
950
+ let settled = false;
951
+ const done = () => {
952
+ if (settled) return;
953
+ settled = true;
954
+ process.stdin.off("data", onEnter);
955
+ if (process.stdin.isTTY) process.stdin.pause();
956
+ resolveWait();
957
+ };
958
+ const onEnter = () => done();
959
+ proc.once("exit", done);
960
+ proc.once("error", (e) => {
961
+ spawnErr = e;
962
+ done();
963
+ });
964
+ if (process.stdin.isTTY) {
965
+ process.stdin.resume();
966
+ process.stdin.on("data", onEnter);
967
+ }
968
+ });
969
+ if (spawnErr) throw new Error(`auth: failed to launch Chrome: ${spawnErr.message}`);
970
+ if (proc.exitCode == null) {
971
+ proc.kill("SIGTERM");
972
+ await new Promise((r) => {
973
+ const tm = setTimeout(() => {
974
+ try {
975
+ proc.kill("SIGKILL");
976
+ } catch {}
977
+ r();
978
+ }, 4e3);
979
+ proc.once("exit", () => {
980
+ clearTimeout(tm);
981
+ r();
982
+ });
983
+ });
984
+ }
985
+ await new Promise((r) => setTimeout(r, 500));
986
+ return { dir };
987
+ }
988
+
866
989
  //#endregion
867
990
  //#region src/edit-server.ts
868
991
  const CONTENT_TYPE = {
@@ -877,7 +1000,11 @@ const CONTENT_TYPE = {
877
1000
  ".ico": "image/x-icon",
878
1001
  ".woff2": "font/woff2",
879
1002
  ".woff": "font/woff",
880
- ".map": "application/json; charset=utf-8"
1003
+ ".map": "application/json; charset=utf-8",
1004
+ ".mp4": "video/mp4",
1005
+ ".m4v": "video/mp4",
1006
+ ".webm": "video/webm",
1007
+ ".mov": "video/quicktime"
881
1008
  };
882
1009
  /** Locate the built editor SPA: prefer the live monorepo build during
883
1010
  * development, then fall back to the bundled copy used by the published
@@ -916,7 +1043,10 @@ async function readBody(req, capBytes = 32 * 1024 * 1024) {
916
1043
  }
917
1044
  return Buffer.concat(chunks).toString("utf8");
918
1045
  }
919
- /** Stream a file with HTTP Range support (206) — required for <video> seeking. */
1046
+ /** Stream a file with HTTP Range support (206) — required for <video> seeking.
1047
+ * Answers HEAD with the same headers and no body: a media element (or a proxy
1048
+ * in front of one) may probe with HEAD before it will range-GET, and the route
1049
+ * table used to let those fall through to the /api/ 404. */
920
1050
  async function serveFile(req, res, filePath) {
921
1051
  const st = await stat(filePath).catch(() => null);
922
1052
  if (!st?.isFile()) {
@@ -924,6 +1054,15 @@ async function serveFile(req, res, filePath) {
924
1054
  return;
925
1055
  }
926
1056
  const type = CONTENT_TYPE[extname(filePath).toLowerCase()] ?? "application/octet-stream";
1057
+ if (req.method === "HEAD") {
1058
+ res.writeHead(200, {
1059
+ "Content-Length": st.size,
1060
+ "Accept-Ranges": "bytes",
1061
+ "Content-Type": type
1062
+ });
1063
+ res.end();
1064
+ return;
1065
+ }
927
1066
  const range = req.headers.range;
928
1067
  if (range) {
929
1068
  const m = /bytes=(\d*)-(\d*)/.exec(range);
@@ -982,7 +1121,7 @@ async function startEditServer(opts, deps = {}) {
982
1121
  return run$1;
983
1122
  };
984
1123
  /** Persist unless someone else wrote first. `baseMtime` is the mtime the
985
- * client last read. Every API write must provide it; 保留我的 re-bases to
1124
+ * client last read. Every API write must provide it; "Keep mine" re-bases to
986
1125
  * the 409's mtime and remains guarded against an even newer write.
987
1126
  *
988
1127
  * We check once before writing the temp file and again immediately before
@@ -1068,7 +1207,7 @@ async function startEditServer(opts, deps = {}) {
1068
1207
  });
1069
1208
  return;
1070
1209
  }
1071
- if (path === "/api/take/video" && method === "GET") {
1210
+ if (path === "/api/take/video" && (method === "GET" || method === "HEAD")) {
1072
1211
  await serveFile(req, res, take.capturePath);
1073
1212
  return;
1074
1213
  }
@@ -1083,7 +1222,7 @@ async function startEditServer(opts, deps = {}) {
1083
1222
  return;
1084
1223
  }
1085
1224
  const line = text.trim().replace(/\s+/g, " ").slice(0, 2e3);
1086
- await appendFile(`${take.base}.notes.md`, `- ${line}\n`);
1225
+ await appendFile(take.notesPath, `- ${line}\n`);
1087
1226
  process.stdout.write(`NOTE ${JSON.stringify({
1088
1227
  take: take.name,
1089
1228
  text: line
@@ -1091,7 +1230,7 @@ async function startEditServer(opts, deps = {}) {
1091
1230
  sendJson(res, 200, { ok: true });
1092
1231
  return;
1093
1232
  }
1094
- if (path === "/api/take/output" && method === "GET") {
1233
+ if (path === "/api/take/output" && (method === "GET" || method === "HEAD")) {
1095
1234
  await serveFile(req, res, take.mp4Path);
1096
1235
  return;
1097
1236
  }
@@ -1198,8 +1337,8 @@ async function startEditServer(opts, deps = {}) {
1198
1337
  sendJson(res, 405, { error: "method not allowed" });
1199
1338
  return;
1200
1339
  }
1201
- const rel = normalize(decodeURIComponent(path)).replace(/^(\.\.[/\\])+/, "");
1202
- let filePath = join(dist, rel === "/" ? "index.html" : rel);
1340
+ const rel$1 = normalize(decodeURIComponent(path)).replace(/^(\.\.[/\\])+/, "");
1341
+ let filePath = join(dist, rel$1 === "/" ? "index.html" : rel$1);
1203
1342
  if (!filePath.startsWith(dist)) {
1204
1343
  sendJson(res, 403, { error: "forbidden" });
1205
1344
  return;
@@ -1212,6 +1351,7 @@ async function startEditServer(opts, deps = {}) {
1212
1351
  }
1213
1352
  });
1214
1353
  async function runRender(j, comp, captureLog) {
1354
+ const staged = await stagePrev(take.mp4Path, take.prevPath);
1215
1355
  try {
1216
1356
  await (deps.renderComposition ?? renderComposition)({
1217
1357
  composition: comp,
@@ -1225,6 +1365,7 @@ async function startEditServer(opts, deps = {}) {
1225
1365
  for (const c of j.clients) emit(c, "progress", { progress: p });
1226
1366
  }
1227
1367
  });
1368
+ await staged.commit();
1228
1369
  j.status = "done";
1229
1370
  j.progress = 1;
1230
1371
  j.mp4Url = `/api/take/output?v=${Date.now().toString(36)}`;
@@ -1233,6 +1374,7 @@ async function startEditServer(opts, deps = {}) {
1233
1374
  c.end();
1234
1375
  }
1235
1376
  } catch (err) {
1377
+ await staged.abort();
1236
1378
  j.status = "error";
1237
1379
  j.error = err instanceof Error ? err.message : String(err);
1238
1380
  for (const c of j.clients) {
@@ -1277,6 +1419,87 @@ function listen(server, startPort) {
1277
1419
  });
1278
1420
  }
1279
1421
 
1422
+ //#endregion
1423
+ //#region src/notes.ts
1424
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
1425
+ const fileSize = async (p) => (await stat(p).catch(() => null))?.size ?? 0;
1426
+ const readBytes = async (p) => await readFile(p).catch(() => Buffer.alloc(0));
1427
+ const readCursor = async (p) => {
1428
+ const n = Number((await readFile(p, "utf8").catch(() => "")).trim());
1429
+ return Number.isFinite(n) && n >= 0 ? n : 0;
1430
+ };
1431
+ /** `- opening is too slow` → `opening is too slow`; blank lines and stray text
1432
+ * are tolerated. Notes are free text in any language — never parsed for meaning. */
1433
+ const parseNotes = (buf) => buf.toString("utf8").split("\n").map((l) => l.replace(/^-\s*/, "").trim()).filter((l) => l.length > 0);
1434
+ /** The notes appended since the last read, and how many the log holds.
1435
+ * Advances the cursor unless `peek`, so a note is delivered exactly once. */
1436
+ async function readNotes(take, opts = {}) {
1437
+ const buf = await readBytes(take.notesPath);
1438
+ const saved = await readCursor(take.notesCursorPath);
1439
+ const from = opts.all || saved > buf.length ? 0 : saved;
1440
+ const end = buf.lastIndexOf(10) + 1;
1441
+ const slice = end > from ? buf.subarray(from, end) : Buffer.alloc(0);
1442
+ const cursor = Math.max(from, end);
1443
+ if (!opts.peek && cursor !== saved) await writeFile(take.notesCursorPath, `${cursor}\n`).catch(() => {});
1444
+ return {
1445
+ notes: parseNotes(slice),
1446
+ total: parseNotes(buf).length,
1447
+ cursor
1448
+ };
1449
+ }
1450
+ /** Block until at least one unread note exists, then return it (and consume
1451
+ * it). Returns immediately when the log already has unread notes — a waiter
1452
+ * started after the user typed still delivers, which is what makes restarting
1453
+ * one between rounds lossless. */
1454
+ async function waitForNotes(take, opts = {}) {
1455
+ const timeoutMs = opts.timeoutMs ?? 30 * 6e4;
1456
+ const pollMs = opts.pollMs ?? 500;
1457
+ const settleMs = opts.settleMs ?? 800;
1458
+ const deadline = Date.now() + timeoutMs;
1459
+ let last = await readNotes(take, opts);
1460
+ if (last.notes.length) return {
1461
+ ...last,
1462
+ timedOut: false
1463
+ };
1464
+ let seen = await fileSize(take.notesPath);
1465
+ while (!opts.signal?.aborted && Date.now() < deadline) {
1466
+ await sleep(Math.min(pollMs, Math.max(0, deadline - Date.now())));
1467
+ if (opts.signal?.aborted) break;
1468
+ if (await fileSize(take.notesPath) === seen) continue;
1469
+ if (settleMs > 0) await sleep(settleMs);
1470
+ last = await readNotes(take, {
1471
+ ...opts,
1472
+ all: false
1473
+ });
1474
+ seen = await fileSize(take.notesPath);
1475
+ if (last.notes.length) return {
1476
+ ...last,
1477
+ timedOut: false
1478
+ };
1479
+ }
1480
+ return {
1481
+ ...last,
1482
+ notes: [],
1483
+ timedOut: true
1484
+ };
1485
+ }
1486
+ const rel = (p) => p.replace(`${process.cwd()}/`, "");
1487
+ /** The wake-up message. Written for an agent reading a finished background
1488
+ * command: what came in, and the one thing it must re-read before editing. */
1489
+ function formatNotes(take, res, opts = {}) {
1490
+ if (!res.notes.length) {
1491
+ if (opts.waited && res.timedOut) return `no notes · ${take.name} (waited out)\n`;
1492
+ return res.total ? `no new notes · ${take.name} (${res.total} already read in ${rel(take.notesPath)})\n` : `no notes yet · ${take.name} (${rel(take.notesPath)})\n`;
1493
+ }
1494
+ const head = `${res.notes.length} new note${res.notes.length > 1 ? "s" : ""} from the editor · ${take.name}`;
1495
+ return [
1496
+ head,
1497
+ ...res.notes.map((n) => `- ${n}`),
1498
+ `(re-read ${rel(take.compositionPath)} before editing it — the editor may have changed it too)`,
1499
+ ""
1500
+ ].join("\n");
1501
+ }
1502
+
1280
1503
  //#endregion
1281
1504
  //#region src/frames.ts
1282
1505
  const COLS = 5;
@@ -1437,7 +1660,7 @@ async function renderFrames(take, opts = {}) {
1437
1660
  const trim = comp.startMs ?? 0;
1438
1661
  const durMs = await mp4Duration(src);
1439
1662
  const ffmpeg$1 = await resolveFfmpeg();
1440
- const framesPath = opts.beat != null ? `${take.base}.frames.beat${opts.beat}.png` : `${take.base}.frames.png`;
1663
+ const framesPath = opts.beat != null ? takeFile(take, `frames.beat${opts.beat}.png`) : take.framesPath;
1441
1664
  const tileW = Math.round(opts.tileWidth ?? (opts.beat != null ? 720 : 480));
1442
1665
  if (!Number.isFinite(tileW) || tileW < 120 || tileW > 1920) throw new Error(`frames: tile width ${tileW} out of range (120-1920)`);
1443
1666
  const tileH = Math.round(tileW * comp.output.height / comp.output.width);
@@ -1490,12 +1713,10 @@ async function renderFrames(take, opts = {}) {
1490
1713
 
1491
1714
  //#endregion
1492
1715
  //#region src/index.ts
1493
- /** `<out>.mp4` → `<out>.capture.mp4` — the raw recording kept beside the
1494
- * polished output so the composition can be re-rendered (refined) later. */
1495
- const capturePathFor = (outPath) => `${resolve(outPath).replace(/\.mp4$/i, "")}.capture.mp4`;
1496
- /** `<x>.capture.mp4` → `<x>.capture.json` — the capture log sits beside the
1497
- * video. Deriving it by convention lets `render` find the ground-truth timing
1498
- * from just the `--video` path. */
1716
+ /** `<video>.mp4` → `<video>.json` — the capture log sits beside its video
1717
+ * (`capture.mp4` → `capture.json` inside the take's working dir). Deriving it
1718
+ * by convention lets `render` find the ground-truth timing from just the
1719
+ * `--video` path. */
1499
1720
  const captureLogPathFor = (capturePath) => resolve(capturePath).replace(/\.mp4$/i, ".json");
1500
1721
  /** Load the capture log that sits beside a capture video, if present. Returns
1501
1722
  * undefined when there's no sibling (e.g. an old capture, or a hand-supplied
@@ -1517,14 +1738,19 @@ async function makeTake(plan, opts) {
1517
1738
  chromePath,
1518
1739
  videoPath: tmpVideo
1519
1740
  });
1520
- const capturePath = capturePathFor(opts.outPath);
1521
- const captureLogPath = captureLogPathFor(capturePath);
1522
- await mkdir(dirname(capturePath), { recursive: true });
1741
+ const take = await resolveTakePaths(opts.outPath);
1742
+ const { capturePath, captureLogPath } = take;
1743
+ await mkdir(dirname(take.mp4Path), { recursive: true });
1744
+ await ensureTakeDir(take);
1523
1745
  await copyFile(tmpVideo, capturePath);
1524
1746
  try {
1525
1747
  opts.onCaptureReady?.(capturePath);
1526
1748
  } catch {}
1527
- const log = opts.frameDiff === false ? raw : await annotateCaptureLog(raw, tmpVideo, { logProgress: opts.verbose === true });
1749
+ const annotated = opts.frameDiff === false ? raw : await annotateCaptureLog(raw, tmpVideo, { logProgress: opts.verbose === true });
1750
+ const log = {
1751
+ ...annotated,
1752
+ url: plan.url
1753
+ };
1528
1754
  await writeFile(captureLogPath, JSON.stringify(log, null, 2));
1529
1755
  const captureFps = opts.capture?.fps ?? 60;
1530
1756
  const planOpts = opts.planOpts?.output?.fps == null ? {
@@ -1535,10 +1761,11 @@ async function makeTake(plan, opts) {
1535
1761
  }
1536
1762
  } : opts.planOpts;
1537
1763
  const composition = planComposition(log, planOpts);
1538
- const { mp4Path, compositionPath } = await renderTake({
1764
+ const { mp4Path, compositionPath, warnings } = await renderTake({
1539
1765
  composition: opts.draft ? toDraft(composition) : composition,
1540
1766
  videoPath: capturePath,
1541
- outPath: resolve(opts.outPath),
1767
+ outPath: take.mp4Path,
1768
+ compositionPath: take.compositionPath,
1542
1769
  logProgress: opts.logProgress ?? false,
1543
1770
  chromePath,
1544
1771
  captureLog: log,
@@ -1548,10 +1775,14 @@ async function makeTake(plan, opts) {
1548
1775
  return {
1549
1776
  mp4Path,
1550
1777
  compositionPath,
1778
+ takeDir: take.dir,
1551
1779
  capturePath,
1552
1780
  captureLogPath,
1553
1781
  composition,
1554
- skipped: log.skipped ?? []
1782
+ skipped: log.skipped ?? [],
1783
+ settleWaits: log.settleWaits ?? [],
1784
+ ...log.paintedFrac != null ? { paintedFrac: log.paintedFrac } : {},
1785
+ warnings
1555
1786
  };
1556
1787
  }
1557
1788
  /** Refine: re-render an EDITED composition over a saved capture — no app
@@ -1561,10 +1792,13 @@ async function makeTake(plan, opts) {
1561
1792
  * capture-locked tMs drift when `captureLog` is supplied. */
1562
1793
  async function renderComposition(opts) {
1563
1794
  const chromePath = await ensureChrome(opts.chromePath);
1795
+ const take = await resolveTakePaths(opts.outPath);
1796
+ if (opts.writeCompositionSibling !== false) await ensureTakeDir(take);
1564
1797
  return renderTake({
1565
1798
  composition: opts.composition,
1566
1799
  videoPath: resolve(opts.capturePath),
1567
- outPath: resolve(opts.outPath),
1800
+ outPath: take.mp4Path,
1801
+ compositionPath: take.compositionPath,
1568
1802
  logProgress: opts.logProgress ?? false,
1569
1803
  chromePath,
1570
1804
  captureLog: opts.captureLog,
@@ -1593,5 +1827,5 @@ async function renderCompositionFile(opts) {
1593
1827
  }
1594
1828
 
1595
1829
  //#endregion
1596
- export { SAY_IT_CARD, annotateCaptureLog, beatLabel, buildBadges, buildBeatSheet, buildFramePlan, buildFrameSheet, captureLogPathFor, captureTake, captureTakeCDP, diffFrames, ensureChrome, formatIssues, inspectPage, loadCaptureLogSibling, makeTake, openPath, renderAbReel, renderBeforeAfter, renderComposition, renderCompositionFile, renderDraft, renderFrames, renderReview, requireTakeFiles, resolveChrome, resolveTakePaths, revealPath, stagePrev, startEditServer, toDraft, validateComposition };
1830
+ export { SAY_IT_CARD, TAKE_DIR_SUFFIX, annotateCaptureLog, authProfile, beatLabel, buildBadges, buildBeatSheet, buildFramePlan, buildFrameSheet, captureLogPathFor, captureTake, captureTakeCDP, diffFrames, ensureChrome, ensureTakeDir, formatIssues, formatNotes, inspectPage, loadCaptureLogSibling, makeTake, openPath, profileDir, readNotes, renderAbReel, renderBeforeAfter, renderComposition, renderCompositionFile, renderDraft, renderFrames, renderReview, requireTakeFiles, resolveChrome, resolveNavigateUrl, resolveTakePaths, revealPath, stagePrev, startEditServer, takeFile, toDraft, validateComposition, waitForNotes };
1597
1831
  //# sourceMappingURL=index.js.map