@kriya-ai/harness 0.2.1 → 0.2.3

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.
@@ -0,0 +1,298 @@
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 { SFX } from "../engine/sfx.js"
11
+ import { paperEdit, shotDigest } from "../index/views.js"
12
+ import { timesIn } from "./revise.js"
13
+
14
+ const FLICKS = 705_600_000
15
+ const ID = { type: "string", maxLength: 64 }
16
+
17
+ export const PLAN_SCHEMA = {
18
+ type: "object",
19
+ properties: {
20
+ say: { type: "string", maxLength: 900 },
21
+ steps: { type: "array", maxItems: 10, items: { type: "string", maxLength: 240 } },
22
+ settings: {
23
+ type: "object",
24
+ properties: {
25
+ format: { type: "string", enum: Object.keys(FORMATS) },
26
+ seconds: { type: "integer", minimum: 5, maximum: 600 },
27
+ captions: { type: "string", enum: ["none", "clean", "karaoke", "boxed"] },
28
+ grade: { type: "string", enum: ["natural", ...Object.keys(GRADES)] },
29
+ music: { type: "string", enum: ["none", "reference", ...Object.keys(MOODS)] },
30
+ cleanVoice: { type: "boolean" },
31
+ hook: { anyOf: [{ type: "null" }, ID] },
32
+ coldOpen: { anyOf: [{ type: "null" }, { type: "object", properties: { from: ID, to: ID, mono: { type: "boolean" } }, required: ["from", "to"], additionalProperties: false }] },
33
+ cutSound: { type: "string", enum: ["none", "whoosh", "pop"] },
34
+ introSound: { type: "string", enum: ["none", "riser", "hit"] },
35
+ punches: { type: "integer", minimum: 0, maximum: 8 },
36
+ angles: { type: "boolean" },
37
+ broll: { type: "string", enum: ["none", "own"] },
38
+ titles: { type: "boolean" },
39
+ ramps: { type: "boolean" },
40
+ },
41
+ additionalProperties: false,
42
+ },
43
+ },
44
+ required: ["say", "steps", "settings"],
45
+ additionalProperties: false,
46
+ }
47
+
48
+ /** What the plan's settings ask of a make job, as the make route takes them. */
49
+ export function briefOf(settings = {}) {
50
+ return {
51
+ ...(settings.format ? { format: settings.format } : {}),
52
+ ...(settings.seconds ? { seconds: settings.seconds } : {}),
53
+ ...(settings.captions && settings.captions !== "none" ? { captions: settings.captions } : {}),
54
+ ...(settings.grade && settings.grade !== "natural" ? { grade: settings.grade } : {}),
55
+ ...(settings.music && Object.hasOwn(MOODS, settings.music) ? { music: `generated:${settings.music}` } : {}),
56
+ ...(settings.cleanVoice ? { cleanVoice: true } : {}),
57
+ ...(settings.hook ? { hook: settings.hook } : {}),
58
+ ...(settings.coldOpen ? { coldOpen: settings.coldOpen } : {}),
59
+ ...(settings.cutSound && Object.hasOwn(SFX, settings.cutSound) ? { cutSound: settings.cutSound } : {}),
60
+ ...(settings.introSound && Object.hasOwn(SFX, settings.introSound) ? { introSound: settings.introSound } : {}),
61
+ ...(Number.isInteger(settings.punches) ? { punches: settings.punches } : {}),
62
+ ...(settings.angles ? { angles: true } : {}),
63
+ ...(settings.broll === "own" ? { broll: "own" } : {}),
64
+ ...(settings.titles ? { titles: true } : {}),
65
+ ...(settings.ramps ? { ramps: true } : {}),
66
+ ...(Array.isArray(settings.cuts) && settings.cuts.length ? { cuts: mergeCuts(settings.cuts) } : {}),
67
+ }
68
+ }
69
+
70
+ // The frame the person asked for in their own words. Code decides it, not the model: found in
71
+ // use, a plan approved for 16:9 left `format` out and the make fell back to 9:16.
72
+ const RATIO = (a, b) => new RegExp(`\\b${a}\\s*(?::|x|×|/|by|to)\\s*${b}\\b`, "gi")
73
+ const FORMAT_CUES = [
74
+ ["16:9", RATIO(16, 9), 2],
75
+ ["9:16", RATIO(9, 16), 2],
76
+ ["1:1", RATIO(1, 1), 2],
77
+ ["4:5", RATIO(4, 5), 2],
78
+ ["16:9", /\b(?:landscape|horizontal|wide ?screen|youtube(?! ?shorts?))\b/gi, 1],
79
+ ["9:16", /\b(?:vertical|portrait|reels?|shorts|tiktok|stories)\b/gi, 1],
80
+ ["1:1", /\bsquare\b/gi, 1],
81
+ ]
82
+ // "not 9:16", "instead of a reel", "from 9:16 to 16:9", "but it made 9:16": a mention turned away from
83
+ 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
84
+
85
+ /** The format one message asks for: a ratio beats a word ("a reel in 16:9"), the last mention wins; null if none. */
86
+ export function formatIn(text) {
87
+ const said = String(text ?? "")
88
+ let best = null
89
+ for (const [format, cue, strength] of FORMAT_CUES) {
90
+ for (const m of said.matchAll(cue)) {
91
+ if (AWAY.test(said.slice(Math.max(0, m.index - 24), m.index))) continue
92
+ if (!best || strength > best.strength || (strength === best.strength && m.index > best.at)) best = { format, strength, at: m.index }
93
+ }
94
+ }
95
+ return best?.format ?? null
96
+ }
97
+
98
+ /** The format the person wants: this message, then their earlier messages (latest first), then the plan being revised. */
99
+ export function formatAsked(text, history = [], previous = null) {
100
+ for (const said of [text, ...history.filter((h) => h.who === "you").map((h) => h.text).reverse()]) {
101
+ const format = formatIn(said)
102
+ if (format) return format
103
+ }
104
+ return Object.hasOwn(FORMATS, previous?.settings?.format ?? "") ? previous.settings.format : null
105
+ }
106
+
107
+ // What words ask for, as plan settings. Used twice: the person's own words decide (trusted);
108
+ // the Director's pitch must be matched by its settings, and code fills what it left out.
109
+ // shortcut: English keywords; a pitch in another language is checked only by its settings
110
+ const SAID = [
111
+ ["captions", /\bno (?:captions?|subtitles?)\b/i, "none"],
112
+ ["captions", /\bkaraoke\b/i, "karaoke"],
113
+ ["captions", /\bboxed\b/i, "boxed"],
114
+ ["captions", /\b(?:captions?|subtitles?)\b/i, "clean"],
115
+ ["grade", /\bcinematic\b|\bcool(?:er)?[- ](?:tone|look|grade)/i, "cinematic"],
116
+ ["grade", /\bwarm(?:er)? (?:grade|look|tone|colou?r)/i, "warm"],
117
+ ["grade", /\bvivid\b/i, "vivid"],
118
+ ["grade", /\bbright(?:er)? (?:grade|look)\b/i, "bright"],
119
+ ["music", /\bno music\b/i, "none"],
120
+ ["music", /\bupbeat\b[^.]{0,24}\bmusic|\bmusic\b[^.]{0,16}\bupbeat/i, "upbeat"],
121
+ ["music", /\bwarm\b[^.]{0,24}\bmusic|\bmusic\b[^.]{0,16}\bwarm/i, "warm"],
122
+ ["music", /\b(?:calm|soft|gentle|low)\b[^.]{0,24}\bmusic|\bmusic\b/i, "calm"],
123
+ ["cleanVoice", /\bnoise\b|\bdenois|\bclean (?:up )?(?:the |my |your )?(?:voice|audio)/i, true],
124
+ ["cutSound", /\bwhoosh/i, "whoosh"],
125
+ ["cutSound", /\bpops? on\b/i, "pop"],
126
+ ["cutSound", /sound ?eff?ect|\bsfx\b|sound design/i, "whoosh"], // typed fast: "bestsound effectes"
127
+ ["introSound", /\briser\b/i, "riser"],
128
+ ["introSound", /\b(?:bass |impact )?hit into\b/i, "hit"],
129
+ ["titles", /\btitle cards?\b/i, true],
130
+ ["angles", /\bangles\b|\bwide (?:and|then) tight\b/i, true],
131
+ ["broll", /\bb-?roll\b/i, "own"],
132
+ ["ramps", /\b(?:speed )?ramp/i, true],
133
+ ["coldOpen", /\bcold open|\bopen(?:s|ing)? cold\b/i, true],
134
+ ]
135
+ const NO = /(?:\bno|\bnot|\bwithout|\bdon't|\bdo not|\bskip)\s+(?:any\s+|the\s+|a\s+)?$/i
136
+
137
+ /** Plan settings the words ask for; a later mention of the same setting wins, "no X" turns X off. */
138
+ export function settingsIn(text) {
139
+ const said = String(text ?? "")
140
+ const out = {}
141
+ const done = new Set()
142
+ for (const [key, cue, value] of SAID) {
143
+ if (done.has(key)) continue
144
+ const m = cue.exec(said)
145
+ if (!m) continue
146
+ done.add(key)
147
+ const away = NO.test(said.slice(Math.max(0, m.index - 16), m.index))
148
+ out[key] = away ? (typeof value === "boolean" ? false : key === "broll" ? "none" : "none") : value
149
+ }
150
+ 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)
151
+ if (punches) out.punches = Math.min(8, Number(punches[1]))
152
+ // The last length that could be a cut's ("about 4 seconds" of a cold open isn't)
153
+ 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)
154
+ if (lengths.length) out.seconds = lengths.at(-1)
155
+ const format = formatIn(said)
156
+ if (format) out.format = format
157
+ return out
158
+ }
159
+
160
+ // Trims in the person's words, per clause so "a whoosh on every cut" never trims anything.
161
+ // "trim it to 0:05–0:20" and "keep 0:05 to 0:20" keep that stretch; "remove/cut/delete 0:05 to
162
+ // 0:09", "everything after 25 seconds", "the first 3 seconds" take it out. Times are the raw take's.
163
+ 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
164
+ const KEEP = /\b(?:keep|only use|use only|trim (?:it |the video |this |the clip )?(?:to|from|down to|between))\b/i
165
+
166
+ /** The stretches of the take the person wants out, in seconds, merged and in order. */
167
+ export function trimsIn(text, duration) {
168
+ const end = duration / FLICKS
169
+ const cuts = []
170
+ for (const clause of String(text ?? "").split(/(?:[;!?\n]|\.(?!\d))+/)) { // "14.6 seconds" stays whole
171
+ 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)
172
+ if (!ranges.length) continue
173
+ if (KEEP.test(clause) && !REMOVE.test(clause)) {
174
+ let at = 0
175
+ 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)))
176
+ if (at < end) cuts.push({ from: at, to: end })
177
+ } else if (REMOVE.test(clause)) cuts.push(...ranges)
178
+ }
179
+ return mergeCuts(cuts, end)
180
+ }
181
+
182
+ /** In order, overlaps joined, inside the take, to the hundredth of a second. At most eight. */
183
+ export function mergeCuts(cuts, end = Infinity) {
184
+ const out = []
185
+ 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)) {
186
+ const last = out.at(-1)
187
+ if (last && c.from <= last.to) last.to = Math.max(last.to, c.to)
188
+ else out.push({ ...c })
189
+ }
190
+ return out.slice(0, 8).map((c) => ({ from: Math.round(c.from * 100) / 100, to: Math.round(c.to * 100) / 100 }))
191
+ }
192
+
193
+ const OFF = { captions: "none", grade: "natural", music: "none", cutSound: "none", introSound: "none", broll: "none" }
194
+ const unset = (settings, key) => settings[key] === undefined || settings[key] === null || settings[key] === false || settings[key] === OFF[key]
195
+
196
+ /** What the pitch says that the settings don't make: the Director is sent back once with these. */
197
+ export function pitchGaps(plan) {
198
+ const promised = settingsIn([plan.say, ...(plan.steps ?? [])].join("\n"))
199
+ const settings = plan.settings ?? {}
200
+ return Object.entries(promised)
201
+ .filter(([key, value]) => key !== "format" && value !== false && value !== "none" && (key === "coldOpen" ? !settings.coldOpen : unset(settings, key)))
202
+ .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`))
203
+ }
204
+
205
+ /**
206
+ * A cold open chosen by code when the pitch promised one and the model gave no ids: 3 to 5
207
+ * seconds of clean speech from the middle of the main take, ending on a sentence end when one is near.
208
+ */
209
+ export function pickColdOpen(index, asset, cuts = []) {
210
+ const out = (w) => cuts.some((c) => (w.start + w.end) / 2 >= c.from * FLICKS && (w.start + w.end) / 2 < c.to * FLICKS)
211
+ const words = (index.words ?? []).filter((w) => w.asset === asset && !out(w))
212
+ if (words.length < 4) return null
213
+ const span = words.at(-1).end - words[0].start
214
+ let i = words.findIndex((w) => w.start >= words[0].start + span * 0.4)
215
+ if (i < 0) return null
216
+ while (i < words.length && words[i].flags?.some((f) => f === "filler" || f === "stutter")) i++
217
+ let end = null
218
+ for (let j = i; j < words.length; j++) {
219
+ const length = words[j].end - words[i].start
220
+ if (length > 6 * FLICKS) break
221
+ if (length >= 3 * FLICKS && (end === null || /[.!?]$/.test(words[j].text))) end = j
222
+ if (end !== null && /[.!?]$/.test(words[end].text)) break
223
+ }
224
+ return end === null ? null : { from: words[i].id, to: words[end].id, mono: true }
225
+ }
226
+
227
+ /** Problems with a plan's settings against this project: unknown ids, a cold open that isn't one short stretch. */
228
+ export function planProblems(settings, index) {
229
+ const problems = []
230
+ const words = new Map((index.words ?? []).map((w) => [w.id, w]))
231
+ 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`)
232
+ if (settings.coldOpen) {
233
+ const from = words.get(settings.coldOpen.from)
234
+ const to = words.get(settings.coldOpen.to)
235
+ if (!from || !to) problems.push("the cold open must name two word ids from the paper edit")
236
+ 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")
237
+ else if (to.end - from.start > 8 * FLICKS) problems.push("a cold open is short: 8 seconds at most")
238
+ }
239
+ return problems
240
+ }
241
+
242
+ /**
243
+ * @param {{ ask: Function, project: object, index: object, text: string, history?: object[], previous?: object, references?: { name: string, lines: string[] }[], choices?: object, signal?: AbortSignal }} input
244
+ * @returns {Promise<{ say: string, steps: string[], settings: object, source: string, reason?: string }>}
245
+ */
246
+ export async function planCut({ ask, project, index, text, history = [], previous = null, references = [], choices = {}, signal }) {
247
+ const assets = project.assets.filter((a) => a.kind === "video" || a.kind === "audio").map((a) => a.id)
248
+ 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."
249
+ const view = [paperEdit(index, { assets }), shotDigest(index, { assets }), refs, `The person's current choices in the Studio: ${JSON.stringify(choices)}`].join("\n\n")
250
+ const asked = formatAsked(text, history, previous)
251
+ // Trims are the person's, read by code from their words (this message and earlier ones) and kept through revisions
252
+ const take = project.assets.find((a) => a.kind === "video" && (index.words ?? []).some((w) => w.asset === a.id)) ?? project.assets.find((a) => a.kind === "video")
253
+ const length = take?.facts?.duration ?? Math.max(0, ...(index.words ?? []).filter((w) => w.asset === take?.id).map((w) => w.end))
254
+ const kept = Array.isArray(previous?.settings?.cuts) ? previous.settings.cuts.filter((c) => c && Number.isFinite(c.from) && Number.isFinite(c.to)) : []
255
+ const cuts = take ? mergeCuts([...kept, ...[...history.filter((h) => h.who === "you").map((h) => h.text), text].flatMap((said) => trimsIn(said, length))], length / FLICKS) : []
256
+ const at = (n) => `${Math.floor(n / 60)}:${(n % 60).toFixed(1).padStart(4, "0")}`
257
+ 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` : ""
258
+ const request = [
259
+ `${earlier}The person says (their own words, trusted): ${JSON.stringify(String(text).slice(0, 2000))}`,
260
+ 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.` : "",
261
+ asked ? `The person wants the ${asked} format: settings.format is "${asked}", and your pitch says ${asked}.` : "",
262
+ previous ? `Your previous plan, which they want changed: ${JSON.stringify(previous).slice(0, 3000)}. Revise it by what they say now; keep what they didn't ask to change.` : "",
263
+ "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.",
264
+ "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.",
265
+ ].filter(Boolean).join("\n")
266
+ // Only real faults go back to the model: a second refusal throws the whole plan away for the
267
+ // fallback, so what the pitch promised and the settings left out is filled by code below instead
268
+ const check = ({ settings }) => planProblems(settings ?? {}, index)
269
+ const fallback = () => ({
270
+ 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.",
271
+ steps: ["Keep each line's best take and cut fillers and restarts", "Use the format, length, captions, look and music you've chosen"],
272
+ 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 },
273
+ })
274
+ const answer = await ask({ task: "plan", tier: "budget", schema: PLAN_SCHEMA, view, request, maxOutput: 2500, check, fallback, signal, priority: 0 })
275
+ const clean = (value) => String(value ?? "").replace(/[\u0000-\u001f<>]/g, " ").trim()
276
+ // The frame is always set, and set by what the person said, never left to a default
277
+ const settings = { ...(answer.value.settings ?? {}) }
278
+ settings.format = asked ?? (Object.hasOwn(FORMATS, settings.format ?? "") ? settings.format : Object.hasOwn(FORMATS, choices.format ?? "") ? choices.format : "9:16")
279
+ // What the pitch promised and the settings left out, code fills; what the person said, code
280
+ // sets. So the approved brief makes what the card says, not just the format
281
+ // Only a model's pitch promises anything: the fallback's own sentence names captions and music without asking for them
282
+ const promised = answer.source === "default" ? {} : settingsIn([answer.value.say, ...(answer.value.steps ?? [])].join("\n"))
283
+ for (const [key, value] of Object.entries(promised)) if (key !== "format" && key !== "coldOpen" && value !== false && unset(settings, key)) settings[key] = value
284
+ const person = [...history.filter((h) => h.who === "you").map((h) => h.text), text].map(settingsIn).reduce((all, one) => ({ ...all, ...one }), {})
285
+ for (const [key, value] of Object.entries(person)) {
286
+ if (key === "format") continue
287
+ if (key === "coldOpen") value ? (promised.coldOpen = true) : (settings.coldOpen = null)
288
+ else settings[key] = value
289
+ }
290
+ if (cuts.length) settings.cuts = cuts
291
+ else delete settings.cuts
292
+ if (promised.coldOpen && !settings.coldOpen && take) settings.coldOpen = pickColdOpen(index, take.id, cuts)
293
+ if (settings.coldOpen && planProblems({ coldOpen: settings.coldOpen }, index).length) settings.coldOpen = null
294
+ // Said plainly when a promise can't be kept, so the card never pitches what won't be made
295
+ const steps = (answer.value.steps ?? []).map((s) => clean(s).slice(0, 240)).filter(Boolean)
296
+ if (promised.coldOpen && !settings.coldOpen) steps.push("No cold open: the footage has no clean 3-second stretch in its middle to open on.")
297
+ return { say: clean(answer.value.say).slice(0, 900), steps: steps.slice(0, 11), settings, source: answer.source, ...(answer.reason ? { reason: answer.reason } : {}) }
298
+ }
@@ -9,9 +9,10 @@ import { paperEdit, shotDigest } from "../index/views.js"
9
9
 
