@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.
@@ -7,9 +7,9 @@ again from Kriya and update the hash below in the same change.
7
7
 
8
8
  | Field | Value |
9
9
  | --- | --- |
10
- | Copied | 2026-11-09 (again: `GET /editing/features`, for the visual scenes) |
11
- | From | Kriya repository `main` (uncommitted) on `a2bb6ed` |
12
- | sha256 | `8bf16886bc6b98bda3f261c9a762c7424324e9a893f5a50ff12f77c4b71ed754` |
10
+ | Copied | 2026-11-10 (again: `motion` and `customMotion` in `GET /editing/features`, for the motion kit) |
11
+ | From | Kriya repository `main` (uncommitted) on `3a0c769` |
12
+ | sha256 | `b6fa9d2424249e8fd9e8b3ab806f7178ef5977bbd4b9d11f12ef85b385f0d6fb` |
13
13
 
14
14
  When the Kriya side commits the file, replace "From" with that commit.
15
15
  `tests/contract.test.js` checks the hash, so a hand edit fails.
@@ -802,9 +802,15 @@
802
802
  },
803
803
  "mediaSearch": {
804
804
  "type": "boolean"
805
+ },
806
+ "motion": {
807
+ "type": "boolean"
808
+ },
809
+ "customMotion": {
810
+ "type": "boolean"
805
811
  }
806
812
  },
807
- "required": ["visuals", "playbooks", "mediaSearch"],
813
+ "required": ["visuals", "playbooks", "mediaSearch", "motion", "customMotion"],
808
814
  "additionalProperties": false
809
815
  }
810
816
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kriya-ai/harness",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
4
4
  "description": "Kriya Harness (beta): a Kriya agent on your machine, built on DeepSeek Harness",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -2,6 +2,7 @@
2
2
  // for spawn, never a shell string. Text passes through one tested escape.
3
3
 
4
4
  import { secondsArg } from "./time.js"
5
+ import { TRANSITIONS } from "./transitions.js"
5
6
 
6
7
  const BT709 = ["-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-color_range", "tv"]
7
8
  // On the frames too: FFmpeg can drop the output flags alone when it converts a format
