@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
@@ -9,9 +9,10 @@ import { paperEdit, shotDigest } from "../index/views.js"
9
9
 
10
10
  const FLICKS = 705_600_000
11
11
 
12
- // What the console may ask for: edits that render today. Captions, motion and sound
13
- // design arrive with their phases (ED8, ED9) and are refused until then
14
- export const CONSOLE_OPS = ["keep_range", "remove_range", "use_take", "reorder", "trim", "split", "ripple_delete", "punch_in", "reframe", "speed", "set_format", "mark"]
12
+ // What the console may ask for: edits that render today, captions and titles included
13
+ // (drawn in the runtime's Chrome when it has no HyperFrames)
14
+ export const CONSOLE_OPS = ["keep_range", "remove_range", "use_take", "reorder", "trim", "split", "ripple_delete", "punch_in", "reframe", "speed", "set_format", "mark", "caption_style", "caption_edit", "caption_emphasis", "add_title", "grade", "clean_voice", "set_level", "speed_ramp", "freeze", "place_broll"]
15
+ export const CAPTION_LOOKS = ["clean", "karaoke", "boxed"]
15
16
 
16
17
  const ID = { type: "string", maxLength: 64 }
17
18
  const EDGE = { type: "string", enum: ["start", "end"] }
@@ -55,6 +56,21 @@ export const OPS_SCHEMA = {
55
56
  width: { type: "integer", minimum: 2 },
56
57
  height: { type: "integer", minimum: 2 },
57
58
  name: { type: "string", maxLength: 80 },
59
+ look: { type: "string", enum: CAPTION_LOOKS },
60
+ words: { type: "array", maxItems: 40, items: ID },
61
+ caption: ID,
62
+ word: ID,
63
+ text: { type: "string", maxLength: 200 },
64
+ lift: { type: "number", minimum: -0.5, maximum: 0.5 },
65
+ gamma: { type: "number", minimum: 0.5, maximum: 2 },
66
+ gain: { type: "number", minimum: 0.5, maximum: 2 },
67
+ saturation: { type: "number", minimum: 0, maximum: 2 },
68
+ temperature: { type: "number", minimum: 2000, maximum: 12000 },
69
+ vibrance: { type: "number", minimum: -2, maximum: 2 },
70
+ vignette: { type: "number", minimum: 0, maximum: 1 },
71
+ strength: { type: "number", minimum: 0, maximum: 1 },
72
+ db: { type: "number", minimum: -40, maximum: 20 },
73
+ peak: RATE,
58
74
  },
59
75
  required: ["op"],
60
76
  additionalProperties: false,
@@ -66,10 +82,13 @@ export const OPS_SCHEMA = {
66
82
  maxItems: 40,
67
83
  items: { type: "object", properties: { word: ID, text: { type: "string", maxLength: 60 } }, required: ["word", "text"], additionalProperties: false },
68
84
  },
85
+ // A short answer in words: what Kriya did, or the answer to a question
86
+ say: { type: "string", maxLength: 600 },
69
87
  // A request about the whole video ("make it stunning", "edit all of it"): the Director's make job does that
70
88
  direct: {
71
89
  anyOf: [
72
90
  { type: "null" },
91
+ { type: "boolean" },
73
92
  { type: "object", properties: { seconds: { type: "integer", minimum: 5, maximum: 600 }, captions: { type: "string", enum: ["clean", "karaoke", "boxed"] } }, additionalProperties: false },
74
93
  ],
75
94
  },
@@ -78,6 +97,19 @@ export const OPS_SCHEMA = {
78
97
  additionalProperties: false,
79
98
  }
80
99
 
100
+ /**
101
+ * What models often send that means nothing: every optional field present as null,
102
+ * and empty lists or no `ops` at all. Tidied before the schema, never invented.
103
+ */
104
+ export function tidyConsole(value) {
105
+ if (!value || typeof value !== "object" || Array.isArray(value)) return value
106
+ const ops = Array.isArray(value.ops) ? value.ops.map((op) => (op && typeof op === "object" ? Object.fromEntries(Object.entries(op).filter(([key, v]) => v !== null || key === "after")) : op)) : (value.ops ?? [])
107
+ const out = { ...value, ops }
108
+ if (out.corrections === null) delete out.corrections
109
+ if (out.direct === false) out.direct = null
110
+ return out
111
+ }
112
+
81
113
  /** A correction's text: one word or a short name, no markup or line breaks. */
82
114
  export const cleanWord = (text) => (typeof text === "string" ? text.replace(/[\u0000-\u001f<>]/g, "").trim().slice(0, 60) : "")
83
115
 