10
10
  const FLICKS = 705_600_000
11
11
 
12
- // What the console may ask for: edits that render today. Captions, motion and sound
13
- // design arrive with their phases (ED8, ED9) and are refused until then
14
- export const CONSOLE_OPS = ["keep_range", "remove_range", "use_take", "reorder", "trim", "split", "ripple_delete", "punch_in", "reframe", "speed", "set_format", "mark"]
12
+ // What the console may ask for: edits that render today, captions and titles included
13
+ // (drawn in the runtime's Chrome when it has no HyperFrames)
14
+ export const CONSOLE_OPS = ["keep_range", "remove_range", "use_take", "reorder", "trim", "split", "ripple_delete", "punch_in", "reframe", "speed", "set_format", "mark", "caption_style", "caption_edit", "caption_emphasis", "add_title", "grade", "clean_voice", "set_level", "speed_ramp", "freeze", "place_broll"]
15
+ export const CAPTION_LOOKS = ["clean", "karaoke", "boxed"]
15
16
 
16
17
  const ID = { type: "string", maxLength: 64 }
17
18
  const EDGE = { type: "string", enum: ["start", "end"] }
@@ -55,16 +56,63 @@ export const OPS_SCHEMA = {
55
56
  width: { type: "integer", minimum: 2 },
56
57
  height: { type: "integer", minimum: 2 },
57
58
  name: { type: "string", maxLength: 80 },
59
+ look: { type: "string", enum: CAPTION_LOOKS },
60
+ words: { type: "array", maxItems: 40, items: ID },
61
+ caption: ID,
62
+ word: ID,
63
+ text: { type: "string", maxLength: 200 },
64
+ lift: { type: "number", minimum: -0.5, maximum: 0.5 },
65
+ gamma: { type: "number", minimum: 0.5, maximum: 2 },
66
+ gain: { type: "number", minimum: 0.5, maximum: 2 },
67
+ saturation: { type: "number", minimum: 0, maximum: 2 },
68
+ temperature: { type: "number", minimum: 2000, maximum: 12000 },
69
+ vibrance: { type: "number", minimum: -2, maximum: 2 },
70
+ vignette: { type: "number", minimum: 0, maximum: 1 },
71
+ strength: { type: "number", minimum: 0, maximum: 1 },
72
+ db: { type: "number", minimum: -40, maximum: 20 },
73
+ peak: RATE,
58
74
  },