@@ -145,7 +146,24 @@ export function segmentArgs(plan, segment, { input, tile, output, encoder, toneM
145
146
  const chains = []
146
147
 
147
148
  const labels = node.picture.map((item, i) => {
148
- chains.push(`[${inputFor(input(item.asset), item.in)}:v]${pictureChain(item, width, height, plan, { input, toneMap })}[p${i}]`)
149
+ const chain = `[${inputFor(input(item.asset), item.in)}:v]${pictureChain(item, width, height, plan, { input, toneMap })}`
150
+ if (!item.enter) {
151
+ chains.push(`${chain}[p${i}]`)
152
+ return `[p${i}]`
153
+ }
154
+ // A transition in (transitions.js): the piece before, held on its last frame, under this
155
+ // piece's first moments; then the rest of the piece. Its length is the piece's own, so the cut doesn't move
156
+ const { kind, duration, from } = item.enter
157
+ if (!Object.hasOwn(TRANSITIONS, kind)) throw new RangeError(`this render can't do a "${kind}" transition`)
158
+ const length = secondsArg(duration)
159
+ // xfade needs both sides alike: one frame rate, one pixel format, one time base
160
+ const alike = `${filter("fps", { fps: `${plan.output.fps.n}/${plan.output.fps.d}` })},format=yuv420p,settb=AVTB`
161
+ chains.push(`${chain},${alike},split[ph${i}][pt${i}]`)
162
+ chains.push(`[${inputFor(input(from.asset), from.in)}:v]${pictureChain(from, width, height, plan, { input, toneMap })},${alike}[pf${i}]`)
163
+ chains.push(`[ph${i}]${filter("trim", { end: length })},setpts=PTS-STARTPTS[pa${i}]`)
164
+ chains.push(`[pf${i}][pa${i}]${filter("xfade", { transition: TRANSITIONS[kind], duration: length, offset: 0 })}[px${i}]`)
165
+ chains.push(`[pt${i}]${filter("trim", { start: length })},setpts=PTS-STARTPTS[pb${i}]`)
166
+ chains.push(`[px${i}][pb${i}]concat=n=2:v=1:a=0,setsar=1,${TAG_BT709}[p${i}]`)
149
167
  return `[p${i}]`
150
168
  })
151
169
  let current = labels[0]
@@ -3,6 +3,7 @@
3
3
  // no inverse per operation: history moves HEAD and replays (history.js).
4
4
 
5
5
  import { anchorSource, openIndex, wordAfter, wordAt, wordBefore } from "./anchors.js"
6
+ import { TRANSITION_MAX, TRANSITION_MIN, TRANSITIONS } from "./transitions.js"
6
7
  import { check, EFFECTS, SHAPES, validateProject } from "./project.js"
7
8
  import { snapToFrame } from "./time.js"
8
9
 
@@ -366,7 +367,11 @@ const OPS = {
366
367
  transition: {
367
368
  fields: { clip: "id", kind: "str", duration: "flicks" },
368
369
  run(op, s) {
369
- setEffect(writable(s, op.clip), { type: "transition", kind: op.kind, duration: op.duration })
370
+ if (!Object.hasOwn(TRANSITIONS, op.kind)) refuse("unknown_transition", `there is no "${op.kind}" transition: ${Object.keys(TRANSITIONS).join(", ")}`)
371
+ if (op.duration < TRANSITION_MIN || op.duration > TRANSITION_MAX) refuse("bad_duration", "a transition lasts 0.2 to 0.8 seconds")
372
+ const clip = writable(s, op.clip)
373
+ if (!clip.source) refuse("not_footage", `clip "${op.clip}" isn't footage, so nothing can transition into it`)
374
+ setEffect(clip, { type: "transition", kind: op.kind, duration: op.duration })
370
375
  },
371
376
  },
372
377
  stabilize: {
@@ -7,11 +7,12 @@ import { outputFaces, unionBox } from "./faces.js"
7
7
  import { canonical, sha256 } from "./project.js"
8
8
  import { solveReframe } from "./reframe.js"
9
9
  import { solve } from "./solver.js"
10
- import { flicksToFrames, FLICKS, framesToFlicks, scaleFlicks, snapToFrame } from "./time.js"
10
+ import { flicksToFrames, FLICKS, frameFlicks, framesToFlicks, scaleFlicks, snapToFrame } from "./time.js"
11
11
 
12
12
  const MAX_SEGMENT = 6 * FLICKS
13
13
  const DRAFT_SHORT_SIDE = 720
14
- const PICTURE_EFFECTS = new Set(["reframe", "grade", "lut", "stabilize", "transition", "fade"])
14
+ // A transition isn't an effect on the piece's own frames: it becomes the piece's `enter` below
15
+ const PICTURE_EFFECTS = new Set(["reframe", "grade", "lut", "stabilize", "fade"])
15
16
  const AUDIO_EFFECTS = new Set(["level", "eq", "duck", "fade", "fit"])
16
17
 
17
18
  const even = (value) => Math.round(value / 2) * 2
@@ -72,6 +73,14 @@ function zoomNode(zoom, start) {
72
73
  return node
73
74
  }
74
75
 
76
+ // The crop's x at one moment of a path: the same straight lines ffmpeg.js draws between its points
77
+ function cropAt(path, t) {
78
+ const after = path.findIndex((point) => point.t >= t)
79
+ if (after <= 0) return path[after === 0 ? 0 : path.length - 1].x
80
+ const [a, b] = [path[after - 1], path[after]]
81
+ return Math.round(a.x + ((b.x - a.x) * (t - a.t)) / (b.t - a.t))
82
+ }
83
+
75
84
  function boundaries(timeline, rawIndex, fps) {
76
85
  const cuts = new Set([0, timeline.duration])
77
86
  for (const piece of timeline.picture) {
@@ -207,6 +216,26 @@ export function compile(project, rawIndex, { engineVersion, runtimeVersion, qual
207
216
  const hidden = (tile) => tile.node.behind === true && mattes.some((m) => m.at <= tile.at && tile.end <= m.end)
208
217
  for (const tile of tiles) if (tile.node.behind && !hidden(tile)) tile.front = true
209
218
 
219
+ // A transition into a piece (transitions.js): the piece before it, frozen on its last frame and
220
+ // dressed as it was, for the incoming piece to arrive over. Only in the segment the piece starts
221
+ // in, never longer than half the piece or than that segment less two frames, so the cut stays put
222
+ const frame = frameFlicks(project.canvas.fps)
223
+ const enterOf = (piece, start, end) => {
224
+ const asked = piece.effects.find((e) => e.type === "transition")
225
+ if (!asked || piece.hold || piece.at !== start) return null
226
+ const before = timeline.picture.find((p) => p !== piece && p.end === piece.at)
227
+ if (!before) return null
228
+ const duration = snapToFrame(Math.min(asked.duration, Math.floor((piece.end - piece.at) / 2), end - start - 2 * frame), project.canvas.fps, "floor")
229
+ if (duration < 2 * frame) return null
230
+ const last = before.hold ? before.in : Math.max(before.in, before.out - scaleFlicks(frame, before.speed))
231
+ const path = crops.get(before.clip)
232
+ const color = sourceColor(before.asset)
233
+ // shortcut: a punch-in still on at the cut is kept only when it's a plain centred one; an eased or focused zoom is left off the held frame
234
+ const zoom = timeline.zooms.find((z) => z.at < piece.at && piece.at <= z.end && z.x === undefined && z.ease !== "smooth")
235
+ const from = { asset: before.asset, in: last, out: before.out, at: 0, end: duration, speed: { n: 1, d: 1 }, hold: true, effects: only(resolved(before), PICTURE_EFFECTS), ...(path ? { crop: [{ t: last, x: cropAt(path, last) }] } : {}), ...(zoom ? { zoom: zoomNode(zoom, start) } : {}), ...(color ? { color } : {}) }
236
+ return { kind: asked.kind, duration, from }
237
+ }
238
+
210
239
  const segments = boundaries(timeline, rawIndex, project.canvas.fps).map(([start, end], i) => {
211
240
  const picture = timeline.picture.filter(during(start, end)).map((piece) => {
212
241
  const part = clipped(piece, start, end)
@@ -214,7 +243,8 @@ export function compile(project, rawIndex, { engineVersion, runtimeVersion, qual
214
243
  const path = crops.get(piece.clip)
215
244
  const crop = path ? cropFor(path, part, (rawIndex.shots ?? []).filter((s) => s.asset === piece.asset).map((s) => s.start)) : undefined
216
245
  const zoom = timeline.zooms.find(during(start, end))
217
- return { ...part, ...(piece.hold ? { hold: true } : {}), effects: only(resolved(piece), PICTURE_EFFECTS), ...(crop ? { crop } : {}), ...(zoom ? { zoom: zoomNode(zoom, start) } : {}), ...(color ? { color } : {}) }
246
+ const enter = enterOf(piece, start, end)
247
+ return { ...part, ...(piece.hold ? { hold: true } : {}), effects: only(resolved(piece), PICTURE_EFFECTS), ...(crop ? { crop } : {}), ...(zoom ? { zoom: zoomNode(zoom, start) } : {}), ...(color ? { color } : {}), ...(enter ? { enter } : {}) }
218
248
  })
219
249
  const overlays = footage.filter(during(start, end)).map((overlay) => ({ ...clipped(overlay, start, end), effects: only(overlay.effects, PICTURE_EFFECTS) }))
220
250
  const node = {
@@ -224,7 +254,7 @@ export function compile(project, rawIndex, { engineVersion, runtimeVersion, qual
224
254
  ...(mattes.some(during(start, end)) ? { mattes: mattes.filter(during(start, end)).map((m) => ({ at: m.at - start, end: m.end - start, box: m.box })) } : {}),
225
255
  }
226
256
  const luts = picture.flatMap((item) => item.effects.filter((e) => e.type === "lut").map((e) => e.asset))
227
- return { id: `s${i}`, start, end, key: key(node, [...picture.map((item) => item.asset), ...overlays.map((item) => item.asset), ...luts]), node }
257
+ return { id: `s${i}`, start, end, key: key(node, [...picture.flatMap((item) => [item.asset, ...(item.enter ? [item.enter.from.asset] : [])]), ...overlays.map((item) => item.asset), ...luts]), node }
228
258
  })
229
259
 
230
260
  issues.push(...crowdedEffects(timeline.audio))
@@ -0,0 +1,17 @@
1
+ // Transitions (MOTION_GRAPHICS.md §6): how one clip arrives over the last frame of the one
2
+ // before it. The cut never moves: the outgoing clip's last frame is held underneath while the
3
+ // incoming clip comes in over its own first moments, so the sound, the captions and every
4
+ // word anchor stay where they were. The kinds are a fixed list; code names the FFmpeg
5
+ // transition, a model never does.
6
+
7
+ const FLICKS = 705_600_000
8
+
9
+ /** What a person or the Director may ask for → FFmpeg's xfade transition. */
10
+ export const TRANSITIONS = { fade: "fade", dip: "fadeblack", flash: "fadewhite", wipe: "wipeleft", slide: "slideleft", zoom: "zoomin" }
11
+ export const TRANSITION_LABELS = { fade: "Fade", dip: "Dip to black", flash: "Flash", wipe: "Wipe", slide: "Slide", zoom: "Zoom" }
12
+ export const TRANSITION_MIN = Math.round(0.2 * FLICKS)
13
+ export const TRANSITION_MAX = Math.round(0.8 * FLICKS)
14
+ export const TRANSITION_DEFAULT = Math.round(0.3 * FLICKS)
15
+
16
+ /** A length inside the allowed range; anything else is the default. */
17
+ export const transitionLength = (duration) => (Number.isSafeInteger(duration) ? Math.min(TRANSITION_MAX, Math.max(TRANSITION_MIN, duration)) : TRANSITION_DEFAULT)
@@ -0,0 +1,129 @@
1
+ // A change asked for after a cut exists is a change to that cut (2026-11-10): the Director
2
+ // revises the plan it made, the story stays unless the length or the trims change, and the
3
+ // person's own edits since are replayed on the remade cut. Pure: the Host keeps the record.
4
+
5
+ import { solve } from "../core/solver.js"
6
+
7
+ // The plan sets these on every make, so an older one isn't carried over it
8
+ const PLANS_OWN = new Set(["set_brief", "set_format", "add_deliverable", "name_version"])
9
+
10
+ /**
11
+ * The operations landed after a version, oldest first: what the person (or the console, on
12
+ * their accepting) did to the cut since it was made.
13
+ * @returns {object[] | null} null when HEAD doesn't descend from that version (the make was undone)
14
+ */
15
+ export function editsSince(log, head) {
16
+ const byId = new Map(log.entries.map((e) => [e.id, e]))
17
+ const chain = []
18
+ for (let at = log.head; at !== head; at = byId.get(at).parent) {
19
+ if (at === null || !byId.has(at)) return null
20
+ chain.unshift(byId.get(at))
21
+ }
22
+ return chain.flatMap((e) => e.ops).filter((op) => !PLANS_OWN.has(op.op))
23
+ }
24
+
25
+ /** The last make's story, when this brief cuts the same footage to the same length; else null and it's chosen again. */
26
+ export function storyFor(last, brief = {}) {
27
+ if (!last?.story || !last.brief) return null
28
+ const same = last.brief.targetDuration === brief.targetDuration && JSON.stringify(last.brief.cuts ?? []) === JSON.stringify(brief.cuts ?? [])
29
+ return same ? last.story : null
30
+ }
31
+
32
+ /**
33
+ * Where each clip of the cut before went in the remade one (a remake gives every clip a new
34
+ * id): a caption by its first word, footage by its track and the most source time it shares.
35
+ * A clip's own source is word anchors, so the times come from the solved timelines.
36
+ * @returns {Map<string, string>}
37
+ */
38
+ export function remapIds(before, after, index) {
39
+ const clipsOf = (project) => project.sequences.find((q) => q.id === project.active)?.clips ?? []
40
+ const caption = (clip) => clip.effects?.find((e) => e.type === "caption")
41
+ // Each footage clip's stretch of its source, as played: asset, first in, last out
42
+ const spans = (project) => {
43
+ const out = new Map()
44
+ for (const p of solve(project, index).picture) {
45
+ if (p.hold) continue
46
+ const span = out.get(p.clip)
47
+ if (span) Object.assign(span, { in: Math.min(span.in, p.in), out: Math.max(span.out, p.out) })
48
+ else out.set(p.clip, { asset: p.asset, in: p.in, out: p.out, echo: !!p.echo })
49
+ }
50
+ return out
51
+ }
52
+ const [was, now] = [spans(before), spans(after)]
53
+ const next = clipsOf(after)
54
+ const ids = new Map()
55
+ for (const old of clipsOf(before)) {
56
+ if (next.some((c) => c.id === old.id)) continue // it survived the remake as it is
57
+ const words = caption(old)?.words
58
+ let found = null
59
+ if (words?.length) found = next.find((c) => caption(c)?.words?.[0] === words[0])?.id ?? null
60
+ else if (was.has(old.id)) {
61
+ const a = was.get(old.id)
62
+ let most = 0
63
+ for (const [id, b] of now) {
64
+ if (b.asset !== a.asset || b.echo !== a.echo || clipsOf(after).find((c) => c.id === id)?.track !== old.track) continue
65
+ const shared = Math.min(a.out, b.out) - Math.max(a.in, b.in)
66
+ if (shared > most) ((most = shared), (found = id))
67
+ }
68
+ }
69
+ if (found) ids.set(old.id, found)
70
+ }
71
+ return ids
72
+ }
73
+
74
+ // What a remake undoes: edits to the picture, the captions and the voice, which it rebuilds.
75
+ // A title, a graphic, B-roll, a marker or a sound sits on its own track and is still there, so
76
+ // replaying it would put it on screen twice; the music and the opening are the plan's to set
77
+ const REMADE = new Set(["keep_range", "remove_range", "use_take", "reorder", "trim", "split", "ripple_delete", "punch_in", "reframe", "speed", "speed_ramp", "freeze", "stabilize", "set_camera", "caption_style", "caption_edit", "caption_emphasis", "text_behind", "transition", "clean_voice", "set_level", "grade", "match_color", "apply_lut", "fix_exposure"])
78
+
79
+ /**
80
+ * The edits worth replaying on a remade cut: those the remake undid. One aimed at a clip
81
+ * that was already gone before the remake has nothing left to do, and is left out quietly.
82
+ */
83
+ export function replayable(edits, before) {
84
+ const there = new Set((before.sequences.find((q) => q.id === before.active)?.clips ?? []).map((c) => c.id))
85
+ return edits.filter((op) => REMADE.has(op.op) && ["clip", "caption"].every((key) => typeof op[key] !== "string" || there.has(op[key])))
86
+ }
87
+
88
+ /** An operation pointed at the remade cut's clips. */
89
+ export function remapOp(op, ids) {
90
+ const out = { ...op }
91
+ for (const key of ["clip", "caption", "after"]) if (typeof out[key] === "string" && ids.has(out[key])) out[key] = ids.get(out[key])
92
+ return out
93
+ }
94
+
95
+ const count = (noun) => (list) => (list?.length ? `${list.length} ${noun}${list.length === 1 ? "" : "s"}` : "none")
96
+ const onOff = (value) => (value ? "on" : "off")
97
+ const plain = (value) => (value === undefined || value === null || value === false || value === "" ? "none" : String(value))
98
+ const LINES = [
99
+ ["format", "Format", plain],
100
+ ["seconds", "Length", (v) => (v ? `${v} s` : "the recipe's")],
101
+ ["captions", "Captions", plain],
102
+ ["grade", "Colour look", plain],
103
+ ["music", "Music", (v) => plain(v).replace(/^generated:/, "")],
104
+ ["cleanVoice", "Voice cleanup", onOff],
105
+ ["hook", "Hook line", (v) => (v ? "chosen" : "none")],
106
+ ["coldOpen", "Cold open", (v) => (v ? `${v.from} to ${v.to}` : "none")],
107
+ ["cutSound", "Sound on cuts", plain],
108
+ ["introSound", "Sound into the story", plain],
109
+ ["punches", "Punch-ins", plain],
110
+ ["angles", "Wide and tight angles", onOff],
111
+ ["broll", "B-roll", plain],
112
+ ["titles", "Title cards", onOff],
113
+ ["ramps", "Speed ramp", onOff],
114
+ ["cuts", "Trims", count("stretch")],
115
+ ["scenes", "Animated scenes", count("scene")],
116
+ ["graphics", "Motion graphics", count("graphic")],
117
+ ["transition", "Transitions", plain],
118
+ ["transitionAll", "Transitions on every cut", onOff],
119
+ ["pictures", "Pictures", count("picture")],
120
+ ["terms", "Definitions", count("definition")],
121
+ ]
122
+
123
+ /** What a revised plan changes, in words, from the two briefs alone: never from a model's pitch. */
124
+ export function planDiff(before = {}, after = {}) {
125
+ return LINES.flatMap(([key, label, show]) => {
126
+ const [was, now] = [show(before[key]), show(after[key])]
127
+ return was === now && JSON.stringify(before[key]) === JSON.stringify(after[key]) ? [] : was === now ? [`${label}: changed`] : [`${label}: ${was} → ${now}`]
128
+ })
129
+ }
@@ -0,0 +1,152 @@
1
+ // The Director's motion graphics (MOTION_GRAPHICS.md, EDD-58): it proposes titles, a name
2
+ // strap, an opening title, an end card, quotes and numbers from the motion kit; code decides
3
+ // what may be shown. Words on screen are the speaker's or the person's own typed words, never
4
+ // the model's; a number is one that was said. Nothing here writes code or draws: the kit does.
5
+
6
+ import { cleanGraphic, GRAPHIC_ACCENTS, GRAPHIC_FONTS, GRAPHIC_KINDS, GRAPHIC_TONES, graphicLength, SUBTITLE_MAX, TEXT_MAX } from "../engine/graphics.js"
7
+ import { paperEdit } from "../index/views.js"
8
+ import { groundProblems } from "./beats.js"
9
+
10
+ const FLICKS = 705_600_000
11
+ export const MAX_GRAPHICS = 8
12
+ const GAP = 1 * FLICKS // the frame rests between graphics
13
+ const NEAR = 6 * FLICKS // a number is "said here" within this of the graphic
14
+ const ONCE = new Set(["intro", "end", "lower"])
15
+ const ID = { type: "string", maxLength: 64 }
16
+
17
+ export const GRAPHICS_SCHEMA = {
18
+ type: "object",
19
+ properties: {
20
+ graphics: {
21
+ type: "array",
22
+ maxItems: 12,
23
+ items: {
24
+ type: "object",
25
+ properties: { kind: { type: "string", enum: Object.keys(GRAPHIC_KINDS) }, style: { type: "string", maxLength: 16 }, text: { type: "string", maxLength: TEXT_MAX }, subtitle: { type: "string", maxLength: SUBTITLE_MAX }, at: ID },
26
+ required: ["kind", "text"],
27
+ additionalProperties: false,
28
+ },
29
+ },
30
+ },
31
+ required: ["graphics"],
32
+ additionalProperties: false,
33
+ }
34
+
35
+ // "no graphics", "without titles" turn them off; naming one asks for them
36
+ const OFF = /\b(?:no|without|skip|remove (?:the|all)(?: the)?|drop the)\s+(?:any\s+)?(?:motion[- ])?(?:graphics?|titles?|text on screen|lower[- ]thirds?|name straps?)\b/i
37
+ const ON = /\b(?:motion[- ]graphics?|graphics|lower[- ]thirds?|name (?:strap|tag|card)|end ?card|outro|intro(?:duction)? (?:title|card)|opening title|title cards?|chapter (?:cards?|titles?)|animated (?:titles?|text)|kinetic)\b/i
38
+
39
+ /** What the person's words say about motion graphics: "on", "off" or null. */
40
+ export const graphicsIn = (text) => (OFF.test(String(text ?? "")) ? "off" : ON.test(String(text ?? "")) ? "on" : null)
41
+
42
+ /** The brand kit in the person's words: a colour, a tone, a font. Code reads it; hex stays in code. */
43
+ export function brandIn(text) {
44
+ const said = String(text ?? "")
45
+ const out = {}
46
+ const accent = Object.keys(GRAPHIC_ACCENTS).find((name) => new RegExp(`\\b${name}\\b[^.]{0,24}\\b(?:graphics?|titles?|accent|brand|colou?r)|\\b(?:accent|brand|colou?r)\\b[^.]{0,16}\\b${name}\\b`, "i").test(said))
47
+ if (accent) out.accent = accent
48
+ if (/\blight (?:graphics?|titles?|plates?|cards?)\b/i.test(said)) out.tone = "light"
49
+ else if (/\bdark (?:graphics?|titles?|plates?|cards?)\b/i.test(said)) out.tone = "dark"
50
+ const font = Object.keys(GRAPHIC_FONTS).find((name) => new RegExp(`\\b${name}(?:[- ]?serif)?\\b[^.]{0,12}\\b(?:font|type|titles?|text)\\b`, "i").test(said))
51
+ if (font) out.font = /\bsans\b/i.test(said) && font === "serif" ? "sans" : font
52
+ return out
53
+ }
54
+
55
+ /**
56
+ * Why a graphic's words can't be shown; empty when they can. Every word is the speaker's or
57
+ * one the person typed, and a number is said near the graphic or typed by the person.
58
+ * @param {object} graphic from cleanGraphic
59
+ * @param {{ spoken: string, near: string, person: string }} said the take's words, those around the graphic, and the person's own messages
60
+ */
61
+ export function graphicProblems(graphic, { spoken, near, person }) {
62
+ return groundProblems({ title: graphic.text, items: graphic.subtitle ? [{ text: graphic.subtitle }] : [] }, { all: `${spoken} ${person}`, near: `${near} ${person}` })
63
+ }
64
+
65
+ /**
66
+ * The graphics a cut can carry, in the order they play: each cleaned, grounded, on a word that
67
+ * is still in the take, clear of the scenes and of each other. The opening title sits on the
68
+ * first word and the end card on the end; one of each, and one name strap.
69
+ * @param {object[]} raw
70
+ * @param {{ index: object, asset: string, cuts?: { from: number, to: number }[], person?: string, scenes?: { from: string, to: string }[], brand?: object, limit?: number }} context cuts in seconds of the take
71
+ * @returns {{ graphics: object[], dropped: { graphic: object, reason: string }[] }}
72
+ */
73
+ export function arrangeGraphics(raw, { index, asset, cuts = [], person = "", scenes = [], brand = {}, limit = MAX_GRAPHICS }) {
74
+ const trimmed = (w) => cuts.some((c) => (w.start + w.end) / 2 >= c.from * FLICKS && (w.start + w.end) / 2 < c.to * FLICKS)
75
+ const words = (index.words ?? []).filter((w) => w.asset === asset && !trimmed(w))
76
+ const byId = new Map(words.map((w) => [w.id, w]))
77
+ const spoken = words.map((w) => w.text).join(" ")
78
+ const under = scenes.map((s) => [byId.get(s.from), byId.get(s.to)]).filter(([a, b]) => a && b).map(([a, b]) => ({ start: a.start, end: b.end }))
79
+ const graphics = []
80
+ const dropped = []
81
+ const once = new Set()
82
+ const candidates = (Array.isArray(raw) ? raw : []).map((item) => cleanGraphic({ ...item, ...brand })).filter(Boolean)
83
+ // Where each starts in the take: the opening title first, the end card last
84
+ const placed = candidates.map((graphic) => ({ graphic, word: graphic.kind === "intro" ? words[0] : graphic.kind === "end" ? words.at(-1) : byId.get(graphic.at) }))
85
+ const order = (p) => (p.graphic.kind === "intro" ? -Infinity : p.graphic.kind === "end" ? Infinity : (p.word?.start ?? 0))
86
+ let free = -Infinity
87
+ for (const { graphic, word } of placed.sort((a, b) => order(a) - order(b))) {
88
+ const drop = (reason) => dropped.push({ graphic, reason })
89
+ if (!word) drop("it isn't on a word of this take")
90
+ else if (ONCE.has(graphic.kind) && once.has(graphic.kind)) drop(`there is already ${graphic.kind === "end" ? "an end card" : graphic.kind === "intro" ? "an opening title" : "a name strap"}`)
91
+ else if (graphics.length >= limit) drop("that is more graphics than this cut can carry")
92
+ else {
93
+ const edge = graphic.kind === "intro" || graphic.kind === "end"
94
+ const near = edge ? spoken : words.filter((w) => w.end >= word.start - NEAR && w.start <= word.start + NEAR).map((w) => w.text).join(" ")
95
+ const problems = graphicProblems(graphic, { spoken, near, person })
96
+ if (problems.length) drop(problems[0])
97
+ else if (!edge && under.some((s) => word.start >= s.start && word.start < s.end)) drop("an animated scene is on screen there")
98
+ else if (!edge && word.start < free) drop("another graphic is still on screen there")
99
+ else {
100
+ once.add(graphic.kind)
101
+ if (!edge) free = word.start + graphicLength(graphic) + GAP
102
+ const { at: _from, ...rest } = graphic
103
+ graphics.push(edge ? rest : { ...rest, at: word.id })
104
+ }
105
+ }
106
+ }
107
+ return { graphics, dropped }
108
+ }
109
+
110
+ /**
111
+ * The graphics for a plan. The person's words come first: "no graphics" means none and no
112
+ * call. A revision that doesn't mention them keeps the ones on the card, restyled if a colour
113
+ * or font was asked for.
114
+ * @returns {Promise<{ graphics: object[], source: string, dropped: object[] }>}
115
+ */
116
+ export async function planGraphics({ ask, index, asset, text, history = [], previous = null, cuts = [], scenes = [], signal }) {
117
+ const said = [...history.filter((h) => h.who === "you").map((h) => h.text), text]
118
+ const person = said.join("\n")
119
+ const verdict = said.map(graphicsIn).filter(Boolean).at(-1) ?? null
120
+ if (verdict === "off") return { graphics: [], source: "person", dropped: [] }
121
+ const kept = previous?.settings?.graphics
122
+ const was = Array.isArray(kept) && kept[0] ? { accent: kept[0].accent, tone: kept[0].tone, font: kept[0].font } : {}
123
+ const brand = said.map(brandIn).reduce((all, one) => ({ ...all, ...one }), was)
124
+ const context = { index, asset, cuts, person, scenes, brand }
125
+ if (Array.isArray(kept) && !graphicsIn(text)) return { ...arrangeGraphics(kept, context), source: "kept" }
126
+ const words = (index.words ?? []).filter((w) => w.asset === asset)
127
+ const usable = words.length ? (words.at(-1).end - words[0].start) / FLICKS : 0
128
+ if (words.length < 4) return { graphics: [], source: "code", dropped: [] }
129
+ // About one every eight seconds at most; a short clip still has room for a title and one more
130
+ const limit = Math.max(1, Math.min(MAX_GRAPHICS, Math.ceil(usable / 8)))
131
+ const kinds = Object.entries(GRAPHIC_KINDS).map(([id, kind]) => `- ${id} (styles: ${kind.styles.join(", ")}): ${kind.when}`).join("\n")
132
+ const request = [
133
+ `The person says (their own words, trusted): ${JSON.stringify(String(text).slice(0, 1200))}`,
134
+ "You are the Director choosing the motion graphics for this cut, the way a top editor dresses a video: a few, each with a reason, never decoration. The speaker stays the film.",
135
+ `Choose up to ${limit}, fewer for a short or personal video. \`at\` is the word id where a graphic appears (the opening title and the end card need none: code places them on the first and last seconds). The kinds:\n${kinds}`,
136
+ `Hard rules, checked by code, which throws away a graphic that breaks them: every word on a graphic is either said by the speaker or typed by the person in their request, in that language, at most ${TEXT_MAX} characters (${SUBTITLE_MAX} for a subtitle); a number only if it is said near that word or the person typed it. Never write a title, name, handle or claim of your own, however good. A name strap, an opening title or an end card only if the person gave its words or the speaker says them.`,
137
+ verdict === "on" ? "The person asked for motion graphics, so use them where they fit." : "If nothing earns a graphic, answer with none.",
138
+ scenes.length ? "Animated scenes already cover some lines; code drops a graphic placed inside one." : "",
139
+ ].filter(Boolean).join("\n")
140
+ // A graphic that fails is dropped below; only an answer with nothing usable goes back to the model
141
+ const check = ({ graphics }) => {
142
+ if (!graphics.length) return []
143
+ const tried = arrangeGraphics(graphics, { ...context, limit })
144
+ return tried.graphics.length ? [] : tried.dropped.slice(0, 3).map((d) => `${d.graphic.kind} "${d.graphic.text}": ${d.reason}`)
145
+ }
146
+ const answer = await ask({ task: "graphics", tier: "budget", schema: GRAPHICS_SCHEMA, view: paperEdit(index, { assets: [asset] }), request, maxOutput: 1200, check, fallback: () => ({ graphics: [] }), signal, priority: 0 })
147
+ return { ...arrangeGraphics(answer.value.graphics ?? [], { ...context, limit }), source: answer.source }
148
+ }
149
+
150
+ /** One line a person reads for a graphic, built by code. */
151
+ export const graphicLine = (graphic) => `${GRAPHIC_KINDS[graphic.kind].label} "${graphic.text}"${graphic.subtitle ? `, "${graphic.subtitle}"` : ""}`
152
+ export { GRAPHIC_TONES }
@@ -11,9 +11,11 @@ import { LOOKS } from "../engine/captions.js"
11
11
  import { SFX } from "../engine/sfx.js"
12
12
  import { paperEdit, shotDigest } from "../index/views.js"
13
13
  import { planScenes, visualsIn } from "./beats.js"
14
+ import { graphicLine, graphicsIn, planGraphics } from "./graphics.js"
14
15
  import { picturesRefused, planLookups } from "./lookups.js"
15
16
  import { applyPlaybook, footageFacts, GENRES, PLAYBOOKS, playbookPrompt } from "./playbooks.js"
16
17
  import { timesIn } from "./revise.js"
18
+ import { TRANSITIONS } from "../core/transitions.js"
17
19
 
18
20
  const FLICKS = 705_600_000
19
21
  // The highlight colours a plan may choose; hex stays in code
@@ -51,6 +53,26 @@ export const PLAN_SCHEMA = {
51
53
  additionalProperties: false,
52
54
  }
53
55
 
56
+ // Transitions in the person's words: a kind, "no transitions", and whether every cut gets one
57
+ const TRANSITION_CUES = [
58
+ ["slide", /\b(?:slide|push)\b/i],
59
+ ["wipe", /\bwipe\b/i],
60
+ ["zoom", /\bzoom\b/i],
61
+ ["flash", /\bflash\b/i],
62
+ ["dip", /\bdip\b|\bto black\b/i],
63
+ ["fade", /\b(?:cross ?fade|dissolve|fade)\b/i],
64
+ ]
65
+ /** @returns {{ transition?: string, transitionAll?: boolean }} empty when the words say nothing of transitions */
66
+ export function transitionIn(text) {
67
+ const said = String(text ?? "")
68
+ // The clause that speaks of transitions, so "zoom in on the price" elsewhere doesn't choose a zoom
69
+ const clause = said.split(/[.;!?\n]+/).find((part) => /\btransitions?\b|\bcross ?fade|\bdissolve/i.test(part))
70
+ if (!clause) return {}
71
+ if (/\b(?:no|without|skip|remove(?: the| all)?|drop the)\s+(?:any\s+)?transitions?\b/i.test(clause)) return { transition: "none" }
72
+ const kind = TRANSITION_CUES.find(([, cue]) => cue.test(clause))?.[0] ?? "fade"
73
+ return { transition: kind, ...(/\b(?:every|each|all)\s+(?:the\s+|of the\s+)?cuts?\b|\beverywhere\b/i.test(clause) ? { transitionAll: true } : {}) }
74
+ }
75
+
54
76
  /** What the plan's settings ask of a make job, as the make route takes them. */
55
77
  export function briefOf(settings = {}) {
56
78
  return {
@@ -78,6 +100,8 @@ export function briefOf(settings = {}) {
78
100
  ...(settings.terms?.length ? { terms: settings.terms.map(({ at, id, term }) => ({ at, id, term })) } : {}),
79
101
  ...(Number.isInteger(settings.soundEvery) && settings.soundEvery > 1 ? { soundEvery: settings.soundEvery } : {}),
80
102
  ...(Array.isArray(settings.scenes) && settings.scenes.length ? { scenes: settings.scenes, sceneSound: settings.sceneSound !== false } : {}),
103
+ ...(Array.isArray(settings.graphics) && settings.graphics.length ? { graphics: settings.graphics } : {}),
104
+ ...(Object.hasOwn(TRANSITIONS, settings.transition ?? "") ? { transition: settings.transition, ...(settings.transitionAll ? { transitionAll: true } : {}) } : {}),
81
105
  }
82
106
  }
83
107
 
@@ -255,11 +279,11 @@ export function planProblems(settings, index) {
255
279
 
256
280
  /**
257
281
  * @param {{ ask: Function, project: object, index: object, text: string, history?: object[], previous?: object, references?: { name: string, lines: string[] }[], choices?: object, visuals?: boolean, playbooks?: boolean, signal?: AbortSignal }} input
258
- * visuals, playbooks: the server's editing.visuals and editing.playbooks; off, this plan is what it always was
282
+ * visuals, playbooks, motion: the server's editing.visuals, editing.playbooks and editing.motion; off, this plan is what it always was
259
283
  * lookups: { search, define, keep } with editing.mediaSearch on; null, no search word leaves the computer
260
284
  * @returns {Promise<{ say: string, steps: string[], settings: object, source: string, reason?: string }>}
261
285
  */
262
- export async function planCut({ ask, project, index, text, history = [], previous = null, references = [], choices = {}, visuals = false, playbooks = false, lookups = null, signal }) {
286
+ export async function planCut({ ask, project, index, text, history = [], previous = null, references = [], choices = {}, visuals = false, playbooks = false, motion = false, lookups = null, signal }) {
263
287
  const assets = project.assets.filter((a) => a.kind === "video" || a.kind === "audio").map((a) => a.id)
264
288
  const refs = references.length ? `References the person added, measured by code:\n${references.map((r) => `- ${r.name}: ${r.lines.join("; ")}`).join("\n")}` : "No references added."
265
289
  const view = [paperEdit(index, { assets }), shotDigest(index, { assets }), refs, `The person's current choices in the Studio: ${JSON.stringify(choices)}`].join("\n\n")
@@ -273,7 +297,7 @@ export async function planCut({ ask, project, index, text, history = [], previou
273
297
  // The scenes first, so the pitch can speak for them; each is checked by code, and the person swaps them on the card
274
298
  const planned = visuals && take ? await planScenes({ ask, index, asset: take.id, text, history, previous, cuts, signal }) : null
275
299
  const scenes = planned?.scenes ?? []
276
- const { scenes: _shownOnTheCard, ...previousSettings } = previous?.settings ?? {}
300
+ const { scenes: _shownOnTheCard, graphics: _alsoOnTheCard, ...previousSettings } = previous?.settings ?? {}
277
301
  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` : ""
278
302
  const request = [
279
303
  `${earlier}The person says (their own words, trusted): ${JSON.stringify(String(text).slice(0, 2000))}`,
@@ -295,7 +319,9 @@ export async function planCut({ ask, project, index, text, history = [], previou
295
319
  })
296
320
  // With playbooks the answer also names the genre; off, the schema is the same object as before
297
321
  const schema = playbooks ? { ...PLAN_SCHEMA, properties: { ...PLAN_SCHEMA.properties, genre: { type: "string", enum: GENRES }, settings: { ...PLAN_SCHEMA.properties.settings, properties: { ...PLAN_SCHEMA.properties.settings.properties, captions: { type: "string", enum: ["none", ...Object.keys(LOOKS)] }, accent: { type: "string", enum: Object.keys(ACCENTS) }, song: { type: "string", maxLength: 64 } } } }, required: [...PLAN_SCHEMA.required, "genre"] } : PLAN_SCHEMA
298
- const answer = await ask({ task: "plan", tier: "budget", schema, view, request, maxOutput: 2500, check, fallback, signal, priority: 0 })
322
+ // With editing.motion the Director may also choose a transition; off, the schema is the object it was
323
+ const asked_ = motion ? { ...schema, properties: { ...schema.properties, settings: { ...schema.properties.settings, properties: { ...schema.properties.settings.properties, transition: { type: "string", enum: ["none", ...Object.keys(TRANSITIONS)] } } } } } : schema
324
+ const answer = await ask({ task: "plan", tier: "budget", schema: asked_, view, request: motion ? `${request}\nYou may also set \`transition\` (${Object.keys(TRANSITIONS).join(", ")}): how the picture arrives where the story changes moment, such as out of a cold open or into a reordered line. Code puts it only at those joins, never on a filler cut. Choose none unless it suits the video.` : request, maxOutput: 2500, check, fallback, signal, priority: 0 })
299
325
  const clean = (value) => String(value ?? "").replace(/[\u0000-\u001f<>]/g, " ").trim()
300
326
  // The frame is always set, and set by what the person said, never left to a default
301
327
  // The fallback plan keeps the person's choices: no model read the speech, so no genre was found
@@ -361,5 +387,24 @@ export async function planCut({ ask, project, index, text, history = [], previou
361
387
  if (visualsIn(text)) steps.push(`No animated scene this time${why ? `: ${why}` : ": nothing in the speech can be drawn from the speaker's own words"}.`)
362
388
  delete settings.scenes
363
389
  }
390
+ // Transitions: the person's words outrank the Director's choice; a revision that says nothing keeps what was approved
391
+ const transitionSaid = motion ? [...history.filter((h) => h.who === "you").map((h) => h.text), text].map(transitionIn).reduce((all, one) => ({ ...all, ...one }), {}) : {}
392
+ const kept_ = motion && previous?.settings?.transition && Object.hasOwn(TRANSITIONS, previous.settings.transition) ? { transition: previous.settings.transition, transitionAll: !!previous.settings.transitionAll } : {}
393
+ const chosen = { ...kept_, ...(Object.hasOwn(TRANSITIONS, settings.transition ?? "") ? { transition: settings.transition } : {}), ...transitionSaid }
394
+ delete settings.transition
395
+ delete settings.transitionAll
396
+ if (motion && Object.hasOwn(TRANSITIONS, chosen.transition ?? "")) {
397
+ settings.transition = chosen.transition
398
+ if (chosen.transitionAll) settings.transitionAll = true
399
+ }
400
+ // Motion graphics from the kit, after the scenes so none is planned under one; each is checked by code
401
+ delete settings.graphics
402
+ if (motion && take) {
403
+ const planned = await planGraphics({ ask, index, asset: take.id, text, history, previous, cuts, scenes: sceneList, signal })
404
+ if (planned.graphics.length) {
405
+ settings.graphics = planned.graphics
406
+ steps.unshift(`Add ${planned.graphics.length} motion graphic${planned.graphics.length === 1 ? "" : "s"}: ${planned.graphics.map(graphicLine).join("; ")}. You can restyle or remove each below.`.slice(0, 240))
407
+ } else if (graphicsIn(text) === "on") steps.push(`No motion graphics this time${planned.dropped[0] ? `: ${planned.dropped[0].reason}` : ": the words for one must be the speaker's or yours, so say what a title or name strap should read"}.`.slice(0, 240))
408
+ }
364
409
  return { say: clean(answer.value.say).slice(0, 900), steps: steps.slice(0, 13), settings, source: answer.source, ...(genre ? { genreLabel: PLAYBOOKS[genre].label } : {}), ...(answer.reason ? { reason: answer.reason } : {}) }
365
410
  }