@kriya-ai/harness 0.2.2 → 0.2.4

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 (45) hide show
  1. package/contract/SOURCE.md +3 -3
  2. package/contract/contract.json +188 -0
  3. package/package.json +1 -1
  4. package/src/edit/core/ffmpeg.js +5 -1
  5. package/src/edit/core/layout.js +26 -1
  6. package/src/edit/core/ops.js +74 -6
  7. package/src/edit/core/plan.js +2 -1
  8. package/src/edit/core/project.js +6 -1
  9. package/src/edit/core/solver.js +66 -15
  10. package/src/edit/director/ask.js +42 -27
  11. package/src/edit/director/beats.js +335 -0
  12. package/src/edit/director/lookups.js +133 -0
  13. package/src/edit/director/plan.js +365 -0
  14. package/src/edit/director/playbooks.js +131 -0
  15. package/src/edit/director/revise.js +171 -12
  16. package/src/edit/engine/captions.js +32 -0
  17. package/src/edit/engine/found-media.js +64 -0
  18. package/src/edit/engine/motion.js +78 -18
  19. package/src/edit/engine/music-bed.js +110 -0
  20. package/src/edit/engine/reference.js +134 -0
  21. package/src/edit/engine/scenes.js +480 -0
  22. package/src/edit/engine/sfx.js +63 -0
  23. package/src/edit/gates/copy.js +25 -5
  24. package/src/edit/gates/index.js +12 -4
  25. package/src/edit/gates/picture.js +5 -0
  26. package/src/edit/gates/text.js +20 -4
  27. package/src/edit/graph/scheduler.js +1 -1
  28. package/src/edit/host/client.js +28 -4
  29. package/src/edit/host/deliver.js +8 -1
  30. package/src/edit/host/jobs.js +43 -0
  31. package/src/edit/host/main.js +4 -2
  32. package/src/edit/host/paths.js +25 -0
  33. package/src/edit/host/projects.js +328 -38
  34. package/src/edit/host/server.js +106 -8
  35. package/src/edit/index/db.js +5 -0
  36. package/src/edit/index/layers/retakes.js +7 -1
  37. package/src/edit/index/views.js +9 -0
  38. package/src/edit/loop/make.js +9 -6
  39. package/src/edit/recipes/montage.js +74 -0
  40. package/src/edit/recipes/programme.js +24 -0
  41. package/src/edit/recipes/reel.js +149 -20
  42. package/src/edit/recipes/scene-clips.js +127 -0
  43. package/src/edit/runtime/fetch.js +32 -0
  44. package/studio/dist/studio.css +62 -4
  45. package/studio/dist/studio.js +4 -2
@@ -4,16 +4,19 @@
4
4
 
5
5
  import { createHash, createHmac, randomBytes } from "node:crypto"
