@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,9 +4,12 @@
4
4
  // −14 LUFS. Code does the editing; the model makes two small choices (the hook and
5
5
  // the lines to drop; the emphasis words), each with a default that needs no model.
6
6
 
7
+ import { isSceneBlock } from "../core/layout.js"
7
8
  import { apply } from "../core/ops.js"
8
- import { LOOKS, pages } from "../engine/captions.js"
9
+ import { solve } from "../core/solver.js"
10
+ import { LOOKS, pages, readablePages } from "../engine/captions.js"
9
11
  import { paperEdit } from "../index/views.js"
12
+ import { sceneOps } from "./scene-clips.js"
10
13
 
11
14
  const FLICKS = 705_600_000
12
15
 
@@ -22,11 +25,50 @@ export const REEL_TALKING_HEAD = {
22
25
  notes: "Recipe: a talking-head reel for phones. The first sentence must work on its own as a hook. Keep the speaker's meaning; drop only lines that repeat or wander.",
23
26
  }
24
27
 
25
- const STRUCK = new Set(["filler", "stutter", "restart"])
28
+ const STRUCK = new Set(["filler", "stutter", "restart", "trimmed"])
29
+
30
+ const clock = (t) => { const s = Math.round(t / (FLICKS / 10)) / 10; return `${Math.floor(s / 60)}:${(s % 60).toFixed(1).padStart(4, "0")}` }
31
+
32
+ /**
33
+ * The person's trims ("remove everything after 0:25"): each word whose middle falls inside a
34
+ * stretch is marked `trimmed`, so the cut lands between words, never inside one (QG-05).
35
+ * @param {{ from: number, to: number }[]} cuts source flicks of `asset`
36
+ */
37
+ export function trimIndex(index, asset, cuts = []) {
38
+ if (!cuts.length) return { index, trimmed: 0 }
39
+ let trimmed = 0
40
+ const inside = (w) => cuts.some((c) => (w.start + w.end) / 2 >= c.from && (w.start + w.end) / 2 < c.to)
41
+ const words = index.words.map((w) => (w.asset === asset && inside(w) ? (trimmed++, { ...w, flags: [...w.flags, "trimmed"] }) : w))
42
+ return { index: { ...index, words }, trimmed }
43
+ }
44
+
45
+ /** Templates' frames: the reel's 9:16 by default; the same cut also makes a landscape, square or 4:5 film. */
46
+ export const FORMATS = {
47
+ "9:16": { width: 1080, height: 1920, preset: "reel-9x16" },
48
+ "16:9": { width: 1920, height: 1080, preset: "landscape-16x9" },
49
+ "1:1": { width: 1080, height: 1080, preset: "square-1x1" },
50
+ "4:5": { width: 1080, height: 1350, preset: "portrait-4x5" },
51
+ }
52
+
53
+ /** Colour looks as FFmpeg renders them: eq, colortemperature, vibrance and vignette. Data, applied by code. */
54
+ export const GRADES = {
55
+ vivid: { saturation: 1.15, gain: 1.06, vibrance: 0.35 },
56
+ cinematic: { saturation: 0.9, gain: 1.12, gamma: 0.95, temperature: 7200, vignette: 0.45 },
57
+ warm: { temperature: 5200, saturation: 1.05, vibrance: 0.2, vignette: 0.2 },
58
+ bright: { lift: 0.04, gamma: 1.1, vibrance: 0.2 },
59
+ mono: { saturation: 0, gain: 1.1, vignette: 0.3 },
60
+ }
61
+
62
+ /** The recipe in the brief's frame: canvas and export follow `brief.format`. */
63
+ export function recipeFor(brief = {}) {
64
+ const format = FORMATS[brief.format] ?? FORMATS["9:16"]
65
+ const base = REEL_TALKING_HEAD
66
+ return { ...base, canvas: { width: format.width, height: format.height }, deliverable: { ...base.deliverable, preset: format.preset, size: { width: format.width, height: format.height } } }
67
+ }
26
68
 
27
69
  /** The recipe's deliverable; with captions asked for, they burn in and the text gates run (ED8). */
28
70
  export function deliverableFor(brief = {}) {
29
- const base = REEL_TALKING_HEAD.deliverable
71
+ const base = recipeFor(brief).deliverable
30
72
  return LOOKS[brief.captions] ? { ...base, burnCaptions: true, gates: [...base.gates, "QG-08", "QG-09", "QG-10"].sort() } : base
31
73
  }
32
74
 
