@kriya-ai/harness 0.2.4 → 0.2.5

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.
@@ -13,6 +13,8 @@ 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
15
  import { cleanScene } from "../engine/scenes.js"
16
+ import { cleanGraphic } from "../engine/graphics.js"
17
+ import { TRANSITIONS } from "../core/transitions.js"
16
18
  import { EngineFailure } from "../engine/tool.js"
17
19
  import { activeRuntime } from "../runtime/setup.js"
18
20
  import { recogniser } from "../index/layers/words.js"
@@ -77,6 +79,8 @@ function page(res, type, body) {
77
79
  }
78
80
 
79
81
  const refuse = (res, status, message) => json(res, status, { error: status, message })
82
+ /** A plan as the Studio sends it back (one being revised, or the one just approved): bounded text and a settings object the Director re-checks. */
83
+ const cleanPlan = (plan) => (plan && typeof plan === "object" ? { say: String(plan.say ?? "").slice(0, 900), steps: Array.isArray(plan.steps) ? plan.steps.slice(0, 10).map((s) => String(s).slice(0, 240)) : [], settings: plan.settings && typeof plan.settings === "object" && !Array.isArray(plan.settings) && JSON.stringify(plan.settings).length <= 20_000 ? plan.settings : {} } : null)
80
84
 
81
85
  async function readJson(req) {
82
86
  const chunks = []
@@ -353,7 +357,7 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
353
357
  return say(200, { ...result, ...projectView(state) })
354
358
  }
355
359
  if (parts[2] === "make" && parts.length === 3 && method === "POST") {
356
- const { asset, brief } = await readJson(req)
360
+ const { asset, brief, plan } = await readJson(req)
357
361
  const clean = {}
358
362
  if (brief && typeof brief === "object") {
359
363
  if (Number.isFinite(brief.seconds) && brief.seconds >= 5 && brief.seconds <= 600) clean.targetDuration = Math.round(brief.seconds * 705_600_000)
@@ -393,6 +397,13 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
393
397
  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
398
  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
399
  }
400
+ // A transition from an approved plan: a kind from the fixed list, under the same switch
401
+ if (allowed.motion && Object.hasOwn(TRANSITIONS, brief.transition ?? "")) {
402
+ clean.transition = brief.transition
403
+ if (brief.transitionAll === true) clean.transitionAll = true
404
+ }
405
+ // Motion graphics from an approved plan, only while the server's switch is on; each cleaned to the kit's shape
406
+ if (Array.isArray(brief.graphics) && brief.graphics.length && allowed.motion) clean.graphics = brief.graphics.slice(0, 12).map(cleanGraphic).filter(Boolean)
396
407
  // Animated scenes from an approved plan, only while the server's switch is on; the recipe checks each again against the speech
397
408
  if (Array.isArray(brief.scenes) && brief.scenes.length && (await projects.features()).visuals) {
398
409
  clean.scenes = brief.scenes.slice(0, 12).map(cleanScene).filter(Boolean)
@@ -400,7 +411,12 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
400
411
  }
401
412
  }
402
413
  if (asset !== undefined && typeof asset !== "string") return refuse(res, 400, "Name the take.")
403
- return say(200, jobs.start(state, { kind: "make", ...(asset ? { asset } : {}), brief: clean }))
414
+ if (brief?.fresh === true) clean.fresh = true
415
+ // The last make's story, set here by the Host (never taken from the browser) so a replay of this job has it too
416
+ const story = projects.keptStory(state, clean)
417
+ if (story) clean.story = story
418
+ const approved = cleanPlan(plan)
419
+ return say(200, jobs.start(state, { kind: "make", ...(asset ? { asset } : {}), brief: clean, ...(approved ? { plan: approved } : {}) }))
404
420
  }
405
421
  // The person fixes a word the recogniser misheard (UX_SPEC §5)
406
422
  if (parts[2] === "words" && parts.length === 4 && method === "POST") {
@@ -427,12 +443,25 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
427
443
  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
444
  return res.end(html)
429
445
  }