@@ -130,6 +162,28 @@ export function describe(op, index) {
130
162
  return op.fit ? "Fitted the music to the cut on its downbeats" : "Shaped the music's fades"
131
163
  case "duck":
132
164
  return "Ducked the music under the speech"
165
+ case "caption_edit":
166
+ return `Changed caption ${op.caption} to "${op.text}"`
167
+ case "caption_emphasis":
168
+ return `Emphasised "${words.get(op.word)?.text ?? op.word}" in caption ${op.caption}`
169
+ case "add_title":
170
+ return `Added the title "${op.text}" at ${place(op.at)}`
171
+ case "add_motion":
172
+ return op.block === "scene" ? `Added an animated ${op.variables?.kind ?? ""} scene, "${op.variables?.text ?? ""}", at ${place(op.at)}` : op.op
173
+ case "grade":
174
+ return `Graded ${op.clip}${op.saturation !== undefined ? `, saturation ${op.saturation}` : ""}${op.gain !== undefined ? `, contrast ${op.gain}` : ""}${op.gamma !== undefined ? `, gamma ${op.gamma}` : ""}${op.lift !== undefined ? `, lift ${op.lift}` : ""}`
175
+ case "speed_ramp":
176
+ return op.peak.n > op.peak.d ? `Ramped ${op.clip} up to ${(op.peak.n / op.peak.d).toFixed(1)}× and back, from ${place(op.from)} to ${place(op.to)}` : `Slow motion in ${op.clip} (${(op.peak.n / op.peak.d).toFixed(2)}×), eased in and out, from ${place(op.from)} to ${place(op.to)}`
177
+ case "freeze":
178
+ return `Froze the frame at ${place(op.at)} for ${seconds(op.duration)}`
179
+ case "add_sfx":
180
+ return `Added a sound effect at ${place(op.peak_at)}`
181
+ case "place_broll":
182
+ return `Laid B-roll ${op.asset} over ${place(op.at)}${op.duration ? ` for ${seconds(op.duration)}` : ""}`
183
+ case "clean_voice":
184
+ return `Cleaned the background noise out of ${op.clip}'s voice`
185
+ case "set_level":
186
+ return `Set ${op.clip} to ${op.db} dB`
133
187
  case "add_deliverable":
134
188
  return `Set up the export: ${op.size?.width ?? "?"}×${op.size?.height ?? "?"}${op.loudness ? `, mastered to ${op.loudness.lufs} LUFS` : ""}${op.burnCaptions ? ", captions burned in" : ""}`
135
189
  default:
@@ -145,7 +199,7 @@ function selectionText(selection, index) {
145
199
  return `The person selected the words ${first} to ${last} in the paper edit, and means them by "this", "here" or "that part".`
146
200
  }
147
201
  if (selection.clip) return `The person selected clip ${selection.clip}, and means it by "this", "here" or "that clip".`
148
- if (Number.isInteger(selection.from) && Number.isInteger(selection.to)) return `The person selected the timeline from ${selection.from} to ${selection.to} flicks.`
202
+ if (Number.isInteger(selection.from) && Number.isInteger(selection.to)) return `The person marked ${clock(selection.from)} to ${clock(selection.to)} on the cut's timeline, and means it by "this", "here" or "that part" (what it points at is below).`
149
203
  if (Number.isInteger(selection.at)) return `The playhead is at ${selection.at} flicks on the timeline.`
150
204
  return "Nothing is selected."
151
205
  }
@@ -177,10 +231,105 @@ export function noteWord(project, index, at) {
177
231
  return (words.find((w) => t >= w.start && t < w.end) ?? words.find((w) => w.start >= t) ?? words.at(-1))?.id ?? null
178
232
  }
179
233
 
