@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
@@ -0,0 +1,365 @@
1
+ // The Director's plan (2026-11-09): the person says what they want in their own words; the
2
+ // Director proposes the whole cut the way an editor pitches it (the opening, the pacing, the
3
+ // captions, the look, the music, the sound, the length) with the exact settings behind it.
4
+ // Nothing is made until the person approves; a change of mind revises the plan, and again
5
+ // nothing is made. Every setting is checked by code: ids must exist, values must be ones the
6
+ // engine renders, and a cold open must be a short stretch of one take.
7
+
8
+ import { FORMATS, GRADES } from "../recipes/reel.js"
9
+ import { MOODS } from "../engine/music-bed.js"
10
+ import { LOOKS } from "../engine/captions.js"
11
+ import { SFX } from "../engine/sfx.js"
12
+ import { paperEdit, shotDigest } from "../index/views.js"
13
+ import { planScenes, visualsIn } from "./beats.js"
14
+ import { picturesRefused, planLookups } from "./lookups.js"
15
+ import { applyPlaybook, footageFacts, GENRES, PLAYBOOKS, playbookPrompt } from "./playbooks.js"
16
+ import { timesIn } from "./revise.js"
17
+
18
+ const FLICKS = 705_600_000
19
+ // The highlight colours a plan may choose; hex stays in code
20
+ export const ACCENTS = { yellow: "#ffd23f", amber: "#ffb347", teal: "#4fd1c5", pink: "#ff7ab6", white: "#ffffff" }
21
+ const ID = { type: "string", maxLength: 64 }
22
+
23
+ export const PLAN_SCHEMA = {
24
+ type: "object",
25
+ properties: {
26
+ say: { type: "string", maxLength: 900 },
27
+ steps: { type: "array", maxItems: 10, items: { type: "string", maxLength: 240 } },
28
+ settings: {
29
+ type: "object",
30
+ properties: {
31
+ format: { type: "string", enum: Object.keys(FORMATS) },
32
+ seconds: { type: "integer", minimum: 5, maximum: 600 },
33
+ captions: { type: "string", enum: ["none", "clean", "karaoke", "boxed"] },
34
+ grade: { type: "string", enum: ["natural", ...Object.keys(GRADES)] },
35
+ music: { type: "string", enum: ["none", "reference", ...Object.keys(MOODS)] },
36
+ cleanVoice: { type: "boolean" },
37
+ hook: { anyOf: [{ type: "null" }, ID] },
38
+ coldOpen: { anyOf: [{ type: "null" }, { type: "object", properties: { from: ID, to: ID, mono: { type: "boolean" } }, required: ["from", "to"], additionalProperties: false }] },
39
+ cutSound: { type: "string", enum: ["none", "whoosh", "pop"] },
40
+ introSound: { type: "string", enum: ["none", "riser", "hit"] },
41
+ punches: { type: "integer", minimum: 0, maximum: 8 },
42
+ angles: { type: "boolean" },
43
+ broll: { type: "string", enum: ["none", "own"] },
44
+ titles: { type: "boolean" },
45
+ ramps: { type: "boolean" },
46
+ },
47
+ additionalProperties: false,
48
+ },
49
+ },
50
+ required: ["say", "steps", "settings"],
51
+ additionalProperties: false,
52
+ }
53
+
54
+ /** What the plan's settings ask of a make job, as the make route takes them. */
55
+ export function briefOf(settings = {}) {
56
+ return {
57
+ ...(settings.format ? { format: settings.format } : {}),
58
+ ...(settings.seconds ? { seconds: settings.seconds } : {}),
59
+ ...(settings.captions && settings.captions !== "none" ? { captions: settings.captions } : {}),
60
+ ...(settings.grade && settings.grade !== "natural" ? { grade: settings.grade } : {}),
61
+ ...(settings.music && Object.hasOwn(MOODS, settings.music) ? { music: `generated:${settings.music}` } : {}),
62
+ ...(settings.cleanVoice ? { cleanVoice: true } : {}),
63
+ ...(settings.hook ? { hook: settings.hook } : {}),
64
+ ...(settings.coldOpen ? { coldOpen: settings.coldOpen } : {}),
65
+ ...(settings.cutSound && Object.hasOwn(SFX, settings.cutSound) ? { cutSound: settings.cutSound } : {}),
66
+ ...(settings.introSound && Object.hasOwn(SFX, settings.introSound) ? { introSound: settings.introSound } : {}),
67
+ ...(Number.isInteger(settings.punches) ? { punches: settings.punches } : {}),
68
+ ...(settings.angles ? { angles: true } : {}),
69
+ ...(settings.broll === "own" ? { broll: "own" } : {}),
70
+ ...(settings.titles ? { titles: true } : {}),
71
+ ...(settings.ramps ? { ramps: true } : {}),
72
+ ...(Array.isArray(settings.cuts) && settings.cuts.length ? { cuts: mergeCuts(settings.cuts) } : {}),
73
+ ...(typeof settings.song === "string" ? { music: settings.song } : {}),
74
+ ...(settings.montage ? { montage: true } : {}),
75
+ ...(settings.multicam ? { multicam: settings.multicam } : {}),
76
+ ...(settings.captionStyle ? { captionStyle: settings.captionStyle } : {}),
77
+ ...(settings.pictures?.length ? { pictures: settings.pictures.map(({ from, to, id }) => ({ from, to, id })) } : {}),
78
+ ...(settings.terms?.length ? { terms: settings.terms.map(({ at, id, term }) => ({ at, id, term })) } : {}),
79
+ ...(Number.isInteger(settings.soundEvery) && settings.soundEvery > 1 ? { soundEvery: settings.soundEvery } : {}),
80
+ ...(Array.isArray(settings.scenes) && settings.scenes.length ? { scenes: settings.scenes, sceneSound: settings.sceneSound !== false } : {}),
81
+ }
82
+ }
83
+
84
+ // The frame the person asked for in their own words. Code decides it, not the model: found in
85
+ // use, a plan approved for 16:9 left `format` out and the make fell back to 9:16.
86
+ const RATIO = (a, b) => new RegExp(`\\b${a}\\s*(?::|x|×|/|by|to)\\s*${b}\\b`, "gi")
87
+ const FORMAT_CUES = [
88
+ ["16:9", RATIO(16, 9), 2],
89
+ ["9:16", RATIO(9, 16), 2],
90
+ ["1:1", RATIO(1, 1), 2],
91
+ ["4:5", RATIO(4, 5), 2],
92
+ ["16:9", /\b(?:landscape|horizontal|wide ?screen|youtube(?! ?shorts?))\b/gi, 1],
93
+ ["9:16", /\b(?:vertical|portrait|reels?|shorts|tiktok|stories)\b/gi, 1],
94
+ ["1:1", /\bsquare\b/gi, 1],
95
+ ]
96
+ // "not 9:16", "instead of a reel", "from 9:16 to 16:9", "but it made 9:16": a mention turned away from
97
+ const AWAY = /(?:\bnot|\bno|\bisn't|\bwasn't|instead of|rather than|\bthan|\bfrom|\bmade(?: it| me)?|\bgave(?: me)?|came out|turned out|\bcurrently|\bbut it's|output (?:is|was))\s+(?:(?:a|an|the|in|at|as|like)\s+)?$/i
98
+
99
+ /** The format one message asks for: a ratio beats a word ("a reel in 16:9"), the last mention wins; null if none. */
100
+ export function formatIn(text) {
101
+ const said = String(text ?? "")
102
+ let best = null
103
+ for (const [format, cue, strength] of FORMAT_CUES) {
104
+ for (const m of said.matchAll(cue)) {
105
+ if (AWAY.test(said.slice(Math.max(0, m.index - 24), m.index))) continue
106
+ if (!best || strength > best.strength || (strength === best.strength && m.index > best.at)) best = { format, strength, at: m.index }
107
+ }
108
+ }
109
+ return best?.format ?? null
110
+ }
111
+
112
+ /** The format the person wants: this message, then their earlier messages (latest first), then the plan being revised. */
113
+ export function formatAsked(text, history = [], previous = null) {
114
+ for (const said of [text, ...history.filter((h) => h.who === "you").map((h) => h.text).reverse()]) {
115
+ const format = formatIn(said)
116
+ if (format) return format
117
+ }
118
+ return Object.hasOwn(FORMATS, previous?.settings?.format ?? "") ? previous.settings.format : null
119
+ }
120
+
121
+ // What words ask for, as plan settings. Used twice: the person's own words decide (trusted);
122
+ // the Director's pitch must be matched by its settings, and code fills what it left out.
123
+ // shortcut: English keywords; a pitch in another language is checked only by its settings
124
+ const SAID = [
125
+ ["captions", /\bno (?:captions?|subtitles?)\b/i, "none"],
126
+ ["captions", /\bkaraoke\b/i, "karaoke"],
127
+ ["captions", /\bboxed\b/i, "boxed"],
128
+ ["captions", /\b(?:captions?|subtitles?)\b/i, "clean"],
129
+ ["grade", /\bcinematic\b|\bcool(?:er)?[- ](?:tone|look|grade)/i, "cinematic"],
130
+ ["grade", /\bwarm(?:er)? (?:grade|look|tone|colou?r)/i, "warm"],
131
+ ["grade", /\bvivid\b/i, "vivid"],
132
+ ["grade", /\bbright(?:er)? (?:grade|look)\b/i, "bright"],
133
+ ["music", /\bno music\b/i, "none"],
134
+ ["music", /\bupbeat\b[^.]{0,24}\bmusic|\bmusic\b[^.]{0,16}\bupbeat/i, "upbeat"],
135
+ ["music", /\bwarm\b[^.]{0,24}\bmusic|\bmusic\b[^.]{0,16}\bwarm/i, "warm"],
136
+ ["music", /\b(?:calm|soft|gentle|low)\b[^.]{0,24}\bmusic|\bmusic\b/i, "calm"],
137
+ ["cleanVoice", /\bnoise\b|\bdenois|\bclean (?:up )?(?:the |my |your )?(?:voice|audio)/i, true],
138
+ ["cutSound", /\bwhoosh/i, "whoosh"],
139
+ ["cutSound", /\bpops? on\b/i, "pop"],
140
+ ["cutSound", /sound ?eff?ect|\bsfx\b|sound design/i, "whoosh"], // typed fast: "bestsound effectes"
141
+ ["introSound", /\briser\b/i, "riser"],
142
+ ["introSound", /\b(?:bass |impact )?hit into\b/i, "hit"],
143
+ ["titles", /\btitle cards?\b/i, true],
144
+ ["angles", /\bangles\b|\bwide (?:and|then) tight\b/i, true],
145
+ ["broll", /\bb-?roll\b/i, "own"],
146
+ ["ramps", /\b(?:speed )?ramp/i, true],
147
+ ["coldOpen", /\bcold open|\bopen(?:s|ing)? cold\b/i, true],
148
+ ]
149
+ const NO = /(?:\bno|\bnot|\bwithout|\bdon't|\bdo not|\bskip)\s+(?:any\s+|the\s+|a\s+)?$/i
150
+
151
+ /** Plan settings the words ask for; a later mention of the same setting wins, "no X" turns X off. */
152
+ export function settingsIn(text) {
153
+ const said = String(text ?? "")
154
+ const out = {}
155
+ const done = new Set()
156
+ for (const [key, cue, value] of SAID) {
157
+ if (done.has(key)) continue
158
+ const m = cue.exec(said)
159
+ if (!m) continue
160
+ done.add(key)
161
+ const away = NO.test(said.slice(Math.max(0, m.index - 16), m.index))
162
+ out[key] = away ? (typeof value === "boolean" ? false : key === "broll" ? "none" : "none") : value
163
+ }
164
+ const punches = /\bpunch(?:[- ]?ins?|ing in)?\b[^.]{0,24}?\b(\d)\b/i.exec(said) ?? /\b(\d)\s*(?:-|to)?\s*\d?\s*(?:key )?(?:words|punch)/i.exec(said)
165
+ if (punches) out.punches = Math.min(8, Number(punches[1]))
166
+ // The last length that could be a cut's ("about 4 seconds" of a cold open isn't)
167
+ const lengths = [...said.matchAll(/\b(?:at|to|under|max(?:imum)?|about|around|of|after(?: the)?|upto|up to|only)\s+(\d{1,3})\s*(?:s|secs?|seconds?)\b|\b(\d{1,3})\s*(?:s|secs?|seconds?)\s+(?:max|long|video|reel|cut|only)\b/gi)].map((m) => Number(m[1] ?? m[2])).filter((n) => n >= 8 && n <= 600)
168
+ if (lengths.length) out.seconds = lengths.at(-1)
169
+ const format = formatIn(said)
170
+ if (format) out.format = format
171
+ return out
172
+ }
173
+
174
+ // Trims in the person's words, per clause so "a whoosh on every cut" never trims anything.
175
+ // "trim it to 0:05–0:20" and "keep 0:05 to 0:20" keep that stretch; "remove/cut/delete 0:05 to
176
+ // 0:09", "everything after 25 seconds", "the first 3 seconds" take it out. Times are the raw take's.
177
+ const REMOVE = /\b(?:remove|delete|drop|erase|skip|chop|get rid of|take out|trim (?:out|off|away)|cut (?:out|off|away|from|the|it|this|that|everything|anything|all|after|before|till|until|up ?to|[0-9]))/i
178
+ const KEEP = /\b(?:keep|only use|use only|trim (?:it |the video |this |the clip )?(?:to|from|down to|between))\b/i
179
+
180
+ /** The stretches of the take the person wants out, in seconds, merged and in order. */
181
+ export function trimsIn(text, duration) {
182
+ const end = duration / FLICKS
183
+ const cuts = []
184
+ for (const clause of String(text ?? "").split(/(?:[;!?\n]|\.(?!\d))+/)) { // "14.6 seconds" stays whole
185
+ const ranges = timesIn(clause, { duration }).filter((r) => r.to !== undefined && r.to > r.at).map((r) => ({ from: r.at / FLICKS, to: Math.min(end, r.to / FLICKS) })).filter((r) => r.from < end)
186
+ if (!ranges.length) continue
187
+ if (KEEP.test(clause) && !REMOVE.test(clause)) {
188
+ let at = 0
189
+ for (const r of [...ranges].sort((a, b) => a.from - b.from)) (r.from > at && cuts.push({ from: at, to: r.from }), (at = Math.max(at, r.to)))
190
+ if (at < end) cuts.push({ from: at, to: end })
191
+ } else if (REMOVE.test(clause)) cuts.push(...ranges)
192
+ }
193
+ return mergeCuts(cuts, end)
194
+ }
195
+
196
+ /** In order, overlaps joined, inside the take, to the hundredth of a second. At most eight. */
197
+ export function mergeCuts(cuts, end = Infinity) {
198
+ const out = []
199
+ for (const c of cuts.filter((c) => Number.isFinite(c.from) && Number.isFinite(c.to)).map((c) => ({ from: Math.max(0, c.from), to: Math.min(end, c.to) })).filter((c) => c.to - c.from >= 0.05).sort((a, b) => a.from - b.from)) {
200
+ const last = out.at(-1)
201
+ if (last && c.from <= last.to) last.to = Math.max(last.to, c.to)
202
+ else out.push({ ...c })
203
+ }
204
+ return out.slice(0, 8).map((c) => ({ from: Math.round(c.from * 100) / 100, to: Math.round(c.to * 100) / 100 }))
205
+ }
206
+
207
+ const OFF = { captions: "none", grade: "natural", music: "none", cutSound: "none", introSound: "none", broll: "none" }
208
+ const unset = (settings, key) => settings[key] === undefined || settings[key] === null || settings[key] === false || settings[key] === OFF[key]
209
+
210
+ /** What the pitch says that the settings don't make: the Director is sent back once with these. */
211
+ export function pitchGaps(plan) {
212
+ const promised = settingsIn([plan.say, ...(plan.steps ?? [])].join("\n"))
213
+ const settings = plan.settings ?? {}
214
+ return Object.entries(promised)
215
+ .filter(([key, value]) => key !== "format" && value !== false && value !== "none" && (key === "coldOpen" ? !settings.coldOpen : unset(settings, key)))
216
+ .map(([key, value]) => (key === "coldOpen" ? "your pitch promises a cold open but settings.coldOpen is empty: give its first and last word ids" : `your pitch promises ${key} ${JSON.stringify(value)} but settings.${key} doesn't make it`))
217
+ }
218
+
219
+ /**
220
+ * A cold open chosen by code when the pitch promised one and the model gave no ids: 3 to 5
221
+ * seconds of clean speech from the middle of the main take, ending on a sentence end when one is near.
222
+ */
223
+ export function pickColdOpen(index, asset, cuts = []) {
224
+ const out = (w) => cuts.some((c) => (w.start + w.end) / 2 >= c.from * FLICKS && (w.start + w.end) / 2 < c.to * FLICKS)
225
+ const words = (index.words ?? []).filter((w) => w.asset === asset && !out(w))
226
+ if (words.length < 4) return null
227
+ const span = words.at(-1).end - words[0].start
228
+ let i = words.findIndex((w) => w.start >= words[0].start + span * 0.4)
229
+ if (i < 0) return null
230
+ while (i < words.length && words[i].flags?.some((f) => f === "filler" || f === "stutter")) i++
231
+ let end = null
232
+ for (let j = i; j < words.length; j++) {
233
+ const length = words[j].end - words[i].start
234
+ if (length > 6 * FLICKS) break
235
+ if (length >= 3 * FLICKS && (end === null || /[.!?]$/.test(words[j].text))) end = j
236
+ if (end !== null && /[.!?]$/.test(words[end].text)) break
237
+ }
238
+ return end === null ? null : { from: words[i].id, to: words[end].id, mono: true }
239
+ }
240
+
241
+ /** Problems with a plan's settings against this project: unknown ids, a cold open that isn't one short stretch. */
242
+ export function planProblems(settings, index) {
243
+ const problems = []
244
+ const words = new Map((index.words ?? []).map((w) => [w.id, w]))
245
+ if (settings.hook && !(index.sentences ?? []).some((s) => s.id === settings.hook)) problems.push(`hook "${settings.hook}" isn't a sentence id from the paper edit`)
246
+ if (settings.coldOpen) {
247
+ const from = words.get(settings.coldOpen.from)
248
+ const to = words.get(settings.coldOpen.to)
249
+ if (!from || !to) problems.push("the cold open must name two word ids from the paper edit")
250
+ else if (from.asset !== to.asset || to.end <= from.start) problems.push("a cold open runs forward within one take: its first word, then its last")
251
+ else if (to.end - from.start > 8 * FLICKS) problems.push("a cold open is short: 8 seconds at most")
252
+ }
253
+ return problems
254
+ }
255
+
256
+ /**
257
+ * @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
259
+ * lookups: { search, define, keep } with editing.mediaSearch on; null, no search word leaves the computer
260
+ * @returns {Promise<{ say: string, steps: string[], settings: object, source: string, reason?: string }>}
261
+ */
262
+ export async function planCut({ ask, project, index, text, history = [], previous = null, references = [], choices = {}, visuals = false, playbooks = false, lookups = null, signal }) {
263
+ const assets = project.assets.filter((a) => a.kind === "video" || a.kind === "audio").map((a) => a.id)
264
+ 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
+ const view = [paperEdit(index, { assets }), shotDigest(index, { assets }), refs, `The person's current choices in the Studio: ${JSON.stringify(choices)}`].join("\n\n")
266
+ const asked = formatAsked(text, history, previous)
267
+ // Trims are the person's, read by code from their words (this message and earlier ones) and kept through revisions
268
+ const take = project.assets.find((a) => a.kind === "video" && (index.words ?? []).some((w) => w.asset === a.id)) ?? project.assets.find((a) => a.kind === "video")
269
+ const length = take?.facts?.duration ?? Math.max(0, ...(index.words ?? []).filter((w) => w.asset === take?.id).map((w) => w.end))
270
+ const kept = Array.isArray(previous?.settings?.cuts) ? previous.settings.cuts.filter((c) => c && Number.isFinite(c.from) && Number.isFinite(c.to)) : []
271
+ const cuts = take ? mergeCuts([...kept, ...[...history.filter((h) => h.who === "you").map((h) => h.text), text].flatMap((said) => trimsIn(said, length))], length / FLICKS) : []
272
+ const at = (n) => `${Math.floor(n / 60)}:${(n % 60).toFixed(1).padStart(4, "0")}`
273
+ // The scenes first, so the pitch can speak for them; each is checked by code, and the person swaps them on the card
274
+ const planned = visuals && take ? await planScenes({ ask, index, asset: take.id, text, history, previous, cuts, signal }) : null
275
+ const scenes = planned?.scenes ?? []
276
+ const { scenes: _shownOnTheCard, ...previousSettings } = previous?.settings ?? {}
277
+ 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
+ const request = [
279
+ `${earlier}The person says (their own words, trusted): ${JSON.stringify(String(text).slice(0, 2000))}`,
280
+ cuts.length ? `The person asked to trim ${cuts.map((c) => `${at(c.from)} to ${at(c.to)}`).join(", ")} of the take (${take.id}); code cuts exactly that, between words. Plan around it: no hook or cold open inside a trimmed stretch, and say the trim in your pitch.` : "",
281
+ asked ? `The person wants the ${asked} format: settings.format is "${asked}", and your pitch says ${asked}.` : "",
282
+ previous ? `Your previous plan, which they want changed: ${JSON.stringify(previous.settings ? { ...previous, settings: previousSettings } : previous).slice(0, 3000)}. Revise it by what they say now; keep what they didn't ask to change.` : "",
283
+ scenes.length ? `Animated explainer scenes that take over the frame while the voice keeps playing are already planned on these lines: ${scenes.map((s) => `${s.from} (${s.kind}: ${s.title || s.items[0].text})`).join("; ")}. Say so in one sentence of your pitch. They're code-drawn from the speaker's words, so promise no others, and don't choose a hook or cold open on those lines.` : "",
284
+ ...(playbooks ? playbookPrompt(footageFacts(project, index, take)) : []),
285
+ "You are the Director: plan the whole cut the way a top editor pitches it. Decide the opening (a hook sentence first, or a cold open: one strong later moment of 2 to 6 seconds played first, in black and white, before the story starts), the pacing (punch-ins), captions, the colour look, music, sound design (a sound on each cut, a riser into the story after a cold open), whether to clean background noise from the voice, the format and the length. You can also cut one camera like two (angles: wide then tight on alternate clips), lay the person's other clips over the story as B-roll (broll 'own', only if the project has other video), pop key words on screen as title cards (titles, when there are no captions), and ramp the speed out of a cold open into the story (ramps). Follow the references where they say something. Don't promise what these settings can't do: no stock footage or generated video.",
286
+ "Answer with JSON only: `say` is your pitch in 2 to 4 plain sentences, `steps` the concrete things you'll do, and `settings` exactly what will be made: every promise in the pitch has its setting (captions, grade, music, cleanVoice, cutSound, introSound, punches, seconds, coldOpen), because only the settings are made. Use sentence ids for `hook` and word ids for `coldOpen`, only from the paper edit. Music 'reference' means follow the music reference.",
287
+ ].filter(Boolean).join("\n")
288
+ // Only real faults go back to the model: a second refusal throws the whole plan away for the
289
+ // fallback, so what the pitch promised and the settings left out is filled by code below instead
290
+ const check = ({ settings }) => planProblems(settings ?? {}, index)
291
+ const fallback = () => ({
292
+ say: "I couldn't reach the Director's model, so here's a plan from your current choices: the best takes, fillers out, and your settings as they are.",
293
+ steps: ["Keep each line's best take and cut fillers and restarts", "Use the format, length, captions, look and music you've chosen"],
294
+ settings: { format: choices.format ?? "9:16", ...(choices.seconds ? { seconds: choices.seconds } : {}), captions: choices.captions ?? "none", grade: choices.grade ?? "natural", music: (choices.music ?? "").replace(/^generated:/, "") || "none", cleanVoice: !!choices.cleanVoice },
295
+ })
296
+ // With playbooks the answer also names the genre; off, the schema is the same object as before
297
+ 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 })
299
+ const clean = (value) => String(value ?? "").replace(/[\u0000-\u001f<>]/g, " ").trim()
300
+ // The frame is always set, and set by what the person said, never left to a default
301
+ // The fallback plan keeps the person's choices: no model read the speech, so no genre was found
302
+ const genre = playbooks && answer.source !== "default" && Object.hasOwn(PLAYBOOKS, answer.value.genre ?? "") ? answer.value.genre : null
303
+ const settings = genre ? applyPlaybook(answer.value.settings ?? {}, genre, length / FLICKS) : { ...(answer.value.settings ?? {}) }
304
+ if (genre) settings.genre = genre
305
+ settings.format = asked ?? (Object.hasOwn(FORMATS, settings.format ?? "") ? settings.format : Object.hasOwn(FORMATS, choices.format ?? "") ? choices.format : "9:16")
306
+ // What the pitch promised and the settings left out, code fills; what the person said, code
307
+ // sets. So the approved brief makes what the card says, not just the format
308
+ // Only a model's pitch promises anything: the fallback's own sentence names captions and music without asking for them
309
+ const promised = answer.source === "default" ? {} : settingsIn([answer.value.say, ...(answer.value.steps ?? [])].join("\n"))
310
+ for (const [key, value] of Object.entries(promised)) if (key !== "format" && key !== "coldOpen" && value !== false && unset(settings, key)) settings[key] = value
311
+ const person = [...history.filter((h) => h.who === "you").map((h) => h.text), text].map(settingsIn).reduce((all, one) => ({ ...all, ...one }), {})
312
+ for (const [key, value] of Object.entries(person)) {
313
+ if (key === "format") continue
314
+ if (key === "coldOpen") value ? (promised.coldOpen = true) : (settings.coldOpen = null)
315
+ else settings[key] = value
316
+ }
317
+ if (cuts.length) settings.cuts = cuts
318
+ else delete settings.cuts
319
+ if (promised.coldOpen && !settings.coldOpen && take) settings.coldOpen = pickColdOpen(index, take.id, cuts)
320
+ if (settings.coldOpen && planProblems({ coldOpen: settings.coldOpen }, index).length) settings.coldOpen = null
321
+ // Said plainly when a promise can't be kept, so the card never pitches what won't be made
322
+ const steps = (answer.value.steps ?? []).map((s) => clean(s).slice(0, 240)).filter(Boolean)
323
+ if (promised.coldOpen && !settings.coldOpen) steps.push("No cold open: the footage has no clean 3-second stretch in its middle to open on.")
324
+ // The genre decides what the plan may reach for; the person's asking outranks it
325
+ const book = genre ? PLAYBOOKS[genre] : null
326
+ const sceneList = book && !book.scenes && !visualsIn(text) ? [] : scenes
327
+ if (genre) {
328
+ const songs = project.assets.filter((a) => a.kind === "audio" && !/kriya-(?:music|sfx)-/.test(a.path ?? ""))
329
+ const wanted = songs.find((a) => a.id === answer.value.settings?.song) ?? (/\b(?:my|this|the) (?:song|track|audio file)\b/i.test(text) || genre === "montage" ? songs[0] : null)
330
+ if (wanted && person.music !== "none") {
331
+ settings.song = wanted.id
332
+ delete settings.music
333
+ } else delete settings.song
334
+ if (genre === "montage" && settings.song && project.assets.some((a) => a.kind === "video")) settings.montage = true
335
+ // Two or more cameras of a conversation: the switcher decides who's on screen
336
+ const cameras = project.assets.filter((a) => a.kind === "video")
337
+ if (genre === "podcast" && cameras.length >= 2 && take) settings.multicam = { master: take.id, angles: cameras.slice(0, 6).map((a, speaker) => ({ asset: a.id, speaker })) }
338
+ if (Object.hasOwn(ACCENTS, answer.value.settings?.accent ?? "")) settings.captionStyle = { accent: ACCENTS[answer.value.settings.accent] }
339
+ delete settings.accent
340
+ }
341
+ // Licensed pictures and cited definitions, only with their switch on and a search to ask
342
+ if (lookups && take && !picturesRefused(text)) {
343
+ const found = await planLookups({ ask, index, asset: take.id, text, scenes: sceneList, cuts, search: lookups.search, define: lookups.define, wantPictures: !book || book.scenes || genre === "documentary", wantTerms: true, signal })
344
+ lookups.keep(found)
345
+ if (found.pictures.length) {
346
+ settings.pictures = found.pictures
347
+ steps.push(`Show ${found.pictures.length} real picture${found.pictures.length === 1 ? "" : "s"} of what's named, from openly licensed sources, credited. You can swap or remove each below; nothing downloads until you approve.`)
348
+ }
349
+ if (found.terms.length) {
350
+ settings.terms = found.terms
351
+ steps.push(`Define ${found.terms.map((t) => `"${t.term}"`).join(", ")} on screen, quoted from ${[...new Set(found.terms.map((t) => t.source))].join(", ")}.`)
352
+ }
353
+ }
354
+ if (sceneList.length) {
355
+ settings.scenes = sceneList
356
+ // A sound as each scene arrives, unless the person said no sound effects
357
+ settings.sceneSound = person.cutSound !== "none"
358
+ steps.push(`Cut away to ${sceneList.length} animated scene${sceneList.length === 1 ? "" : "s"} while the voice keeps playing. You can swap or remove each one below.`)
359
+ } else if (planned && planned.source !== "person") {
360
+ const why = planned.dropped[0]?.reason
361
+ 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
+ delete settings.scenes
363
+ }
364
+ 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
+ }
@@ -0,0 +1,131 @@
1
+ // The Director's playbooks (DIRECTOR_PLAYBOOKS.md, EDD-56): how each kind of video is edited,
2
+ // as data a person reviewed. No command, path, URL, model or price. The Director names the
3
+ // genre from the transcript; code fills what the plan left open; the person's words outrank both.
4
+ // Numbers are starting points to tune by KriyaEditBench, not facts about any editor.
5
+
6
+ const FLICKS = 705_600_000
7
+
8
+ export const PLAYBOOKS = {
9
+ explainer: {
10
+ label: "Science or explainer",
11
+ rules: "Show what's hard to picture while the voice continues. Let a hard idea land before the next one. Keep the speaker for the hook, for anything personal and for the close.",
12
+ settings: { captions: "clean", grade: "cinematic", music: "calm", cleanVoice: true },
13
+ punchesPerMinute: 2,
14
+ soundEvery: 4,
15
+ scenes: true,
16
+ },
17
+ documentary: {
18
+ label: "Documentary or place story",
19
+ rules: "Slow, with room to look. What's named should be seen. Ambience and silence before score; few cuts, each for a reason.",
20
+ settings: { captions: "story", grade: "warm", music: "calm", cleanVoice: true },
21
+ punchesPerMinute: 0,
22
+ soundEvery: 0,
23
+ scenes: true,
24
+ },
25
+ podcast: {
26
+ label: "Podcast or interview",
27
+ rules: "Show who is talking, and sometimes who is listening. Follow the talk; don't cut on a timer. Let pauses and reactions breathe. Voice only, almost nothing else.",
28
+ settings: { captions: "minimal", grade: "natural", music: "none", cleanVoice: true },
29
+ punchesPerMinute: 1,
30
+ soundEvery: 0,
31
+ scenes: false,
32
+ },
33
+ tutorial: {
34
+ label: "Tutorial",
35
+ rules: "Tight on the action, no waiting. Show the step as it's said. Quiet sound; the viewer is following along.",
36
+ settings: { captions: "clean", grade: "natural", music: "none", cleanVoice: true },
37
+ punchesPerMinute: 2,
38
+ soundEvery: 0,
39
+ scenes: true,
40
+ },
41
+ opinion: {
42
+ label: "Opinion or talking head",
43
+ rules: "Brisk, with one real breath. Hook first. Punch in on the point, not on a timer. Numbers and names on screen. Keep every emotional beat on the face.",
44
+ settings: { captions: "karaoke", grade: "vivid", music: "none", cleanVoice: true },
45
+ punchesPerMinute: 4,
46
+ soundEvery: 3,
47
+ scenes: false,
48
+ },
49
+ promo: {
50
+ label: "Promo or ad",
51
+ rules: "One message. The offer early, an end on what to do next. Fast, led by the beat.",
52
+ settings: { captions: "pop", grade: "vivid", music: "upbeat", cleanVoice: true },
53
+ punchesPerMinute: 5,
54
+ soundEvery: 2,
55
+ scenes: true,
56
+ },
57
+ vlog: {
58
+ label: "Vlog or personal story",
59
+ rules: "Feeling first. No diagrams. Varied pace, the person's own B-roll, and quiet where the moment is quiet.",
60
+ settings: { captions: "clean", grade: "warm", music: "warm", cleanVoice: true },
61
+ punchesPerMinute: 1,
62
+ soundEvery: 0,
63
+ scenes: false,
64
+ },
65
+ montage: {
66
+ label: "Music-led montage",
67
+ rules: "The song leads. Cut on its beats, leave words out unless they matter.",
68
+ settings: { captions: "none", grade: "vivid", music: "upbeat", cleanVoice: false },
69
+ punchesPerMinute: 0,
70
+ soundEvery: 0,
71
+ scenes: false,
72
+ },
73
+ }
74
+
75
+ export const GENRES = Object.keys(PLAYBOOKS)
76
+
77
+ /**
78
+ * What the footage has and lacks, measured by code, so the Director plans from facts.
79
+ * @returns {string[]} plain lines; nothing from the media but counts
80
+ */
81
+ export function footageFacts(project, index, take) {
82
+ const lines = []
83
+ const videos = project.assets.filter((a) => a.kind === "video")
84
+ const songs = project.assets.filter((a) => a.kind === "audio" && !/kriya-(?:music|sfx)-/.test(a.path ?? ""))
85
+ const words = (index.words ?? []).filter((w) => w.asset === take?.id)
86
+ lines.push(`${videos.length} video file${videos.length === 1 ? "" : "s"}${videos.length > 1 ? ": other clips can be B-roll, or angles if they were shot together" : ": no other footage to cut to"}.`)
87
+ lines.push(songs.length ? `Sound files of the person's own in the bin, by id: ${songs.map((a) => a.id).join(", ")}; settings.song uses one.` : "No music of the person's own.")
88
+ if (words.length > 1) {
89
+ const minutes = (words.at(-1).end - words[0].start) / FLICKS / 60
90
+ const numbers = words.filter((w) => /\d/.test(w.text)).length
91
+ const pauses = words.slice(1).filter((w, i) => w.start - words[i].end > FLICKS).length
92
+ lines.push(`${Math.round(minutes * 60)} seconds of speech, about ${Math.round(words.length / Math.max(minutes, 0.01))} words a minute, ${pauses} pause${pauses === 1 ? "" : "s"} over a second, ${numbers} spoken number${numbers === 1 ? "" : "s"}.`)
93
+ }
94
+ const faces = new Set((index.faces ?? []).filter((f) => f.asset === take?.id).map((f) => f.identity))
95
+ if (faces.size) lines.push(`${faces.size} face${faces.size === 1 ? "" : "s"} seen in the take.`)
96
+ return lines
97
+ }
98
+
99
+ /** The plan slot's extra lines. */
100
+ export function playbookPrompt(facts) {
101
+ return [
102
+ "Think like a top editor. Emotion and story come before rhythm; every cut, zoom and sound needs a reason in what is being said, and over-cutting is a fault. First work out from the transcript what kind of video this is, then what it has and what it lacks.",
103
+ `What the footage has, measured: ${facts.join(" ")}`,
104
+ `Set \`genre\` to one of these, and plan by its rules:\n${GENRES.map((id) => `- ${id} (${PLAYBOOKS[id].label}): ${PLAYBOOKS[id].rules}`).join("\n")}`,
105
+ "Choose the caption look for this film in settings.captions (clean, karaoke, boxed, pop, story, minimal) and its highlight colour in settings.accent, once, for the whole film.",
106
+ "Each of your `steps` says what you'll do and why, pointing at what the speaker says. Don't apply an effect because you can.",
107
+ ]
108
+ }
109
+
110
+ const OPEN = { captions: "none", grade: "natural", music: "none", cutSound: "none" }
111
+ const isOpen = (settings, key) => settings[key] === undefined || settings[key] === null
112
+
113
+ /**
114
+ * Fills what the plan left open from the genre's playbook; what's set stays. The caller applies
115
+ * the person's words after this, so they outrank it.
116
+ * @param {object} settings the plan's settings
117
+ * @param {string} genre
118
+ * @param {number} seconds speech in the take
119
+ * @returns {object} new settings
120
+ */
121
+ export function applyPlaybook(settings, genre, seconds = 0) {
122
+ const book = PLAYBOOKS[genre]
123
+ if (!book) return settings
124
+ const out = { ...settings }
125
+ for (const [key, value] of Object.entries(book.settings)) if (isOpen(out, key)) out[key] = value
126
+ if (isOpen(out, "punches") && book.punchesPerMinute >= 0) out.punches = Math.min(8, Math.round((seconds / 60) * book.punchesPerMinute))
127
+ // Restraint: a sound on some cuts, not all. A genre with none adds none, and the plan's own stays
128
+ if (isOpen(out, "cutSound") && book.soundEvery > 0) out.cutSound = "whoosh"
129
+ if (out.cutSound && out.cutSound !== OPEN.cutSound && book.soundEvery > 1) out.soundEvery = book.soundEvery
130
+ return out
131
+ }