cuetake 0.1.0 → 0.3.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/README.md CHANGED
@@ -1,15 +1,18 @@
1
1
  # CueTake
2
2
 
3
+ [![skills.sh](https://skills.sh/b/levyxdev/cuetake)](https://skills.sh/levyxdev/cuetake) [![npm](https://img.shields.io/npm/v/cuetake)](https://www.npmjs.com/package/cuetake)
4
+
3
5
  **Script the flow. Keep the take.**
4
6
 
5
7
  Built entirely for AI agents, CueTake turns browser interactions into sharp product demo videos with a precise cursor and continuous camera moves. Give an agent a scenario, then capture, render, and verify the result locally.
6
8
 
7
- ![A CueTake Final: the page in a browser window on a gradient, the camera zooming to the field being typed into](docs/media/demo.gif)
9
+ ![A CueTake Final: Excalidraw in a browser window over purple fluted glass, the camera following as a sign-up flow is drawn, labeled, linked and filled](docs/media/demo.gif)
8
10
 
9
11
  - Retina tab capture at 30 or 60 fps and a 2× pixel scale, headless by default.
10
12
  - An automatic camera in the style of Screen Studio: it arrives just before each click, field and drag, follows the cursor on a spring, and ends on the wide shot.
11
- - The page framed in a browser or macOS window on a gradient, brand-colored or blurred background, at 16:9, 1:1 or 9:16.
13
+ - The page framed in a browser or macOS window over fluted glass lit in the product's brand color, at any output size; backgrounds, chrome, cursors and click effects are shaders or drawing code the agent can write.
12
14
  - Cursor and click sparks drawn at Render time, so a Take can be restyled without recording again.
15
+ - Styling chosen in conversation: the agent shows Previews of candidate Looks side by side in about a second, and the Look you pick is saved for later Takes.
13
16
  - Rendering in Chromium with WebGL and WebCodecs: no FFmpeg, 4K60 by default.
14
17
  - A separate folder for every Take: Source, Timeline, Edit, Final MP4, and verification.
15
18
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cuetake",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Local recording runtime for AI agents: plan a browser demo, capture it, and render a finished take.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -8,7 +8,6 @@
8
8
  },
9
9
  "files": [
10
10
  "src",
11
- "skills",
12
11
  "examples",
13
12
  "README.md",
14
13
  "LICENSE"
package/src/cli.js CHANGED
@@ -1,7 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import { parseArgs } from 'node:util';
3
3
  import pkg from '../package.json' with { type: 'json' };
4
- import { recordScenario, renderTake, verifyTake } from './pipeline.js';
4
+ import { recordScenario, renderTake, verifyTake, previewTake, applyLookToTake, saveLookFromTake } from './pipeline.js';
5
+ import { listLooks, removeLook } from './look.js';
6
+ import { BUILTINS, BUILTIN_DIR } from './styles.js';
5
7
  import { doctor, installBrowser } from './environment.js';
6
8
  import { login } from './auth.js';
7
9
  import { extractFrame } from './render.js';
@@ -12,27 +14,43 @@ const help = `CueTake ${pkg.version} — browser demos directed by code
12
14
 
13
15
  cuetake doctor
14
16
  cuetake install-browser
15
- cuetake record <scenario.mjs> [--out <new-directory>] [--auth-profile <name>] [--headed]
17
+ cuetake record <scenario.mjs> [--out <new-directory>] [--auth-profile <name>] [--look <name|file.json>] [--headed]
18
+ cuetake preview <take-directory> [--look <name|file.json>]... [--at <seconds>]
16
19
  cuetake render <take-directory>
17
20
  cuetake verify <take-directory>
18
21
  cuetake frame <take-directory> <seconds> [--out <file.png>]
19
22
  cuetake login <profile> <login-url>
23
+ cuetake look list
24
+ cuetake look save <name> <take-directory> [--global] [--replace]
25
+ cuetake look apply <name|file.json> <take-directory>
26
+ cuetake look rm <name> [--global]
27
+ cuetake styles
20
28
 
21
29
  install-browser downloads the Chromium build this CueTake version drives (about 150 MB).
22
30
  record captures, renders and verifies a new take; an existing directory is never overwritten.
23
31
  Capture runs headless; --headed shows the browser window while recording.
32
+ --look seeds the first Edit from a Look; fields the Scenario config names win.
33
+ preview writes preview.png in the take: the current Edit beside each Look, at --at seconds
34
+ or at the end with the camera wide. It never changes edit.json or final.mp4.
24
35
  render reuses source.webm, timeline.json and edit.json, replacing final.mp4 only on success.
25
36
  frame saves one Final frame as a PNG for inspection.
26
37
  login opens a separate browser; close its window after logging in to save the profile.
38
+ A Look is a take's reusable styling, with the files it draws with. Looks are saved locally
39
+ (.cuetake/looks in this directory) unless --global; a local Look hides a global one with the same
40
+ name. list names the code each Look runs. apply rewrites edit.json and copies files into styles/.
41
+ styles lists the built-in shaders and drawing code, with their files and starting parameters.
42
+ Styling is agent-written code and is not validated; the render page has no network.
27
43
  Scenario files are trusted JavaScript. Recording runs locally, without audio.
28
44
  `;
29
45
  try {
30
- const { values, positionals } = parseArgs({ args: process.argv.slice(2), allowPositionals: true, options: { out: { type: 'string' }, help: { type: 'boolean', short: 'h' }, 'auth-profile': { type: 'string' }, headed: { type: 'boolean' } } });
31
- const [command, target] = positionals;
46
+ const { values, positionals } = parseArgs({ args: process.argv.slice(2), allowPositionals: true, options: { out: { type: 'string' }, help: { type: 'boolean', short: 'h' }, 'auth-profile': { type: 'string' }, headed: { type: 'boolean' }, look: { type: 'string', multiple: true }, at: { type: 'string' }, global: { type: 'boolean' }, replace: { type: 'boolean' } } });
47
+ const [command, target] = positionals, looks = values.look ?? [];
48
+ const print = data => console.log(JSON.stringify(data, null, 2));
32
49
  if (values.help || !command) console.log(help);
33
50
  else if (command === 'doctor') { const result = await doctor(); console.log(JSON.stringify(result, null, 2)); if (!result.ok) process.exitCode = 1; }
34
51
  else if (command === 'install-browser') console.log(JSON.stringify(await installBrowser(), null, 2));
35
- else if (command === 'record' && target) console.log(JSON.stringify(await recordScenario(target, values.out, { authProfile: values['auth-profile'], headed: values.headed }), null, 2));
52
+ else if (command === 'record' && target && looks.length <= 1) print(await recordScenario(target, values.out, { authProfile: values['auth-profile'], look: looks[0], headed: values.headed }));
53
+ else if (command === 'preview' && target) print(await previewTake(target, looks, { at: values.at === undefined ? undefined : Number(values.at) }));
36
54
  else if (command === 'render' && target) { await renderTake(target); console.log(JSON.stringify(await verifyTake(target), null, 2)); }
37
55
  else if (command === 'verify' && target) console.log(JSON.stringify(await verifyTake(target), null, 2));
38
56
  else if (command === 'frame' && target && positionals[2]) {
@@ -41,5 +59,10 @@ try {
41
59
  console.log(out);
42
60
  }
43
61
  else if (command === 'login' && target && positionals[2]) console.log(JSON.stringify(await login(positionals[2], target), null, 2));
62
+ else if (command === 'look' && target === 'list') print(await listLooks());
63
+ else if (command === 'look' && target === 'save' && positionals[3]) print(await saveLookFromTake(positionals[2], positionals[3], { global: values.global, replace: values.replace }));
64
+ else if (command === 'look' && target === 'apply' && positionals[3]) print(await applyLookToTake(positionals[2], positionals[3]));
65
+ else if (command === 'look' && target === 'rm' && positionals[2]) print(await removeLook(positionals[2], { global: values.global }));
66
+ else if (command === 'styles') print(Object.entries(BUILTINS).map(([name, { file, params }]) => ({ name, kind: file.endsWith('.glsl') ? 'shader' : 'draw', path: join(BUILTIN_DIR, file), params })));
44
67
  else throw new Error(`Unknown or incomplete command.\n${help}`);
45
68
  } catch (error) { console.error(`CueTake: ${error.message}`); process.exitCode = 1; }
package/src/cursor.js CHANGED
@@ -20,38 +20,9 @@ export function presses(events) {
20
20
  : event.type === 'drag' ? [{ t: event.t, ...event.from }] : []);
21
21
  }
22
22
 
23
- /** Sparks alive at `t`, each with its progress from 0 to 1. */
23
+ /** Click effects alive at `t`, each with its progress from 0 to 1; `clickEffect: false` shows none. */
24
24
  export function sparksAt(pressList, clickEffect, t) {
25
- if (clickEffect.style === 'none') return [];
26
- const life = clickEffect.duration / 1000;
25
+ if (!clickEffect) return [];
26
+ const life = (clickEffect.duration ?? 400) / 1000;
27
27
  return pressList.filter(p => t >= p.t && t < p.t + life).map(p => ({ x: p.x, y: p.y, progress: (t - p.t) / life }));
28
28
  }
29
-
30
- /** Arrow outline in its 28×36 design box; the hotspot is the tip at (2, 2). */
31
- export const ARROW_PATH = 'M2 2 L2 27 L8.5 21 L14 33 L19 30.5 L13.5 19 L23 19 Z';
32
-
33
- /** Cursor sprite geometry in CSS pixels: drawn size and the hotspot offset from its top-left. */
34
- export function cursorGeometry(cursor) {
35
- return cursor.style === 'arrow'
36
- ? { width: cursor.size, height: cursor.size * 36 / 28, hotspot: { x: cursor.size * 2 / 28, y: cursor.size * 2 / 28 } }
37
- : { width: cursor.size, height: cursor.size, hotspot: { x: cursor.size / 2, y: cursor.size / 2 } };
38
- }
39
-
40
- /** Draws one spark centered in a 2D context whose unit is one CSS pixel. */
41
- export function drawSpark(ctx, x, y, progress, clickEffect, color) {
42
- const eased = 1 - (1 - progress) ** 3;
43
- const distance = 5 + eased * clickEffect.radius;
44
- const length = clickEffect.length * (1 - eased);
45
- ctx.globalAlpha = 1 - progress;
46
- ctx.lineCap = 'round';
47
- for (let i = 0; i < clickEffect.count; i++) {
48
- const angle = 2 * Math.PI * i / clickEffect.count + Math.PI / 8;
49
- ctx.beginPath();
50
- ctx.moveTo(x + distance * Math.cos(angle), y + distance * Math.sin(angle));
51
- ctx.lineTo(x + (distance + length) * Math.cos(angle), y + (distance + length) * Math.sin(angle));
52
- // A dark edge under a cursor-colored core stays legible on light and dark pages.
53
- ctx.strokeStyle = '#171717'; ctx.lineWidth = 4.5; ctx.stroke();
54
- ctx.strokeStyle = color; ctx.lineWidth = 2.5; ctx.stroke();
55
- }
56
- ctx.globalAlpha = 1;
57
- }
package/src/edit.js CHANGED
@@ -1,58 +1,55 @@
1
1
  import { z } from 'zod';
2
- import { SHORT_SIDE, CHROME_HEIGHT, BACKGROUNDS } from './stage.js';
3
2
 
4
- /** An Edit holds every choice Render makes; a Scenario's config only seeds the first one. */
3
+ /**
4
+ * An Edit holds every choice Render makes; a Scenario's config only seeds the first one. Styling is
5
+ * agent-written and not validated (ADR 0005): defaults fill in what an Edit leaves out, and anything
6
+ * else an item names is passed to its shader or drawing code as a parameter.
7
+ *
8
+ * Drawn things are items: `{ shader }`, `{ draw }` or `{ image }` naming a file (relative to the Take)
9
+ * or a built-in (a name without an extension, see styles.js), plus optional `files` and parameters.
10
+ */
11
+ export const EDIT_VERSION = 3;
5
12
  export const evenSize = z.number().int().min(240).max(7680).refine(n => n % 2 === 0, 'Must be an even pixel count');
6
- const box = z.object({ x: z.number(), y: z.number(), width: z.number().nonnegative(), height: z.number().nonnegative() });
7
-
8
- // size names the Final's short side; quality is the H.264 quantizer (lower is sharper and larger).
9
- const outputFields = z.object({
10
- size: z.union([z.enum(Object.keys(SHORT_SIDE)), evenSize]).default('2160p'),
11
- aspect: z.enum(['16:9', '1:1', '9:16']).default('16:9'),
12
- quality: z.number().int().min(10).max(40).default(22),
13
- });
14
13
 
15
14
  /** Times are seconds except clickEffect.duration, which is milliseconds; geometry is CSS pixels. */
16
- export const editFields = {
17
- cursor: z.object({ style: z.enum(['arrow', 'dot']).default('arrow'), size: z.number().min(12).max(64).default(24), color: z.string().regex(/^#[a-fA-F0-9]{6}$/).default('#ffffff') }).default({}),
18
- clickEffect: z.object({ style: z.enum(['spark', 'none']).default('spark'), radius: z.number().min(8).max(80).default(32), length: z.number().min(4).max(40).default(16), count: z.number().int().min(4).max(16).default(8), duration: z.number().min(150).max(1000).default(420) }).default({}),
19
- output: outputFields.default({}),
20
- // The page in a window on a background; `false` lets the page fill the Final. Radius is in 1080p pixels.
21
- frame: z.union([z.literal(false), z.object({
22
- window: z.enum(Object.keys(CHROME_HEIGHT)).default('browser'),
23
- background: z.enum([...Object.keys(BACKGROUNDS), 'auto', 'blur']).default('aurora'),
24
- padding: z.number().min(0).max(0.3).default(0.08),
25
- radius: z.number().min(0).max(48).default(12),
26
- shadow: z.boolean().default(true),
27
- url: z.string().max(200).optional(),
28
- })]).default({}),
15
+ export const DEFAULT_STYLE = {
16
+ cursor: { draw: 'arrow', size: 24, color: '#ffffff' },
17
+ clickEffect: { draw: 'spark', duration: 420 },
18
+ // quality is the H.264 quantizer (lower is sharper and larger).
19
+ output: { width: 3840, height: 2160, quality: 22 },
20
+ // padding is a fraction of the short side, one number or [top, right, bottom, left]; radius is in 1080p pixels.
21
+ frame: { padding: 0.08, radius: 12, chrome: { draw: 'browser' }, background: [{ shader: 'fluted' }], effects: [{ shader: 'shadow' }] },
29
22
  // See camera.js. Each target is framed with `padding` CSS px around it, zooming at most `maxZoom`;
30
23
  // fits below `minZoom` stay wide. The camera arrives `lead` before an action, holds `hold` after the
31
24
  // last one in a segment, settles in about `response`, and returns wide `endWide` before the end.
32
- camera: z.object({
33
- maxZoom: z.number().min(1).max(4).default(2), minZoom: z.number().min(1).max(4).default(1.2), padding: z.number().min(0).max(400).default(48),
34
- lead: z.number().min(0).max(3).default(0.6), hold: z.number().min(0).max(30).default(1.5), chainGap: z.number().min(0).max(30).default(2),
35
- response: z.number().min(0.1).max(3).default(0.6), follow: z.boolean().default(true), endWide: z.number().min(0).max(10).default(1.5),
36
- }).default({}),
25
+ camera: { maxZoom: 2, minZoom: 1.2, padding: 48, lead: 0.6, hold: 1.5, chainGap: 2, response: 0.6, follow: true, endWide: 1.5 },
37
26
  };
38
27
 
39
- /** A camera target is a CSS-pixel box the camera reaches at `t` seconds and holds at least until `until`, optionally at a fixed `zoom`. */
40
- const target = z.object({ t: z.number().nonnegative(), box, until: z.number().nonnegative().optional(), zoom: z.number().min(1).max(4).optional() });
28
+ const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
29
+ /** Naming what draws an item starts a new item, so the old drawing's parameters do not leak into it. */
30
+ const namesDrawing = value => ['shader', 'draw', 'image'].some(key => key in value);
31
+ /** `over` wins field by field: nested objects merge; anything else, including arrays and `false`, replaces. */
32
+ export function merge(base, over) {
33
+ const merged = { ...base };
34
+ for (const [key, value] of Object.entries(over ?? {})) {
35
+ if (value === undefined) continue;
36
+ merged[key] = isObject(value) && isObject(base?.[key]) && !namesDrawing(value) ? merge(base[key], value) : value;
37
+ }
38
+ return merged;
39
+ }
41
40
 
42
- export const editSchema = z.object({
43
- schemaVersion: z.literal(2),
44
- ...editFields,
45
- camera: editFields.camera.removeDefault().extend({ targets: z.array(target).default([]) }).default({}),
46
- // The Final's frame rate; a new Take takes it from the Scenario's capture rate.
47
- output: outputFields.extend({ fps: z.union([z.literal(30), z.literal(60)]).default(60) }).default({}),
48
- });
41
+ /** A complete Edit: the defaults under whatever `edit` names. */
42
+ export function withDefaults(edit) {
43
+ return merge({ schemaVersion: EDIT_VERSION, ...DEFAULT_STYLE, output: { ...DEFAULT_STYLE.output, fps: 60 }, camera: { ...DEFAULT_STYLE.camera, targets: [] } }, edit);
44
+ }
49
45
 
50
46
  /**
51
47
  * Camera targets: observed clicks, typing and drags, except those inside a `wide` window ({ start, end }
52
48
  * seconds) from an action with `focus: false`. Like a manual zoom in Screen Studio, an explicit focus
53
49
  * target replaces only the automatic targets inside its own span (from `lead` before it to `hold` after).
54
50
  */
55
- export function cameraTargets(timeline, focus, wide = [], { lead, hold } = editFields.camera.parse({})) {
51
+ export function cameraTargets(timeline, focus, wide = [], camera = {}) {
52
+ const { lead, hold } = { ...DEFAULT_STYLE.camera, ...camera };
56
53
  const spans = focus.map(f => ({ start: f.t - lead, end: (f.until ?? f.t) + hold }));
57
54
  const inside = (t, windows) => windows.some(w => t >= w.start && t <= w.end);
58
55
  const automatic = timeline.events.filter(event => !inside(event.t, wide) && !inside(event.t, spans)).flatMap(event => {
@@ -68,11 +65,10 @@ export function cameraTargets(timeline, focus, wide = [], { lead, hold } = editF
68
65
  }
69
66
 
70
67
  export function createEdit(config, timeline, focus, wide = []) {
71
- return editSchema.parse({
72
- schemaVersion: 2,
68
+ return withDefaults({
73
69
  cursor: config.cursor, clickEffect: config.clickEffect, output: { ...config.output, fps: config.capture.fps },
74
70
  // The browser chrome shows the Scenario's host unless the config names something else.
75
- frame: config.frame && { url: new URL(config.url).host, ...config.frame },
71
+ frame: { url: new URL(config.url).host, ...config.frame },
76
72
  camera: { ...config.camera, targets: cameraTargets(timeline, focus, wide, config.camera) },
77
73
  });
78
74
  }
package/src/look.js ADDED
@@ -0,0 +1,121 @@
1
+ import fs from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { basename, dirname, join, resolve } from 'node:path';
4
+ import { merge } from './edit.js';
5
+ import { absolute, bundle, codeRefs, fileRefs } from './styles.js';
6
+
7
+ /**
8
+ * A Look is the part of an Edit that does not depend on one Take: everything except camera targets,
9
+ * the address bar's url and the frame rate. A Look sets only what it names, and is not validated.
10
+ */
11
+ export const mergeLook = merge;
12
+
13
+ /** The Look an Edit carries. */
14
+ export function lookFromEdit(edit) {
15
+ const { schemaVersion, output: { fps, ...output } = {}, frame, camera: { targets, ...camera } = {}, ...rest } = edit;
16
+ const { url, ...styling } = frame ?? {};
17
+ return { ...rest, output, frame: styling, camera };
18
+ }
19
+
20
+ /** The Edit with a Look adopted. Camera targets and the frame rate stay; the address bar keeps its url, else shows `host`. */
21
+ export function applyLook(edit, look, host) {
22
+ const next = merge(edit, look);
23
+ next.frame = { ...next.frame, url: edit.frame?.url ?? host };
24
+ return next;
25
+ }
26
+
27
+ const label = item => item && typeof item === 'object' ? basename(String(item.shader ?? item.draw ?? item.image ?? '')) : item === false ? 'none' : null;
28
+ /** One line for listings, such as "browser-dark · fluted · 3840×2160". */
29
+ export function summarize(look) {
30
+ const { frame, output } = look;
31
+ const parts = [label(frame?.chrome), ...(Array.isArray(frame?.background) ? frame.background.map(label) : []), output?.width && output?.height ? `${output.width}×${output.height}` : null];
32
+ return parts.filter(Boolean).join(' · ') || Object.keys(look).join(', ') || 'empty';
33
+ }
34
+
35
+ /** Local Looks live in the directory CueTake runs in; global ones serve every directory. */
36
+ const scopes = (cwd = process.cwd()) => ({
37
+ local: join(cwd, '.cuetake', 'looks'),
38
+ global: process.env.CUETAKE_LOOK_DIR || join(homedir(), '.local/share/cuetake/looks'),
39
+ });
40
+ function checkName(name) {
41
+ if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(name)) throw new Error('Use a short lowercase Look name, such as brand');
42
+ }
43
+ const readIfPresent = path => fs.readFile(path, 'utf8').catch(error => { if (['ENOENT', 'ENOTDIR'].includes(error.code)) return null; throw error; });
44
+ const parse = (text, path) => { try { return JSON.parse(text); } catch (error) { throw new Error(`${path} is not JSON: ${error.message}`); } };
45
+
46
+ /** A saved Look is `<name>.json`, or a `<name>/` folder holding `look.json` and the files it names. */
47
+ async function readSaved(dir, name) {
48
+ for (const path of [join(dir, `${name}.json`), join(dir, name, 'look.json')]) {
49
+ const text = await readIfPresent(path);
50
+ if (text !== null) return { path, dir: dirname(path), look: parse(text, path) };
51
+ }
52
+ return null;
53
+ }
54
+
55
+ /**
56
+ * A Look by name, local before global, or from a JSON file labeled by its `name` or file name. `dir` is
57
+ * where its file refs resolve.
58
+ */
59
+ export async function loadLook(ref, cwd = process.cwd()) {
60
+ if (ref.endsWith('.json')) {
61
+ const path = resolve(cwd, ref);
62
+ const { name = basename(ref, '.json'), ...look } = parse(await fs.readFile(path, 'utf8'), path);
63
+ return { name: String(name), dir: dirname(path), look };
64
+ }
65
+ checkName(ref);
66
+ for (const [scope, root] of Object.entries(scopes(cwd))) {
67
+ const saved = await readSaved(root, ref);
68
+ if (saved) return { name: ref, scope, dir: saved.dir, look: saved.look };
69
+ }
70
+ const { local, global } = scopes(cwd);
71
+ throw new Error(`No Look named '${ref}' in ${local} or ${global}`);
72
+ }
73
+
74
+ /** A Look's styling with its file refs made absolute, ready to merge with styling from elsewhere. */
75
+ export const resolvedLook = ({ look, dir }) => absolute(look, dir);
76
+
77
+ /** Every saved Look, with the code files it runs; a global Look hidden by a local one with the same name is marked shadowed. */
78
+ export async function listLooks(cwd = process.cwd()) {
79
+ const found = [];
80
+ for (const [scope, root] of Object.entries(scopes(cwd))) {
81
+ const entries = await fs.readdir(root, { withFileTypes: true }).catch(error => { if (error.code === 'ENOENT') return []; throw error; });
82
+ const names = entries.flatMap(e => e.isDirectory() ? [e.name] : e.name.endsWith('.json') ? [basename(e.name, '.json')] : []).sort();
83
+ for (const name of new Set(names)) {
84
+ const saved = await readSaved(root, name).catch(error => ({ error }));
85
+ if (!saved) continue;
86
+ const entry = { name, scope, shadowed: scope === 'global' && found.some(l => l.scope === 'local' && l.name === name), path: saved.path ?? join(root, name) };
87
+ if (saved.error) found.push({ ...entry, summary: `invalid: ${saved.error.message}` });
88
+ else found.push({ ...entry, summary: summarize(saved.look), code: codeRefs(absolute(saved.look, saved.dir)) });
89
+ }
90
+ }
91
+ return found;
92
+ }
93
+
94
+ /**
95
+ * Saves a Look locally unless `global`, with its file refs resolved against `from`. A Look that names
96
+ * files becomes a folder holding copies of them. An existing Look with the name is kept unless `replace`.
97
+ */
98
+ export async function saveLook(name, look, { global = false, replace = false, cwd, from = cwd ?? process.cwd() } = {}) {
99
+ checkName(name);
100
+ const scope = global ? 'global' : 'local', root = scopes(cwd)[scope];
101
+ const existing = await readSaved(root, name);
102
+ if (existing && !replace) throw new Error(`A ${scope} Look named '${name}' already exists at ${existing.path}; pass --replace to overwrite it`);
103
+ await fs.rm(join(root, `${name}.json`), { force: true });
104
+ await fs.rm(join(root, name), { recursive: true, force: true });
105
+ const hasFiles = fileRefs(look).length > 0, dir = hasFiles ? join(root, name) : root;
106
+ const saved = hasFiles ? await bundle(look, from, dir) : look;
107
+ const path = hasFiles ? join(dir, 'look.json') : join(root, `${name}.json`);
108
+ await fs.mkdir(dirname(path), { recursive: true });
109
+ await fs.writeFile(path, JSON.stringify(saved, null, 2) + '\n');
110
+ return { name, scope, path, summary: summarize(saved), code: codeRefs(absolute(saved, dir)) };
111
+ }
112
+
113
+ export async function removeLook(name, { global = false, cwd } = {}) {
114
+ checkName(name);
115
+ const scope = global ? 'global' : 'local', root = scopes(cwd)[scope];
116
+ const saved = await readSaved(root, name);
117
+ if (!saved) throw new Error(`No ${scope} Look named '${name}' in ${root}`);
118
+ const removed = saved.path === join(root, `${name}.json`) ? saved.path : saved.dir;
119
+ await fs.rm(removed, { recursive: true, force: true });
120
+ return { name, scope, removed };
121
+ }
package/src/pipeline.js CHANGED
@@ -1,33 +1,37 @@
1
1
  import fs from 'node:fs/promises';
2
- import { join, resolve } from 'node:path';
2
+ import { dirname, join, resolve } from 'node:path';
3
3
  import { pathToFileURL } from 'node:url';
4
4
  import { doctor } from './environment.js';
5
5
  import { z } from 'zod';
6
6
  import { startRecording, getRecordingPage, beginCapture, stopRecording, cleanup } from './recorder.js';
7
- import { renderFinal, inspectFinal } from './render.js';
8
- import { outputSize } from './stage.js';
7
+ import { renderFinal, inspectFinal, composePreview } from './render.js';
8
+ import { outputSize, atShortSide } from './stage.js';
9
9
  import { resolveAuthProfile } from './auth.js';
10
10
  import { createDirector } from './director.js';
11
11
  import { collectTimeline } from './probe.js';
12
- import { editFields, editSchema, createEdit, evenSize } from './edit.js';
12
+ import { createEdit, evenSize, merge, withDefaults } from './edit.js';
13
+ import { loadLook, resolvedLook, applyLook, lookFromEdit, saveLook, summarize } from './look.js';
14
+ import { absolute, bundle, forRender } from './styles.js';
13
15
  import pkg from '../package.json' with { type: 'json' };
14
16
 
15
- const SCHEMA_VERSION = 2;
16
- /** Scenario config: capture settings plus the defaults that seed each Take's Edit. */
17
+ const SCHEMA_VERSION = 3;
18
+ /** Scenario config: capture settings, validated, plus styling that seeds each Take's Edit, which is not (ADR 0005). */
17
19
  export const scenarioSchema = z.object({
18
20
  name: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
19
21
  url: z.string().url().refine(s => /^https?:/.test(s), 'Capture requires HTTP(S)'),
20
22
  viewport: z.object({ width: evenSize, height: evenSize }).default({ width: 1440, height: 900 }),
21
23
  capture: z.object({ fps: z.union([z.literal(30), z.literal(60)]).default(60), resolutionScale: z.union([z.literal(1), z.literal(2)]).default(2) }).default({}),
22
- ...editFields,
23
- });
24
+ }).passthrough();
24
25
  const writeJson = (path, data) => fs.writeFile(path, JSON.stringify(data, null, 2) + '\n');
25
26
  const readJson = async path => JSON.parse(await fs.readFile(path, 'utf8'));
26
27
 
27
28
  /** New take directories are exclusive: reruns never overwrite a previous take. */
28
29
  export async function recordScenario(scenarioPath, outputDir, options = {}) {
29
30
  const scenario = await import(pathToFileURL(resolve(scenarioPath)).href);
30
- const config = scenarioSchema.parse(scenario.config);
31
+ // A Look sits under the Scenario: every field the config names wins over it. File refs resolve
32
+ // against the Look and the Scenario file, and the files are copied into the Take.
33
+ const look = options.look ? await loadLook(options.look) : null;
34
+ const config = scenarioSchema.parse(merge(look ? resolvedLook(look) : {}, absolute(scenario.config, dirname(resolve(scenarioPath)))));
31
35
  if (typeof scenario.run !== 'function') throw new Error('Scenario must export run(director)');
32
36
  const authState = options.authProfile ? await resolveAuthProfile(options.authProfile) : undefined;
33
37
  const ready = await doctor();
@@ -35,7 +39,7 @@ export async function recordScenario(scenarioPath, outputDir, options = {}) {
35
39
  const dir = resolve(outputDir || join('recordings', config.name, new Date().toISOString().replace(/[:.]/g, '-')));
36
40
  await fs.mkdir(resolve(dir, '..'), { recursive: true });
37
41
  await fs.mkdir(dir); // EEXIST is intentional, including for empty existing folders.
38
- let project = { schemaVersion: SCHEMA_VERSION, tool: 'CueTake', version: pkg.version, createdAt: new Date().toISOString(), status: 'recording', authenticated: Boolean(authState), config };
42
+ let project = { schemaVersion: SCHEMA_VERSION, tool: 'CueTake', version: pkg.version, createdAt: new Date().toISOString(), status: 'recording', authenticated: Boolean(authState), ...(look && { look: look.name }), config };
39
43
  await writeJson(join(dir, 'project.json'), project);
40
44
  await fs.copyFile(resolve(scenarioPath), join(dir, 'scenario.mjs'));
41
45
  try {
@@ -60,7 +64,7 @@ export async function recordScenario(scenarioPath, outputDir, options = {}) {
60
64
  pointer: observed.pointer, events: [...observed.events, ...focus.map(f => ({ type: 'focus', ...f }))].sort((a, b) => a.t - b.t),
61
65
  };
62
66
  await writeJson(join(dir, 'timeline.json'), timeline);
63
- await writeJson(join(dir, 'edit.json'), createEdit(config, timeline, focus, wide));
67
+ await writeJson(join(dir, 'edit.json'), await intoTake(createEdit(config, timeline, focus, wide), dir));
64
68
  project = { ...project, status: 'captured', duration: stopped.durationSeconds, evidence: evidence ?? null };
65
69
  await writeJson(join(dir, 'project.json'), project);
66
70
  } catch (error) {
@@ -72,11 +76,48 @@ export async function recordScenario(scenarioPath, outputDir, options = {}) {
72
76
  return { directory: dir, final: join(dir, 'final.mp4'), verification };
73
77
  }
74
78
 
79
+ /** The Edit with every file it names copied into the Take's styles/ folder, so the Take stands alone (ADR 0002). */
80
+ const intoTake = (edit, dir) => bundle(edit, dir, join(dir, 'styles'), 'styles/');
81
+
75
82
  /** Reads a Take's project.json, Timeline and Edit, refusing Takes from an older schema. */
76
83
  async function loadTake(dir) {
77
84
  const project = await readJson(join(dir, 'project.json'));
78
85
  if (project.schemaVersion !== SCHEMA_VERSION) throw new Error(`${dir} was recorded by an older CueTake (schema ${project.schemaVersion ?? 1}); record it again`);
79
- return { project, config: scenarioSchema.parse(project.config), timeline: await readJson(join(dir, 'timeline.json')), edit: editSchema.parse(await readJson(join(dir, 'edit.json'))) };
86
+ return { project, config: scenarioSchema.parse(project.config), timeline: await readJson(join(dir, 'timeline.json')), edit: withDefaults(await readJson(join(dir, 'edit.json'))) };
87
+ }
88
+
89
+ /**
90
+ * Writes preview.png: the Take's current Edit beside each Look (names or JSON files), composed with a
91
+ * 1080-pixel short side in each output's own proportions. Without `at` it shows the last moment with the camera wide.
92
+ */
93
+ export async function previewTake(directory, refs = [], { at } = {}) {
94
+ const dir = resolve(directory);
95
+ const { config, timeline, edit } = await loadTake(dir);
96
+ if (at !== undefined && !(at >= 0 && at <= timeline.duration)) throw new Error(`--at must be between 0 and ${timeline.duration} seconds`);
97
+ const host = new URL(config.url).host;
98
+ const looks = await Promise.all(refs.map(ref => loadLook(ref)));
99
+ const tiles = [{ name: 'current', edit }, ...looks.map(look => ({ name: look.name, edit: applyLook(edit, resolvedLook(look), host) }))];
100
+ const files = {}, shown = tiles.map(({ name, edit }) => ({ name, edit: forRender(atShortSide(edit, 1080), dir, files).edit }));
101
+ const png = await composePreview({ sourcePath: join(dir, 'source.webm'), timeline, at, tiles: shown, files });
102
+ const preview = join(dir, 'preview.png');
103
+ await fs.writeFile(preview, png);
104
+ return { preview, at: at ?? 'end, camera wide', tiles: tiles.map(({ name, edit }) => ({ name, summary: summarize(lookFromEdit(edit)) })) };
105
+ }
106
+
107
+ /** Adopts a Look into the Take's edit.json; the Final changes only after the next Render. */
108
+ export async function applyLookToTake(ref, directory) {
109
+ const dir = resolve(directory);
110
+ const { config, edit } = await loadTake(dir);
111
+ const look = await loadLook(ref);
112
+ const next = await intoTake(applyLook(edit, resolvedLook(look), new URL(config.url).host), dir);
113
+ await writeJson(join(dir, 'edit.json'), next);
114
+ return { look: look.name, edit: join(dir, 'edit.json'), summary: summarize(lookFromEdit(next)), next: `cuetake render ${dir}` };
115
+ }
116
+
117
+ /** Saves the Take's styling as a Look, locally unless `global`. */
118
+ export async function saveLookFromTake(name, directory, options) {
119
+ const dir = resolve(directory), { edit } = await loadTake(dir);
120
+ return saveLook(name, lookFromEdit(edit), { ...options, from: dir });
80
121
  }
81
122
 
82
123
  export async function renderTake(directory) {
@@ -85,7 +126,7 @@ export async function renderTake(directory) {
85
126
  // Render to a temporary output; preserve the last complete final if encoding fails.
86
127
  const temporary = join(dir, 'final.pending.mp4');
87
128
  try {
88
- const render = await renderFinal({ sourcePath: join(dir, 'source.webm'), finalPath: temporary, timeline, edit });
129
+ const render = await renderFinal({ sourcePath: join(dir, 'source.webm'), finalPath: temporary, timeline, ...forRender(edit, dir) });
89
130
  await fs.rename(temporary, join(dir, 'final.mp4'));
90
131
  await writeJson(join(dir, 'render.json'), render);
91
132
  await fs.rm(join(dir, 'verification.json'), { force: true });
@@ -106,7 +147,7 @@ export async function verifyTake(directory) {
106
147
  const { project, config, timeline, edit } = await loadTake(dir);
107
148
  const media = await inspectFinal(join(dir, 'final.mp4'));
108
149
  const { fps } = edit.output;
109
- const expected = { ...outputSize(edit, timeline.viewport), fps, frames: Math.round(project.duration * fps) };
150
+ const expected = { ...outputSize(edit), fps, frames: Math.round(project.duration * fps) };
110
151
  const problems = [
111
152
  media.width !== expected.width || media.height !== expected.height ? `size ${media.width}×${media.height}, expected ${expected.width}×${expected.height}` : null,
112
153
  Math.abs(media.fps - expected.fps) > 0.01 ? `${media.fps} fps, expected ${expected.fps}` : null,