234
+ /** A time on the cut as the person reads it in the Studio: 1:02.5 */
235
+ export const clock = (flicks) => {
236
+ const total = Math.max(0, flicks) / FLICKS
237
+ const minutes = Math.floor(total / 60)
238
+ return `${minutes}:${(total - minutes * 60).toFixed(1).padStart(4, "0")}`
239
+ }
240
+
180
241
  function clipsView(project, index) {
181
- const { picture } = solve(project, index)
182
- const lines = picture.map((p) => `[${p.clip} ${p.asset} source ${p.in}-${p.out} at ${p.at}-${p.end}]`)
183
- return `Clips on the timeline, in order:\n${lines.join("\n") || "(none yet)"}`
242
+ const { picture, captions, duration } = solve(project, index)
243
+ const lines = picture.map((p) => `[${p.clip} ${clock(p.at)}-${clock(p.end)} from ${p.asset} ${seconds(p.in)}-${seconds(p.out)}; flicks source ${p.in}-${p.out} at ${p.at}-${p.end}]`)
244
+ const said = captions.map((c) => `[caption ${c.clip} ${clock(c.at)}-${clock(c.end)} ${c.look ?? ""} ${JSON.stringify(String(c.text).replace(/[<>]/g, ""))}]`)
245
+ return [`The cut, on its own timeline: it starts at 0:00 and is ${clock(duration)} long. Clips in order:`, lines.join("\n") || "(none yet)", ...(said.length ? ["Captions on screen:", said.join("\n")] : [])].join("\n")
246
+ }
247
+
248
+ const JOIN = /^\s*(?:-|–|—|to|until|till|and|through)\s*$/i
249
+ // Seconds as people type them, typos included: s, sec, secs, second, seconds, secods, secnds
250
+ const UNIT = "(?:s|sec\\w*|se?c?o?n?d?s?\\b)(?![a-z])"
251
+
252
+ /**
253
+ * Times in the person's words, on the cut's timeline: 0:05, 1:02.5, 5s, 5 sec, 5 seconds,
254
+ * and ranges joined by to, -, until or and ("from 5 to 9 seconds", "between 0:05 and 0:09").
255
+ * @returns {{ at: number, to?: number }[]} in flicks
256
+ */
257
+ export function timesIn(text, { duration = null } = {}) {
258
+ const said = String(text)
259
+ // Relative stretches first: "the first 5 seconds", "the last 5 s" (needs the cut's length)
260
+ const relative = []
261
+ for (const m of said.matchAll(new RegExp(`\\b(first|last|final|opening)\\s+(\\d+(?:\\.\\d+)?)\\s*${UNIT}`, "gi"))) {
262
+ const n = Math.round(Number(m[2]) * FLICKS)
263
+ if (/first|opening/i.test(m[1])) relative.push({ at: 0, to: n })
264
+ else if (duration) relative.push({ at: Math.max(0, duration - n), to: duration })
265
+ }
266
+ const text2 = said.replace(new RegExp(`\\b(first|last|final|opening)\\s+\\d+(?:\\.\\d+)?\\s*${UNIT}`, "gi"), (m) => " ".repeat(m.length))
267
+ const tokens = [...text2.matchAll(new RegExp(`(\\d{1,2}):(\\d{2}(?:\\.\\d+)?)|(\\d+(?:\\.\\d+)?)(\\s*${UNIT})?`, "gi"))].map((m) => ({
268
+ t: m[1] !== undefined ? Number(m[1]) * 60 + Number(m[2]) : Number(m[3]),
269
+ unit: m[1] !== undefined || !!m[4],
270
+ start: m.index,
271
+ end: m.index + m[0].length,
272
+ }))
273
+ const between = (a, b) => text2.slice(a.end, b.start)
274
+ const before = (tok) => text2.slice(Math.max(0, tok.start - 24), tok.start)
275
+ // A bare number is a time only as the first half of a range whose second half is one
276
+ const times = tokens.filter((tok, i) => tok.unit || (tokens[i + 1]?.unit && JOIN.test(between(tok, tokens[i + 1]))))
277
+ const out = [...relative]
278
+ for (let i = 0; i < times.length; i++) {
279
+ const next = times[i + 1]
280
+ const at = Math.round(times[i].t * FLICKS)
281
+ if (next && JOIN.test(between(times[i], next)) && next.t > times[i].t) {
282
+ out.push({ at, to: Math.round(next.t * FLICKS) })
283
+ i++
284
+ } else if (duration && /\b(?:after|from|form|frm|fron|since|onwards?|starting(?: at)?|beyond|past)\s*(?:the\s*)?$/i.test(before(times[i]))) out.push({ at, to: duration })
285
+ else if (/\b(?:before|until|till|up to|upto)\s*(?:the\s*)?$/i.test(before(times[i]))) out.push({ at: 0, to: at })
286
+ else out.push({ at })
287
+ }
288
+ return out.slice(0, 8)
289
+ }
290
+
291
+ /** Where a moment of the cut comes from: its clip, and the source time inside it. */
292
+ function sourceAt(picture, t) {
293
+ const piece = picture.find((p) => t >= p.at && t < p.end)
294
+ if (!piece) return null
295
+ return { piece, t: piece.in + Math.round(((t - piece.at) * (piece.out - piece.in)) / (piece.end - piece.at || 1)) }
296
+ }
297
+
298
+ /**
299
+ * What each mentioned time points at, worked out by code so the model never does
300
+ * arithmetic on flicks: the clip, the words (with ids) and the captions there.
301
+ */
302
+ export function timesView(text, project, index) {
303
+ const { picture, captions, duration } = solve(project, index)
304
+ const asked = timesIn(text, { duration })
305
+ if (!asked.length) return ""
306
+ const words = index.words ?? []
307
+ const wordAt = (piece, t) => words.find((w) => w.asset === piece.asset && t >= w.start && t < w.end) ?? words.find((w) => w.asset === piece.asset && w.start >= t && w.start < piece.out)
308
+ const quote = (list) => JSON.stringify(list.map((w) => w.text).join(" ").replace(/[<>]/g, "").slice(0, 300))
309
+ const lines = asked.map(({ at, to }) => {
310
+ if (at >= duration) return `${clock(at)}: past the end of the cut (${clock(duration)} long).`
311
+ if (to === undefined) {
312
+ const found = sourceAt(picture, at)
313
+ const word = found && wordAt(found.piece, found.t)
314
+ const on = captions.filter((c) => at >= c.at && at < c.end).map((c) => `caption ${c.clip}`)
315
+ return `${clock(at)}: clip ${found?.piece.clip ?? "?"}${word ? `, word ${word.id} ${JSON.stringify(word.text)}` : ", no word spoken there"}${on.length ? `, ${on.join(", ")}` : ""}.`
316
+ }
317
+ const end = Math.min(to, duration)
318
+ const pieces = picture.filter((p) => p.at < end && p.end > at)
319
+ const spans = pieces.map((p) => {
320
+ const from = sourceAt(picture, Math.max(at, p.at))?.t ?? p.in
321
+ const until = Math.min(p.out, Math.max(from + 1, (sourceAt(picture, Math.min(end, p.end) - 1)?.t ?? p.out) + 1))
322
+ return { asset: p.asset, from, until }
323
+ })
324
+ const inside = spans.flatMap(({ asset, from, until }) => words.filter((w) => w.asset === asset && w.end > from && w.start < until))
325
+ const on = captions.filter((c) => c.at < end && c.end > at).map((c) => `caption ${c.clip}`)
326
+ const spoken = inside.length ? `words ${inside[0].id} to ${inside.at(-1).id}: ${quote(inside)}` : "no words spoken"
327
+ // The exact operation to take this stretch out, in each source's own flicks, so a removal
328
+ // never depends on where words happen to fall (found in use: "remove from 25 seconds")
329
+ const removal = spans.map(({ asset, from, until }) => JSON.stringify({ op: "remove_range", asset, from, to: until })).join(" ")
330
+ return `${clock(at)}-${clock(end)}: clip${pieces.length === 1 ? "" : "s"} ${pieces.map((p) => p.clip).join(", ") || "?"}, ${spoken}${on.length ? `; ${on.join(", ")}` : ""}. To take it out exactly: ${removal}`
331
+ })
332
+ return `Times the person mentioned, worked out by code on the cut's timeline:\n${lines.join("\n")}`
184
333
  }
185
334
 
186
335
  /**
@@ -188,12 +337,21 @@ function clipsView(project, index) {
188
337
  * @param {{ ask: ReturnType<import("./ask.js").createAsk>, project: object, index: object, text: string, selection?: object, signal?: AbortSignal }} input
189
338
  * @returns {Promise<{ ops: object[], changes: string[], project: object | null, source: string, reason?: string, calls: number }>}
190
339
  */