59
75
  required: ["op"],
60
76
  additionalProperties: false,
61
77
  },
62
78
  },
79
+ // Words the recogniser got wrong, when the person asks to fix the transcript
80
+ corrections: {
81
+ type: "array",
82
+ maxItems: 40,
83
+ items: { type: "object", properties: { word: ID, text: { type: "string", maxLength: 60 } }, required: ["word", "text"], additionalProperties: false },
84
+ },
85
+ // A short answer in words: what Kriya did, or the answer to a question
86
+ say: { type: "string", maxLength: 600 },
87
+ // A request about the whole video ("make it stunning", "edit all of it"): the Director's make job does that
88
+ direct: {
89
+ anyOf: [
90
+ { type: "null" },
91
+ { type: "boolean" },
92
+ { type: "object", properties: { seconds: { type: "integer", minimum: 5, maximum: 600 }, captions: { type: "string", enum: ["clean", "karaoke", "boxed"] } }, additionalProperties: false },
93
+ ],
94
+ },
63
95
  },
64
96
  required: ["ops"],
65
97
  additionalProperties: false,
66
98
  }
67
99
 
100
+ /**
101
+ * What models often send that means nothing: every optional field present as null,
102
+ * and empty lists or no `ops` at all. Tidied before the schema, never invented.
103
+ */
104
+ export function tidyConsole(value) {
105
+ if (!value || typeof value !== "object" || Array.isArray(value)) return value
106
+ const ops = Array.isArray(value.ops) ? value.ops.map((op) => (op && typeof op === "object" ? Object.fromEntries(Object.entries(op).filter(([key, v]) => v !== null || key === "after")) : op)) : (value.ops ?? [])
107
+ const out = { ...value, ops }
108
+ if (out.corrections === null) delete out.corrections
109
+ if (out.direct === false) out.direct = null
110
+ return out
111
+ }
112
+
113
+ /** A correction's text: one word or a short name, no markup or line breaks. */
114
+ export const cleanWord = (text) => (typeof text === "string" ? text.replace(/[\u0000-\u001f<>]/g, "").trim().slice(0, 60) : "")
115
+
68
116
  const seconds = (flicks) => `${(flicks / FLICKS).toFixed(2)} s`