6
6
  import { createReadStream, createWriteStream, existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs"
7
- import { basename, extname, isAbsolute, join } from "node:path"
7
+ import { basename, dirname, extname, isAbsolute, join } from "node:path"
8
8
  import { pipeline } from "node:stream/promises"
9
9
 
10
10
  import { compile } from "../core/plan.js"
11
11
  import { solve } from "../core/solver.js"
12
12
  import { LOOKS } from "../engine/captions.js"
13
13
  import { ENGINE_VERSION, guardPath } from "../engine/index.js"
14
+ import { cleanRefs } from "../engine/reference.js"
15
+ import { cleanScene } from "../engine/scenes.js"
14
16
  import { EngineFailure } from "../engine/tool.js"
15
17
  import { activeRuntime } from "../runtime/setup.js"
16
18
  import { recogniser } from "../index/layers/words.js"
19
+ import { FORMATS, GRADES } from "../recipes/reel.js"
17
20
 
18
21
  const HEADERS = {
19
22
  "cross-origin-opener-policy": "same-origin",
@@ -91,9 +94,11 @@ async function readJson(req) {
91
94
  }
92
95
  }
93
96
 
94
- function sendFile(req, res, file) {
97
+ function sendFile(req, res, file, { download = false } = {}) {
95
98
  const { size } = statSync(file)
96
99
  const type = TYPES[extname(file).toLowerCase()] ?? "application/octet-stream"
100
+ // A download keeps the export's own name (made by the Engine: letters, digits, dashes)
101
+ if (download) res.setHeader("content-disposition", `attachment; filename="${basename(file).replace(/[^\w.-]/g, "_")}"`)
97
102
  const range = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range ?? "")
98
103
  if (req.headers.range && !range) return refuse(res, 416, "Bad range.")
99
104
  if (!range) {
@@ -110,14 +115,14 @@ function sendFile(req, res, file) {
110
115
  createReadStream(file, { start, end }).pipe(res)
111
116
  }
112
117
 
113
- const statusOf = (error) => ({ outside_project: 403, missing_file: 404, exists: 409, too_large: 413, empty: 409 })[error.reason] ?? 400
118
+ const statusOf = (error) => ({ outside_project: 403, missing_file: 404, exists: 409, too_large: 413, empty: 409, busy: 409, no_project: 404 })[error.reason] ?? 400
114
119
 
115
120
  /**
116
121
  * @param {{ home: string, roots: string[], projects: object, jobs: object, tools: () => Promise<object>, tokenTtlMs: number, port: () => number, onActivity: (inFlight?: number) => void, onStop: () => void, sse: Set<object>, log: (line: string) => void, pid: number }} options
117
122
  */
118
123
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
119
124
 
120
- export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenTtlMs, port, onActivity, onStop, onLive = () => {}, sse, log, pid }) {
125
+ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenTtlMs, port, onActivity, onStop, onLive = () => {}, sse, log, pid, stamp = null, busy = () => 0 }) {
121
126
  const tokens = new Map() // sha256 of a launch token → { expires, back }
122
127
  const sessions = new Set()
123
128
  const mediaSecret = randomBytes(32)
@@ -250,7 +255,25 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
250
255
  const entries = readdirSync(root, { withFileTypes: true })
251
256
  .filter((item) => !item.name.startsWith("."))
252
257
  .map((item) => ({ name: item.name, kind: item.isDirectory() ? "folder" : item.isFile() ? "file" : "other" }))
253
- return say(200, { root, entries })
258
+ .sort((a, b) => (a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === "folder" ? -1 : 1))
259
+ // The Studio's folder picker: up, while still inside the allowed folders
260
+ let parent = null
261
+ try {
262
+ if (dirname(root) !== root) parent = guardPath(dirname(root), roots)
263
+ } catch {
264
+ // Above the allowed folders: no way up
265
+ }
266
+ return say(200, { root, parent, roots, entries })
267
+ }
268
+ // A new folder for a project, inside the allowed folders only
269
+ if (method === "POST" && pathname === "/browse/folder") {
270
+ const { parent, name } = await readJson(req)
271
+ const clean = typeof name === "string" ? name.trim().replace(/[^\p{L}\p{N} _.-]+/gu, "-").replace(/^\.+/, "") : ""
272
+ if (!clean || clean.length > 80 || typeof parent !== "string") return refuse(res, 400, "Give the new folder a name.")
273
+ const at = join(guardPath(parent, roots), clean)
274
+ if (existsSync(at)) return refuse(res, 409, "A folder with that name is already there.")
275
+ mkdirSync(at)
276
+ return say(200, { folder: guardPath(at, roots) })
254
277
  }
255
278
 
256
279
  // The person's own screen. Never on the socket, so nothing but a Studio session can
@@ -287,6 +310,7 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
287
310
  const state = await needProject(res, parts[1])
288
311
  if (!state) return
289
312
  if (parts.length === 2 && method === "GET") return say(200, projectView(state))