446
+ // One motion graphic on the Plan Card, as the render will draw it: its own sandboxed document, no network
447
+ if (parts[2] === "graphic-preview" && parts.length === 3 && method === "GET") {
448
+ if (!(await projects.features()).motion) return refuse(res, 404, "Motion graphics aren't on.")
449
+ let graphic = null
450
+ try {
451
+ graphic = JSON.parse(url.searchParams.get("graphic") ?? "null")
452
+ } catch {
453
+ return refuse(res, 400, "That isn't a graphic.")
454
+ }
455
+ const html = projects.graphicPreview(state, graphic, url.searchParams.get("format"))
456
+ 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" })
457
+ return res.end(html)
458
+ }
430
459
  // The Director's plan: proposed in words with its settings; nothing is made here
431
460
  if (parts[2] === "plan" && parts.length === 3 && method === "POST") {
432
461
  const { text, history, previous, choices } = await readJson(req)
433
462
  if (typeof text !== "string" || !text.trim() || text.length > 2000) return refuse(res, 400, "Say what you want, in up to 2,000 characters.")
434
463
  const turns = Array.isArray(history) ? history.filter((h) => h && (h.who === "you" || h.who === "kriya") && typeof h.text === "string").slice(-6).map((h) => ({ who: h.who, text: h.text.slice(0, 400) })) : []
435
- const prior = previous && typeof previous === "object" ? { say: String(previous.say ?? "").slice(0, 900), steps: Array.isArray(previous.steps) ? previous.steps.slice(0, 10).map((s) => String(s).slice(0, 240)) : [], settings: previous.settings && typeof previous.settings === "object" ? previous.settings : {} } : null
464
+ const prior = cleanPlan(previous)
436
465
  return say(200, await projects.plan(state, { text, history: turns, previous: prior, choices: choices && typeof choices === "object" ? choices : {} }))
437
466
  }
438
467
  // A reference's classified analysis, measured once and kept
@@ -8,6 +8,7 @@
8
8
  import { apply } from "../core/ops.js"
9
9
  import { compile } from "../core/plan.js"
10
10
  import { runGates } from "../gates/index.js"
11
+ import { remapIds, remapOp, replayable } from "../director/continuity.js"
11
12
  import { planReel, recipeFor } from "../recipes/reel.js"
12
13
  import { search } from "./loop.js"
13
14
  import { repairLadder } from "./repair.js"
@@ -39,7 +40,8 @@ export function planVerdict(project, index, recipe, { engineVersion = "f0", runt
39
40
  * gateKit?: { tilePath?: Function, motion?: object, work?: string }, the Engine's tiles and Chrome, for QG-08 and QG-09
40
41
  * }} input
41
42
  */