@@ -112,9 +154,12 @@ const EMPHASIS_SCHEMA = { type: "object", properties: { emphasis: { type: "array
112
154
  * @param {{ project: object, index: object, asset: string, ask: Function, brief?: object, variant?: { tighter?: number, noHook?: boolean }, signal?: AbortSignal }} input
113
155
  * @returns {Promise<{ ops: object[], project: object, notes: string[], calls: number, slots: Record<string, string> }>}
114
156
  */
115
- export async function planReel({ project, index, asset, ask, brief = {}, variant = {}, signal }) {
116
- const recipe = REEL_TALKING_HEAD
157
+ export async function planReel({ project, index: fullIndex, asset, ask, brief = {}, variant = {}, signal }) {
158
+ const recipe = recipeFor(brief)
117
159
  const notes = []
160
+ const cuts = (brief.cuts ?? []).filter((c) => Number.isFinite(c.from) && Number.isFinite(c.to) && c.to > c.from)
161
+ const { index, trimmed } = trimIndex(fullIndex, asset, cuts)
162
+ if (cuts.length) notes.push(`Trimmed ${cuts.map((c) => `${clock(c.from)} to ${clock(c.to)}`).join(", ")} of the take, as you asked (${trimmed} word${trimmed === 1 ? "" : "s"}, cut between words).`)
118
163
  const slots = {}
119
164
  let calls = 0
120
165
  const lines = candidateLines(index, asset, brief.picks)
@@ -137,44 +182,77 @@ export async function planReel({ project, index, asset, ask, brief = {}, variant
137
182
  calls += story.calls
138
183
  slots.story = story.source
139
184
  if (story.reason) notes.push(`Story: ${story.reason} Kept every line, in order.`)
140
- const hook = variant.noHook ? null : story.value.hook
141
- let chosen = lines.filter((l) => !story.value.drop.includes(l.id) || mustKeep.includes(l.id))
185
+ // A hook the person approved in the Director's plan wins over the model's pick
186
+ const planned = typeof brief.hook === "string" && lines.some((l) => l.id === brief.hook) ? brief.hook : null
187
+ const hook = variant.noHook ? null : (planned ?? story.value.hook)
188
+ // The lines under an approved scene stay: fitting the length mustn't take a scene the person approved (found on real footage)
189
+ const wordsById = new Map(index.words.map((w) => [w.id, w]))
190
+ const sceneLines = [...(brief.scenes ?? []), ...(brief.pictures ?? [])].flatMap((scene) => {
191
+ const from = wordsById.get(scene.from)
192
+ const to = wordsById.get(scene.to)
193
+ return from && to ? lines.filter((l) => l.start < to.end && from.start < l.end).map((l) => l.id) : []
194
+ })
195
+ let chosen = lines.filter((l) => !story.value.drop.includes(l.id) || mustKeep.includes(l.id) || sceneLines.includes(l.id))
142
196
 
143
197
  // Length: fit under the maximum, the hook and must-keeps always in
144
- const max = Math.round(recipe.target.max * (variant.tighter ?? 1))
145
- const required = new Set([...mustKeep, ...(hook ? [hook] : [])])
198
+ // With scenes, the length the person asked for is the limit, even past the reel's 60 s
199
+ const longest = brief.scenes?.length || brief.pictures?.length ? Math.max(recipe.target.max, brief.targetDuration ?? 0) : recipe.target.max
200
+ const max = Math.round(longest * (variant.tighter ?? 1))
201
+ const required = new Set([...mustKeep, ...sceneLines, ...(hook ? [hook] : [])])
146
202
  if (chosen.reduce((sum, l) => sum + lengthOf(l), 0) > max) chosen = fitLines(chosen, max, required)
147
203
  const total = chosen.reduce((sum, l) => sum + lengthOf(l), 0)
148
- if (total < recipe.target.min) notes.push(`The footage gives ${(total / FLICKS).toFixed(1)} s of usable speech, under the ${recipe.target.min / FLICKS} s the recipe aims for.`)
204
+ // Short footage sets the length: a 29 s take makes a 29 s cut, not a cut that "needs you"
205
+ // for missing a 30 s target nobody can meet (found in use)
206
+ const asked = brief.targetDuration ?? recipe.target.default
207
+ const target = total > 0 && total < asked ? total : asked
208
+ if (target < asked) notes.push(`The footage gives ${(total / FLICKS).toFixed(1)} s of usable speech, so the cut is that long (you asked for about ${Math.round(asked / FLICKS)} s).`)
149
209
  if (hook && chosen.some((l) => l.id === hook)) chosen = [chosen.find((l) => l.id === hook), ...chosen.filter((l) => l.id !== hook)]
150
210
  if (hook && chosen[0]?.id === hook && lines[0]?.id !== hook) notes.push(`Moved "${hook}" to the front as the hook.`)
151
211
 
152
212
  // The cut: replace whatever is there with the kept runs
153
213
  const sequence = project.sequences.find((q) => q.id === project.active)
154
214
  const base = new Set(sequence.tracks.filter((t) => t.role === "base").map((t) => t.id))
215
+ // The last cut's captions and music go with it: they hang on its words, and a second
216
+ // make left them all on screen twice (found in use, 2026-11-09)
217
+ const rebuilt = new Set(sequence.tracks.filter((t) => ["base", "caption", "music"].includes(t.role)).map((t) => t.id))
155
218
  const ops = [
156
- ...sequence.clips.filter((c) => base.has(c.track)).map((c) => ({ op: "ripple_delete", clip: c.id })),
157
- { op: "set_brief", format: recipe.id, targetDuration: brief.targetDuration ?? recipe.target.default, mustKeep: brief.mustKeep ?? [], mustCut: brief.mustCut ?? [], effort: brief.effort ?? "best", ...(brief.language ? { language: brief.language } : {}) },
219
+ // Scenes too: an earlier make's scenes hang on the words of that cut
220
+ ...sequence.clips.filter((c) => rebuilt.has(c.track) || c.effects?.some((e) => isSceneBlock(e))).map((c) => ({ op: "ripple_delete", clip: c.id })),
221
+ { op: "set_brief", format: recipe.id, targetDuration: target, mustKeep: brief.mustKeep ?? [], mustCut: brief.mustCut ?? [], effort: brief.effort ?? "best", ...(brief.language ? { language: brief.language } : {}) },
158
222
  { op: "set_format", width: recipe.canvas.width, height: recipe.canvas.height, fps: recipe.deliverable.fps },
159
223
  ...(project.deliverables.some((d) => d.preset === recipe.deliverable.preset) ? [] : [{ op: "add_deliverable", ...deliverableFor(brief) }]),
160
224
  ]
161
225
  for (const line of chosen) for (const run of runsOf(line)) ops.push({ op: "keep_range", asset, from: { word: run[0].id, edge: "start" }, to: { word: run.at(-1).id, edge: "end" } })
226
+ // A cold open: a later moment first (an echo, so captions stay on the moment), in black and white
227
+ const takeWords = new Set(index.words.filter((w) => w.asset === asset).map((w) => w.id))
228
+ const cutOut = new Set(index.words.filter((w) => w.flags.includes("trimmed")).map((w) => w.id))
229
+ const coldTrimmed = brief.coldOpen && index.words.some((w) => cutOut.has(w.id) && w.asset === asset && w.start >= (index.words.find((x) => x.id === brief.coldOpen.from)?.start ?? Infinity) && w.end <= (index.words.find((x) => x.id === brief.coldOpen.to)?.end ?? -Infinity))
230
+ if (coldTrimmed) notes.push("No cold open: its moment is inside a stretch you asked to trim.")
231
+ const cold = !coldTrimmed && brief.coldOpen && takeWords.has(brief.coldOpen.from) && takeWords.has(brief.coldOpen.to) ? brief.coldOpen : null
232
+ if (cold) {
233
+ ops.push({ op: "cold_open", asset, from: { word: cold.from, edge: "start" }, to: { word: cold.to, edge: "end" }, mono: cold.mono !== false })
234
+ notes.push(`Opened cold on "${index.words.find((w) => w.id === cold.from).text} …"${cold.mono !== false ? " in black and white" : ""}, then the story starts.`)
235
+ }
162
236
  let step = apply(project, ops, { index, author: "agent" })
163
237
  if (!step.applied) throw new Error(`The reel's cut was refused: ${step.diagnostics[0].message}`)
164
238
 
165
239
  // Emphasis: a few words worth a punch-in; a reference's pace can ask for more (EDD-23)
166
240
  const most = Number.isInteger(brief.punches) && brief.punches > 0 ? Math.min(brief.punches, 8) : recipe.punch.max
167
241
  const kept = chosen.flatMap((l) => runsOf(l).flat())
168
- const keptIds = new Set(kept.map((w) => w.id))
242
+ // The approved plan's scenes, on the cut as solved. A zoom or title under one would never be seen
243
+ const scenes = brief.scenes?.length || brief.pictures?.length || brief.terms?.length ? sceneOps({ scenes: brief.scenes ?? [], pictures: brief.pictures ?? [], terms: brief.terms ?? [], project: step.project, index, asset, kept, captions: !!LOOKS[brief.captions], sound: { scene: brief.sfx?.scene, reveal: brief.sfx?.reveal } }) : { ops: [], covered: new Set(), notes: [] }
244
+ notes.push(...scenes.notes)
245
+ const visible = kept.filter((w) => !scenes.covered.has(w.id))
246
+ const keptIds = new Set(visible.map((w) => w.id))
169
247
  const emphasis = await ask({
170
248
  task: "emphasis",
171
249
  schema: EMPHASIS_SCHEMA,
172
250
  recipe: recipe.notes,
173
- view: paperEdit({ ...scoped, sentences: chosen }, { assets: [asset] }),
251
+ view: paperEdit({ ...scoped, sentences: chosen.filter((l) => l.words.some((w) => keptIds.has(w.id))) }, { assets: [asset] }),
174
252
  request: `Pick up to ${most} single words to emphasise with a quick zoom: numbers, names, the point of a line. Word ids only.`,
175
253
  maxOutput: 200,
176
254
  check: ({ emphasis: picked }) => picked.filter((id) => !keptIds.has(id)).map((id) => `"${id}" isn't a kept word`),
177
- fallback: () => ({ emphasis: kept.filter((w) => /\d/.test(w.text)).slice(0, most).map((w) => w.id) }),
255
+ fallback: () => ({ emphasis: visible.filter((w) => /\d/.test(w.text)).slice(0, most).map((w) => w.id) }),
178
256
  signal,
179
257
  })
180
258
  calls += emphasis.calls
@@ -182,21 +260,72 @@ export async function planReel({ project, index, asset, ask, brief = {}, variant
182
260
  if (emphasis.reason) notes.push(`Emphasis: ${emphasis.reason}`)
183
261
  const punches = [...new Set(emphasis.value.emphasis)].slice(0, most).map((id) => ({ op: "punch_in", at: { word: id, edge: "start" }, until: { word: id, edge: "end" }, scale: brief.zoom ?? recipe.punch.scale }))
184
262
 
185
- // Reframe to 9:16: follow the speaker where the index has one, else hold the centre
263
+ // Reframe to the template's frame: follow the speaker where the index has one, else hold
264
+ // the centre. A frame as wide as the take or wider keeps the whole picture
186
265
  const facts = project.assets.find((a) => a.id === asset).facts
187
266
  const cropWidth = Math.round((facts.height * recipe.canvas.width) / recipe.canvas.height)
267
+ const crops = cropWidth < facts.width
188
268
  const subject = (index.subjects?.[asset]?.length ?? 0) > 0
189
- if (!subject) notes.push("No face track for this take, so the frame holds the centre.")
269
+ if (crops && !subject) notes.push("No face track for this take, so the frame holds the centre.")
190
270
  const clips = step.project.sequences.find((q) => q.id === step.project.active).clips.filter((c) => base.has(c.track))
191
- const framing = clips.map((c) => (subject ? { op: "reframe", clip: c.id, mode: "subject" } : { op: "reframe", clip: c.id, mode: "fixed", x: Math.max(0, Math.round((facts.width - cropWidth) / 2)) }))
271
+ const framing = crops ? clips.map((c) => (subject ? { op: "reframe", clip: c.id, mode: "subject" } : { op: "reframe", clip: c.id, mode: "fixed", x: Math.max(0, Math.round((facts.width - cropWidth) / 2)) })) : []
272
+ // The template's colour look, on every picture clip
273
+ // The look on every story clip; a cold open keeps its own black and white
274
+ const look = GRADES[brief.grade] ?? (brief.customGrade && typeof brief.customGrade === "object" ? brief.customGrade : null)
275
+ const grading = look ? clips.filter((c) => !c.echo).map((c) => ({ op: "grade", clip: c.id, ...look })) : []
276
+ // Sound design: an effect on every cut of the story, a riser into it after a cold open.
277
+ // Each is placed by its peak, so the loudest moment lands on the cut
278
+ const storyClips = clips.filter((c) => !c.echo)
279
+ // A playbook's restraint: a sound on every nth cut, not on all of them
280
+ const every = Number.isInteger(brief.soundEvery) && brief.soundEvery > 1 ? brief.soundEvery : 1
281
+ const cutSounds = brief.sfx?.cut ? storyClips.slice(1).filter((_, i) => i % every === 0).map((c) => ({ op: "add_sfx", asset: brief.sfx.cut, peak_at: { clip: c.id, edge: "start" } })) : []
282
+ const introSound = brief.sfx?.intro && cold && storyClips[0] ? [{ op: "add_sfx", asset: brief.sfx.intro, peak_at: { clip: storyClips[0].id, edge: "start" } }] : []
283
+ const sounds = [...cutSounds, ...introSound]
284
+
285
+ // Angles: one camera cut like two, wide then tight on alternate story clips (a punch the
286
+ // length of the clip). Emphasis punch-ins come after, so they win on their own clips
287
+ const angles = brief.angles ? storyClips.filter((_, i) => i % 2 === 1).map((c) => ({ op: "punch_in", at: { clip: c.id, edge: "start" }, until: { clip: c.id, edge: "end" }, scale: 1.18 })) : []
288
+ // B-roll from the person's own other clips, over every other story clip after the first,
289
+ // 2.5 s or the clip's length, each from a new part of its source
290
+ const brollSources = brief.broll === "own" ? project.assets.filter((a) => a.kind === "video" && a.id !== asset && (a.facts.duration ?? 0) > FLICKS) : []
291
+ const pieces = solve(step.project, index).picture
292
+ const lengthOfClip = (id) => pieces.filter((p) => p.clip === id).reduce((sum, p) => sum + (p.end - p.at), 0)
293
+ const broll = brollSources.length
294
+ ? storyClips
295
+ .slice(1)
296
+ .filter((_, i) => i % 2 === 0)
297
+ .map((c, i) => {
298
+ const source = brollSources[i % brollSources.length]
299
+ const duration = Math.min(Math.round(2.5 * FLICKS), lengthOfClip(c.id))
300
+ const room = Math.max(0, source.facts.duration - duration)
301
+ const from = room ? Math.round((i * 3 * FLICKS) % room) : 0
302
+ return duration > FLICKS / 2 ? { op: "place_broll", asset: source.id, at: { clip: c.id, edge: "start" }, in: from, duration } : null
303
+ })
304
+ .filter(Boolean)
305
+ : []
306
+ if (brief.broll === "own" && !brollSources.length) notes.push("There's no other video in the bin, so the cut has no B-roll. Add clips to the bin and make it again.")
307
+ // Title cards: each emphasis word pops on screen, unless captions already carry the words
308
+ const titleWords = brief.titles && !LOOKS[brief.captions] ? [...new Set(emphasis.value.emphasis)].slice(0, most).map((wid) => index.words.find((w) => w.id === wid)).filter(Boolean) : []
309
+ if (brief.titles && LOOKS[brief.captions]) notes.push("Captions already put the words on screen, so there are no separate title cards.")
310
+ const titles = titleWords.map((w) => ({ op: "add_title", text: w.text.replace(/[^\p{L}\p{N}%$₹' -]/gu, "").toUpperCase().slice(0, 40) || w.text, at: { word: w.id, edge: "start" }, duration: Math.round(1.2 * FLICKS) }))
311
+ // A speed ramp out of the cold open: its last 1.2 s rushes up to 2× into the story
312
+ const coldClip = clips.find((c) => c.echo)
313
+ const coldEnd = cold && index.words.find((w) => w.id === cold.to)?.end
314
+ const coldStart = cold && index.words.find((w) => w.id === cold.from)?.start
315
+ const rampFrom = coldEnd ? Math.max(coldEnd - Math.round(1.2 * FLICKS), coldStart + Math.round((coldEnd - coldStart) / 3)) : 0
316
+ const ramps = brief.ramps && coldClip && coldEnd ? [{ op: "speed_ramp", clip: coldClip.id, from: rampFrom, to: coldEnd, peak: { n: 2, d: 1 } }] : []
317
+ // Background noise out of the voice: FFmpeg's own denoise, EQ, de-ess and compression (clean_voice)
318
+ const cleaning = brief.cleanVoice ? clips.map((c) => ({ op: "clean_voice", clip: c.id, strength: 0.6 })) : []
192
319
 
193
320
  // Captions, when the brief asks for a look: pages of the kept words, timed to the speech
194
- const captions = LOOKS[brief.captions] ? chosen.flatMap((l) => runsOf(l)).flatMap((run) => pages(run)).map((ids) => ({ op: "caption_style", look: brief.captions, words: ids })) : []
321
+ const captions = LOOKS[brief.captions] ? chosen.flatMap((l) => runsOf(l)).flatMap((run) => readablePages(pages(run), run)).map((ids) => ({ op: "caption_style", look: brief.captions, words: ids })) : []
195
322
  // Music, when the brief names a sound in the project: fitted on its downbeats, ducked under the speech (ED9)
196
323
  const song = brief.music ? project.assets.find((a) => a.id === brief.music && a.kind === "audio") : null
197
324
  if (brief.music && !song) notes.push(`There is no sound "${brief.music}" in this project, so the reel has no music.`)
198
325
  const music = song ? [{ op: "set_music", asset: song.id }, { op: "music_shape", fit: true, fadeIn: Math.round(FLICKS * 0.3) }, { op: "duck" }] : []
199
- const all = [...ops, ...punches, ...framing, ...captions, ...music]
326
+ const captionLook = { ...(brief.captionStyle ?? {}), ...(brief.holdCaptions ? { hold: true } : {}) }
327
+ const style = LOOKS[brief.captions] && Object.keys(captionLook).length ? [{ op: "set_look", caption: captionLook }] : []
328
+ const all = [...ops, ...style, ...angles, ...punches, ...framing, ...grading, ...cleaning, ...broll, ...titles, ...scenes.ops, ...captions, ...music, ...sounds, ...ramps]
200
329
  step = apply(project, all, { index, author: "agent" })
201
330
  if (!step.applied) throw new Error(`The reel was refused: ${step.diagnostics[0].message}`)
202
331
  return { ops: all, project: step.project, notes, calls, slots }
@@ -0,0 +1,127 @@
1
+ // Scene clips (VISUAL_SCENES.md §3.2): an approved plan's scenes as operations on the cut as
2
+ // solved. The words anchor them, so a scene moves with its speech; each label is timed to the
3
+ // word it's said on; code checks again what the plan checked, since a re-cut can drop a line.
4
+
5
+ import { arrangeScenes, MAX_SHARE, revealWords } from "../director/beats.js"
6
+ import { cleanScene, SCENE_BLOCK, SCENE_THEMES, SCENE_VERSION } from "../engine/scenes.js"
7
+ import { solve } from "../core/solver.js"
8
+
9
+ const FLICKS = 705_600_000
10
+ const OPENING = 2 * FLICKS // the speaker is seen first
11
+ // Removing pauses can tighten an approved gap: closer than this, the first scene holds until the next starts, so the speaker doesn't flash between them
12
+ const MIN_GAP = 1 * FLICKS
13
+ const MIN_LENGTH = 2 * FLICKS
14
+ const MAX_LENGTH = 15 * FLICKS
15
+ const REVEAL_GAP = 0.6 * FLICKS // pops closer than this blur together
16
+
17
+ /**
18
+ * pictures: approved licensed clips, resolved to assets; terms: quoted definitions to show on their words.
19
+ * @param {{ scenes: object[], pictures?: { asset: string, from: string, to: string }[], terms?: { at: string, term: string, quote: string, source: string }[], project: object, index: object, asset: string, kept: { id: string }[], captions?: boolean, sound?: { scene?: string, reveal?: string } }} input
20
+ * project: with the cut applied; kept: the words the cut keeps
21
+ * @returns {{ ops: object[], covered: Set<string>, notes: string[] }} covered: the words under a scene
22
+ */
23
+ export function sceneOps({ scenes, pictures = [], terms = [], project, index, asset, kept, captions = false, sound = {} }) {
24
+ const notes = []
25
+ const covered = new Set()
26
+ const ops = []
27
+ const { scenes: arranged, dropped } = arrangeScenes(scenes, { index, asset })
28
+ for (const { scene, reason } of dropped) notes.push(`Left out the ${scene.kind} scene: ${reason}.`)
29
+ const timeline = solve(project, index)
30
+ const story = timeline.picture.filter((p) => !p.echo && !p.hold)
31
+ const start = story[0]?.at ?? 0
32
+ const outputOf = (word, edge) => {
33
+ const t = edge === "start" ? word.start : word.end
34
+ const piece = story.find((p) => p.asset === asset && t >= p.in && t <= p.out)
35
+ return piece ? piece.at + (t - piece.in) : null
36
+ }
37
+ const keptIds = new Set(kept.map((w) => w.id))
38
+ const words = index.words.filter((w) => w.asset === asset)
39
+ const byId = new Map(words.map((w) => [w.id, w]))
40
+ let last = -Infinity
41
+ let previous = null
42
+ let used = 0
43
+ for (const raw of arranged) {
44
+ const scene = cleanScene(raw)
45
+ const from = byId.get(scene.from)
46
+ const to = byId.get(scene.to)
47
+ const name = `"${scene.title || scene.items[0].text}"`
48
+ const spoken = words.filter((w) => w.start >= from.start && w.end <= to.end && keptIds.has(w.id))
49
+ if (!spoken.length) {
50
+ notes.push(`Left out the scene ${name}: its lines aren't in this cut.`)
51
+ continue
52
+ }
53
+ const at = outputOf(spoken[0], "start")
54
+ const end = outputOf(spoken.at(-1), "end")
55
+ const length = end - at
56
+ const refuse = at === null || end === null || !(length > 0) ? "its lines aren't together in this cut" : at < start + OPENING ? "the speaker is seen first" : length < MIN_LENGTH ? "its lines are too short in this cut" : length > MAX_LENGTH ? "its lines are apart in this cut" : at < last ? "its lines come before the last scene in this cut" : used + length > timeline.duration * MAX_SHARE ? "the speaker would hardly be seen" : null
57
+ if (refuse) {
58
+ notes.push(`Left out the scene ${name}: ${refuse}.`)
59
+ continue
60
+ }
61
+ if (previous && at - last < MIN_GAP) previous.until = { word: spoken[0].id, edge: "start" }
62
+ const landing = revealWords(scene, spoken)
63
+ const items = scene.items.map((item, i) => {
64
+ const t = landing[i] && outputOf(landing[i], "start")
65
+ return { ...item, ...(t === null || t === undefined ? {} : { reveal: Math.round(((t - at) / FLICKS) * 1000) }) }
66
+ })
67
+ last = end
68
+ used += length
69
+ for (const word of spoken) covered.add(word.id)
70
+ previous = {
71
+ op: "add_motion",
72
+ block: SCENE_BLOCK,
73
+ version: SCENE_VERSION,
74
+ variables: { kind: scene.kind, theme: scene.theme, title: scene.title, text: scene.title || scene.items[0].text, items, ...(scene.mode ? { mode: scene.mode } : {}), ...(captions && SCENE_THEMES[scene.theme].band ? { band: true } : {}) },
75
+ at: { word: spoken[0].id, edge: "start" },
76
+ until: { word: spoken.at(-1).id, edge: "end" },
77
+ }
78
+ ops.push(previous)
79
+ if (sound.scene) ops.push({ op: "add_sfx", asset: sound.scene, peak_at: { word: spoken[0].id, edge: "start" } })
80
+ if (sound.reveal) {
81
+ let lastPop = at
82
+ for (const word of landing) {
83
+ const t = word && outputOf(word, "start")
84
+ if (t === null || t === undefined || t - lastPop < REVEAL_GAP) continue
85
+ lastPop = t
86
+ ops.push({ op: "add_sfx", asset: sound.reveal, peak_at: { word: word.id, edge: "start" } })
87
+ }
88
+ }
89
+ }
90
+ const taken = ops.filter((o) => o.op === "add_motion").map((o) => ({ at: outputOf(byId.get(o.at.word), "start"), end: outputOf(byId.get(o.until.word), "end") }))
91
+ for (const picture of pictures) {
92
+ const from = byId.get(picture.from)
93
+ const to = byId.get(picture.to)
94
+ const asset_ = project.assets.find((a) => a.id === picture.asset)
95
+ const spoken = from && to ? words.filter((w) => w.start >= from.start && w.end <= to.end && keptIds.has(w.id)) : []
96
+ if (!spoken.length || !asset_) {
97
+ notes.push("Left out a picture: its lines aren't in this cut.")
98
+ continue
99
+ }
100
+ const at = outputOf(spoken[0], "start")
101
+ const end = outputOf(spoken.at(-1), "end")
102
+ const length = end - at
103
+ const refuse = at === null || end === null || !(length > 0) ? "its lines aren't together in this cut" : at < start + OPENING ? "the speaker is seen first" : length < MIN_LENGTH || length > MAX_LENGTH ? "its lines don't fit it in this cut" : taken.some((t) => at < t.end && t.at < end) ? "a scene is already there" : length > (asset_.facts.duration ?? 0) ? "the clip is too short for its lines" : used + length > timeline.duration * MAX_SHARE ? "the speaker would hardly be seen" : null
104
+ if (refuse) {
105
+ notes.push(`Left out a picture: ${refuse}.`)
106
+ continue
107
+ }
108
+ used += length
109
+ taken.push({ at, end })
110
+ for (const word of spoken) covered.add(word.id)
111
+ ops.push({ op: "place_broll", asset: asset_.id, at: { word: spoken[0].id, edge: "start" }, until: { word: spoken.at(-1).id, edge: "end" } })
112
+ if (sound.scene) ops.push({ op: "add_sfx", asset: sound.scene, peak_at: { word: spoken[0].id, edge: "start" } })
113
+ }
114
+ for (const term of terms) {
115
+ const word = byId.get(term.at)
116
+ const at = word && keptIds.has(word.id) ? outputOf(word, "start") : null
117
+ if (at === null || taken.some((t) => at >= t.at && at < t.end)) {
118
+ notes.push(`Left out the definition of "${term.term}": something else is on screen there, or the line isn't in this cut.`)
119
+ continue
120
+ }
121
+ // Long enough to read: letters over 15 a second, plus a second and a half
122
+ const seconds = Math.min(7, (term.term.length + term.quote.length + term.source.length) / 15 + 1.5)
123
+ const duration = Math.round(Math.min(seconds * FLICKS, Math.max(FLICKS, timeline.duration - at)))
124
+ ops.push({ op: "add_motion", block: "term", version: 1, variables: { text: term.term, quote: term.quote, source: term.source, ...(term.page ? { page: term.page } : {}) }, at: { word: word.id, edge: "start" }, duration })
125
+ }
126
+ return { ops, covered, notes }
127
+ }
@@ -4,6 +4,38 @@
4
4
  import { call, KriyaError } from "../../api.js"
5
5
  import { openManifest, RuntimeError, TRUSTED_KEYS } from "./manifest.js"
6
6
 
7
+ /**
8
+ * What this Kriya has switched on for editing (EH-01). Any failure, a server with no such
9
+ * route among them, means off: the server ships first, and a client never assumes (track E rule 17).
10
+ * @returns {Promise<{ visuals: boolean, playbooks: boolean, mediaSearch: boolean }>}
11
+ */
12
+ export async function fetchFeatures(device) {
13
+ try {
14
+ const found = await call(device.url, "GET", "/editing/features", { token: device.token })
15
+ return { visuals: found?.visuals === true, playbooks: found?.playbooks === true, mediaSearch: found?.mediaSearch === true }
16
+ } catch {
17
+ return { visuals: false, playbooks: false, mediaSearch: false }
18
+ }
19
+ }
20
+
21
+ /** Licensed pictures for these words; nothing found on any failure, so a plan never fails on a search. */
22
+ export async function searchMedia(device, queries) {
23
+ try {
24
+ return (await call(device.url, "POST", "/editing/media", { token: device.token, body: { queries } }))?.results ?? []
25
+ } catch {
26
+ return []
27
+ }
28
+ }
29
+
30
+ /** Cited definitions for these terms; none on any failure. */
31
+ export async function defineTerms(device, terms) {
32
+ try {
33
+ return (await call(device.url, "POST", "/editing/define", { token: device.token, body: { terms } }))?.definitions ?? []
34
+ } catch {
35
+ return []
36
+ }
37
+ }
38
+
7
39
  /** The manifest for this device. A 404 is how a client learns this Kriya has no editing (EH-01). */
8
40
  export async function fetchManifest(device, trusted = TRUSTED_KEYS) {
9
41
  try {
@@ -107,10 +107,14 @@ a { color: var(--teal); }
107
107
  .projects { list-style: none; padding: 0; margin: 0; display: grid; gap: 8px; }
108
108
 
109
109
  .workspace { display: flex; flex-direction: column; min-height: 100%; }
110
- .grid { flex: 1; display: grid; gap: 12px; padding: 12px; min-height: 0; grid-template-columns: minmax(0, 1fr) 320px; grid-template-areas: "monitor kriya" "transcript transcript" "strip strip"; align-content: start; }
110
+ /* --side: the Kriya panel's width; it fits the window unless the person drags it (main.js) */
111
+ .grid { flex: 1; display: grid; gap: 12px; padding: 12px; min-height: 0; grid-template-columns: minmax(0, 1fr) min(var(--side, clamp(340px, 32vw, 560px)), 62vw); grid-template-areas: "monitor kriya" "transcript transcript" "strip strip"; align-content: start; }
111
112
  .area-bin { grid-area: bin; }
112
113
  .area-monitor { grid-area: monitor; background: var(--surround); color: #eee; }
113
- .area-kriya { grid-area: kriya; }
114
+ .area-kriya { grid-area: kriya; position: relative; }
115
+ .side-handle { position: absolute; left: -12px; top: 0; bottom: 0; width: 12px; cursor: col-resize; touch-action: none; border-radius: 6px; }
116
+ .side-handle::after { content: ""; position: absolute; left: 4px; top: 50%; width: 4px; height: 48px; margin-top: -24px; border-radius: 999px; background: var(--edge); }
117
+ .side-handle:hover::after, .side-handle:focus-visible::after { background: var(--teal); }
114
118
  .area-transcript { grid-area: transcript; }
115
119
  .area-strip { grid-area: strip; }
116
120
  .area-timeline { grid-area: timeline; }
@@ -118,7 +122,15 @@ a { color: var(--teal); }
118
122
  .workspace[data-mode="direct"] :is(.area-bin, .area-timeline, .area-finish) { display: none; }
119
123
  .workspace[data-mode="edit"] .grid { grid-template-columns: 280px minmax(0, 1fr) 320px; grid-template-areas: "bin monitor transcript" "timeline timeline timeline"; }
120
124
  .workspace[data-mode="edit"] :is(.area-kriya, .area-strip, .area-finish) { display: none; }
121
- .workspace[data-mode="finish"] .grid { grid-template-columns: minmax(0, 1fr) 360px; grid-template-areas: "monitor finish"; }
125
+ .area-final { grid-area: final; display: none; }
126
+ .workspace[data-mode="finish"] .area-final { display: block; }
127
+ .workspace[data-mode="finish"] .grid { grid-template-columns: minmax(0, 1fr) 360px; grid-template-areas: "final finish" "monitor finish"; }
128
+ .final-film { width: 100%; max-height: 62vh; background: #000; border-radius: 8px; display: block; }
129
+ .final .row { margin-top: 8px; }
130
+ .final .row select { flex: 1 1 220px; width: auto; min-width: 0; max-width: 100%; }
131
+ .final .note.stale { color: var(--saffron); }
132
+ .final [hidden] { display: none; }
133
+ .did li.watch::before { content: none; }
122
134
  .workspace[data-mode="finish"] :is(.area-bin, .area-kriya, .area-transcript, .area-strip, .area-timeline) { display: none; }
123
135
 
124
136
  .monitor-frame { display: flex; justify-content: center; align-items: center; min-height: 200px; }
@@ -181,11 +193,57 @@ a { color: var(--teal); }
181
193
 
182
194
  /* Review mode under 760 px (UX_SPEC §12): preview, Kriya, export. No timeline, no bin */
183
195
  @media (max-width: 760px) {
184
- .grid, .workspace[data-mode] .grid { grid-template-columns: minmax(0, 1fr); grid-template-areas: "monitor" "kriya" "transcript" "finish"; padding: 8px; }
196
+ .grid, .workspace[data-mode] .grid { grid-template-columns: minmax(0, 1fr); grid-template-areas: "final" "monitor" "kriya" "transcript" "finish"; padding: 8px; }
185
197
  .workspace[data-mode] :is(.area-bin, .area-timeline, .area-strip) { display: none; }
186
198
  .workspace[data-mode="edit"] .area-kriya { display: block; }
187
199
  .modes { margin-left: 0; width: 100%; }
200
+ .side-handle { display: none; }
188
201
  .modes .btn { flex: 1; }
189
202
  .monitor { max-height: 50vh; }
190
203
  }
204
+ /* Home: a project's row with its delete; the folder picker */
205
+ .project-row { display: flex; gap: 8px; align-items: center; }
206
+ .project-row .open { flex: 1; justify-content: flex-start; }
207
+ .btn.danger { color: var(--error); }
208
+ .picker { width: min(560px, 92vw); max-height: 80vh; border: 0; border-radius: 14px; padding: 18px; background: var(--sheet); color: var(--ink); box-shadow: 0 12px 40px rgb(0 0 0 / 0.35); display: grid; gap: 10px; }
209
+ .picker::backdrop { background: rgb(0 0 0 / 0.45); }
210
+ .picker .where { word-break: break-all; color: var(--ink-2); margin: 0; }
211
+ .folders { list-style: none; padding: 0; margin: 0; display: grid; gap: 4px; max-height: 46vh; overflow: auto; }
212
+ .btn.folder { width: 100%; justify-content: flex-start; }
213
+ .row.end { justify-content: flex-end; }
214
+
215
+ /* Chat with Kriya */
216
+ .chat { list-style: none; padding: 0; margin: 0 0 8px; display: grid; gap: 8px; max-height: 58vh; overflow: auto; }
217
+ .chat:empty { display: none; }
218
+ .msg { padding: 8px 10px; border-radius: 10px; background: var(--hover); }
219
+ .msg.you { background: color-mix(in srgb, var(--teal) 14%, transparent); }
220
+ .msg .who { font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--ink-2); }
221
+ .msg p { margin: 2px 0 0; white-space: pre-wrap; }
222
+ .msg .proposal { margin-top: 8px; }
223
+ .chat-input { min-height: 64px; padding: 10px 12px; resize: vertical; line-height: 1.4; }
224
+ .prompt { align-items: flex-end; }
225
+ .time-link { font: inherit; font-family: ui-monospace, "JetBrains Mono", monospace; font-size: 0.92em; color: var(--teal); background: none; border: 0; padding: 0 2px; min-height: 24px; text-decoration: underline; cursor: pointer; }
226
+ .marks { display: inline-flex; gap: 6px; }
227
+ .send { display: grid; gap: 6px; }
228
+ .extras { display: flex; flex-wrap: wrap; gap: 0 14px; }
229
+ .plan .steps { margin: 4px 0; padding-left: 20px; display: grid; gap: 4px; }
230
+ .scenes { display: grid; gap: 8px; }
231
+ .scene-head { justify-content: space-between; align-items: center; }
232
+ .scene-head .field { width: auto; }
233
+ .scene-info .field { width: auto; flex: 1 1 140px; min-width: 0; }
234
+ .scene-list { list-style: none; padding: 0; margin: 0; display: grid; gap: 12px; }
235
+ .proposal .scene-row { display: flex; gap: 10px; align-items: flex-start; justify-content: flex-start; }
236
+ .found-thumb { flex: none; width: 120px; height: 90px; object-fit: cover; border-radius: 6px; background: #000; }
237
+ .scenes .row .field { width: auto; flex: 1 1 120px; min-width: 0; }
238
+ .scene-picture { flex: none; overflow: hidden; border-radius: 6px; background: #000; }
239
+ .scene-picture iframe { border: 0; display: block; transform-origin: 0 0; pointer-events: none; }
240
+ .scene-info { min-width: 0; display: grid; gap: 4px; }
241
+ .scene-info p { margin: 0; overflow-wrap: anywhere; }
242
+ .scene-info .row { flex-wrap: wrap; gap: 6px; }
243
+ .scene-time { font-family: ui-monospace, "JetBrains Mono", monospace; color: var(--teal); }
244
+ .refs-direct { margin: 0; }
245
+ .refs-direct:empty { display: none; }
246
+ .ref .ref-lines { list-style: none; padding: 0; margin: 2px 0; font-size: 13px; color: var(--ink-2); display: grid; gap: 2px; }
247
+ .area-monitor .marks .btn { background: #2a2a2a; color: #eee; }
248
+
191
249
  @media (prefers-reduced-motion: reduce) { * { transition: none !important; animation: none !important; } }