191
- export async function revise({ ask, project, index, text, selection, signal }) {
340
+ export async function revise({ ask, project, index, text, selection, history = [], signal }) {
192
341
  const assets = project.assets.map((a) => a.id)
193
- const view = [paperEdit(index, { assets }), shotDigest(index, { assets }), clipsView(project, index), selectionText(selection, index)].join("\n\n")
342
+ // A marked range reads like a typed one: code says what it points at
343
+ const marked = Number.isInteger(selection?.from) && Number.isInteger(selection?.to) ? ` from ${clock(selection.from)} to ${clock(selection.to)}` : ""
344
+ const times = timesView(`${text}${marked}`, project, index)
345
+ const bin = `Footage in the project: ${project.assets.filter((a) => ["video", "audio"].includes(a.kind)).map((a) => `${a.id} (${a.kind}, ${seconds(a.facts.duration ?? 0)})`).join(", ")}`
346
+ const view = [paperEdit(index, { assets }), shotDigest(index, { assets }), clipsView(project, index), bin, selectionText(selection, index), times].filter(Boolean).join("\n\n")
347
+ // The last turns of this chat, so "shorter" or "no, the other one" mean something. The
348
+ // person's lines are theirs; Kriya's are what it said before, not instructions
349
+ const earlier = history.length ? `Earlier in this chat:\n${history.map((h) => `${h.who === "you" ? "Person" : "Kriya"}: ${JSON.stringify(h.text)}`).join("\n")}\n\n` : ""
194
350
  const request = [
195
- `The person asks (their own words, trusted): ${JSON.stringify(String(text).slice(0, 2000))}`,
351
+ `${earlier}The person asks (their own words, trusted): ${JSON.stringify(String(text).slice(0, 2000))}`,
196
352
  "Answer with JSON only. Put in `ops` the operations that do exactly what they ask, and nothing else.",
353
+ "Times like 0:05 are on the cut's timeline; the lines above say which clip, words and captions each time points at. Use those ids, never compute flicks yourself. To take out a stretch the person names by time, use the exact remove_range given for it above, unchanged; for a stretch named by words, remove_range from its first word (edge start) to its last word (edge end). To change what a caption says, caption_edit with its caption id; to remove a caption, ripple_delete its caption id; to caption words, caption_style with their word ids and a look; to put a title on screen, add_title with text and a word anchor; to take background noise out of the voice, clean_voice on each picture clip; to warm or cool the picture, grade with temperature (lower is warmer, 6500 neutral), vibrance or vignette; for a speed ramp or slow motion, speed_ramp on the clip with from and to (source flicks from the lines above, or word anchors) and peak {n, d} (2/1 speeds up and back, 1/2 is eased slow motion); for a constant speed, speed; to lay other footage over a moment, place_broll with a video asset id from the project, at a word anchor or clip edge, and duration in flicks.",
354
+ "Put one plain sentence in `say`: what you changed, or the answer if they asked a question.",
197
355
  "If they ask to fix or correct the transcript (names, misheard words), put each wrong word in `corrections` as {word: its id, text: the right word}, only where you are confident from the context.",
198
356
  "If they ask for the whole video to be made, directed, edited or improved (not one part of it), set `direct` to an object (with `seconds` and a caption look if they say so) and leave `ops` empty: the Director makes the whole cut.",
199
357
  'If none of these can do it, answer {"ops": []}.',
@@ -205,17 +363,18 @@ export async function revise({ ask, project, index, text, selection, signal }) {
205
363
  const tried = apply(project, ops, { index, author: "agent" })
206
364
  return tried.applied ? [] : tried.diagnostics.map((d) => `operation ${d.op + 1}: ${d.message}`)
207
365
  }
208
- const answer = await ask({ task: "console", tier: "budget", schema: OPS_SCHEMA, view, request, maxOutput: 2000, check, fallback: () => ({ ops: [] }), signal, priority: 0 })
366
+ const answer = await ask({ task: "console", tier: "budget", schema: OPS_SCHEMA, view, request, maxOutput: 2000, check, clean: tidyConsole, fallback: () => ({ ops: [] }), signal, priority: 0 })
209
367
  const ops = answer.value.ops
210
368
  const tried = ops.length ? apply(project, ops, { index, author: "agent" }) : null
211
369
  // A correction that changes nothing, or isn't a known word, isn't offered
212
370
  const corrections = (answer.value.corrections ?? []).map((c) => ({ word: c.word, text: cleanWord(c.text) })).filter((c) => words.has(c.word) && c.text && c.text !== words.get(c.word).text)
213
- const direct = answer.value.direct && typeof answer.value.direct === "object" ? answer.value.direct : null
371
+ const direct = answer.value.direct === true ? {} : answer.value.direct && typeof answer.value.direct === "object" ? answer.value.direct : null
214
372
  return {
215
373
  ops: tried?.applied ? ops : [],
216
374
  changes: tried?.applied ? ops.map((op) => describe(op, index)) : [],
217
375
  corrections: corrections.map((c) => ({ ...c, change: `Corrected "${words.get(c.word).text}" to "${c.text}"` })),
218
376
  direct,
377
+ say: typeof answer.value.say === "string" ? answer.value.say.replace(/[\u0000-\u001f<>]/g, " ").trim().slice(0, 600) : "",
219
378
  project: tried?.applied ? tried.project : null,
220
379
  source: answer.source,
221
380
  reason: answer.reason,
@@ -21,6 +21,10 @@ export const LOOKS = {
21
21
  clean: { font: "sans", weight: 800, size: 0.042, color: "#ffffff", accent: "#ffd23f", box: null, stroke: "#000000", highlight: false },
22
22
  karaoke: { font: "sans", weight: 800, size: 0.046, color: "#ffffff", accent: "#ffd23f", box: { color: "#0a0a0a", alpha: 0.7 }, stroke: null, highlight: true },
23
23
  boxed: { font: "sans", weight: 700, size: 0.04, color: "#f2eadf", accent: "#ffb347", box: { color: "#13292b", alpha: 0.92 }, stroke: null, highlight: false },
24
+ // The playbooks' looks (DP3): bold and word by word for a promo, quieter for a story, plain for a talk
25
+ pop: { font: "rounded", weight: 800, size: 0.05, color: "#ffffff", accent: "#ffe14d", box: null, stroke: "#000000", highlight: true },
26
+ story: { font: "serif", weight: 700, size: 0.036, color: "#fff8ec", accent: "#ffd9a0", box: { color: "#14110d", alpha: 0.78 }, stroke: null, highlight: false },
27
+ minimal: { font: "sans", weight: 700, size: 0.034, color: "#ffffff", accent: "#ffffff", box: { color: "#000000", alpha: 0.72 }, stroke: null, highlight: false },
24
28
  }
25
29
 
26
30
  const HEX = /^#[0-9a-f]{6}$/i
@@ -34,6 +38,7 @@ export function lookOf(id, style = {}) {
34
38
  if (style.font in FONTS) look.font = style.font
35
39
  if (Number.isFinite(style.size) && style.size >= 0.02 && style.size <= 0.1) look.size = style.size
36
40
  if (HEX.test(style.box ?? "") && look.box) look.box = { ...look.box, color: style.box }
41
+ if (style.stroke === "none") look.stroke = null
37
42
  // The repair ladder's contrast fix (QUALITY_GATES §4 rung 0): a dark scrim behind the words
38
43
  if (style.scrim === true) look.box = look.box ? { ...look.box, alpha: Math.max(look.box.alpha, 0.85) } : { color: "#000000", alpha: 0.8 }
39
44
  return look
@@ -99,6 +104,33 @@ export function scriptOf(text) {
99
104
  return "other"
100
105
  }
101
106
 
107
+ /**
108
+ * Pages a reader keeps up with: a burst of fast speech joins its neighbour, so it stays on screen
109
+ * longer, rather than flash by (found on real footage). A page that's readable is left alone.
110
+ * @param {string[][]} list pages of word ids, from pages()
111
+ * @param {{ id: string, text: string, start: number, end: number }[]} words
112
+ */
113
+ export function readablePages(list, words) {
114
+ const byId = new Map(words.map((w) => [w.id, w]))
115
+ const tooFast = (ids) => {
116
+ const script = scriptOf(ids.map((id) => byId.get(id)?.text ?? "").join(" "))
117
+ const seconds = (byId.get(ids.at(-1)).end - byId.get(ids[0]).start) / FLICKS
118
+ return seconds < 1.2 && ids.length / Math.max(seconds, 1e-3) > READING_LIMITS[script]
119
+ }
120
+ const out = list.map((p) => [...p])
121
+ for (let i = 0; i < out.length && out.length > 1; i++) {
122
+ if (!tooFast(out[i])) continue
123
+ // With the smaller neighbour, so the page stays short; never over ten words, and the gate says so if it's still fast
124
+ const before = i > 0 ? out[i - 1].length : Infinity
125
+ const after = i + 1 < out.length ? out[i + 1].length : Infinity
126
+ const into = before < after ? i - 1 : i
127
+ if (Math.min(before, after) + out[i].length > 10) continue
128
+ out.splice(into, 2, [...out[into], ...out[into + 1]])
129
+ i = into - 1
130
+ }
131
+ return out
132
+ }
133
+
102
134
  /* ─────────────────────────────── the composition ─────────────────────────────── */
103
135
 
104
136
  const ENTRANCE = { damping: 0.7, frequency: 14, ms: 320 }
@@ -0,0 +1,64 @@
1
+ // Licensed media the person approved on the Plan Card (EDD-52): downloaded by the Host, only over
2
+ // HTTPS, only from the hosts the server's search reads, with no redirects and a size limit. A still
3
+ // becomes a short clip with a slow move, so it goes through the same render as any B-roll.
4
+
5
+ import { createWriteStream, renameSync, rmSync } from "node:fs"
6
+ import { Readable } from "node:stream"
7
+ import { pipeline } from "node:stream/promises"
8
+
9
+ import { EngineFailure } from "./tool.js"
10
+
11
+ export const MEDIA_HOSTS = ["upload.wikimedia.org", "thumb.wikimedia.org", "images-assets.nasa.gov", "live.staticflickr.com"]
12
+ export const MEDIA_TYPES = { "image/jpeg": ".jpg", "image/png": ".png", "image/webp": ".webp", "video/webm": ".webm", "video/mp4": ".mp4", "video/ogg": ".ogv", "application/ogg": ".ogv" }
13
+ const MAX_BYTES = 100 * 1024 * 1024
14
+ const TIMEOUT_MS = 120_000
15
+
16
+ export function allowedMediaUrl(url) {
17
+ try {
18
+ const parsed = new URL(String(url))
19
+ return parsed.protocol === "https:" && !parsed.username && !parsed.password && !parsed.port && MEDIA_HOSTS.includes(parsed.hostname)
20
+ } catch {
21
+ return false
22
+ }
23
+ }
24
+
25
+ /**
26
+ * @param {string} url
27
+ * @param {string} base the file's path without its extension; the type the server states picks it
28
+ * @returns {Promise<{ file: string, type: string }>}
29
+ */
30
+ export async function downloadMedia(url, base, { signal, maxBytes = MAX_BYTES, get = fetch } = {}) {
31
+ if (!allowedMediaUrl(url)) throw new EngineFailure("input", "bad_media_url", "That picture isn't from a source Kriya may download from.")
32
+ const limit = AbortSignal.timeout(TIMEOUT_MS)
33
+ const response = await get(url, { redirect: "error", headers: { "user-agent": "KriyaEditingStudio/1.0 (https://github.com/zuko14/kriya-harness)" }, signal: signal ? AbortSignal.any([signal, limit]) : limit })
34
+ if (!response.ok) throw new EngineFailure("environment", "media_download", `The source answered ${response.status}.`)
35
+ const type = String(response.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase()
36
+ const extension = MEDIA_TYPES[type]
37
+ if (!extension) throw new EngineFailure("input", "bad_media_type", "That file isn't a picture or video Kriya can use.")
38
+ if (Number(response.headers.get("content-length") ?? 0) > maxBytes) throw new EngineFailure("input", "media_too_big", "That file is too big.")
39
+ const file = `${base}${extension}`
40
+ const part = `${file}.${process.pid}.part`
41
+ let seen = 0
42
+ const counted = async function* (source) {
43
+ for await (const chunk of source) {
44
+ seen += chunk.length
45
+ if (seen > maxBytes) throw new EngineFailure("input", "media_too_big", "That file is too big.")
46
+ yield chunk
47
+ }
48
+ }
49
+ try {
50
+ await pipeline(Readable.fromWeb(response.body), counted, createWriteStream(part))
51
+ renameSync(part, file)
52
+ } catch (error) {
53
+ rmSync(part, { force: true })
54
+ throw error
55
+ }
56
+ return { file, type }
57
+ }
58
+
59
+ /** FFmpeg's arguments for a still as a clip: filling the frame, moving slowly in or out. No sound. */
60
+ export function stillClipArgs({ image, output, width, height, seconds, fps = 30, inward = true }) {
61
+ const frames = Math.max(1, Math.round(seconds * fps))
62
+ const zoom = inward ? `1+0.1*on/${frames}` : `1.1-0.1*on/${frames}`
63
+ return ["-hide_banner", "-nostdin", "-loglevel", "error", "-protocol_whitelist", "file,pipe", "-i", image, "-vf", `scale=${width * 2}:${height * 2}:force_original_aspect_ratio=increase,crop=${width * 2}:${height * 2},zoompan=z='${zoom}':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d=${frames}:s=${width}x${height}:fps=${fps},format=yuv420p`, "-frames:v", String(frames), "-c:v", "libx264", "-preset", "veryfast", "-crf", "18", "-an", "-y", output]
64
+ }
@@ -9,6 +9,7 @@ import { join } from "node:path"
9
9
 
10
10
  import { childEnv } from "../runtime/setup.js"
11
11
  import { confine, confinement, installOf } from "./confine.js"
12
+ import { buildScene, SCENE_VERSION } from "./scenes.js"
12
13
  import { EngineFailure, runTool } from "./tool.js"
13
14
 
14
15
  const FLICKS = 705_600_000
@@ -118,6 +119,22 @@ export const BLOCKS = {
118
119
  animations: [{ id: "t", keyframes: springKeyframes({ ...RISE, from: { y: Math.round(size * 6), scale: 0.8, opacity: 0 }, to: { y: 0, scale: 1, opacity: 1 } }), options: { duration: RISE.ms, fill: "both" } }],
119
120
  }),
120
121
  },
122
+ // A hard term, its definition quoted with its source (EDD-57). The words are never edited
123
+ term: {
124
+ version: 1,
125
+ build: ({ variables, area, size, output }) => {
126
+ const floor = Math.ceil(output.height * 0.0205)
127
+ const quote = Math.max(floor, Math.round(size * 0.72))
128
+ const cite = Math.max(floor, Math.round(size * 0.6))
129
+ return {
130
+ css: `#a{position:absolute;left:${area.x}px;top:${area.y}px;width:${area.w}px;height:${area.h}px;display:flex;align-items:flex-end}#t{width:100%;box-sizing:border-box;font-family:'Helvetica Neue',Helvetica,Arial,sans-serif;background:#13292b;color:#f2eadf;padding:${Math.round(size * 0.4)}px ${Math.round(size * 0.55)}px;border-left:${Math.round(size * 0.18)}px solid #ffb347;border-radius:${Math.round(size * 0.2)}px}#t b,#t q,#t small{display:block;background:#13292b}#t b{font-size:${Math.round(size * 1.05)}px;font-weight:800}#t q{font-size:${quote}px;line-height:1.2;margin:${Math.round(size * 0.15)}px 0;quotes:'“' '”'}#t small{font-size:${cite}px;color:#ffb347}`,
131
+ body: `<div id="a"><div id="t"><b data-text>${escapeText(textVar(variables, "text", 60))}</b><q data-text>${escapeText(textVar(variables, "quote", 120))}</q><small data-text>${escapeText(textVar(variables, "source", 40))}</small></div></div>`,
132
+ animations: [{ id: "t", keyframes: springKeyframes({ ...RISE, from: { y: Math.round(size * 2), opacity: 0 }, to: { y: 0, opacity: 1 } }), options: { duration: RISE.ms, fill: "both" } }],
133
+ }
134
+ },
135
+ },
136
+ // An explainer scene (VISUAL_SCENES.md): an opaque cutaway; `placement` is its content box
137
+ scene: { version: SCENE_VERSION, build: (parts) => buildScene(parts, springKeyframes) },
121
138
  }
122
139
 
123
140
  /** A block tile's composition. An unknown block or version is refused, never drawn as something else. */
@@ -129,7 +146,7 @@ export function blockComposition(node, { output, canvas }) {
129
146
  const box = node.placement ?? { x: Math.round(canvas.width * 0.1), y: Math.round(canvas.height * 0.4), w: Math.round(canvas.width * 0.8), h: Math.round(canvas.height * 0.12) }
130
147
  const area = { x: Math.round(box.x * sx), y: Math.round(box.y * sy), w: Math.round(box.w * sx), h: Math.round(box.h * sy) }
131
148
  const size = Math.round(output.height * 0.03)
132
- return tileDocument({ width: output.width, height: output.height, duration: node.duration, ...block.build({ variables: node.variables, area, size }) })
149
+ return tileDocument({ width: output.width, height: output.height, duration: node.duration, ...block.build({ variables: node.variables, area, size, output, duration: node.duration }) })
133
150
  }
134
151
 
135
152
  /* ─────────────────────────────── model-written code ─────────────────────────────── */
@@ -191,8 +208,9 @@ export function motionRuntime(runtime, platform = `${process.platform}-${process
191
208
  const cli = join(runtime.dir, ...CLI)
192
209
  const chrome = runtime.manifest?.platforms?.[platform]?.artifacts?.find((a) => a.id === "chrome-headless-shell")
193
210
  const chromePath = chrome ? join(runtime.dir, chrome.id, chrome.entry) : null
194
- if (!existsSync(cli)) return { missing: "This Media Runtime has no HyperFrames, so captions and motion can't render. A newer runtime brings it." }
195
211
  if (!chromePath || !existsSync(chromePath)) return { missing: "This Media Runtime has no Chrome for the motion layer." }
212
+ // Without HyperFrames, Kriya draws tiles in the runtime's own Chrome, frame by frame (renderTileInChrome)
213
+ if (!existsSync(cli)) return { cli: null, chrome: chromePath, dir: runtime.dir, reads: [runtime.dir, realpathSync(join(runtime.dir, chrome.id))] }
196
214
  // The runtime's own folders, after links: all a confined render may read of it
197
215
  return { cli, chrome: chromePath, dir: runtime.dir, reads: [runtime.dir, realpathSync(join(runtime.dir, "hyperframes")), realpathSync(join(runtime.dir, chrome.id))] }
198
216
  }
@@ -207,8 +225,9 @@ export function motionEnv(work, runtime, env = process.env) {
207
225
  * @param {{ html: string, work: string, output: string, fps: { n: number, d: number }, runtime: ReturnType<typeof motionRuntime>, run?: typeof runTool, signal?: AbortSignal, which?: ReturnType<typeof confinement>, seconds?: number }} input
208
226
  * work: a folder of this tile's own; output: where the tile goes
209
227
  */
210
- export async function renderTile({ html, work, output, fps, runtime, run = runTool, signal, which = confinement(), seconds = 10 }) {
228
+ export async function renderTile({ html, work, output, fps, runtime, run = runTool, signal, which = confinement(), seconds = 10, launch }) {
211
229
  if (runtime.missing) throw new EngineFailure("environment", "missing_feature", runtime.missing)
230
+ if (!runtime.cli) return renderTileInChrome({ html, work, output, fps, runtime, run, signal, which, seconds, launch })
212
231
  const comp = join(work, "comp")
213
232
  mkdirSync(join(work, "tmp"), { recursive: true })
214
233
  mkdirSync(comp, { recursive: true })
@@ -220,6 +239,59 @@ export async function renderTile({ html, work, output, fps, runtime, run = runTo
220
239
  if (!existsSync(output)) throw new EngineFailure("render", "failed", "The motion renderer finished without writing its tile.")
221
240
  }
222
241
 
242
+ /**
243
+ * A tile without HyperFrames: the composition in the runtime's Chrome, inside the same
244
+ * sandbox, every animation paused at each frame's time and the stage captured with its
245
+ * transparency, then encoded by our FFmpeg to the same ProRes 4444 tile. The runtime
246
+ * signed for 2026.11.0 carries Chrome but not HyperFrames, so captions never rendered.
247
+ */
248
+ export async function renderTileInChrome({ html, work, output, fps, runtime, run = runTool, signal, which = confinement(), seconds = 10, launch }) {
249
+ const frames = Math.max(1, Math.round((seconds * fps.n) / fps.d))
250
+ const dir = join(work, "frames")
251
+ mkdirSync(dir, { recursive: true })
252
+ await withChrome({ work, runtime, which, launch }, async (page) => {
253
+ writeFileSync(join(work, "index.html"), html)
254
+ await page.goto(`file://${join(work, "index.html")}`)
255
+ const [width, height] = await page.evaluate(() => {
256
+ const stage = document.getElementById("stage")
257
+ return [Number(stage.dataset.width), Number(stage.dataset.height)]
258
+ })
259
+ await page.setViewportSize({ width, height })
260
+ const stage = page.locator("#stage")
261
+ for (let i = 0; i < frames; i++) {
262
+ if (signal?.aborted) throw signal.reason
263
+ await page.evaluate((t) => {
264
+ for (const animation of document.getAnimations()) {
265
+ animation.pause()
266
+ animation.currentTime = t
267
+ }
268
+ }, (i * 1000 * fps.d) / fps.n)
269
+ await stage.screenshot({ path: join(dir, `${String(i).padStart(6, "0")}.png`), omitBackground: true, animations: "allow" })
270
+ }
271
+ })
272
+ await run("ffmpeg", ["-hide_banner", "-nostdin", "-loglevel", "error", "-protocol_whitelist", "file,pipe", "-framerate", `${fps.n}/${fps.d}`, "-i", join(dir, "%06d.png"), "-c:v", "prores_ks", "-profile:v", "4444", "-pix_fmt", "yuva444p10le", "-vendor", "apl0", "-y", output], { signal, timeoutMs: 60_000 + seconds * 10_000 })
273
+ if (!existsSync(output)) throw new EngineFailure("render", "failed", "The caption renderer finished without writing its tile.")
274
+ }
275
+
276
+ /** The runtime's Chrome, started confined by playwright through a sandbox wrapper; one page. */
277
+ async function withChrome({ work, runtime, which, launch }, use) {
278
+ const { chromium } = launch ? {} : await import("playwright-core")
279
+ const open = launch ?? ((dir, options) => chromium.launchPersistentContext(dir, options))
280
+ if ([work, runtime.chrome].some((path) => path.includes("'"))) throw new EngineFailure("environment", "bad_path", "A folder name with a quote can't hold the motion layer's work.")
281
+ mkdirSync(join(work, "tmp"), { recursive: true })
282
+ // Playwright starts this script; the script starts Chrome inside the sandbox
283
+ const { args } = confine(runtime.chrome, [], { read: [...runtime.reads, work], write: [work] }, which)
284
+ writeFileSync(join(work, "chrome.sb"), args[1])
285
+ const wrapper = join(work, "chrome.sh")
286
+ writeFileSync(wrapper, `#!/bin/sh\nexec /usr/bin/sandbox-exec -f '${join(work, "chrome.sb")}' '${runtime.chrome}' "$@"\n`, { mode: 0o755 })
287
+ const context = await open(join(work, "profile"), { executablePath: wrapper, headless: true, offline: true, env: { HOME: work, TMPDIR: join(work, "tmp") } })
288
+ try {
289
+ return await use(context.pages()[0] ?? (await context.newPage()))
290
+ } finally {
291
+ await context.close()
292
+ }
293
+ }
294
+
223
295
  // HyperFrames encodes with the FFmpeg on PATH; Homebrew's lives outside the runtime (EDD-06)
224
296
  function ffmpegHome() {
225
297
  return ["/opt/homebrew", "/usr/local/Cellar", "/usr/local/opt", "/usr/local/bin"].filter((path) => existsSync(path))
@@ -238,7 +310,7 @@ function readBoxes(times) {
238
310
  const r = el.getBoundingClientRect()
239
311
  const style = getComputedStyle(el)
240
312
  const colours = new Set([style.color, ...[...el.querySelectorAll("span")].map((span) => getComputedStyle(span).color)])
241
- return { x: r.x, y: r.y, w: r.width, h: r.height, text: el.textContent, size: parseFloat(style.fontSize), colours: [...colours], plate: style.backgroundColor, clipped: el.scrollWidth > el.clientWidth + 1 || el.scrollHeight > el.clientHeight + 1 }
313
+ return { x: r.x, y: r.y, w: r.width, h: r.height, text: el.textContent, size: parseFloat(style.fontSize), colours: [...colours], plate: style.backgroundColor, stroke: style.webkitTextStrokeColor, strokeWidth: parseFloat(style.webkitTextStrokeWidth) || 0, clipped: el.scrollWidth > el.clientWidth + 1 || el.scrollHeight > el.clientHeight + 1 }
242
314
  })
243
315
  })