69
117
 
70
118
  /** What one operation did, in plain words, from the operation and the index only (track-A rule 7). */
@@ -114,6 +162,28 @@ export function describe(op, index) {
114
162
  return op.fit ? "Fitted the music to the cut on its downbeats" : "Shaped the music's fades"
115
163
  case "duck":
116
164
  return "Ducked the music under the speech"
165
+ case "caption_edit":
166
+ return `Changed caption ${op.caption} to "${op.text}"`
167
+ case "caption_emphasis":
168
+ return `Emphasised "${words.get(op.word)?.text ?? op.word}" in caption ${op.caption}`
169
+ case "add_title":
170
+ return `Added the title "${op.text}" at ${place(op.at)}`
171
+ case "grade":
172
+ return `Graded ${op.clip}${op.saturation !== undefined ? `, saturation ${op.saturation}` : ""}${op.gain !== undefined ? `, contrast ${op.gain}` : ""}${op.gamma !== undefined ? `, gamma ${op.gamma}` : ""}${op.lift !== undefined ? `, lift ${op.lift}` : ""}`
173
+ case "speed_ramp":
174
+ return op.peak.n > op.peak.d ? `Ramped ${op.clip} up to ${(op.peak.n / op.peak.d).toFixed(1)}× and back, from ${place(op.from)} to ${place(op.to)}` : `Slow motion in ${op.clip} (${(op.peak.n / op.peak.d).toFixed(2)}×), eased in and out, from ${place(op.from)} to ${place(op.to)}`
175
+ case "freeze":
176
+ return `Froze the frame at ${place(op.at)} for ${seconds(op.duration)}`
177
+ case "add_sfx":
178
+ return `Added a sound effect at ${place(op.peak_at)}`
179
+ case "place_broll":
180
+ return `Laid B-roll ${op.asset} over ${place(op.at)}${op.duration ? ` for ${seconds(op.duration)}` : ""}`
181
+ case "clean_voice":
182
+ return `Cleaned the background noise out of ${op.clip}'s voice`
183
+ case "set_level":
184
+ return `Set ${op.clip} to ${op.db} dB`
185
+ case "add_deliverable":
186
+ return `Set up the export: ${op.size?.width ?? "?"}×${op.size?.height ?? "?"}${op.loudness ? `, mastered to ${op.loudness.lufs} LUFS` : ""}${op.burnCaptions ? ", captions burned in" : ""}`
117
187
  default:
118
188
  return op.op
119
189
  }
