@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
@@ -60,32 +60,42 @@ export function schemaErrors(schema, value, path = "$") {
60
60
  * A reply cut off by its output limit says so, since "too long" is what to fix.
61
61
  */
62
62
  export function parseReply(text, finish) {
63
- const raw = String(text ?? "").replace(/<think>[\s\S]*?<\/think>/g, "").trim()
64
- try {
65
- return { value: JSON.parse(raw.replace(/^```(?:json)?\s*|\s*```$/g, "")) }
66
- } catch {
67
- // The first balanced {...}, skipping braces inside strings
68
- for (let start = raw.indexOf("{"); start !== -1; start = raw.indexOf("{", start + 1)) {
69
- let depth = 0
70
- let quoted = false
71
- for (let i = start; i < raw.length; i++) {
72
- const c = raw[i]
73
- if (quoted) {
74
- if (c === "\\") i++
75
- else if (c === '"') quoted = false
76
- } else if (c === '"') quoted = true
77
- else if (c === "{") depth++
78
- else if (c === "}" && --depth === 0) {
79
- try {
80
- return { value: JSON.parse(raw.slice(start, i + 1)) }
81
- } catch {
82
- break
83
- }
84
- }
63
+ // Some providers send the content as parts: [{ type: "text", text }]
64
+ const joined = Array.isArray(text) ? text.map((part) => (typeof part === "string" ? part : (part?.text ?? ""))).join("") : text
65
+ const raw = String(joined ?? "").replace(/<think>[\s\S]*?<\/think>/g, "").trim()
66
+ // A trailing comma is the commonest near-miss; a comma before a closer is never meaningful
67
+ const lenient = (json) => {
68
+ try {
69
+ return { value: JSON.parse(json) }
70
+ } catch {
71
+ try {
72
+ return { value: JSON.parse(json.replace(/,(\s*[}\]])/g, "$1")) }
73
+ } catch {
74
+ return null
75
+ }
76
+ }
77
+ }
78
+ const whole = lenient(raw.replace(/^```(?:json)?\s*|\s*```$/g, ""))
79
+ if (whole) return whole
80
+ // The first balanced {...}, skipping braces inside strings
81
+ for (let start = raw.indexOf("{"); start !== -1; start = raw.indexOf("{", start + 1)) {
82
+ let depth = 0
83
+ let quoted = false
84
+ for (let i = start; i < raw.length; i++) {
85
+ const c = raw[i]
86
+ if (quoted) {
87
+ if (c === "\\") i++
88
+ else if (c === '"') quoted = false
89
+ } else if (c === '"') quoted = true
90
+ else if (c === "{") depth++
91
+ else if (c === "}" && --depth === 0) {
92
+ const found = lenient(raw.slice(start, i + 1))
93
+ if (found) return found
94
+ break
85
95
  }
86
96
  }
87
- return { problem: finish === "length" || !raw ? "was cut off before it finished (too long)" : "isn't valid JSON" }
88
97
  }
98
+ return finish === "length" || !raw ? { problem: "was cut off before it finished (too long)", kind: "cut_off" } : { problem: "isn't valid JSON", kind: "no_json" }
89
99
  }
90
100
 
91
101
  /**
@@ -102,10 +112,11 @@ export function createAsk({ governor, record = () => {}, budget = { take: () =>
102
112
  // through the Governor's backoff for half an hour
103
113
  let unavailable = false
104
114
  /**
105
- * @param {{ task: string, tier?: string, schema: object, recipe?: string, view: string, request: string, maxOutput: number, check?: (value: any) => string[], fallback: () => any, priority?: number, signal?: AbortSignal }} slot
115
+ * @param {{ task: string, tier?: string, schema: object, recipe?: string, view: string, request: string, maxOutput: number, check?: (value: any) => string[], clean?: (value: any) => any, fallback: () => any, priority?: number, signal?: AbortSignal }} slot
116
+ * clean: tidies a parsed answer before the schema sees it (a model's nulls for absent fields)
106
117
  * @returns {Promise<{ value: any, source: "model" | "repaired" | "default", reason?: string, calls: number }>}
107
118
  */
108
- return async function ask({ task, tier = "budget", schema, recipe = "", view, request, maxOutput, check = () => [], fallback, priority = PRIORITY.job, signal }) {
119
+ return async function ask({ task, tier = "budget", schema, recipe = "", view, request, maxOutput, check = () => [], clean = (value) => value, fallback, priority = PRIORITY.job, signal }) {
109
120
  const messages = [
110
121
  { role: "system", content: `${DIRECTOR_CORE}\n\n${recipe}`.trim() },
111
122
  { role: "user", content: `${view}\n\n${request}` },
@@ -135,8 +146,12 @@ export function createAsk({ governor, record = () => {}, budget = { take: () =>
135
146
  const usage = reply?.usage ?? {}
136
147
  const content = reply?.choices?.[0]?.message?.content
137
148
  const parsed = parseReply(content, reply?.choices?.[0]?.finish_reason)
138
- const problems = parsed.problem ? [parsed.problem] : [...schemaErrors(schema, parsed.value), ...(schemaErrors(schema, parsed.value).length ? [] : check(parsed.value))]
139
- record({ task, tier, input_tokens: usage.prompt_tokens ?? null, cached_tokens: usage.prompt_tokens_details?.cached_tokens ?? null, output_tokens: usage.completion_tokens ?? null, ms: Date.now() - started, result: problems.length ? "invalid" : attempt ? "repaired" : "ok" })
149
+ if (!parsed.problem) parsed.value = clean(parsed.value)
150
+ const shape = parsed.problem ? [] : schemaErrors(schema, parsed.value)
151
+ const problems = parsed.problem ? [parsed.problem] : [...shape, ...(shape.length ? [] : check(parsed.value))]
152
+ // Why it was refused, never what it said: the journal holds no answer (ES-12)
153
+ const why = parsed.kind ?? (shape.length ? "schema" : "meaning")
154
+ record({ task, tier, input_tokens: usage.prompt_tokens ?? null, cached_tokens: usage.prompt_tokens_details?.cached_tokens ?? null, output_tokens: usage.completion_tokens ?? null, ms: Date.now() - started, result: problems.length ? `invalid:${why}` : attempt ? "repaired" : "ok" })
140
155
  if (!problems.length) return { value: parsed.value, source: attempt ? "repaired" : "model", calls }
141
156
  if (attempt === 0) {
142
157
  // One repair, with the exact reasons
@@ -0,0 +1,335 @@
1
+ // Visual beats (VISUAL_SCENES.md, EDD-51): which moments of the speech become an explainer
2
+ // scene. One model slot proposes them as typed JSON; code decides everything that can be
3
+ // decided: the words must have been said, the numbers must have been said here, and each
4
+ // scene spans whole sentences of a sensible length. With no model, code's own patterns
5
+ // find what they can, and only what they are sure of.
6
+
7
+ import { cleanScene, FLOW_MODES, SCENE_KINDS, SCENE_THEMES } from "../engine/scenes.js"
8
+ import { phraseView } from "../index/views.js"
9
+
10
+ const FLICKS = 705_600_000
11
+ const MIN_SCENE = 2.5 * FLICKS
12
+ const MAX_SCENE = 14 * FLICKS
13
+ const MIN_GAP = 1.5 * FLICKS
14
+ export const MAX_SHARE = 0.65 // of the cut under scenes: the speaker stays part of the film
15
+ export const MAX_SCENES = 10
16
+
17
+ /* ─────────────────────────────── what was said ─────────────────────────────── */
18
+
19
+ const SMALL = new Set("a an the of to in on at by for from with and or but so if as is are was were be been it its this that these those your you we our their his her they he she i my me not no do does did has have had will would can could should then than very more most into out up down over under about how what why when where which who".split(" "))
20
+ const tokens = (text) => String(text).normalize("NFKC").toLowerCase().split(/[^\p{L}\p{N}.,%]+/u).map((t) => t.replace(/^[.,]+|[.,]+$/g, "")).filter(Boolean)
21
+ // shortcut: English endings only; a label in another language must match the transcript's word as it stands
22
+ const stem = (word) => (word.length > 4 ? word.replace(/(?:ing|ed|es|s)$/, "") : word)
23
+ const isNumber = (token) => /^\d[\d.,]*%?$/.test(token)
24
+ const bare = (token) => token.replace(/%$/, "").replace(/,/g, "")
25
+
26
+ const ONES = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
27
+ const TENS = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
28
+
29
+ /** Numbers in spoken words, as digits: "seventy five" → "75", "two hundred" → "200", "a thousand" → "1000". */
30
+ export function numbersSaid(text) {
31
+ const out = new Set()
32
+ const words = tokens(text)
33
+ let current = null
34
+ const flush = () => {
35
+ if (current !== null) out.add(String(current))
36
+ current = null
37
+ }
38
+ for (const word of words) {
39
+ if (isNumber(word)) {
40
+ flush()
41
+ out.add(bare(word))
42
+ continue
43
+ }
44
+ const one = ONES.indexOf(word)
45
+ const ten = TENS.indexOf(word)
46
+ if (one >= 0) current = (current ?? 0) + one
47
+ else if (ten >= 2) current = (current ?? 0) + ten * 10
48
+ else if (word === "hundred" || word === "thousand") current = (current ?? 1) * (word === "hundred" ? 100 : 1000)
49
+ else if (!(word === "and" && current !== null)) flush()
50
+ }
51
+ flush()
52
+ return out
53
+ }
54
+
55
+ const UNITS = { "%": /percent|per cent|%/i, mg: /milligram|\bmg\b/i, g: /\bgrams?\b|\bg\b/i, kg: /kilo/i, km: /kilomet/i, m: /\bmet(?:er|re)s?\b/i, cm: /centimet/i, mm: /millimet/i, l: /lit(?:er|re)s?\b/i, ml: /millilit/i, s: /\bseconds?\b/i, min: /\bminutes?\b/i, h: /\bhours?\b/i, x: /\btimes\b/i, "₹": /rupee|₹/i, $: /dollar|\$/ }
56
+
57
+ /**
58
+ * Why a scene's words aren't the speaker's: every word on screen was said somewhere in the
59
+ * take, and every number was said in or next to this scene's own lines. Nothing else
60
+ * reaches the screen, so a model can't add a fact (a figure, a name) the person never said.
61
+ * @param {object} scene from cleanScene
62
+ * @param {{ all: string, near: string }} said the whole take's text, and this scene's lines with their neighbours
63
+ * @returns {string[]}
64
+ */
65
+ export function groundProblems(scene, { all, near }) {
66
+ const problems = []
67
+ const known = new Set(tokens(all).map(stem))
68
+ const numbers = numbersSaid(near)
69
+ const check = (text) => {
70
+ for (const token of tokens(text)) {
71
+ if (isNumber(token)) {
72
+ if (!numbers.has(bare(token))) problems.push(`the number "${token}" isn't said in this scene's lines`)
73
+ } else if (!SMALL.has(token) && !known.has(stem(token))) problems.push(`"${token}" isn't in the speaker's words`)
74
+ }
75
+ }
76
+ check(scene.title)
77
+ for (const item of scene.items) {
78
+ check(item.text)
79
+ if (item.value !== undefined && !numbers.has(item.value.replace(/,/g, ""))) problems.push(`the number "${item.value}" isn't said in this scene's lines`)
80
+ if (item.unit) {
81
+ const cue = UNITS[item.unit.toLowerCase()]
82
+ if (cue ? !cue.test(near) : !known.has(stem(item.unit.toLowerCase()))) problems.push(`the unit "${item.unit}" isn't said in this scene's lines`)
83
+ }
84
+ }
85
+ return problems
86
+ }
87
+
88
+ /* ─────────────────────────────── phrases ─────────────────────────────── */
89
+
90
+ const MAX_PHRASE = 8 * FLICKS
91
+ const MIN_PHRASE = 1.2 * FLICKS
92
+ const PAUSE = 0.35 * FLICKS
93
+ const CLAUSE = /^(?:so|but|because|where|which|as|then|when|while|resulting|despite|without|until|since|although)$/i
94
+
95
+ /**
96
+ * A take's phrases: what a scene can start and end on. Recognised speech has few sentence
97
+ * marks (found on a real take: one "sentence" of 29 s, another of 22 s), so a sentence is too
98
+ * coarse; a phrase ends at a sentence end, a pause or a new clause, and caps at 8 s.
99
+ * @returns {{ first: number, last: number, start: number, end: number, text: string }[]} first, last: positions in `words`
100
+ */
101
+ export function phrasesOf(index, asset) {
102
+ const words = (index.words ?? []).filter((w) => w.asset === asset)
103
+ const ends = new Set((index.sentences ?? []).filter((s) => s.asset === asset).map((s) => s.lastWord))
104
+ const out = []
105
+ let first = 0
106
+ const close = (last) => {
107
+ out.push({ first, last, start: words[first].start, end: words[last].end, text: words.slice(first, last + 1).map((w) => w.text).join(" ") })
108
+ first = last + 1
109
+ }
110
+ for (let i = 0; i < words.length; i++) {
111
+ const next = words[i + 1]
112
+ if (!next || ends.has(words[i].id)) {
113
+ close(i)
114
+ continue
115
+ }
116
+ const length = words[i].end - words[first].start
117
+ if (next.start - words[i].end >= PAUSE && length >= MIN_PHRASE) close(i)
118
+ else if (CLAUSE.test(tokens(next.text)[0] ?? "") && length >= MIN_PHRASE) close(i)
119
+ else if (next.end - words[first].start > MAX_PHRASE) close(i)
120
+ }
121
+ return out
122
+ }
123
+
124
+ /* ─────────────────────────────── placing ─────────────────────────────── */
125
+
126
+ const out = (word, cuts) => cuts.some((c) => (word.start + word.end) / 2 >= c.from * FLICKS && (word.start + word.end) / 2 < c.to * FLICKS)
127
+ const OPENING = 3 * FLICKS // the speaker is seen first
128
+ const NEAR = 6 * FLICKS // "said in or next to this scene's lines"
129
+
130
+ /**
131
+ * Scenes that may be made, in order: real words, forward, on phrase edges, a sensible length,
132
+ * room between them, under the share, words grounded. Each dropped one says why.
133
+ * @param {object[]} raw a model's or a browser's scenes; from and to are word ids or sentence ids
134
+ * @param {{ index: object, asset: string, cuts?: { from: number, to: number }[], limit?: number }} input cuts in seconds of the take
135
+ */
136
+ export function arrangeScenes(raw, { index, asset, cuts = [], limit = MAX_SCENES }) {
137
+ const words = (index.words ?? []).filter((w) => w.asset === asset)
138
+ const total = words.length ? words.at(-1).end - words[0].start : 0
139
+ const phrases = phrasesOf(index, asset)
140
+ const position = new Map(words.map((w, i) => [w.id, i]))
141
+ const sentence = new Map((index.sentences ?? []).filter((s) => s.asset === asset).map((s) => [s.id, s]))
142
+ const phraseAt = (i) => phrases.findIndex((p) => i >= p.first && i <= p.last)
143
+ const startOf = (id) => phraseAt(position.get(sentence.get(id)?.firstWord ?? id) ?? -1)
144
+ const endOf = (id) => phraseAt(position.get(sentence.get(id)?.lastWord ?? id) ?? -1)
145
+ const all = words.map((w) => w.text).join(" ")
146
+ const dropped = []
147
+ const placed = []
148
+ const spans = (Array.isArray(raw) ? raw : [])
149
+ .map(cleanScene)
150
+ .filter(Boolean)
151
+ .map((scene) => ({ scene, i: startOf(scene.from), k: endOf(scene.to) }))
152
+ .sort((a, b) => (a.i < 0 ? Infinity : a.i) - (b.i < 0 ? Infinity : b.i))
153
+ let used = 0
154
+ for (const { scene, i, k: asked } of spans) {
155
+ const drop = (reason) => dropped.push({ scene, reason })
156
+ if (i < 0 || asked < i) {
157
+ drop("its lines aren't in this take")
158
+ continue
159
+ }
160
+ let k = asked
161
+ // A short phrase takes the next one with it, so a scene is on screen long enough to read
162
+ while (k + 1 < phrases.length && phrases[k].end - phrases[i].start < MIN_SCENE) k++
163
+ const start = phrases[i].start
164
+ const end = phrases[k].end
165
+ const span = end - start
166
+ if (!words.length || start - words[0].start < OPENING) drop("the first line stays on the speaker, as the hook")
167
+ else if (span < MIN_SCENE) drop("its lines are too short to read a scene")
168
+ else if (span > MAX_SCENE) drop("its lines run too long for one scene")
169
+ else if (words.some((w) => w.start >= start && w.end <= end && out(w, cuts))) drop("it covers a stretch you asked to trim")
170
+ else if (placed.length && start - placed.at(-1).end < MIN_GAP) drop("it comes too soon after the last scene")
171
+ else if (placed.length >= limit) drop("there are already enough scenes")
172
+ else if (total && used + span > total * MAX_SHARE) drop("the speaker would hardly be seen")
173
+ else {
174
+ const near = words.filter((w) => w.end >= start - NEAR && w.start <= end + NEAR).map((w) => w.text).join(" ")
175
+ const wrong = groundProblems(scene, { all, near })
176
+ if (wrong.length) drop(wrong[0])
177
+ else {
178
+ used += span
179
+ placed.push({ start, end, scene: { ...scene, from: words[phrases[i].first].id, to: words[phrases[k].last].id } })
180
+ }
181
+ }
182
+ }
183
+ return { scenes: placed.map((p) => p.scene), dropped }
184
+ }
185
+
186
+ /**
187
+ * The word each label is spoken on, in order, so it lands as it's said; null where the
188
+ * label's words aren't in these words (it then comes in evenly).
189
+ * @param {object} scene
190
+ * @param {{ id: string, text: string }[]} spoken the scene's words, in order
191
+ */
192
+ export function revealWords(scene, spoken) {
193
+ let from = 0
194
+ return scene.items.map((item) => {
195
+ const wanted = new Set([...tokens(item.text), ...(item.value ? [item.value] : [])].filter((t) => !SMALL.has(t)).map(stem))
196
+ for (let i = from; i < spoken.length; i++) {
197
+ if (tokens(spoken[i].text).some((t) => wanted.has(stem(t)) || wanted.has(bare(t)))) {
198
+ from = i + 1
199
+ return spoken[i]
200
+ }
201
+ }
202
+ return null
203
+ })
204
+ }
205
+
206
+ /* ─────────────────────────────── code's own beats ─────────────────────────────── */
207
+
208
+ const LEAD = /^(?:(?:so|and|but|then|now|that|this|the|a|an|your|our|it|when|because|which|without)\s+)+/i
209
+ const HELPERS = /\s+(?:starts?|begins?|keeps?|tends?|continues?|is|are|was|were|will)(?:\s+to)?$/i
210
+ function phrase(text, words = 4) {
211
+ const cleaned = String(text).replace(/[^\p{L}\p{N}%' -]+/gu, " ").replace(/\s+/g, " ").trim().replace(LEAD, "").replace(HELPERS, "")
212
+ return cleaned.split(" ").slice(-words).join(" ").slice(0, 32).trim()
213
+ }
214
+ const CHAIN = /\s*(?:\bwhich (?:then )?(?:leads? to|causes?|makes?)\b|\bleads? to\b|\bcauses?\b|\bturns? into\b|\bresults? in\b|\band then\b|\bthen\b|→)\s*/i
215
+ const FLOW = /\b([\p{L}\p{N} '-]{3,30}?)\s+(flood|flow|mov|enter|travel|pass|go)(?:s|es|ing|ed)?\s+(?:in ?to|through|to)\s+(?:the\s+|your\s+|a\s+)?([\p{L}\p{N} '-]{3,30})/iu
216
+ const VERSUS = /\b([\p{L}\p{N} '-]{3,30}?)\s+(?:versus|vs\.?|compared (?:to|with)|unlike)\s+(?:the\s+|a\s+)?([\p{L}\p{N} '-]{3,30})/iu
217
+ const PERCENT = /\b(\d{1,3}(?:\.\d{1,2})?)\s*(?:%|percent\b|per cent\b)\s*(?:of\s+)?([\p{L}\p{N} '-]{3,40})?/iu
218
+
219
+ /**
220
+ * The beats code is sure of, from what the sentence says outright.
221
+ * shortcut: English patterns only; with no model, speech in another language gets no scene. A model reads any language.
222
+ */
223
+ export function codeBeats(index, asset) {
224
+ const out = []
225
+ const words = (index.words ?? []).filter((w) => w.asset === asset)
226
+ for (const { first, last, text } of phrasesOf(index, asset)) {
227
+ const base = { from: words[first].id, to: words[last].id, title: "" }
228
+ const percent = PERCENT.exec(text)
229
+ const flow = FLOW.exec(text)
230
+ const versus = VERSUS.exec(text)
231
+ const chain = text.split(CHAIN).map((part) => phrase(part)).filter(Boolean)
232
+ if (percent && phrase(percent[2] ?? "")) out.push({ ...base, kind: "stat", items: [{ text: String(percent[2]).trim().split(" ").slice(0, 5).join(" ").slice(0, 32).trim(), value: percent[1], unit: "%" }] })
233
+ else if (versus && phrase(versus[1]) && phrase(versus[2])) out.push({ ...base, kind: "compare", items: [{ text: phrase(versus[1]) }, { text: String(versus[2]).trim().split(" ").slice(0, 4).join(" ").slice(0, 32).trim() }] })
234
+ else if (flow && phrase(flow[1]) && phrase(flow[3])) out.push({ ...base, kind: "flow", mode: /flood/i.test(flow[2]) ? "floods" : /\b(?:can't|cannot|can not|blocked|stops?)\b/i.test(text) ? "blocked" : "flows", items: [{ text: phrase(flow[1]) }, { text: String(flow[3]).trim().split(" ").slice(0, 4).join(" ").slice(0, 32).trim() }] })
235
+ else if (chain.length >= 3 && chain.length <= 5) out.push({ ...base, kind: "process", items: chain.map((text) => ({ text })) })
236
+ }
237
+ return out
238
+ }
239
+
240
+ /* ─────────────────────────────── the slot ─────────────────────────────── */
241
+
242
+ const SCENES_SCHEMA = {
243
+ type: "object",
244
+ properties: {
245
+ contentType: { type: "string", enum: ["explainer", "tutorial", "story", "opinion", "interview", "vlog", "promo", "other"] },
246
+ theme: { type: "string", enum: Object.keys(SCENE_THEMES) },
247
+ scenes: {
248
+ type: "array",
249
+ maxItems: MAX_SCENES,
250
+ items: {
251
+ type: "object",
252
+ properties: {
253
+ from: { type: "string", maxLength: 64 },
254
+ to: { type: "string", maxLength: 64 },
255
+ kind: { type: "string", enum: Object.keys(SCENE_KINDS) },
256
+ mode: { type: "string", enum: FLOW_MODES },
257
+ title: { type: "string", maxLength: 60 },
258
+ items: {
259
+ type: "array",
260
+ maxItems: 6,
261
+ items: { type: "object", properties: { text: { type: "string", maxLength: 32 }, value: { type: "string", maxLength: 12 }, unit: { type: "string", maxLength: 8 } }, required: ["text"], additionalProperties: false },
262
+ },
263
+ },
264
+ required: ["from", "to", "kind", "title", "items"],
265
+ additionalProperties: false,
266
+ },
267
+ },
268
+ },
269
+ required: ["contentType", "theme", "scenes"],
270
+ additionalProperties: false,
271
+ }
272
+
273
+ const SAID_OFF = /\b(?:no|without|skip|don't (?:want|add|use)|do not (?:want|add|use))\s+(?:any\s+|the\s+)?(?:animations?|diagrams?|visuals?|graphics|scenes|illustrations?)\b/i
274
+ const SAID_ON = /\b(?:animat\w*|diagrams?|visuals?|graphics|illustrat\w*|explainer|cutaways?)\b/i
275
+ const SAID_THEMES = [[/\bblue ?prints?\b/i, "blueprint"], [/\bchalk ?(?:board)?\b|\bblackboard\b/i, "chalk"], [/\bpaper\b|\bwhite ?board\b|\blight (?:look|theme|background)\b/i, "paper"], [/\blab\b|\bdark (?:look|theme|background)\b/i, "lab"]]
276
+ // Types of video where a diagram is usually what the viewer needs
277
+ const EXPLAINS = new Set(["explainer", "tutorial", "promo"])
278
+
279
+ /** What the person's words say about scenes: "off", "on", or null. */
280
+ export function visualsIn(text) {
281
+ return SAID_OFF.test(text) ? "off" : SAID_ON.test(text) ? "on" : null
282
+ }
283
+
284
+ const themeIn = (text) => SAID_THEMES.find(([cue]) => cue.test(text))?.[1] ?? null
285
+
286
+ /**
287
+ * The scenes for a plan. The person's words come first: "no animations" means none and no
288
+ * call. A revision that doesn't mention them keeps the ones on the card.
289
+ * @param {{ ask: Function, index: object, asset: string, text: string, history?: object[], previous?: object | null, cuts?: object[], signal?: AbortSignal }} input
290
+ * @returns {Promise<{ scenes: object[], contentType: string | null, source: string, dropped: object[] }>}
291
+ */
292
+ export async function planScenes({ ask, index, asset, text, history = [], previous = null, cuts = [], signal }) {
293
+ const said = [...history.filter((h) => h.who === "you").map((h) => h.text), text]
294
+ const verdict = said.map(visualsIn).filter(Boolean).at(-1) ?? null
295
+ if (verdict === "off") return { scenes: [], contentType: null, source: "person", dropped: [] }
296
+ const themeSaid = said.map(themeIn).filter(Boolean).at(-1) ?? null
297
+ const restyle = (scenes) => (themeSaid ? scenes.map((scene) => ({ ...scene, theme: themeSaid })) : scenes)
298
+ const kept = previous?.settings?.scenes
299
+ if (Array.isArray(kept) && !visualsIn(text)) {
300
+ const { scenes, dropped } = arrangeScenes(restyle(kept), { index, asset, cuts })
301
+ return { scenes, contentType: null, source: "kept", dropped }
302
+ }
303
+ const words = (index.words ?? []).filter((w) => w.asset === asset)
304
+ const phrases = phrasesOf(index, asset)
305
+ const usable = words.length ? (words.at(-1).end - words[0].start) / FLICKS : 0
306
+ const limit = Math.max(1, Math.min(MAX_SCENES, Math.round(usable / 9)))
307
+ if (phrases.length < 2) return { scenes: [], contentType: null, source: "code", dropped: [] }
308
+ const hints = codeBeats(index, asset)
309
+ const kinds = Object.entries(SCENE_KINDS).map(([id, kind]) => `- ${id} (${kind.min === kind.max ? kind.min : `${kind.min} to ${kind.max}`} items): ${kind.when}`).join("\n")
310
+ const request = [
311
+ `The person says (their own words, trusted): ${JSON.stringify(String(text).slice(0, 1200))}`,
312
+ "You are the Director choosing the moments where an animated explainer scene takes over the frame while the speaker's voice keeps playing, the way a top science channel cuts away from the presenter to show the idea. First decide the contentType of this video.",
313
+ verdict === "on" ? "The person asked for visuals, so propose them whatever the contentType." : "If this video isn't explaining something (a story, an opinion, a personal moment, a vlog), answer with no scenes: a diagram would get in the way.",
314
+ `Choose up to ${limit} scenes, the moments that are hard to picture from words alone: how something works, a cause and effect, a process, numbers. Keep the speaker on screen for the opening line, for anything personal or emotional and for calls to action. Let the film breathe: leave the speaker on screen between scenes.`,
315
+ `A scene covers whole phrases, about 3 to 12 seconds: \`from\` is the first word id of its first phrase, \`to\` the last word id of its last phrase. Choose lines where something can be shown, and start each scene as the idea starts. The kinds:\n${kinds}`,
316
+ "Hard rules, checked by code, which throws away a scene that breaks them: every word on the scene comes from what the speaker actually says, in the speaker's language, as short labels of 1 to 4 words; a number only if the speaker says it in those lines, as digits, in `value`, with `unit` only if they say the unit. Never add a fact, figure or name of your own, however true. List items in the order they are spoken. `title` is at most 6 of the speaker's words, or empty.",
317
+ "Use a variety of kinds, each right for its moment. Choose one theme for the whole film: lab (dark, scientific), blueprint (engineering), chalk (a lesson), paper (light).",
318
+ hints.length ? `Code found these candidates, which may help: ${JSON.stringify(hints.slice(0, 8).map((h) => ({ from: h.from, kind: h.kind })))}.` : "",
319
+ ].filter(Boolean).join("\n")
320
+ // A scene that fails is dropped below; only a whole answer with nothing usable goes back to the model
321
+ const check = ({ scenes }) => {
322
+ if (!scenes.length) return []
323
+ const tried = arrangeScenes(scenes, { index, asset, cuts, limit })
324
+ return tried.scenes.length ? [] : tried.dropped.slice(0, 3).map((d) => `scene on ${d.scene.from}: ${d.reason}`)
325
+ }
326
+ const slot = (tier) => ask({ task: "scenes", tier, schema: SCENES_SCHEMA, view: phraseView(phrases.map((p) => ({ ...p, from: words[p.first].id, to: words[p.last].id }))), request, maxOutput: 2200, check, fallback: () => ({ contentType: "other", theme: "lab", scenes: hints }), signal, priority: 0 })
327
+ let answer = await slot("balanced")
328
+ // Refused before it answered (a plan without that tier): the budget model can still do this
329
+ if (answer.source === "default" && answer.calls === 1) answer = await slot("budget")
330
+ const { value } = answer
331
+ if (answer.source !== "default" && verdict !== "on" && !EXPLAINS.has(value.contentType)) return { scenes: [], contentType: value.contentType, source: answer.source, dropped: [] }
332
+ const themed = restyle((value.scenes ?? []).map((scene) => ({ ...scene, theme: value.theme })))
333
+ const { scenes, dropped } = arrangeScenes(themed, { index, asset, cuts, limit })
334
+ return { scenes, contentType: value.contentType ?? null, source: answer.source, dropped }
335
+ }
@@ -0,0 +1,133 @@
1
+ // What the speech names that the footage doesn't show (DP4, DP6, EDD-52, EDD-57): one slot picks the
2
+ // lines where viewers would want to see a real place or thing and the hard terms worth defining;
3
+ // code places them, the server searches licensed sources, and the person approves each on the card.
4
+ // Search words leave the computer, so this runs only with editing.mediaSearch on.
5
+
6
+ import { paperEdit } from "../index/views.js"
7
+ import { phrasesOf } from "./beats.js"
8
+
9
+ const FLICKS = 705_600_000
10
+ const OPENING = 3 * FLICKS
11
+ const MIN = 2.5 * FLICKS
12
+ const MAX = 12 * FLICKS
13
+ const GAP = 1 * FLICKS
14
+ export const MAX_PICTURES = 8
15
+ export const MAX_TERMS = 4
16
+
17
+ const LOOKUPS_SCHEMA = {
18
+ type: "object",
19
+ properties: {
20
+ pictures: { type: "array", maxItems: MAX_PICTURES, items: { type: "object", properties: { from: { type: "string", maxLength: 64 }, to: { type: "string", maxLength: 64 }, query: { type: "string", maxLength: 80 } }, required: ["from", "to", "query"], additionalProperties: false } },
21
+ terms: { type: "array", maxItems: MAX_TERMS, items: { type: "object", properties: { at: { type: "string", maxLength: 64 }, term: { type: "string", maxLength: 60 } }, required: ["at", "term"], additionalProperties: false } },
22
+ },
23
+ required: ["pictures", "terms"],
24
+ additionalProperties: false,
25
+ }
26
+
27
+ const SAID_OFF = /\b(?:no|without|skip|don't (?:want|add|use)|do not (?:want|add|use))\s+(?:any\s+|the\s+)?(?:images?|photos?|pictures?|footage from|stock|internet)\b/i
28
+
29
+ /** Where the person said no pictures. */
30
+ export const picturesRefused = (text) => SAID_OFF.test(text)
31
+
32
+ /** The id a term's definition is kept under. */
33
+ export const termId = (term) => `term:${lower(term)}`
34
+
35
+ const lower = (text) => String(text).normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N} ]+/gu, " ").replace(/\s+/g, " ").trim()
36
+
37
+ /**
38
+ * A slot's picks, on phrase edges, clear of the scenes and each other; a term only where its words are said.
39
+ * @returns {{ pictures: { from: string, to: string, query: string }[], terms: { at: string, term: string }[] }}
40
+ */
41
+ export function arrangeLookups({ pictures = [], terms = [] }, { index, asset, scenes = [], cuts = [] }) {
42
+ const words = (index.words ?? []).filter((w) => w.asset === asset)
43
+ const position = new Map(words.map((w, i) => [w.id, i]))
44
+ const phrases = phrasesOf(index, asset)
45
+ const phraseAt = (i) => phrases.findIndex((p) => i >= p.first && i <= p.last)
46
+ const trimmed = (w) => cuts.some((c) => (w.start + w.end) / 2 >= c.from * FLICKS && (w.start + w.end) / 2 < c.to * FLICKS)
47
+ const taken = scenes.flatMap((s) => (position.has(s.from) && position.has(s.to) ? [{ start: words[position.get(s.from)].start, end: words[position.get(s.to)].end }] : []))
48
+ const out = []
49
+ const spans = pictures.map((p) => ({ p, i: phraseAt(position.get(p.from) ?? -1), k: phraseAt(position.get(p.to) ?? -1) })).filter(({ i, k }) => i >= 0 && k >= i).sort((a, b) => a.i - b.i)
50
+ for (const { p, i, k: asked } of spans) {
51
+ let k = asked
52
+ while (k + 1 < phrases.length && phrases[k].end - phrases[i].start < MIN) k++
53
+ const start = phrases[i].start
54
+ const end = phrases[k].end
55
+ const query = String(p.query ?? "").replace(/[\u0000-\u001f<>]/g, " ").trim().slice(0, 80)
56
+ if (query.length < 2 || start - words[0].start < OPENING || end - start > MAX || end - start < MIN) continue
57
+ if (words.some((w) => w.start >= start && w.end <= end && trimmed(w))) continue
58
+ if ([...taken, ...out].some((t) => start < t.end + GAP && t.start < end + GAP)) continue
59
+ out.push({ start, end, from: words[phrases[i].first].id, to: words[phrases[k].last].id, query })
60
+ }
61
+ const shown = new Set()
62
+ const keptTerms = terms.flatMap((t) => {
63
+ const at = position.get(t.at)
64
+ const term = String(t.term ?? "").replace(/[\u0000-\u001f<>]/g, " ").trim().slice(0, 60)
65
+ const said = lower(words.slice(Math.max(0, (at ?? 0) - 1), (at ?? 0) + 6).map((w) => w.text).join(" "))
66
+ const key = lower(term)
67
+ if (at === undefined || term.length < 3 || trimmed(words[at]) || shown.has(key) || !said.includes(key)) return []
68
+ if ([...taken, ...out].some((s) => words[at].start >= s.start - GAP && words[at].start <= s.end + GAP)) return []
69
+ shown.add(key)
70
+ return [{ at: t.at, term }]
71
+ })
72
+ return { pictures: out.slice(0, MAX_PICTURES).map(({ from, to, query }) => ({ from, to, query })), terms: keptTerms.slice(0, MAX_TERMS) }
73
+ }
74
+
75
+ // Clinical photographs nobody asked to see in an explainer (found live: "human pancreas" gave a skull with lesions)
76
+ const GRAPHIC = /metasta|lesion|carcinoma|tumou?r|cancer|autops|cadaver|corpse|necro|gangren|wound|surgery|surgical|dissect|injur|blood ?stain|dead body|execution/i
77
+
78
+ /**
79
+ * Search engines drift. A picture must be named for what was asked, the closest title first: every word
80
+ * asked for, then the fewest others. The person still sees each one before anything is downloaded.
81
+ */
82
+ export function rankPictures(query, items) {
83
+ const wanted = lower(query).split(" ").filter((w) => w.length > 2)
84
+ const main = [...wanted].sort((a, b) => b.length - a.length)[0]
85
+ const score = (item) => {
86
+ const title = lower(item.title.replace(/\.[a-z0-9]{3,4}$/i, ""))
87
+ const hits = wanted.filter((w) => title.includes(w)).length
88
+ return hits * 10 - title.split(" ").length
89
+ }
90
+ return items.filter((item) => !GRAPHIC.test(item.title) && (!main || lower(item.title).includes(main))).sort((a, b) => score(b) - score(a))
91
+ }
92
+
93
+ /**
94
+ * @param {{ ask: Function, index: object, asset: string, text: string, scenes?: object[], cuts?: object[], search: (queries: string[]) => Promise<object[]>, define: (terms: string[]) => Promise<object[]>, wantTerms?: boolean, wantPictures?: boolean, signal?: AbortSignal }} input
95
+ * @returns {Promise<{ pictures: object[], terms: object[], items: object[], definitions: object[] }>} items, definitions: everything found, for the Host to keep
96
+ */
97
+ export async function planLookups({ ask, index, asset, text, scenes = [], cuts = [], search, define, wantTerms = true, wantPictures = true, signal }) {
98
+ const none = { pictures: [], terms: [], items: [], definitions: [] }
99
+ const sentences = (index.sentences ?? []).filter((s) => s.asset === asset)
100
+ if (!sentences.length) return none
101
+ const answer = await ask({
102
+ task: "lookups",
103
+ tier: "budget",
104
+ schema: LOOKUPS_SCHEMA,
105
+ view: paperEdit({ ...index, sentences, takes: [] }, { assets: [asset] }),
106
+ request: [
107
+ `The person says (their own words, trusted): ${JSON.stringify(String(text).slice(0, 800))}`,
108
+ wantPictures ? `pictures: the moments where the speaker names a real place, building, object, animal or event the viewer would want to see and the footage doesn't show. \`from\` and \`to\` are word ids covering about 3 to 10 seconds; \`query\` is 2 to 6 English words naming that exact thing for an encyclopaedia image search. Never a private person, never a generic mood. Leave it empty if nothing is named.` : "pictures: leave empty.",
109
+ wantTerms ? "terms: up to 4 hard technical terms a general viewer wouldn't know, exactly as spoken, with `at`, the id of the term's first word. Leave it empty if there are none." : "terms: leave empty.",
110
+ ].join("\n"),
111
+ maxOutput: 900,
112
+ fallback: () => ({ pictures: [], terms: [] }),
113
+ signal,
114
+ priority: 0,
115
+ })
116
+ const arranged = arrangeLookups(answer.value, { index, asset, scenes, cuts })
117
+ const results = arranged.pictures.length ? await search([...new Set(arranged.pictures.map((p) => p.query))].slice(0, 6)) : []
118
+ const definitions = arranged.terms.length ? await define(arranged.terms.map((t) => t.term)) : []
119
+ const byQuery = new Map(results.map((r) => [r.query, r.items ?? []]))
120
+ const used = new Set()
121
+ const pictures = arranged.pictures.flatMap((p) => {
122
+ const items = rankPictures(p.query, byQuery.get(p.query) ?? []).filter((item) => !used.has(item.id))
123
+ if (!items.length) return []
124
+ used.add(items[0].id)
125
+ return [{ ...p, id: items[0].id, options: items.slice(0, 4).map(({ id, title, licence, creator, kind }) => ({ id, title, licence, creator, kind })) }]
126
+ })
127
+ const byTerm = new Map(definitions.map((d) => [d.term, d]))
128
+ const terms = arranged.terms.flatMap((t) => {
129
+ const d = byTerm.get(t.term)
130
+ return d ? [{ at: t.at, term: t.term, id: termId(t.term), quote: d.quote, source: d.source }] : []
131
+ })
132
+ return { pictures, terms, items: results.flatMap((r) => r.items ?? []), definitions }
133
+ }