313
+ if (parts.length === 2 && method === "DELETE") return say(200, projects.remove(state.id, { running: (id) => jobs.runningIn(id) }))
290
314
  if (parts.length === 2 && method === "PATCH") {
291
315
  const { ops, undo } = await readJson(req)
292
316
  if (undo === true) {
@@ -302,6 +326,13 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
302
326
  return say(200, withMedia(state, await projects.addAsset(state, path)))
303
327
  }
304
328
  if (parts[2] === "upload" && method === "POST") return upload(req, res, state, url)
329
+ // The finished films, to watch in Finish before downloading: listed, then streamed by job number
330
+ if (parts[2] === "renders" && parts.length === 3 && method === "GET") return say(200, { renders: jobs.renders(state) })
331
+ if (parts[2] === "renders" && parts.length === 4 && method === "GET") {
332
+ const file = /^\d{1,9}$/.test(parts[3]) ? jobs.renderFile(state, Number(parts[3])) : null
333
+ if (!file) return refuse(res, 404, "That film isn't there any more.")
334
+ return sendFile(req, res, file, { download: url.searchParams.get("download") === "1" })
335
+ }
305
336
  if (parts[2] === "plan" && method === "GET") {
306
337
  const { version } = await tools()
307
338
  // The solver's timeline too: the Studio's monitor and timeline place clips from it
@@ -309,9 +340,11 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
309
340
  return say(200, { ...compile(state.log.current, state.index, { engineVersion: ENGINE_VERSION, runtimeVersion: version }), timeline: { picture, audio, overlays, captions, duration } })
310
341
  }
311
342
  if (parts[2] === "ask" && parts.length === 3 && method === "POST") {
312
- const { text, selection } = await readJson(req)
343
+ const { text, selection, history } = await readJson(req)
313
344
  if (typeof text !== "string" || !text.trim() || text.length > 2000) return refuse(res, 400, "Say what you want changed, in up to 2,000 characters.")
314
- return say(200, await projects.ask(state, { text, selection }))
345
+ // The chat's last turns, short and text only: nothing else of the browser's reaches the model
346
+ const turns = Array.isArray(history) ? history.filter((h) => h && (h.who === "you" || h.who === "kriya") && typeof h.text === "string").slice(-6).map((h) => ({ who: h.who, text: h.text.slice(0, 400) })) : []
347
+ return say(200, await projects.ask(state, { text, selection, history: turns }))
315
348
  }
316
349
  if (parts[2] === "proposals" && parts.length === 4 && method === "POST") {
317
350
  const { accept, only } = await readJson(req)
@@ -329,6 +362,42 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
329
362
  if (typeof brief.captions === "string" && Object.hasOwn(LOOKS, brief.captions)) clean.captions = brief.captions
330
363
  if (typeof brief.music === "string" && /^[A-Za-z0-9:_-]{1,64}$/.test(brief.music)) clean.music = brief.music
331
364
  if (typeof brief.reference === "string" && /^[A-Za-z0-9:_-]{1,64}$/.test(brief.reference)) clean.reference = brief.reference
365
+ if (Object.hasOwn(FORMATS, brief.format)) clean.format = brief.format
366
+ if (Object.hasOwn(GRADES, brief.grade)) clean.grade = brief.grade
367
+ if (brief.cleanVoice === true) clean.cleanVoice = true
368
+ // From the Director's approved plan: checked again in the recipe against the index
369
+ const safeId = (v) => typeof v === "string" && /^[A-Za-z0-9:_-]{1,64}$/.test(v)
370
+ // Each as an id (everything it shows) or { id, aspect }: editing, sound, colour or graphics only
371
+ if (Array.isArray(brief.references)) clean.references = cleanRefs(brief.references)
372
+ if (safeId(brief.hook)) clean.hook = brief.hook
373
+ if (brief.coldOpen && safeId(brief.coldOpen.from) && safeId(brief.coldOpen.to)) clean.coldOpen = { from: brief.coldOpen.from, to: brief.coldOpen.to, mono: brief.coldOpen.mono !== false }
374
+ if (["whoosh", "pop"].includes(brief.cutSound)) clean.cutSound = brief.cutSound
375
+ if (["riser", "hit"].includes(brief.introSound)) clean.introSound = brief.introSound
376
+ if (Number.isInteger(brief.punches) && brief.punches >= 0 && brief.punches <= 8) clean.punches = brief.punches
377
+ for (const flag of ["angles", "titles", "ramps"]) if (brief[flag] === true) clean[flag] = true
378
+ if (brief.broll === "own") clean.broll = "own"
379
+ // The person's trims from an approved plan, in seconds of the take: up to eight, in order, checked
380
+ if (Array.isArray(brief.cuts)) clean.cuts = brief.cuts.filter((c) => c && Number.isFinite(c.from) && Number.isFinite(c.to) && c.from >= 0 && c.to > c.from && c.to <= 86_400).slice(0, 8).map((c) => ({ from: Math.round(c.from * 705_600_000), to: Math.round(c.to * 705_600_000) }))
381
+ const allowed = await projects.features()
382
+ if (Number.isInteger(brief.soundEvery) && brief.soundEvery >= 2 && brief.soundEvery <= 8 && allowed.playbooks) clean.soundEvery = brief.soundEvery
383
+ if (allowed.playbooks) {
384
+ clean.holdCaptions = true
385
+ if (brief.montage === true) clean.montage = true
386
+ if (brief.multicam && safeId(brief.multicam.master) && Array.isArray(brief.multicam.angles) && brief.multicam.angles.length >= 2 && brief.multicam.angles.length <= 6 && brief.multicam.angles.every((a, i) => safeId(a?.asset) && a.speaker === i)) clean.multicam = { master: brief.multicam.master, angles: brief.multicam.angles.map((a) => ({ asset: a.asset, speaker: a.speaker })) }
387
+ const style = brief.captionStyle
388
+ if (style && typeof style === "object" && /^#[0-9a-f]{6}$/i.test(style.accent ?? "")) clean.captionStyle = { accent: style.accent }
389
+ }
390
+ // Only ids this project's plan found: the Host holds their URLs and licences, so a browser can't supply one
391
+ if (allowed.mediaSearch) {
392
+ const foundId = (id) => typeof id === "string" && /^[A-Za-z0-9:_. -]{3,160}$/.test(id)
393
+ if (Array.isArray(brief.pictures)) clean.pictures = brief.pictures.filter((p) => p && foundId(p.id) && safeId(p.from) && safeId(p.to)).slice(0, 8).map(({ id, from, to }) => ({ id, from, to }))
394
+ if (Array.isArray(brief.terms)) clean.terms = brief.terms.filter((t) => t && foundId(t.id) && safeId(t.at)).slice(0, 4).map(({ id, at }) => ({ id, at }))
395
+ }
396
+ // Animated scenes from an approved plan, only while the server's switch is on; the recipe checks each again against the speech
397
+ if (Array.isArray(brief.scenes) && brief.scenes.length && (await projects.features()).visuals) {
398
+ clean.scenes = brief.scenes.slice(0, 12).map(cleanScene).filter(Boolean)
399
+ clean.sceneSound = brief.sceneSound !== false
400
+ }
332
401
  }
333
402
  if (asset !== undefined && typeof asset !== "string") return refuse(res, 400, "Name the take.")
334
403
  return say(200, jobs.start(state, { kind: "make", ...(asset ? { asset } : {}), brief: clean }))
@@ -339,6 +408,35 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
339
408
  if (typeof text !== "string" || text.length > 60 || /[\n\r<>]/.test(text)) return refuse(res, 400, "Give the word as it should read, in up to 60 characters.")
340
409
  return say(200, { word: projects.correctWord(state, decodeURIComponent(parts[3]), text) })
341
410
  }
411
+ // A found picture's small version for the Plan Card
412
+ if (parts[2] === "found-thumb" && parts.length === 3 && method === "GET") {
413
+ const { file, type } = await projects.foundThumb(state, url.searchParams.get("id") ?? "")
414
+ res.writeHead(200, { ...HEADERS, "content-type": type, "cross-origin-resource-policy": "same-origin" })
415
+ return createReadStream(file).pipe(res)
416
+ }
417
+ // One scene on the Plan Card, as the render will draw it. A document of its own, sandboxed, with no network
418
+ if (parts[2] === "scene-preview" && parts.length === 3 && method === "GET") {
419
+ if (!(await projects.features()).visuals) return refuse(res, 404, "Animated scenes aren't on.")
420
+ let scene = null
421
+ try {
422
+ scene = JSON.parse(url.searchParams.get("scene") ?? "null")
423
+ } catch {
424
+ return refuse(res, 400, "That isn't a scene.")
425
+ }
426
+ const html = projects.scenePreview(state, scene, url.searchParams.get("format"))
427
+ res.writeHead(200, { ...HEADERS, "content-type": "text/html; charset=utf-8", "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; frame-ancestors 'self'; sandbox allow-scripts" })
428
+ return res.end(html)
429
+ }
430
+ // The Director's plan: proposed in words with its settings; nothing is made here
431
+ if (parts[2] === "plan" && parts.length === 3 && method === "POST") {
432
+ const { text, history, previous, choices } = await readJson(req)
433
+ if (typeof text !== "string" || !text.trim() || text.length > 2000) return refuse(res, 400, "Say what you want, in up to 2,000 characters.")
434
+ const turns = Array.isArray(history) ? history.filter((h) => h && (h.who === "you" || h.who === "kriya") && typeof h.text === "string").slice(-6).map((h) => ({ who: h.who, text: h.text.slice(0, 400) })) : []
435
+ const prior = previous && typeof previous === "object" ? { say: String(previous.say ?? "").slice(0, 900), steps: Array.isArray(previous.steps) ? previous.steps.slice(0, 10).map((s) => String(s).slice(0, 240)) : [], settings: previous.settings && typeof previous.settings === "object" ? previous.settings : {} } : null
436
+ return say(200, await projects.plan(state, { text, history: turns, previous: prior, choices: choices && typeof choices === "object" ? choices : {} }))
437
+ }
438
+ // A reference's classified analysis, measured once and kept
439
+ if (parts[2] === "references" && parts.length === 4 && method === "GET") return say(200, await projects.referenceAnalysis(state, decodeURIComponent(parts[3])))
342
440
  if (parts[2] === "export" && parts[3] === "handoff" && parts.length === 4 && method === "POST") return say(200, projects.handoff(state))
343
441
  if (parts[2] === "index" && parts.length === 3 && method === "GET") {
344
442
  const { words, sentences, takes, shots } = state.index
@@ -385,7 +483,7 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
385
483
  const url = new URL(req.url, "http://host")
386
484
  try {
387
485
  if (overSocket) {
388
- if (url.pathname === "/internal/info") return json(res, 200, { pid, port: port() })
486
+ if (url.pathname === "/internal/info") return json(res, 200, { pid, port: port(), stamp, busy: busy() })
389
487
  if (url.pathname === "/internal/launch" && req.method === "POST") {
390
488
  const token = mintToken((await readJson(req)).back)
391
489
  return json(res, 200, { token, url: `http://127.0.0.1:${port()}/launch#${token}` })
@@ -5,6 +5,8 @@
5
5
 
6
6
  import { DatabaseSync } from "node:sqlite"
7
7
 
8
+ import { decimalSplit } from "./layers/retakes.js"
9
+
8
10
  const SCHEMA = `
9
11
  create table if not exists assets (asset text primary key, media text not null, kind text not null);
10
12
  create table if not exists layers (media text not null, layer text not null, model_version text not null, status text not null, notice text, data text, updated_at text not null, primary key (media, layer));
@@ -100,6 +102,9 @@ export function openIndexDb(file) {
100
102
  const fixed = fix && fix.was === w.text
101
103
  raw.words.push({ id, asset, start: w.start, end: w.end, text: fixed ? fix.text : w.text, conf: fixed ? 1 : w.conf, flags: flagList(w.flags).filter((f) => !fixed || f !== "low_confidence"), ...(fixed ? { heard: w.text } : {}) })
102
104
  }
105
+ // An index made before decimalSplit flagged "5" in "5 .5" as a stutter: unflagged on read, so it isn't cut
106
+ const spoken = raw.words.filter((w) => w.asset === asset)
107
+ spoken.forEach((w, i) => w.flags.includes("stutter") && decimalSplit(w, spoken[i + 1]) && (w.flags = w.flags.filter((f) => f !== "stutter")))
103
108
  for (const s of db.prepare('select * from sentences where media = ? order by n').all(media)) {
104
109
  raw.sentences.push({ id: `${asset}:s${s.n}`, asset, start: s.start, end: s.end, firstWord: `${asset}:w${s.first_word}`, lastWord: `${asset}:w${s.last_word}`, takeGroup: s.take_group === null ? null : `${asset}:g${s.take_group}`, score: s.score })
105
110
  }
@@ -37,6 +37,12 @@ function prefixOf(short, long) {
37
37
  return a.length >= 3 && a.length < b.length && a.every((token, i) => token === b[i])
38
38
  }
39
39
 
40
+ /**
41
+ * "4.5" heard as "5" then ".5" (found in use: "Opus 4.5"): the same digits after punctuation are
42
+ * one number split in two, not a stutter, and cutting the first half cuts inside the word (QG-05).
43
+ */
44
+ export const decimalSplit = (word, next) => /^\d+$/.test(bare(word.text)) && /^[.,:]\d/.test(String(next?.text ?? "").trim())
45
+
40
46
  /** Word flags: filler, stutter, low_confidence. Times decide a soft filler, not the word alone. */
41
47
  export function flagWords(words, language = "en") {
42
48
  const soft = new Set(SOFT_FILLERS[language.split("-")[0]] ?? SOFT_FILLERS.en)
@@ -49,7 +55,7 @@ export function flagWords(words, language = "en") {
49
55
  const setApart = (before >= FILLER_PAUSE || ends(words[i - 1]?.text ?? ".") || /,$/.test(words[i - 1]?.text ?? "")) && (after >= FILLER_PAUSE || /[,.!?]$/.test(word.text))
50
56
  if (HESITATIONS.has(token) || (soft.has(token) && setApart)) flags.push("filler")
51
57
  const next = words[i + 1]
52
- if (next && token && (bare(next.text) === token || (word.text.endsWith("-") && bare(next.text).startsWith(token)))) flags.push("stutter")
58
+ if (next && token && !decimalSplit(word, next) && (bare(next.text) === token || (word.text.endsWith("-") && bare(next.text).startsWith(token)))) flags.push("stutter")
53
59
  if (typeof word.conf === "number" && word.conf < LOW_CONFIDENCE) flags.push("low_confidence")
54
60
  return flags
55
61
  })
@@ -59,6 +59,15 @@ export function paperEdit(raw, { assets, budget = BUDGETS.paper } = {}) {
59
59
  return fence("Paper edit: one sentence a line, [sentence id, word ids, seconds, flags] then the words as heard.", lines, budget, (left) => `[${left} more sentences not shown: ask for a slice]`)
60
60
  }
61
61
 
62
+ /**
63
+ * The phrases a scene can start and end on, for the visual beats slot. `[a1:w12-a1:w19 2.4s] "…"`
64
+ * @param {{ from: string, to: string, start: number, end: number, text: string }[]} phrases
65
+ */
66
+ export function phraseView(phrases, budget = BUDGETS.paper) {
67
+ const lines = phrases.map((p) => `[${p.from}-${p.to} ${seconds(p.end - p.start)}s] ${quote(p.text)}`)
68
+ return fence("The speech in phrases: [first word id-last word id, seconds] then the words as heard.", lines, budget, (left) => `[${left} more phrases not shown]`)
69
+ }
70
+
62
71
  /** The shot digest: ids, exact flicks, length, faces, movement and picture flags. */
63
72
  export function shotDigest(raw, { assets, budget = BUDGETS.shots } = {}) {
64
73
  const faces = new Map()
@@ -8,11 +8,12 @@
8
8
  import { apply } from "../core/ops.js"
9
9
  import { compile } from "../core/plan.js"
10
10
  import { runGates } from "../gates/index.js"
11
- import { planReel, REEL_TALKING_HEAD } from "../recipes/reel.js"
11
+ import { planReel, recipeFor } from "../recipes/reel.js"
12
12
  import { search } from "./loop.js"
13
13
  import { repairLadder } from "./repair.js"
14
14
 
15
15
  const FLICKS = 705_600_000
16
+ const TEXT_GATES = new Set(["QG-08", "QG-09", "QG-10", "QG-11"])
16
17
 
17
18
  /** F0: what the plan alone shows. Nothing renders for an attempt that fails here (ET-LOOP-04). */
18
19
  export function planVerdict(project, index, recipe, { engineVersion = "f0", runtimeVersion = "f0" } = {}) {
@@ -38,15 +39,16 @@ export function planVerdict(project, index, recipe, { engineVersion = "f0", runt
38
39
  * gateKit?: { tilePath?: Function, motion?: object, work?: string }, the Engine's tiles and Chrome, for QG-08 and QG-09
39
40
  * }} input
40
41
  */
41
- export async function makeReel({ project, head, index, asset, brief = {}, ask, render, sourcePath, signal, onStage = () => {}, run, gateKit = {} }) {
42
- const recipe = REEL_TALKING_HEAD
42
+ export async function makeReel({ project, head, index, asset, brief = {}, ask, render, sourcePath, signal, onStage = () => {}, run, gateKit = {}, planner = null, plannerRecipe = null }) {
43
+ // planner: a recipe with no variants to try (a programme, a montage), instead of the reel
44
+ const recipe = plannerRecipe ?? recipeFor(brief)
43
45
  let calls = 0
44
46
  const notes = []
45
47
  const slots = {}
46
48
 
47
49
  const variantOf = async (variant) => {
48
50
  onStage("story")
49
- const made = await planReel({ project, index, asset, ask, brief, variant, signal })
51
+ const made = planner ? await planner() : await planReel({ project, index, asset, ask, brief, variant, signal })
50
52
  calls += made.calls
51
53
  Object.assign(slots, made.slots)
52
54
  for (const note of made.notes) if (!notes.includes(note)) notes.push(note)
@@ -73,13 +75,14 @@ export async function makeReel({ project, head, index, asset, brief = {}, ask, r
73
75
  }
74
76
  Object.assign(candidate, { project: attempt.project, ops: attempt.ops, file: attempt.file, plan: attempt.plan, gates: attempt.checked })
75
77
  const checked = attempt.checked
76
- return { level: "F5", blocking: checked.blocking, briefMisses: checked.briefMisses, notes: checked.notes, quality: f0.quality, verdict: checked.verdict }
78
+ return { level: "F5", blocking: checked.blocking, briefMisses: checked.briefMisses, notes: checked.notes, quality: f0.quality, verdict: checked.verdict, failed: checked.gates?.filter((g) => g.status === "failed" && g.severity !== "note").map((g) => g.id) ?? [] }
77
79
  }
78
80
 
79
81
  const outcome = await search({
80
82
  start: { start: true, project },
81
83
  // Round 1: the recipe as planned. Later rounds: a tighter cut, then the original order
82
- propose: async (best, round) => [await variantOf(round === 1 ? {} : round === 2 ? { tighter: 0.85 } : { noHook: true })],
84
+ // Another length or order can't fix what's wrong with how text is drawn: those rounds only cost time
85
+ propose: async (best, round) => (round > 1 && (planner || (best.verdict.briefMisses === 0 && best.verdict.failed?.length && best.verdict.failed.every((id) => TEXT_GATES.has(id)))) ? [] : [await variantOf(round === 1 ? {} : round === 2 ? { tighter: 0.85 } : { noHook: true })]),
83
86
  evaluate,
84
87
  signal,
85
88
  rounds: 3,
@@ -0,0 +1,74 @@
1
+ // A music-led montage (DP5): the person's song leads, and their clips cut on its beats. Each cut lands
2
+ // on a beat of the song's own grid, each clip moves through new parts of its source, and the clips'
3
+ // own sound goes, so what's heard is the song.
4
+
5
+ import { apply } from "../core/ops.js"
6
+ import { solve } from "../core/solver.js"
7
+ import { recipeFor } from "./reel.js"
8
+
9
+ const FLICKS = 705_600_000
10
+ const MIN_SHOT = 0.8 * FLICKS
11
+ const MAX_SHOT = 5 * FLICKS
12
+
13
+ /** Shot lengths from the song's beats: every beat that's at least MIN_SHOT on from the last cut, up to `total`. */
14
+ export function beatCuts(beats, total) {
15
+ const times = [...new Set(beats.map((b) => b.t))].filter((t) => t > 0 && t <= total).sort((a, b) => a - b)
16
+ const cuts = []
17
+ let last = 0
18
+ for (const t of times) {
19
+ if (t - last < MIN_SHOT) continue
20
+ // A long gap in the beat grid still gets a picture change
21
+ while (t - last > MAX_SHOT) {
22
+ last += MAX_SHOT
23
+ cuts.push(last)
24
+ }
25
+ cuts.push(t)
26
+ last = t
27
+ }
28
+ return cuts
29
+ }
30
+
31
+ /** @param {{ project: object, index: object, brief: object }} input brief.music: the song's asset id */
32
+ export function planMontage({ project, index, brief = {} }) {
33
+ const recipe = recipeFor(brief)
34
+ const song = project.assets.find((a) => a.id === brief.music && a.kind === "audio")
35
+ const clips = project.assets.filter((a) => a.kind === "video" && (a.facts.duration ?? 0) >= MIN_SHOT)
36
+ if (!song) throw new Error("A montage needs a song in the project.")
37
+ if (!clips.length) throw new Error("A montage needs at least one video in the project.")
38
+ const footage = clips.reduce((sum, a) => sum + a.facts.duration, 0)
39
+ const total = Math.min(brief.targetDuration ?? song.facts.duration, song.facts.duration, footage)
40
+ const beats = (index.beats ?? []).filter((b) => b.asset === song.id)
41
+ const notes = []
42
+ if (!beats.length) notes.push("This song has no beat grid, so the cuts follow an even rhythm instead of its beats.")
43
+ const cuts = beats.length ? beatCuts(beats, total) : Array.from({ length: Math.floor(total / (2 * FLICKS)) }, (_, i) => (i + 1) * 2 * FLICKS)
44
+ const edges = [0, ...cuts.filter((c) => c < total - MIN_SHOT), total]
45
+ const sequence = project.sequences.find((q) => q.id === project.active)
46
+ const rebuilt = new Set(sequence.tracks.filter((t) => ["base", "caption", "music"].includes(t.role)).map((t) => t.id))
47
+ const ops = [
48
+ ...sequence.clips.filter((c) => rebuilt.has(c.track) || c.effects?.some((e) => e.blockId === "scene")).map((c) => ({ op: "ripple_delete", clip: c.id })),
49
+ { op: "set_brief", format: recipe.id, targetDuration: total, mustKeep: [], mustCut: [], effort: brief.effort ?? "best" },
50
+ { op: "set_format", width: recipe.canvas.width, height: recipe.canvas.height, fps: recipe.deliverable.fps },
51
+ ...(project.deliverables.some((d) => d.preset === recipe.deliverable.preset) ? [] : [{ op: "add_deliverable", ...recipe.deliverable }]),
52
+ ]
53
+ // Round the clips, each from where it last stopped, wrapping when one runs out
54
+ const played = new Map(clips.map((a) => [a.id, 0]))
55
+ for (let i = 0; i + 1 < edges.length; i++) {
56
+ const length = edges[i + 1] - edges[i]
57
+ const clip = clips[i % clips.length]
58
+ let from = played.get(clip.id)
59
+ if (from + length > clip.facts.duration) from = 0
60
+ const to = Math.min(from + length, clip.facts.duration)
61
+ played.set(clip.id, to)
62
+ ops.push({ op: "keep_range", asset: clip.id, from, to, exact: true })
63
+ }
64
+ const cut = apply(project, ops, { index, author: "agent" })
65
+ if (!cut.applied) throw new Error(`The montage was refused: ${cut.diagnostics[0].message}`)
66
+ const after = cut.project.sequences.find((q) => q.id === cut.project.active)
67
+ const base = new Set(after.tracks.filter((t) => t.role === "base").map((t) => t.id))
68
+ const placed = after.clips.filter((c) => base.has(c.track))
69
+ const all = [...ops, ...placed.map((c) => ({ op: "set_level", clip: c.id, db: -60 })), { op: "set_music", asset: song.id }, { op: "music_shape", fit: true, fadeIn: Math.round(FLICKS * 0.1) }]
70
+ const step = apply(project, all, { index, author: "agent" })
71
+ if (!step.applied) throw new Error(`The montage was refused: ${step.diagnostics[0].message}`)
72
+ notes.push(`Cut ${placed.length} shots to the song's beats over ${(solve(step.project, index).duration / FLICKS).toFixed(1)} s.`)
73
+ return { ops: all, project: step.project, notes, calls: 0, slots: {} }
74
+ }
@@ -0,0 +1,24 @@
1
+ // A podcast from a plan (DP2): `planMulticam` makes the switching, this dresses it with what the
2
+ // brief asked for. Captions read the master's words, so they follow the talk through every switch.
3
+
4
+ import { apply } from "../core/ops.js"
5
+ import { LOOKS, pages, readablePages } from "../engine/captions.js"
6
+ import { planMulticam, PODCAST_MULTICAM } from "./multicam.js"
7
+
8
+ export const programmeRecipe = { ...PODCAST_MULTICAM }
9
+
10
+ /** @param {{ project: object, index: object, brief: object, multicam: { master: string, angles: object[], analysis: object } }} input */
11
+ export function planProgramme({ project, index, brief = {}, multicam }) {
12
+ const made = planMulticam({ project, index, ...multicam, brief })
13
+ const words = (index.words ?? []).filter((w) => w.asset === multicam.master && !w.flags?.includes("trimmed"))
14
+ const captions = LOOKS[brief.captions] ? (index.sentences ?? []).filter((s) => s.asset === multicam.master).flatMap((s) => {
15
+ const run = words.filter((w) => w.start >= s.start && w.end <= s.end)
16
+ return readablePages(pages(run), run)
17
+ }).map((ids) => ({ op: "caption_style", look: brief.captions, words: ids })) : []
18
+ const captionLook = { ...(brief.captionStyle ?? {}), ...(brief.holdCaptions ? { hold: true } : {}) }
19
+ const style = Object.keys(captionLook).length ? [{ op: "set_look", caption: captionLook }] : []
20
+ const ops = [...made.ops, ...style, ...captions]
21
+ const step = apply(project, ops, { index, author: "agent" })
22
+ if (!step.applied) throw new Error(`The programme was refused: ${step.diagnostics[0].message}`)
23
+ return { ops, project: step.project, notes: made.notes, calls: 0, slots: {} }
24
+ }