@@ -127,7 +197,7 @@ function selectionText(selection, index) {
127
197
  return `The person selected the words ${first} to ${last} in the paper edit, and means them by "this", "here" or "that part".`
128
198
  }
129
199
  if (selection.clip) return `The person selected clip ${selection.clip}, and means it by "this", "here" or "that clip".`
130
- if (Number.isInteger(selection.from) && Number.isInteger(selection.to)) return `The person selected the timeline from ${selection.from} to ${selection.to} flicks.`
200
+ if (Number.isInteger(selection.from) && Number.isInteger(selection.to)) return `The person marked ${clock(selection.from)} to ${clock(selection.to)} on the cut's timeline, and means it by "this", "here" or "that part" (what it points at is below).`
131
201
  if (Number.isInteger(selection.at)) return `The playhead is at ${selection.at} flicks on the timeline.`
132
202
  return "Nothing is selected."
133
203
  }
@@ -159,10 +229,105 @@ export function noteWord(project, index, at) {
159
229
  return (words.find((w) => t >= w.start && t < w.end) ?? words.find((w) => w.start >= t) ?? words.at(-1))?.id ?? null
160
230
  }
161
231
 
232
+ /** A time on the cut as the person reads it in the Studio: 1:02.5 */
233
+ export const clock = (flicks) => {
234
+ const total = Math.max(0, flicks) / FLICKS
235
+ const minutes = Math.floor(total / 60)
236
+ return `${minutes}:${(total - minutes * 60).toFixed(1).padStart(4, "0")}`
237
+ }
238
+
162
239
  function clipsView(project, index) {
163
- const { picture } = solve(project, index)
164
- const lines = picture.map((p) => `[${p.clip} ${p.asset} source ${p.in}-${p.out} at ${p.at}-${p.end}]`)
165
- return `Clips on the timeline, in order:\n${lines.join("\n") || "(none yet)"}`
240
+ const { picture, captions, duration } = solve(project, index)
241
+ const lines = picture.map((p) => `[${p.clip} ${clock(p.at)}-${clock(p.end)} from ${p.asset} ${seconds(p.in)}-${seconds(p.out)}; flicks source ${p.in}-${p.out} at ${p.at}-${p.end}]`)
242
+ const said = captions.map((c) => `[caption ${c.clip} ${clock(c.at)}-${clock(c.end)} ${c.look ?? ""} ${JSON.stringify(String(c.text).replace(/[<>]/g, ""))}]`)
243
+ return [`The cut, on its own timeline: it starts at 0:00 and is ${clock(duration)} long. Clips in order:`, lines.join("\n") || "(none yet)", ...(said.length ? ["Captions on screen:", said.join("\n")] : [])].join("\n")
244
+ }
245
+
246
+ const JOIN = /^\s*(?:-|–|—|to|until|till|and|through)\s*$/i
247
+ // Seconds as people type them, typos included: s, sec, secs, second, seconds, secods, secnds
248
+ const UNIT = "(?:s|sec\\w*|se?c?o?n?d?s?\\b)(?![a-z])"
249
+
250
+ /**
251
+ * Times in the person's words, on the cut's timeline: 0:05, 1:02.5, 5s, 5 sec, 5 seconds,
252
+ * and ranges joined by to, -, until or and ("from 5 to 9 seconds", "between 0:05 and 0:09").
253
+ * @returns {{ at: number, to?: number }[]} in flicks
254
+ */
255
+ export function timesIn(text, { duration = null } = {}) {
256
+ const said = String(text)
257
+ // Relative stretches first: "the first 5 seconds", "the last 5 s" (needs the cut's length)
258
+ const relative = []
259
+ for (const m of said.matchAll(new RegExp(`\\b(first|last|final|opening)\\s+(\\d+(?:\\.\\d+)?)\\s*${UNIT}`, "gi"))) {
260
+ const n = Math.round(Number(m[2]) * FLICKS)
261
+ if (/first|opening/i.test(m[1])) relative.push({ at: 0, to: n })
262
+ else if (duration) relative.push({ at: Math.max(0, duration - n), to: duration })
263
+ }
264
+ const text2 = said.replace(new RegExp(`\\b(first|last|final|opening)\\s+\\d+(?:\\.\\d+)?\\s*${UNIT}`, "gi"), (m) => " ".repeat(m.length))
265
+ const tokens = [...text2.matchAll(new RegExp(`(\\d{1,2}):(\\d{2}(?:\\.\\d+)?)|(\\d+(?:\\.\\d+)?)(\\s*${UNIT})?`, "gi"))].map((m) => ({
266
+ t: m[1] !== undefined ? Number(m[1]) * 60 + Number(m[2]) : Number(m[3]),
267
+ unit: m[1] !== undefined || !!m[4],
268
+ start: m.index,
269
+ end: m.index + m[0].length,
270
+ }))
271
+ const between = (a, b) => text2.slice(a.end, b.start)
272
+ const before = (tok) => text2.slice(Math.max(0, tok.start - 24), tok.start)
273
+ // A bare number is a time only as the first half of a range whose second half is one
274
+ const times = tokens.filter((tok, i) => tok.unit || (tokens[i + 1]?.unit && JOIN.test(between(tok, tokens[i + 1]))))
275
+ const out = [...relative]
276
+ for (let i = 0; i < times.length; i++) {
277
+ const next = times[i + 1]
278
+ const at = Math.round(times[i].t * FLICKS)
279
+ if (next && JOIN.test(between(times[i], next)) && next.t > times[i].t) {
280
+ out.push({ at, to: Math.round(next.t * FLICKS) })
281
+ i++
282
+ } else if (duration && /\b(?:after|from|form|frm|fron|since|onwards?|starting(?: at)?|beyond|past)\s*(?:the\s*)?$/i.test(before(times[i]))) out.push({ at, to: duration })
283
+ else if (/\b(?:before|until|till|up to|upto)\s*(?:the\s*)?$/i.test(before(times[i]))) out.push({ at: 0, to: at })
284
+ else out.push({ at })
285
+ }
286
+ return out.slice(0, 8)
287
+ }
288
+
289
+ /** Where a moment of the cut comes from: its clip, and the source time inside it. */
290
+ function sourceAt(picture, t) {
291
+ const piece = picture.find((p) => t >= p.at && t < p.end)
292
+ if (!piece) return null
293
+ return { piece, t: piece.in + Math.round(((t - piece.at) * (piece.out - piece.in)) / (piece.end - piece.at || 1)) }
294
+ }
295
+
296
+ /**
297
+ * What each mentioned time points at, worked out by code so the model never does
298
+ * arithmetic on flicks: the clip, the words (with ids) and the captions there.
299
+ */
300
+ export function timesView(text, project, index) {
301
+ const { picture, captions, duration } = solve(project, index)
302
+ const asked = timesIn(text, { duration })
303
+ if (!asked.length) return ""
304
+ const words = index.words ?? []
305
+ const wordAt = (piece, t) => words.find((w) => w.asset === piece.asset && t >= w.start && t < w.end) ?? words.find((w) => w.asset === piece.asset && w.start >= t && w.start < piece.out)
306
+ const quote = (list) => JSON.stringify(list.map((w) => w.text).join(" ").replace(/[<>]/g, "").slice(0, 300))
307
+ const lines = asked.map(({ at, to }) => {
308
+ if (at >= duration) return `${clock(at)}: past the end of the cut (${clock(duration)} long).`
309
+ if (to === undefined) {
310
+ const found = sourceAt(picture, at)
311
+ const word = found && wordAt(found.piece, found.t)
312
+ const on = captions.filter((c) => at >= c.at && at < c.end).map((c) => `caption ${c.clip}`)
313
+ return `${clock(at)}: clip ${found?.piece.clip ?? "?"}${word ? `, word ${word.id} ${JSON.stringify(word.text)}` : ", no word spoken there"}${on.length ? `, ${on.join(", ")}` : ""}.`
314
+ }
315
+ const end = Math.min(to, duration)
316
+ const pieces = picture.filter((p) => p.at < end && p.end > at)
317
+ const spans = pieces.map((p) => {
318
+ const from = sourceAt(picture, Math.max(at, p.at))?.t ?? p.in
319
+ const until = Math.min(p.out, Math.max(from + 1, (sourceAt(picture, Math.min(end, p.end) - 1)?.t ?? p.out) + 1))
320
+ return { asset: p.asset, from, until }
321
+ })
322
+ const inside = spans.flatMap(({ asset, from, until }) => words.filter((w) => w.asset === asset && w.end > from && w.start < until))
323
+ const on = captions.filter((c) => c.at < end && c.end > at).map((c) => `caption ${c.clip}`)
324
+ const spoken = inside.length ? `words ${inside[0].id} to ${inside.at(-1).id}: ${quote(inside)}` : "no words spoken"
325
+ // The exact operation to take this stretch out, in each source's own flicks, so a removal
326
+ // never depends on where words happen to fall (found in use: "remove from 25 seconds")
327
+ const removal = spans.map(({ asset, from, until }) => JSON.stringify({ op: "remove_range", asset, from, to: until })).join(" ")
328
+ return `${clock(at)}-${clock(end)}: clip${pieces.length === 1 ? "" : "s"} ${pieces.map((p) => p.clip).join(", ") || "?"}, ${spoken}${on.length ? `; ${on.join(", ")}` : ""}. To take it out exactly: ${removal}`
329
+ })
330
+ return `Times the person mentioned, worked out by code on the cut's timeline:\n${lines.join("\n")}`
166
331
  }
