@kriya-ai/harness 0.2.3 → 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.
@@ -7,7 +7,7 @@ import { join } from "node:path"
7
7
 
8
8
  import { outputFaces } from "../core/faces.js"
9
9
  import { segmentArgs } from "../core/ffmpeg.js"
10
- import { safeZoneFor } from "../core/layout.js"
10
+ import { isSceneBlock, safeZoneFor } from "../core/layout.js"
11
11
  import { wholeSegment } from "../core/plan.js"
12
12
  import { captionComposition, READING_LIMITS, scriptOf } from "../engine/captions.js"
13
13
  import { compositionFor, measureText } from "../engine/motion.js"
@@ -15,6 +15,7 @@ import { compositionFor, measureText } from "../engine/motion.js"
15
15
  const FLICKS = 705_600_000
16
16
  const SETTLE_MS = { caption: 350, block: 950 } // the entrances' lengths, so a beat sees text at rest
17
17
 
18
+ const MIN_PAGE_SECONDS = 1.2
18
19
  const overlaps = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
19
20
  const frameMs = (fps) => (1000 * fps.d) / fps.n
20
21
  const rounded = (box) => ({ x: Math.round(box.x), y: Math.round(box.y), w: Math.round(box.w), h: Math.round(box.h) })
@@ -85,7 +86,10 @@ export function judgeLayout({ plan, project, index, measured }) {
85
86
  if (box.clipped) fail("clipped", item)
86
87
  // Behind-the-speaker text may cross the face: the matte draws the speaker over it
87
88
  const behind = item.tile.node.behind === true && !item.tile.front
88
- if (!behind) {
89
+ // A scene covers the frame while it's on: no face is in the picture under its text or its captions
90
+ // Other footage laid over the whole frame hides it the same way
91
+ const covered = plan.tiles.some((tile) => isSceneBlock(tile.node) && tile.at <= item.t && item.t < tile.end) || wholeSegment(plan).node.overlays.some((o) => o.at <= item.t && item.t < o.end)
92
+ if (!behind && !covered) {
89
93
  const face = faces.find((f) => Math.abs(f.t - item.t) <= FLICKS * 0.6 && overlaps(box, f.box))
90
94
  if (face) fail("on_face", item, { face: face.box })
91
95
  }
@@ -142,6 +146,14 @@ export function boxContrast(rgb, width, height, box, { colours, plate }, share =
142
146
  return values.length ? values[Math.floor(values.length * share)] : null
143
147
  }
144
148
 
149
+ /** The contrast of text against its own outline, when the outline is thick enough to read as one; else null. */
150
+ export function strokeContrast({ colours, stroke, strokeWidth, size }) {
151
+ const edge = parseColour(stroke)
152
+ if (!edge || !(strokeWidth >= Math.max(2, (size ?? 0) * 0.05))) return null
153
+ const texts = (colours ?? []).map(parseColour).filter(Boolean).map((c) => luminance(c.rgb))
154
+ return texts.length ? Math.min(...texts.map((t) => contrast(t, luminance(edge.rgb)))) : null
155
+ }
156
+
145
157
  /** Raw RGB frames of the plan, without the tiles `without` names, at frame numbers. */
146
158
  async function stills(plan, frames, { inputPath, tilePath, run, without }) {
147
159
  const { width, height } = plan.output
@@ -176,7 +188,10 @@ export async function judgeLegibility({ plan, measured, inputPath, tilePath, run
176
188
  const pictures = await stills(plan, frames, { inputPath, tilePath, run, without })
177
189
  if (pictures.length !== frames.length) throw new Error("the frames behind the text couldn't be read")
178
190
  for (const item of own) {
179
- const value = boxContrast(pictures[frames.indexOf(frameOf(item.t))], width, height, item.box, item.box)
191
+ const seen = boxContrast(pictures[frames.indexOf(frameOf(item.t))], width, height, item.box, item.box)
192
+ // A real outline separates text from any picture: it counts as what's behind the text (found on real footage)
193
+ const outline = strokeContrast(item.box)
194
+ const value = seen === null ? null : Math.max(seen, outline ?? 0)
180
195
  if (value === null) continue
181
196
  worst = Math.min(worst, value)
182
197
  if (value < thresholds.contrast) fail("low_contrast", item, { contrast: Math.round(value * 100) / 100, needed: thresholds.contrast })
@@ -189,7 +204,8 @@ export async function judgeLegibility({ plan, measured, inputPath, tilePath, run
189
204
  const words = item.tile.node.words.length
190
205
  const script = scriptOf(item.tile.node.text)
191
206
  const rate = words / Math.max(seconds, 1e-3)
192
- if (rate > READING_LIMITS[script]) fail("too_fast", item, { wordsPerSecond: Math.round(rate * 100) / 100, limit: READING_LIMITS[script], script })
207
+ // Captions show what's said, so a fast speaker's page can't be slower than the speech. What a reader can't take is a page that flashes by
208
+ if (rate > READING_LIMITS[script] && seconds < MIN_PAGE_SECONDS) fail("too_fast", item, { wordsPerSecond: Math.round(rate * 100) / 100, limit: READING_LIMITS[script], script })
193
209
  }
194
210
  const numbers = { texts: items.length, worstContrast: worst === Infinity ? null : Math.round(worst * 100) / 100, needed: thresholds.contrast, failures: failures.length }
195
211
  return { status: failures.length ? "failed" : "passed", numbers, failures }
@@ -5,7 +5,7 @@
5
5
 
6
6
  import { availableParallelism } from "node:os"
7
7
 
8
- export const DEFAULT_SLOTS = { cpu: Math.max(2, availableParallelism() - 2), gpu: 1, encoder: 2, chrome: 1, model: 2, disk: 2 }
8
+ export const DEFAULT_SLOTS = { cpu: Math.max(2, availableParallelism() - 2), gpu: 1, encoder: 2, chrome: Math.min(3, Math.max(1, Math.floor(availableParallelism() / 3))), model: 2, disk: 2 }
9
9
 
10
10
  export function createScheduler(slots = DEFAULT_SLOTS) {
11
11
  const held = new Map()
@@ -64,7 +64,14 @@ export async function writeDelivery({ file, title, project, parent, plan, source
64
64
  const rights = project.assets.filter((a) => used.has(a.id)).map((a) => ({ id: a.id, rights: a.rights, role: a.role }))
65
65
  const report = reportPath(file)
66
66
  writeFileSync(report, reportHtml({ receipt, title, before, after, changes, notes, rights, repairs }))
67
- return { receipt: receiptFile, report, verdict: receipt.verdict }
67
+ // What the viewer's description must carry (CC BY asks for it): who made what was borrowed, and what's quoted
68
+ const credits = [...project.assets.filter((a) => used.has(a.id) && a.rights !== "own" && a.rightsNote && a.kind !== "reference").map((a) => a.rightsNote), ...plan.tiles.filter((t) => t.node.blockId === "term").map((t) => `"${t.node.variables.quote}" ${t.node.variables.source}${t.node.variables.page ? `, ${t.node.variables.page}` : ""}`)]
69
+ let creditsFile = null
70
+ if (credits.length) {
71
+ creditsFile = `${file}.credits.txt`
72
+ writeFileSync(creditsFile, `${[...new Set(credits)].join("\n")}\n`)
73
+ }
74
+ return { receipt: receiptFile, report, verdict: receipt.verdict, ...(creditsFile ? { credits: creditsFile } : {}) }
68
75
  }
69
76
 
70
77
  /**
@@ -8,20 +8,30 @@ import { dirname, extname, isAbsolute, join, relative, sep } from "node:path"
8
8
  import { checkout, commit, createLog, parseEntry, undo, versions } from "../core/history.js"
9
9
  import { canonical, newProject, parseProject, serialize, sha256 } from "../core/project.js"
10
10
  import { createEngine, ENGINE_VERSION, guardPath } from "../engine/index.js"
11
- import { motionRuntime } from "../engine/motion.js"
11
+ import { blockComposition, motionRuntime } from "../engine/motion.js"
12
+ import { cleanScene, SCENE_BLOCK, SCENE_KINDS, SCENE_THEMES, SCENE_VERSION, swapsFor } from "../engine/scenes.js"
12
13
  import { parseCube } from "../engine/color.js"
13
14
  import { fingerprint } from "../engine/media.js"
14
15
  import { probe } from "../engine/probe.js"
15
16
  import { EngineFailure, runTool } from "../engine/tool.js"
16
17
  import { openJournal } from "../graph/journal.js"
17
- import { solve } from "../core/solver.js"
18
+ import { DEFAULT_RULES, solve } from "../core/solver.js"
19
+ import { safeZoneFor, sceneFrame } from "../core/layout.js"
20
+ import { revealWords } from "../director/beats.js"
21
+ import { termId } from "../director/lookups.js"
22
+ import { allowedMediaUrl, downloadMedia, MEDIA_TYPES, stillClipArgs } from "../engine/found-media.js"
23
+ import { planMontage } from "../recipes/montage.js"
24
+ import { analyseMulticam, PODCAST_MULTICAM } from "../recipes/multicam.js"
25
+ import { planProgramme, programmeRecipe } from "../recipes/programme.js"
26
+ import { defineTerms, fetchFeatures, searchMedia } from "../runtime/fetch.js"
27
+ import { readDevice } from "../../store.js"
18
28
  import { createAsk } from "../director/ask.js"
19
29
  import { LOOKS } from "../engine/captions.js"
20
30
  import { cleanSelection, cleanWord, describe, noteWord, revise } from "../director/revise.js"
21
31
  import { openIndexDb } from "../index/db.js"
22
32
  import { makeReel, rebase } from "../loop/make.js"
23
33
  import { runGates } from "../gates/index.js"
24
- import { REEL_TALKING_HEAD } from "../recipes/reel.js"
34
+ import { FORMATS, REEL_TALKING_HEAD } from "../recipes/reel.js"
25
35
  import { compareRuns, replayAsk } from "../loop/replay.js"
26
36
  import { verifiedRecogniser, writeDelivery, writeHandoff } from "./deliver.js"
27
37
  import { createIndexer, layersFor } from "../index/index.js"
@@ -77,8 +87,17 @@ const FLICKS = 705_600_000
77
87
  // Director model calls a job may make (DIRECTOR_AND_AGENT §13, short form)
78
88
  const JOB_CALLS = 40
79
89
 
80
- export function createProjects({ home, roots, scheduler, tools, governor = null }) {
90
+ // What the server has switched on, asked for at most once a minute, so turning a switch off takes effect soon
91
+ const FEATURES_MS = 60_000
92
+ const askServer = async () => {
93
+ const device = readDevice()
94
+ return device ? fetchFeatures(device) : { visuals: false, playbooks: false, mediaSearch: false }
95
+ }
96
+ const NOTHING_FOUND = { items: {}, definitions: {} }
97
+
98
+ export function createProjects({ home, roots, scheduler, tools, governor = null, features = askServer }) {
81
99
  const base = editHome(home)
100
+ let known = null
82
101
  const taste = createTaste({ home })
83
102
  const registry = join(base, "projects.json")
84
103
  const open = new Map()
@@ -300,6 +319,104 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
300
319
  return { applied: ops.length + fixes.length, dropped: dropped.map((d) => ({ change: describe(d.op, state.index), reason: d.reason })) }
301
320
  },
302
321
 
322
+ /** What this Kriya allows now. A failed question means off. */
323
+ async features() {
324
+ if (!known || Date.now() - known.at > FEATURES_MS) known = { at: Date.now(), value: await features().catch(() => ({ visuals: false, playbooks: false, mediaSearch: false })) }
325
+ return known.value
326
+ },
327
+
328
+ /**
329
+ * One scene as the render will draw it, for the Plan Card: the words fall where they will,
330
+ * so the person sees the real thing before anything is rendered.
331
+ * @returns {string} a complete document
332
+ */
333
+ scenePreview(state, raw, format) {
334
+ const scene = cleanScene(raw)
335
+ const words = new Map(state.index.words.map((w) => [w.id, w]))
336
+ const from = words.get(scene?.from)
337
+ const to = words.get(scene?.to)
338
+ if (!from || !to || to.end <= from.start) throw new EngineFailure("input", "bad_scene", "That isn't a scene from this project's plan.")
339
+ const shape = FORMATS[format] ?? FORMATS["9:16"]
340
+ const canvas = { width: shape.width, height: shape.height }
341
+ const safe = safeZoneFor({ canvas, deliverables: [{ preset: shape.preset, size: canvas }] })
342
+ const { content } = sceneFrame(canvas, safe, { w: Math.floor((canvas.width * DEFAULT_RULES.boxWidth) / 100), h: Math.floor((canvas.height * DEFAULT_RULES.boxHeight) / 100) })
343
+ const duration = to.end - from.start
344
+ const landing = revealWords(scene, state.index.words.filter((w) => w.asset === from.asset && w.start >= from.start && w.end <= to.end))
345
+ const items = scene.items.map((item, i) => ({ ...item, ...(landing[i] ? { reveal: Math.round(((landing[i].start - from.start) / FLICKS) * 1000) } : {}) }))
346
+ return blockComposition({ blockId: SCENE_BLOCK, version: SCENE_VERSION, variables: { ...scene, items }, placement: content, duration }, { output: canvas, canvas })
347
+ },
348
+
349
+ foundOf(state) {
350
+ const file = join(dirOf(state.id), "cache", "found.json")
351
+ return existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : NOTHING_FOUND
352
+ },
353
+
354
+ keepFound(state, { items = [], definitions = [] }) {
355
+ const dir = join(dirOf(state.id), "cache")
356
+ mkdirSync(dir, { recursive: true })
357
+ const known = this.foundOf(state)
358
+ const next = { items: { ...known.items, ...Object.fromEntries(items.map((item) => [item.id, item])) }, definitions: { ...known.definitions, ...Object.fromEntries(definitions.map((d) => [termId(d.term), d])) } }
359
+ atomicWrite(join(dir, "found.json"), JSON.stringify(next))
360
+ },
361
+
362
+ /** A found picture's small version for the Plan Card, fetched once. Only ids this project's plan found. */
363
+ async foundThumb(state, id, { signal } = {}) {
364
+ const item = this.foundOf(state).items[id]
365
+ if (!item || !allowedMediaUrl(item.thumb)) throw new EngineFailure("input", "unknown_media", "That picture isn't from this project's plan.")
366
+ const dir = join(dirOf(state.id), "cache", "found-thumbs")
367
+ mkdirSync(dir, { recursive: true })
368
+ const base = join(dir, sha256(id).slice(0, 24))
369
+ for (const [type, extension] of Object.entries(MEDIA_TYPES)) if (existsSync(`${base}${extension}`)) return { file: `${base}${extension}`, type }
370
+ return downloadMedia(item.thumb, base, { signal, maxBytes: 12 * 1024 * 1024 })
371
+ },
372
+
373
+ /**
374
+ * The approved pictures on disk, as assets with their credit, and the approved definitions as
375
+ * kept. A still becomes a clip with a slow move. One that can't be had is left out with a note.
376
+ */
377
+ async resolveFound(state, brief, { signal, say }) {
378
+ const found = this.foundOf(state)
379
+ const words = new Map(state.index.words.map((w) => [w.id, w]))
380
+ const shape = FORMATS[brief.format] ?? FORMATS["9:16"]
381
+ const media = join(state.folder, "media")
382
+ const pictures = []
383
+ for (const { from, to, id } of brief.pictures ?? []) {
384
+ const item = found.items[id]
385
+ const first = words.get(from)
386
+ const last = words.get(to)
387
+ if (!item || !first || !last || !allowedMediaUrl(item.url)) {
388
+ say("Left out a picture that isn't from this project's plan.")
389
+ continue
390
+ }
391
+ try {
392
+ mkdirSync(media, { recursive: true })
393
+ const tag = `found-${sha256(id).slice(0, 16)}`
394
+ const seconds = Math.min(16, Math.ceil((last.end - first.start) / FLICKS) + 2)
395
+ const clipName = `${tag}-${shape.width}x${shape.height}-${seconds}s.mp4`
396
+ const note = `${item.title} by ${item.creator}, ${item.licence}, ${item.page}`
397
+ let known = state.log.current.assets.find((a) => a.path.endsWith(item.kind === "video" ? tag : clipName) || a.path.includes(`${tag}.`))
398
+ if (!known) {
399
+ const { file } = await downloadMedia(item.url, join(media, tag), { signal })
400
+ let path = file
401
+ if (item.kind === "image") {
402
+ path = join(media, clipName)
403
+ await runTool("ffmpeg", stillClipArgs({ image: file, output: path, width: shape.width, height: shape.height, seconds, inward: pictures.length % 2 === 0 }), { signal, timeoutMs: 180_000 })
404
+ }
405
+ known = await this.addAsset(state, path, { rights: item.rights, rightsNote: note })
406
+ }
407
+ pictures.push({ asset: known.id, from, to })
408
+ } catch (error) {
409
+ if (signal?.aborted) throw error
410
+ say(`Left out the picture "${item.title}": ${error.message}`)
411
+ }
412
+ }
413
+ const terms = (brief.terms ?? []).flatMap(({ at, id }) => {
414
+ const d = found.definitions[id]
415
+ return d && words.has(at) ? [{ at, term: d.term, quote: d.quote, source: d.source, page: d.page }] : []
416
+ })
417
+ return { pictures, terms }
418
+ },
419
+
303
420
  /** The Director's plan for the whole cut: proposed, never made until the person approves it. */
304
421
  async plan(state, { text, history = [], previous = null, choices = {}, job = 0, signal } = {}) {
305
422
  // The references in use, each only for what the person took it for; with none named, every reference, whole
@@ -314,9 +431,19 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
314
431
  const name = `${ref.path.split(/[\\/]/).at(-1)}${aspect === "all" ? "" : ` (only for: ${ASPECTS[aspect]})`}`
315
432
  references.push({ name, lines: taken.lines.length ? taken.lines : [`nothing measured for ${ASPECTS[aspect].toLowerCase()}`] })
316
433
  }
317
- const plan = await planCut({ ask: this.askFor(state, job), project: state.log.current, index: state.index, text, history, previous, references, choices, signal })
434
+ const { visuals, playbooks, mediaSearch } = await this.features()
435
+ const device = mediaSearch ? readDevice() : null
436
+ // What was found is kept here, so an approval names an id and never carries a URL or a licence from the browser
437
+ const lookups = device ? { search: (queries) => searchMedia(device, queries), define: (terms) => defineTerms(device, terms), keep: (found) => this.keepFound(state, found) } : null
438
+ const plan = await planCut({ ask: this.askFor(state, job), project: state.log.current, index: state.index, text, history, previous, references, choices, visuals: visuals && !state.engine.motion().missing, playbooks, lookups, signal })
439
+ const scenes = plan.settings.scenes ?? []
318
440
  // The exact brief an approval makes, so the Studio sends back what was shown
319
- return { ...plan, brief: briefOf(plan.settings) }
441
+ return {
442
+ ...plan,
443
+ brief: briefOf(plan.settings),
444
+ // What the card may swap each scene to; code says, so it can't offer what won't draw
445
+ ...(scenes.length ? { sceneChoices: { kinds: Object.fromEntries(Object.entries(SCENE_KINDS).map(([id, kind]) => [id, kind.label])), themes: Object.fromEntries(Object.entries(SCENE_THEMES).map(([id, theme]) => [id, theme.label])), swaps: scenes.map(swapsFor) } } : {}),
446
+ }
320
447
  },
321
448
 
322
449
  /** A reference's classified analysis (reference.js), kept by its fingerprint so it's measured once. */
@@ -421,9 +548,21 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
421
548
  const bed = known ?? (await this.addAsset(state, file, { rights: "own", rightsNote: "Made by Kriya's music generator: no one else's recording." }))
422
549
  request = { ...request, brief: { ...request.brief, music: bed.id } }
423
550
  }
424
- // Sound design Kriya writes itself (sfx.js): a cut sound and an intro sound, each knowing its peak
425
- const wanted = { cut: request.brief?.cutSound, intro: request.brief?.introSound }
426
- if (!replay && (wanted.cut || wanted.intro)) {
551
+ // The pictures the person approved, downloaded now and not before, and their definitions as found
552
+ if (request.brief?.pictures?.length || request.brief?.terms?.length) {
553
+ const resolved = replay ? { pictures: [], terms: [] } : await this.resolveFound(state, request.brief, { signal, say: (line) => styled.push(line) })
554
+ request = { ...request, brief: { ...request.brief, ...resolved } }
555
+ }
556
+ // Scenes are drawn by the motion layer: without it they go, with a note, rather than fail the cut
557
+ if ((request.brief?.scenes?.length || request.brief?.terms?.length) && state.engine.motion().missing) {
558
+ request = { ...request, brief: { ...request.brief, scenes: undefined, terms: undefined } }
559
+ styled.push(`No animated scenes or definitions this time: ${state.engine.motion().missing}`)
560
+ }
561
+ // Sound design Kriya writes itself (sfx.js): a cut sound and an intro sound, each knowing its peak;
562
+ // a whoosh as a scene arrives and a pop as each of its labels lands
563
+ const sceneSound = (request.brief?.scenes?.length || request.brief?.pictures?.length) && request.brief.sceneSound !== false
564
+ const wanted = { cut: request.brief?.cutSound, intro: request.brief?.introSound, scene: sceneSound ? "whoosh" : undefined, reveal: sceneSound ? "pop" : undefined }
565
+ if (!replay && (wanted.cut || wanted.intro || wanted.scene)) {
427
566
  const media = join(state.folder, "media")
428
567
  mkdirSync(media, { recursive: true })
429
568
  const sfx = {}
@@ -461,6 +600,24 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
461
600
  const run = runTool
462
601
  const work = join(dirOf(state.id), "cache", "gates")
463
602
  const sourcePath = sourcesOf(state)
603
+ // A podcast's cameras or a montage's song: their own recipes, with the same render and gates.
604
+ // Cameras that won't sync fall back to the reel, and it says so
605
+ let planner = null
606
+ let plannerRecipe = null
607
+ const direct = { ...extra, ...request.brief }
608
+ if (!replay && direct.multicam) {
609
+ const { master, angles } = direct.multicam
610
+ const facts = (id) => state.log.current.assets.find((a) => a.id === id)?.facts
611
+ if (facts(master)?.duration && angles.every((a) => facts(a.asset))) {
612
+ const analysis = await analyseMulticam({ master: { asset: master, file: sourcePath(master), duration: facts(master).duration }, angles: angles.map((a) => ({ ...a, file: sourcePath(a.asset) })) }, { signal })
613
+ if (angles.every((a) => analysis.sync[a.asset].confidence >= PODCAST_MULTICAM.syncFloor)) {
614
+ planner = () => planProgramme({ project: state.log.current, index: state.index, brief: direct, multicam: { master, angles, analysis } })
615
+ plannerRecipe = programmeRecipe
616
+ } else styled.push("The cameras' sound didn't match well enough to sync them, so this is cut from one camera.")
617
+ }
618
+ } else if (!replay && direct.montage && direct.music) {
619
+ planner = () => planMontage({ project: state.log.current, index: state.index, brief: direct })
620
+ }
464
621
  const runtime = activeRuntime(home)
465
622
  const ask = replay ? replayAsk(replay.answers) : this.askFor(state, job)
466
623
  const parent = state.log.head
@@ -474,6 +631,8 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
474
631
  render: (project, deliverable, abort) => state.engine.render({ quality: "master", deliverable, project, job, signal: abort }),
475
632
  sourcePath,
476
633
  signal,
634
+ planner,
635
+ plannerRecipe,
477
636
  onStage: (stage) => onStep(stages.indexOf(stage) + 1, stages.length + 1),
478
637
  gateKit: {
479
638
  tilePath: state.engine.tilePath,
@@ -504,8 +663,10 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
504
663
  const delivery = result.best.file
505
664
  ? await writeDelivery({ file: result.best.file, title: state.log.current.name, project: result.best.project, parent, plan: result.best.plan, sourcePath, tools: { engine: ENGINE_VERSION, ffmpeg: version, runtime: runtime?.version ?? null }, gates: gates?.gates ?? [], verdict: gates?.verdict ?? "not_checked", calls: state.journal.calls(job), changes, notes, repairs, beforeFrom: sourcePath(asset), run, work })
506
665
  : null
666
+ if (delivery?.credits) changes.push(`Credits for your description are in ${delivery.credits.split(/[\\/]/).at(-1)}`)
507
667
  return {
508
668
  verdict: gates?.verdict ?? "not_checked",
669
+ credits: delivery?.credits ?? null,
509
670
  file: result.best.file ?? null,
510
671
  head: state.log.head, // the version this file shows, so the Studio can say when it's out of date
511
672
  receipt: delivery?.receipt ?? null,
@@ -12,6 +12,7 @@ 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
14
  import { cleanRefs } from "../engine/reference.js"
15
+ import { cleanScene } from "../engine/scenes.js"
15
16
  import { EngineFailure } from "../engine/tool.js"
16
17
  import { activeRuntime } from "../runtime/setup.js"
17
18
  import { recogniser } from "../index/layers/words.js"
@@ -377,6 +378,26 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
377
378
  if (brief.broll === "own") clean.broll = "own"
378
379
  // The person's trims from an approved plan, in seconds of the take: up to eight, in order, checked
379
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
+ }
380
401
  }
381
402
  if (asset !== undefined && typeof asset !== "string") return refuse(res, 400, "Name the take.")
382
403
  return say(200, jobs.start(state, { kind: "make", ...(asset ? { asset } : {}), brief: clean }))
@@ -387,6 +408,25 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
387
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.")
388
409
  return say(200, { word: projects.correctWord(state, decodeURIComponent(parts[3]), text) })
389
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
+ }
390
430
  // The Director's plan: proposed in words with its settings; nothing is made here
391
431
  if (parts[2] === "plan" && parts.length === 3 && method === "POST") {
392
432
  const { text, history, previous, choices } = await readJson(req)
@@ -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()
@@ -13,6 +13,7 @@ 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 = recipeFor(brief)
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
+ }