42
- export async function makeReel({ project, head, index, asset, brief = {}, ask, render, sourcePath, signal, onStage = () => {}, run, gateKit = {}, planner = null, plannerRecipe = null }) {
43
+ export async function makeReel({ project, head, index, asset, brief = {}, ask, render, sourcePath, signal, onStage = () => {}, run, gateKit = {}, planner = null, plannerRecipe = null, edits = [] }) {
44
+ // edits: what the person did to the last cut, replayed on each candidate before it is rendered and gated
43
45
  // planner: a recipe with no variants to try (a programme, a montage), instead of the reel
44
46
  const recipe = plannerRecipe ?? recipeFor(brief)
45
47
  let calls = 0
@@ -52,7 +54,7 @@ export async function makeReel({ project, head, index, asset, brief = {}, ask, r
52
54
  calls += made.calls
53
55
  Object.assign(slots, made.slots)
54
56
  for (const note of made.notes) if (!notes.includes(note)) notes.push(note)
55
- return { ...made, variant }
57
+ return { ...carryEdits(made, edits, { before: project, index }), variant }
56
58
  }
57
59
 
58
60
  const evaluate = async (candidate) => {
@@ -94,6 +96,20 @@ export async function makeReel({ project, head, index, asset, brief = {}, ask, r
94
96
  return { best: best.start ? null : best, outcome, notes, calls, slots, head }
95
97
  }
96
98
 
99
+ /**
100
+ * The person's edits since the last make, replayed on a remade cut: each pointed at the clip
101
+ * that replaced its own, applied if it still fits and listed if it doesn't, never forced.
102
+ * @returns the candidate with those operations after its own, and `dropped`
103
+ */
104
+ export function carryEdits(made, edits, { before, index }) {
105
+ const worth = replayable(edits, before)
106
+ if (!worth.length) return made
107
+ const ids = remapIds(before, made.project, index)
108
+ const { ops, dropped } = rebase(made.project, worth.map((op) => remapOp(op, ids)), index)
109
+ const landed = ops.length ? apply(made.project, ops, { index, author: "agent" }) : null
110
+ return { ...made, ops: [...made.ops, ...ops], project: landed?.applied ? landed.project : made.project, carried: landed?.applied ? ops : [], dropped }
111
+ }
112
+
97
113
  /**
98
114
  * Lands the winner on HEAD. Unchanged HEAD: one entry. Changed: each operation is tried
99
115
  * on the new HEAD, and one that conflicts is dropped and listed, never forced.
@@ -0,0 +1,57 @@
1
+ // Graphic clips (MOTION_GRAPHICS.md): an approved plan's motion graphics as operations on the
2
+ // cut as solved. Each is anchored to its word, so it moves with the speech; code checks again
3
+ // what the plan checked, since a re-cut can drop a line or put a scene where a graphic was.
4
+
5
+ import { solve } from "../core/solver.js"
6
+ import { cleanGraphic, GRAPHIC_BLOCK, GRAPHIC_VERSION, graphicLength } from "../engine/graphics.js"
7
+ import { graphicLine } from "../director/graphics.js"
8
+
9
+ const FLICKS = 705_600_000
10
+ const MIN_LENGTH = 1.2 * FLICKS
11
+ const GAP = 0.5 * FLICKS
12
+
13
+ /** A graphic an approved plan put there, which a remake replaces (one added in chat stays). */
14
+ export const isPlanGraphic = (effect) => effect?.type === "block" && effect.blockId === GRAPHIC_BLOCK && effect.variables?.plan === true
15
+
16
+ /**
17
+ * @param {{ graphics: object[], project: object, index: object, asset: string, kept: { id: string }[] }} input
18
+ * project: with the cut and its scenes applied; kept: the words the cut keeps, in order
19
+ * @returns {{ ops: object[], notes: string[] }}
20
+ */
21
+ export function graphicOps({ graphics, project, index, asset, kept }) {
22
+ const ops = []
23
+ const notes = []
24
+ const timeline = solve(project, index)
25
+ const story = timeline.picture.filter((p) => !p.echo && !p.hold)
26
+ const outputOf = (word) => {
27
+ const piece = story.find((p) => p.asset === asset && word.start >= p.in && word.start <= p.out)
28
+ return piece ? piece.at + (word.start - piece.in) : null
29
+ }
30
+ // Whatever already takes over the frame: scenes, definitions, pictures laid over the story
31
+ const taken = timeline.overlays.map((o) => ({ at: o.at, end: o.end }))
32
+ const words = kept.map((w) => ({ ...w, out: outputOf(w) })).filter((w) => w.out !== null).sort((a, b) => a.out - b.out)
33
+ if (!words.length) return { ops, notes }
34
+ for (const raw of graphics) {
35
+ const graphic = cleanGraphic(raw)
36
+ if (!graphic) continue
37
+ const length = graphicLength(graphic)
38
+ const leave = (reason) => notes.push(`Left out the ${graphicLine(graphic)}: ${reason}.`)
39
+ // The end card starts on the last word that leaves it its full length; the opening title on the first
40
+ const word = graphic.kind === "intro" ? words[0] : graphic.kind === "end" ? (words.findLast((w) => w.out <= timeline.duration - length) ?? words[0]) : words.find((w) => w.id === graphic.at)
41
+ if (!word) {
42
+ leave("its line isn't in this cut")
43
+ continue
44
+ }
45
+ const at = word.out
46
+ const duration = Math.min(length, timeline.duration - at)
47
+ const end = at + duration
48
+ if (duration < MIN_LENGTH) leave("there isn't time for it before the cut ends")
49
+ else if (taken.some((t) => at < t.end + GAP && t.at < end + GAP)) leave("something else is on screen there")
50
+ else {
51
+ taken.push({ at, end })
52
+ const { at: _word, ...variables } = graphic
53
+ ops.push({ op: "add_motion", block: GRAPHIC_BLOCK, version: GRAPHIC_VERSION, variables: { ...variables, plan: true }, at: { word: word.id, edge: "start" }, duration })
54
+ }
55
+ }
56
+ return { ops, notes }
57
+ }
@@ -5,6 +5,8 @@
5
5
  // the lines to drop; the emphasis words), each with a default that needs no model.
6
6
 
7
7
  import { isSceneBlock } from "../core/layout.js"
8
+ import { graphicOps, isPlanGraphic } from "./graphic-clips.js"
9
+ import { TRANSITION_DEFAULT, TRANSITIONS } from "../core/transitions.js"
8
10
  import { apply } from "../core/ops.js"
9
11
  import { solve } from "../core/solver.js"
10
12
  import { LOOKS, pages, readablePages } from "../engine/captions.js"
@@ -168,7 +170,10 @@ export async function planReel({ project, index: fullIndex, asset, ask, brief =
168
170
  const scoped = { ...index, sentences: lines, words: lines.flatMap((l) => l.words), takes: [] }
169
171
 
170
172
  // Story: the hook, and the lines that add nothing (sentence ids only)
171
- const story = await ask({
173
+ // A change to a cut that's already made keeps its story (continuity.js): the Host passes the
174
+ // last make's choice, checked here against this footage, and no model is asked
175
+ const keptStory = brief.story && typeof brief.story === "object" ? { hook: ids.has(brief.story.hook) ? brief.story.hook : null, drop: (Array.isArray(brief.story.drop) ? brief.story.drop : []).filter((id) => ids.has(id)) } : null
176
+ const story = keptStory ? { value: keptStory, source: "kept", calls: 0 } : await ask({
172
177
  task: "story",
173
178
  schema: STORY_SCHEMA,
174
179
  recipe: recipe.notes,
@@ -217,7 +222,7 @@ export async function planReel({ project, index: fullIndex, asset, ask, brief =
217
222
  const rebuilt = new Set(sequence.tracks.filter((t) => ["base", "caption", "music"].includes(t.role)).map((t) => t.id))
218
223
  const ops = [
219
224
  // 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 })),
225
+ ...sequence.clips.filter((c) => rebuilt.has(c.track) || c.effects?.some((e) => isSceneBlock(e) || isPlanGraphic(e))).map((c) => ({ op: "ripple_delete", clip: c.id })),
221
226
  { op: "set_brief", format: recipe.id, targetDuration: target, mustKeep: brief.mustKeep ?? [], mustCut: brief.mustCut ?? [], effort: brief.effort ?? "best", ...(brief.language ? { language: brief.language } : {}) },
222
227
  { op: "set_format", width: recipe.canvas.width, height: recipe.canvas.height, fps: recipe.deliverable.fps },
223
228
  ...(project.deliverables.some((d) => d.preset === recipe.deliverable.preset) ? [] : [{ op: "add_deliverable", ...deliverableFor(brief) }]),
@@ -242,9 +247,16 @@ export async function planReel({ project, index: fullIndex, asset, ask, brief =
242
247
  // The approved plan's scenes, on the cut as solved. A zoom or title under one would never be seen
243
248
  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
249
  notes.push(...scenes.notes)
250
+ // The approved plan's motion graphics (MOTION_GRAPHICS.md), placed on the cut with its scenes in, so none lands on one
251
+ const withScenes = scenes.ops.length ? apply(step.project, scenes.ops, { index, author: "agent" }) : null
252
+ const graphics = brief.graphics?.length ? graphicOps({ graphics: brief.graphics, project: withScenes?.applied ? withScenes.project : step.project, index, asset, kept }) : { ops: [], notes: [] }
253
+ notes.push(...graphics.notes)
245
254
  const visible = kept.filter((w) => !scenes.covered.has(w.id))
246
255
  const keptIds = new Set(visible.map((w) => w.id))
247
- const emphasis = await ask({
256
+ // The same words stay punched in while the plan asks for as many as before
257
+ const was = keptStory && brief.story.emphasis
258
+ const keptWords = was && was.most === most && Array.isArray(was.ids) ? was.ids.filter((id) => keptIds.has(id)) : null
259
+ const emphasis = keptWords ? { value: { emphasis: keptWords }, source: "kept", calls: 0 } : await ask({
248
260
  task: "emphasis",
249
261
  schema: EMPHASIS_SCHEMA,
250
262
  recipe: recipe.notes,
@@ -325,8 +337,27 @@ export async function planReel({ project, index: fullIndex, asset, ask, brief =
325
337
  const music = song ? [{ op: "set_music", asset: song.id }, { op: "music_shape", fit: true, fadeIn: Math.round(FLICKS * 0.3) }, { op: "duck" }] : []
326
338
  const captionLook = { ...(brief.captionStyle ?? {}), ...(brief.holdCaptions ? { hold: true } : {}) }
327
339
  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]
340
+ // Transitions (transitions.js): where the story changes moment (out of the cold open, a line moved
341
+ // up, a jump of seconds in the take), or on every cut when the person asked. A filler cut stays a cut
342
+ const joins = []
343
+ if (Object.hasOwn(TRANSITIONS, brief.transition ?? "")) {
344
+ const SECTION = 3 * FLICKS
345
+ // The story as it plays: each clip's stretch of the take, in order (a clip's own source is word anchors)
346
+ const played = []
347
+ for (const p of solve(step.project, index).picture) {
348
+ if (p.hold) continue
349
+ if (played.at(-1)?.clip === p.clip) played.at(-1).out = p.out
350
+ else played.push({ clip: p.clip, asset: p.asset, in: p.in, out: p.out, echo: !!p.echo })
351
+ }
352
+ for (let i = 1; i < played.length; i++) {
353
+ const [a, b] = [played[i - 1], played[i]]
354
+ const moment = a.echo !== b.echo || a.asset !== b.asset || b.in < a.out || b.in - a.out > SECTION
355
+ if (brief.transitionAll || moment) joins.push({ op: "transition", clip: b.clip, kind: brief.transition, duration: TRANSITION_DEFAULT })
356
+ }
357
+ if (!joins.length) notes.push(`No ${brief.transition} transition: this cut runs straight through, with no change of moment to dress.`)
358
+ }
359
+ const all = [...ops, ...style, ...angles, ...punches, ...framing, ...grading, ...cleaning, ...broll, ...titles, ...scenes.ops, ...graphics.ops, ...captions, ...music, ...sounds, ...ramps, ...joins]
329
360
  step = apply(project, all, { index, author: "agent" })
330
361
  if (!step.applied) throw new Error(`The reel was refused: ${step.diagnostics[0].message}`)
331
- return { ops: all, project: step.project, notes, calls, slots }
362
+ return { ops: all, project: step.project, notes, calls, slots, story: { hook: story.value.hook ?? null, drop: story.value.drop ?? [], emphasis: { most, ids: [...new Set(emphasis.value.emphasis)].slice(0, most) } } }
332
363
  }
@@ -7,14 +7,15 @@ import { openManifest, RuntimeError, TRUSTED_KEYS } from "./manifest.js"
7
7
  /**
8
8
  * What this Kriya has switched on for editing (EH-01). Any failure, a server with no such
9
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 }>}
10
+ * @returns {Promise<{ visuals: boolean, playbooks: boolean, mediaSearch: boolean, motion: boolean, customMotion: boolean }>}
11
11
  */
12
12
  export async function fetchFeatures(device) {
13
13
  try {
14
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 }
15
+ // motion, customMotion: a server from before them says nothing, which is off
16
+ return { visuals: found?.visuals === true, playbooks: found?.playbooks === true, mediaSearch: found?.mediaSearch === true, motion: found?.motion === true, customMotion: found?.customMotion === true }
16
17
  } catch {
17
- return { visuals: false, playbooks: false, mediaSearch: false }
18
+ return { visuals: false, playbooks: false, mediaSearch: false, motion: false, customMotion: false }
18
19
  }
19
20
  }
20
21
 
@@ -232,12 +232,13 @@ a { color: var(--teal); }
232
232
  .scene-head .field { width: auto; }
233
233
  .scene-info .field { width: auto; flex: 1 1 140px; min-width: 0; }
234
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; }
235
+ /* A wide (16:9) preview and its controls don't fit side by side on a phone: the controls drop under it */
236
+ .proposal .scene-row { display: flex; flex-wrap: wrap; gap: 10px; align-items: flex-start; justify-content: flex-start; }
236
237
  .found-thumb { flex: none; width: 120px; height: 90px; object-fit: cover; border-radius: 6px; background: #000; }
237
238
  .scenes .row .field { width: auto; flex: 1 1 120px; min-width: 0; }
238
239
  .scene-picture { flex: none; overflow: hidden; border-radius: 6px; background: #000; }
239
240
  .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 { min-width: 0; flex: 1 1 140px; display: grid; gap: 4px; }
241
242
  .scene-info p { margin: 0; overflow-wrap: anywhere; }
242
243
  .scene-info .row { flex-wrap: wrap; gap: 6px; }
243
244
  .scene-time { font-family: ui-monospace, "JetBrains Mono", monospace; color: var(--teal); }