167
332
 
168
333
  /**
@@ -170,17 +335,47 @@ function clipsView(project, index) {
170
335
  * @param {{ ask: ReturnType<import("./ask.js").createAsk>, project: object, index: object, text: string, selection?: object, signal?: AbortSignal }} input
171
336
  * @returns {Promise<{ ops: object[], changes: string[], project: object | null, source: string, reason?: string, calls: number }>}
172
337
  */
173
- export async function revise({ ask, project, index, text, selection, signal }) {
338
+ export async function revise({ ask, project, index, text, selection, history = [], signal }) {
174
339
  const assets = project.assets.map((a) => a.id)
175
- const view = [paperEdit(index, { assets }), shotDigest(index, { assets }), clipsView(project, index), selectionText(selection, index)].join("\n\n")
176
- const request = `The person asks (their own words, trusted): ${JSON.stringify(String(text).slice(0, 2000))}\nAnswer with the operations that do exactly this, and nothing else. If it can't be done with these operations, answer {"ops": []}.`
340
+ // A marked range reads like a typed one: code says what it points at
341
+ const marked = Number.isInteger(selection?.from) && Number.isInteger(selection?.to) ? ` from ${clock(selection.from)} to ${clock(selection.to)}` : ""
342
+ const times = timesView(`${text}${marked}`, project, index)
343
+ const bin = `Footage in the project: ${project.assets.filter((a) => ["video", "audio"].includes(a.kind)).map((a) => `${a.id} (${a.kind}, ${seconds(a.facts.duration ?? 0)})`).join(", ")}`
344
+ const view = [paperEdit(index, { assets }), shotDigest(index, { assets }), clipsView(project, index), bin, selectionText(selection, index), times].filter(Boolean).join("\n\n")
345
+ // The last turns of this chat, so "shorter" or "no, the other one" mean something. The
346
+ // person's lines are theirs; Kriya's are what it said before, not instructions
347
+ 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` : ""
348
+ const request = [
349
+ `${earlier}The person asks (their own words, trusted): ${JSON.stringify(String(text).slice(0, 2000))}`,
350
+ "Answer with JSON only. Put in `ops` the operations that do exactly what they ask, and nothing else.",
351
+ "Times like 0:05 are on the cut's timeline; the lines above say which clip, words and captions each time points at. Use those ids, never compute flicks yourself. To take out a stretch the person names by time, use the exact remove_range given for it above, unchanged; for a stretch named by words, remove_range from its first word (edge start) to its last word (edge end). To change what a caption says, caption_edit with its caption id; to remove a caption, ripple_delete its caption id; to caption words, caption_style with their word ids and a look; to put a title on screen, add_title with text and a word anchor; to take background noise out of the voice, clean_voice on each picture clip; to warm or cool the picture, grade with temperature (lower is warmer, 6500 neutral), vibrance or vignette; for a speed ramp or slow motion, speed_ramp on the clip with from and to (source flicks from the lines above, or word anchors) and peak {n, d} (2/1 speeds up and back, 1/2 is eased slow motion); for a constant speed, speed; to lay other footage over a moment, place_broll with a video asset id from the project, at a word anchor or clip edge, and duration in flicks.",
352
+ "Put one plain sentence in `say`: what you changed, or the answer if they asked a question.",
353
+ "If they ask to fix or correct the transcript (names, misheard words), put each wrong word in `corrections` as {word: its id, text: the right word}, only where you are confident from the context.",
354
+ "If they ask for the whole video to be made, directed, edited or improved (not one part of it), set `direct` to an object (with `seconds` and a caption look if they say so) and leave `ops` empty: the Director makes the whole cut.",
355
+ 'If none of these can do it, answer {"ops": []}.',
356
+ ].join("\n")
357
+ const words = new Map((index.words ?? []).map((w) => [w.id, w]))
358
+ // Operations must apply; a correction on an unknown word is only dropped, never worth a second call
177
359
  const check = ({ ops }) => {
178
360
  if (!ops.length) return []
179
361
  const tried = apply(project, ops, { index, author: "agent" })
180
362
  return tried.applied ? [] : tried.diagnostics.map((d) => `operation ${d.op + 1}: ${d.message}`)
181
363
  }
182
- const answer = await ask({ task: "console", tier: "budget", schema: OPS_SCHEMA, view, request, maxOutput: 800, check, fallback: () => ({ ops: [] }), signal, priority: 0 })
364
+ const answer = await ask({ task: "console", tier: "budget", schema: OPS_SCHEMA, view, request, maxOutput: 2000, check, clean: tidyConsole, fallback: () => ({ ops: [] }), signal, priority: 0 })
183
365
  const ops = answer.value.ops
184
366
  const tried = ops.length ? apply(project, ops, { index, author: "agent" }) : null
185
- return { ops: tried?.applied ? ops : [], changes: tried?.applied ? ops.map((op) => describe(op, index)) : [], project: tried?.applied ? tried.project : null, source: answer.source, reason: answer.reason, calls: answer.calls }
367
+ // A correction that changes nothing, or isn't a known word, isn't offered
368
+ const corrections = (answer.value.corrections ?? []).map((c) => ({ word: c.word, text: cleanWord(c.text) })).filter((c) => words.has(c.word) && c.text && c.text !== words.get(c.word).text)
369
+ const direct = answer.value.direct === true ? {} : answer.value.direct && typeof answer.value.direct === "object" ? answer.value.direct : null
370
+ return {
371
+ ops: tried?.applied ? ops : [],
372
+ changes: tried?.applied ? ops.map((op) => describe(op, index)) : [],
373
+ corrections: corrections.map((c) => ({ ...c, change: `Corrected "${words.get(c.word).text}" to "${c.text}"` })),
374
+ direct,
375
+ say: typeof answer.value.say === "string" ? answer.value.say.replace(/[\u0000-\u001f<>]/g, " ").trim().slice(0, 600) : "",
376
+ project: tried?.applied ? tried.project : null,
377
+ source: answer.source,
378
+ reason: answer.reason,
379
+ calls: answer.calls,
380
+ }
186
381
  }