244
316
  }
@@ -251,9 +323,6 @@ function readBoxes(times) {
251
323
  */
252
324
  export async function measureText({ items, work, runtime, which = confinement(), launch }) {
253
325
  if (runtime.missing) throw new EngineFailure("environment", "missing_feature", runtime.missing)
254
- const { chromium } = launch ? {} : await import("playwright-core")
255
- const open = launch ?? ((dir, options) => chromium.launchPersistentContext(dir, options))
256
- if ([work, runtime.chrome].some((path) => path.includes("'"))) throw new EngineFailure("environment", "bad_path", "A folder name with a quote can't hold the motion layer's work.")
257
326
  mkdirSync(join(work, "tmp"), { recursive: true })
258
327
  const files = items.map((item, i) => {
259
328
  const dir = join(work, `c${i}`)
@@ -261,21 +330,12 @@ export async function measureText({ items, work, runtime, which = confinement(),
261
330
  writeFileSync(join(dir, "index.html"), item.html)
262
331
  return join(dir, "index.html")
263
332
  })
264
- // Playwright starts this script; the script starts Chrome inside the sandbox
265
- const { args } = confine(runtime.chrome, [], { read: [...runtime.reads, work], write: [work] }, which)
266
- writeFileSync(join(work, "chrome.sb"), args[1])
267
- const wrapper = join(work, "chrome.sh")
268
- writeFileSync(wrapper, `#!/bin/sh\nexec /usr/bin/sandbox-exec -f '${join(work, "chrome.sb")}' '${runtime.chrome}' "$@"\n`, { mode: 0o755 })
269
- const context = await open(join(work, "profile"), { executablePath: wrapper, headless: true, offline: true, env: { HOME: work, TMPDIR: join(work, "tmp") } })
270
- try {
271
- const page = context.pages()[0] ?? (await context.newPage())
333
+ return withChrome({ work, runtime, which, launch }, async (page) => {
272
334
  const out = new Map()
273
335
  for (const [i, item] of items.entries()) {
274
336
  await page.goto(`file://${files[i]}`)
275
337
  out.set(item.id, await page.evaluate(readBoxes, item.times))
276
338
  }
277
339
  return out
278
- } finally {
279
- await context.close()
280
- }
340
+ })
281
341
  }