@kriya-ai/harness 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/contract/SOURCE.md +3 -3
  2. package/contract/contract.json +194 -0
  3. package/package.json +1 -1
  4. package/src/edit/core/ffmpeg.js +19 -1
  5. package/src/edit/core/layout.js +24 -1
  6. package/src/edit/core/ops.js +9 -3
  7. package/src/edit/core/plan.js +36 -5
  8. package/src/edit/core/solver.js +39 -3
  9. package/src/edit/core/transitions.js +17 -0
  10. package/src/edit/director/beats.js +335 -0
  11. package/src/edit/director/continuity.js +129 -0
  12. package/src/edit/director/graphics.js +152 -0
  13. package/src/edit/director/lookups.js +133 -0
  14. package/src/edit/director/plan.js +118 -6
  15. package/src/edit/director/playbooks.js +131 -0
  16. package/src/edit/director/revise.js +49 -5
  17. package/src/edit/engine/captions.js +32 -0
  18. package/src/edit/engine/found-media.js +64 -0
  19. package/src/edit/engine/graphics.js +178 -0
  20. package/src/edit/engine/motion.js +24 -3
  21. package/src/edit/engine/scenes.js +480 -0
  22. package/src/edit/gates/copy.js +25 -5
  23. package/src/edit/gates/index.js +16 -5
  24. package/src/edit/gates/picture.js +11 -3
  25. package/src/edit/gates/text.js +20 -4
  26. package/src/edit/graph/scheduler.js +1 -1
  27. package/src/edit/host/deliver.js +8 -1
  28. package/src/edit/host/main.js +8 -5
  29. package/src/edit/host/paths.js +15 -2
  30. package/src/edit/host/projects.js +229 -12
  31. package/src/edit/host/server.js +72 -3
  32. package/src/edit/index/views.js +9 -0
  33. package/src/edit/loop/make.js +25 -6
  34. package/src/edit/recipes/graphic-clips.js +57 -0
  35. package/src/edit/recipes/montage.js +74 -0
  36. package/src/edit/recipes/programme.js +24 -0
  37. package/src/edit/recipes/reel.js +65 -14
  38. package/src/edit/recipes/scene-clips.js +127 -0
  39. package/src/edit/runtime/fetch.js +33 -0
  40. package/studio/dist/studio.css +15 -0
  41. package/studio/dist/studio.js +3 -3
@@ -7,7 +7,7 @@ import { join } from "node:path"
7
7
 
8
8
  import { outputFaces } from "../core/faces.js"
9
9
  import { segmentArgs } from "../core/ffmpeg.js"
10
- import { safeZoneFor } from "../core/layout.js"
10
+ import { isSceneBlock, safeZoneFor } from "../core/layout.js"
11
11
  import { wholeSegment } from "../core/plan.js"
12
12
  import { captionComposition, READING_LIMITS, scriptOf } from "../engine/captions.js"
13
13
  import { compositionFor, measureText } from "../engine/motion.js"
@@ -15,6 +15,7 @@ import { compositionFor, measureText } from "../engine/motion.js"
15
15
  const FLICKS = 705_600_000
16
16
  const SETTLE_MS = { caption: 350, block: 950 } // the entrances' lengths, so a beat sees text at rest
17
17
 
18
+ const MIN_PAGE_SECONDS = 1.2
18
19
  const overlaps = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
19
20
  const frameMs = (fps) => (1000 * fps.d) / fps.n
20
21
  const rounded = (box) => ({ x: Math.round(box.x), y: Math.round(box.y), w: Math.round(box.w), h: Math.round(box.h) })
@@ -85,7 +86,10 @@ export function judgeLayout({ plan, project, index, measured }) {
85
86
  if (box.clipped) fail("clipped", item)
86
87
  // Behind-the-speaker text may cross the face: the matte draws the speaker over it
87
88
  const behind = item.tile.node.behind === true && !item.tile.front
88
- if (!behind) {
89
+ // A scene covers the frame while it's on: no face is in the picture under its text or its captions
90
+ // Other footage laid over the whole frame hides it the same way
91
+ const covered = plan.tiles.some((tile) => isSceneBlock(tile.node) && tile.at <= item.t && item.t < tile.end) || wholeSegment(plan).node.overlays.some((o) => o.at <= item.t && item.t < o.end)
92
+ if (!behind && !covered) {
89
93
  const face = faces.find((f) => Math.abs(f.t - item.t) <= FLICKS * 0.6 && overlaps(box, f.box))
90
94
  if (face) fail("on_face", item, { face: face.box })
91
95
  }
@@ -142,6 +146,14 @@ export function boxContrast(rgb, width, height, box, { colours, plate }, share =
142
146
  return values.length ? values[Math.floor(values.length * share)] : null
143
147
  }
144
148
 
149
+ /** The contrast of text against its own outline, when the outline is thick enough to read as one; else null. */
150
+ export function strokeContrast({ colours, stroke, strokeWidth, size }) {
151
+ const edge = parseColour(stroke)
152
+ if (!edge || !(strokeWidth >= Math.max(2, (size ?? 0) * 0.05))) return null
153
+ const texts = (colours ?? []).map(parseColour).filter(Boolean).map((c) => luminance(c.rgb))
154
+ return texts.length ? Math.min(...texts.map((t) => contrast(t, luminance(edge.rgb)))) : null
155
+ }
156
+
145
157
  /** Raw RGB frames of the plan, without the tiles `without` names, at frame numbers. */
146
158
  async function stills(plan, frames, { inputPath, tilePath, run, without }) {
147
159
  const { width, height } = plan.output
@@ -176,7 +188,10 @@ export async function judgeLegibility({ plan, measured, inputPath, tilePath, run
176
188
  const pictures = await stills(plan, frames, { inputPath, tilePath, run, without })
177
189
  if (pictures.length !== frames.length) throw new Error("the frames behind the text couldn't be read")
178
190
  for (const item of own) {
179
- const value = boxContrast(pictures[frames.indexOf(frameOf(item.t))], width, height, item.box, item.box)
191
+ const seen = boxContrast(pictures[frames.indexOf(frameOf(item.t))], width, height, item.box, item.box)
192
+ // A real outline separates text from any picture: it counts as what's behind the text (found on real footage)
193
+ const outline = strokeContrast(item.box)
194
+ const value = seen === null ? null : Math.max(seen, outline ?? 0)
180
195
  if (value === null) continue
181
196
  worst = Math.min(worst, value)
182
197
  if (value < thresholds.contrast) fail("low_contrast", item, { contrast: Math.round(value * 100) / 100, needed: thresholds.contrast })
@@ -189,7 +204,8 @@ export async function judgeLegibility({ plan, measured, inputPath, tilePath, run
189
204
  const words = item.tile.node.words.length
190
205
  const script = scriptOf(item.tile.node.text)
191
206
  const rate = words / Math.max(seconds, 1e-3)
192
- if (rate > READING_LIMITS[script]) fail("too_fast", item, { wordsPerSecond: Math.round(rate * 100) / 100, limit: READING_LIMITS[script], script })
207
+ // Captions show what's said, so a fast speaker's page can't be slower than the speech. What a reader can't take is a page that flashes by
208
+ if (rate > READING_LIMITS[script] && seconds < MIN_PAGE_SECONDS) fail("too_fast", item, { wordsPerSecond: Math.round(rate * 100) / 100, limit: READING_LIMITS[script], script })
193
209
  }
194
210
  const numbers = { texts: items.length, worstContrast: worst === Infinity ? null : Math.round(worst * 100) / 100, needed: thresholds.contrast, failures: failures.length }
195
211
  return { status: failures.length ? "failed" : "passed", numbers, failures }
@@ -5,7 +5,7 @@
5
5
 
6
6
  import { availableParallelism } from "node:os"
7
7
 
8
- export const DEFAULT_SLOTS = { cpu: Math.max(2, availableParallelism() - 2), gpu: 1, encoder: 2, chrome: 1, model: 2, disk: 2 }
8
+ export const DEFAULT_SLOTS = { cpu: Math.max(2, availableParallelism() - 2), gpu: 1, encoder: 2, chrome: Math.min(3, Math.max(1, Math.floor(availableParallelism() / 3))), model: 2, disk: 2 }
9
9
 
10
10
  export function createScheduler(slots = DEFAULT_SLOTS) {
11
11
  const held = new Map()
@@ -64,7 +64,14 @@ export async function writeDelivery({ file, title, project, parent, plan, source
64
64
  const rights = project.assets.filter((a) => used.has(a.id)).map((a) => ({ id: a.id, rights: a.rights, role: a.role }))
65
65
  const report = reportPath(file)
66
66
  writeFileSync(report, reportHtml({ receipt, title, before, after, changes, notes, rights, repairs }))
67
- return { receipt: receiptFile, report, verdict: receipt.verdict }
67
+ // What the viewer's description must carry (CC BY asks for it): who made what was borrowed, and what's quoted
68
+ const credits = [...project.assets.filter((a) => used.has(a.id) && a.rights !== "own" && a.rightsNote && a.kind !== "reference").map((a) => a.rightsNote), ...plan.tiles.filter((t) => t.node.blockId === "term").map((t) => `"${t.node.variables.quote}" ${t.node.variables.source}${t.node.variables.page ? `, ${t.node.variables.page}` : ""}`)]
69
+ let creditsFile = null
70
+ if (credits.length) {
71
+ creditsFile = `${file}.credits.txt`
72
+ writeFileSync(creditsFile, `${[...new Set(credits)].join("\n")}\n`)
73
+ }
74
+ return { receipt: receiptFile, report, verdict: receipt.verdict, ...(creditsFile ? { credits: creditsFile } : {}) }
68
75
  }
69
76
 
70
77
  /**
@@ -12,7 +12,7 @@ import { createScheduler, DEFAULT_SLOTS } from "../graph/scheduler.js"
12
12
  import { createGovernor } from "../loop/governor.js"
13
13
  import { kriyaHome } from "../../paths.js"
14
14
  import { createJobs } from "./jobs.js"
15
- import { codeStamp, editHome, lockPath, portPath, socketPath } from "./paths.js"
15
+ import { codeStamp, editHome, isPipe, lockPath, portPath, socketPath } from "./paths.js"
16
16
  import { createProjects } from "./projects.js"
17
17
  import { createHandler } from "./server.js"
18
18
  import { createTavi } from "./tavi.js"
@@ -91,7 +91,7 @@ function shutdown() {
91
91
  server.close()
92
92
  server.closeAllConnections()
93
93
  }
94
- rmSync(socketPath(home), { force: true })
94
+ if (!isPipe(socketPath(home))) rmSync(socketPath(home), { force: true })
95
95
  tavi.close()
96
96
  watcher.close()
97
97
  projects.close()
@@ -123,9 +123,12 @@ function storedPort() {
123
123
 
124
124
  port = await listen(storedPort())
125
125
  writeFileSync(portPath(home), String(port))
126
- rmSync(socketPath(home), { force: true })
127
- await new Promise((done) => local.listen(socketPath(home), done))
128
- chmodSync(socketPath(home), 0o600)
126
+ // A Unix socket is a file: a stale one is cleared first, and only its owner may open it.
127
+ // A Windows named pipe is neither (paths.js): it goes when the Host does, and has no mode
128
+ const socket = socketPath(home)
129
+ if (!isPipe(socket)) rmSync(socket, { force: true })
130
+ await new Promise((done) => local.listen(socket, done))
131
+ if (!isPipe(socket)) chmodSync(socket, 0o600)
129
132
  log(`listening on 127.0.0.1:${port}`)
130
133
 
131
134
  void readTools()
@@ -2,12 +2,25 @@
2
2
 
3
3
  import { createHash } from "node:crypto"
4
4
  import { readdirSync, statSync } from "node:fs"
5
- import { join } from "node:path"
5
+ import { join, resolve } from "node:path"
6
6
 
7
7
  import { kriyaHome } from "../../paths.js"
8
8
 
9
9
  export const editHome = (home = kriyaHome()) => join(home, "edit")
10
- export const socketPath = (home) => join(editHome(home), "host.sock")
10
+ const PIPE = "\\\\.\\pipe\\"
11
+ /** True for a Windows named pipe: it isn't a file, so it has no mode to set and nothing to remove. */
12
+ export const isPipe = (path) => path.startsWith(PIPE)
13
+ /**
14
+ * Where the Host listens for this computer's own commands. A Unix socket in the Host's folder;
15
+ * on Windows, which has none there, a named pipe, one per Kriya home (a hash of its path,
16
+ * which Windows compares without case).
17
+ * shortcut: a pipe gets Windows' default access rules, not the socket's owner-only mode; a pipe
18
+ * limited to the signed-in person needs a native call Node doesn't offer. Not yet run on Windows.
19
+ */
20
+ export function socketPath(home = kriyaHome(), platform = process.platform) {
21
+ if (platform !== "win32") return join(editHome(home), "host.sock")
22
+ return `${PIPE}kriya-edit-host-${createHash("sha256").update(resolve(home).toLowerCase()).digest("hex").slice(0, 16)}`
23
+ }
11
24
  export const lockPath = (home) => join(editHome(home), "host.lock")
12
25
  export const portPath = (home) => join(editHome(home), "port")
13
26
  export const logPath = (home) => join(editHome(home), "host.log")
@@ -8,20 +8,30 @@ import { dirname, extname, isAbsolute, join, relative, sep } from "node:path"
8
8
  import { checkout, commit, createLog, parseEntry, undo, versions } from "../core/history.js"
9
9
  import { canonical, newProject, parseProject, serialize, sha256 } from "../core/project.js"
10
10
  import { createEngine, ENGINE_VERSION, guardPath } from "../engine/index.js"
11
- import { motionRuntime } from "../engine/motion.js"
11
+ import { blockComposition, motionRuntime } from "../engine/motion.js"
12
+ import { cleanScene, SCENE_BLOCK, SCENE_KINDS, SCENE_THEMES, SCENE_VERSION, swapsFor } from "../engine/scenes.js"
12
13
  import { parseCube } from "../engine/color.js"
13
14
  import { fingerprint } from "../engine/media.js"
14
15
  import { probe } from "../engine/probe.js"
15
16
  import { EngineFailure, runTool } from "../engine/tool.js"
16
17
  import { openJournal } from "../graph/journal.js"
17
- import { solve } from "../core/solver.js"
18
+ import { DEFAULT_RULES, solve } from "../core/solver.js"
19
+ import { safeZoneFor, sceneFrame } from "../core/layout.js"
20
+ import { revealWords } from "../director/beats.js"
21
+ import { termId } from "../director/lookups.js"
22
+ import { allowedMediaUrl, downloadMedia, MEDIA_TYPES, stillClipArgs } from "../engine/found-media.js"
23
+ import { planMontage } from "../recipes/montage.js"
24
+ import { analyseMulticam, PODCAST_MULTICAM } from "../recipes/multicam.js"
25
+ import { planProgramme, programmeRecipe } from "../recipes/programme.js"
26
+ import { defineTerms, fetchFeatures, searchMedia } from "../runtime/fetch.js"
27
+ import { readDevice } from "../../store.js"
18
28
  import { createAsk } from "../director/ask.js"
19
29
  import { LOOKS } from "../engine/captions.js"
20
30
  import { cleanSelection, cleanWord, describe, noteWord, revise } from "../director/revise.js"
21
31
  import { openIndexDb } from "../index/db.js"
22
32
  import { makeReel, rebase } from "../loop/make.js"
23
33
  import { runGates } from "../gates/index.js"
24
- import { REEL_TALKING_HEAD } from "../recipes/reel.js"
34
+ import { FORMATS, REEL_TALKING_HEAD } from "../recipes/reel.js"
25
35
  import { compareRuns, replayAsk } from "../loop/replay.js"
26
36
  import { verifiedRecogniser, writeDelivery, writeHandoff } from "./deliver.js"
27
37
  import { createIndexer, layersFor } from "../index/index.js"
@@ -30,9 +40,14 @@ import { editHome } from "./paths.js"
30
40
  import { createTaste } from "./taste.js"
31
41
  import { ASPECTS, analyseReference, cleanRefs, takeFrom } from "../engine/reference.js"
32
42
  import { briefOf, planCut } from "../director/plan.js"
43
+ import { editsSince, planDiff, storyFor } from "../director/continuity.js"
44
+ import { cleanGraphic, GRAPHIC_ACCENTS, GRAPHIC_BLOCK, GRAPHIC_FONTS, GRAPHIC_KINDS, GRAPHIC_TONES, GRAPHIC_VERSION, graphicLength, STYLE_LABELS } from "../engine/graphics.js"
33
45
  import { MOODS, writeMusicBed } from "../engine/music-bed.js"
34
46
  import { SFX, writeSfx } from "../engine/sfx.js"
35
47
 
48
+ // "start over", "from scratch": the one way a request after a make isn't a change to that cut
49
+ const STARTS_OVER = /\b(?:start (?:over|again|afresh)|from scratch|fresh (?:cut|edit|start)|brand[- ]new (?:cut|edit))\b/i
50
+
36
51
  function atomicWrite(file, text) {
37
52
  const part = `${file}.${process.pid}.tmp`
38
53
  const handle = openSync(part, "w")
@@ -77,8 +92,17 @@ const FLICKS = 705_600_000
77
92
  // Director model calls a job may make (DIRECTOR_AND_AGENT §13, short form)
78
93
  const JOB_CALLS = 40
79
94
 
80
- export function createProjects({ home, roots, scheduler, tools, governor = null }) {
95
+ // What the server has switched on, asked for at most once a minute, so turning a switch off takes effect soon
96
+ const FEATURES_MS = 60_000
97
+ const askServer = async () => {
98
+ const device = readDevice()
99
+ return device ? fetchFeatures(device) : { visuals: false, playbooks: false, mediaSearch: false }
100
+ }
101
+ const NOTHING_FOUND = { items: {}, definitions: {} }
102
+
103
+ export function createProjects({ home, roots, scheduler, tools, governor = null, features = askServer }) {
81
104
  const base = editHome(home)
105
+ let known = null
82
106
  const taste = createTaste({ home })
83
107
  const registry = join(base, "projects.json")
84
108
  const open = new Map()
@@ -270,7 +294,8 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
270
294
  /** The console: words → a proposal, applied to a copy, nothing landing yet (UX_SPEC §4, §5). */
271
295
  async ask(state, { text, selection, history = [], job = 0 }) {
272
296
  const chosen = cleanSelection(selection, state.log.current, state.index)
273
- const result = await revise({ ask: this.askFor(state, job), project: state.log.current, index: state.index, text, selection: chosen, history })
297
+ const { motion } = await this.features()
298
+ const result = await revise({ ask: this.askFor(state, job), project: state.log.current, index: state.index, text, selection: chosen, history, motion: motion && !state.engine.motion().missing })
274
299
  // A request about the whole video goes to the Director's make job; the Studio offers it
275
300
  const direct = result.direct ? { brief: { ...(result.direct.seconds ? { seconds: result.direct.seconds } : {}), ...(result.direct.captions ? { captions: result.direct.captions } : {}) } } : null
276
301
  if (!result.ops.length && !result.corrections.length) return { proposal: null, direct, say: result.say, source: result.source, reason: direct || result.say ? null : (result.reason ?? "Kriya couldn't turn that into an edit. Try saying it another way.") }
@@ -300,8 +325,143 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
300
325
  return { applied: ops.length + fixes.length, dropped: dropped.map((d) => ({ change: describe(d.op, state.index), reason: d.reason })) }
301
326
  },
302
327
 
328
+ /** What this Kriya allows now. A failed question means off. */
329
+ async features() {
330
+ if (!known || Date.now() - known.at > FEATURES_MS) known = { at: Date.now(), value: await features().catch(() => ({ visuals: false, playbooks: false, mediaSearch: false })) }
331
+ // A server from before editing.motion says nothing of it: off
332
+ return { motion: false, customMotion: false, ...known.value }
333
+ },
334
+
335
+ /** One motion graphic as the render will draw it, for the Plan Card. @returns {string} a complete document */
336
+ graphicPreview(state, raw, format) {
337
+ const graphic = cleanGraphic(raw)
338
+ if (!graphic) throw new EngineFailure("input", "bad_graphic", "That isn't a graphic from this project's plan.")
339
+ const shape = FORMATS[format] ?? FORMATS["9:16"]
340
+ const canvas = { width: shape.width, height: shape.height }
341
+ // Where a strap or a title usually lands; the make places each clear of the face and the captions
342
+ const low = graphic.kind === "lower" || graphic.kind === "end"
343
+ const placement = { x: Math.round(canvas.width * 0.1), y: Math.round(canvas.height * (low ? 0.66 : 0.42)), w: Math.floor((canvas.width * DEFAULT_RULES.boxWidth) / 100), h: Math.floor((canvas.height * DEFAULT_RULES.boxHeight) / 100) }
344
+ // A graphic sits over footage; the card shows it on a plain backdrop so a light or dark plate both read
345
+ return blockComposition({ blockId: GRAPHIC_BLOCK, version: GRAPHIC_VERSION, variables: graphic, placement, duration: graphicLength(graphic) }, { output: canvas, canvas }).replace("html,body{margin:0;background:transparent", "html,body{margin:0;background:linear-gradient(160deg,#6b7b80,#2a3437)")
346
+ },
347
+
348
+ /**
349
+ * One scene as the render will draw it, for the Plan Card: the words fall where they will,
350
+ * so the person sees the real thing before anything is rendered.
351
+ * @returns {string} a complete document
352
+ */
353
+ scenePreview(state, raw, format) {
354
+ const scene = cleanScene(raw)
355
+ const words = new Map(state.index.words.map((w) => [w.id, w]))
356
+ const from = words.get(scene?.from)
357
+ const to = words.get(scene?.to)
358
+ if (!from || !to || to.end <= from.start) throw new EngineFailure("input", "bad_scene", "That isn't a scene from this project's plan.")
359
+ const shape = FORMATS[format] ?? FORMATS["9:16"]
360
+ const canvas = { width: shape.width, height: shape.height }
361
+ const safe = safeZoneFor({ canvas, deliverables: [{ preset: shape.preset, size: canvas }] })
362
+ const { content } = sceneFrame(canvas, safe, { w: Math.floor((canvas.width * DEFAULT_RULES.boxWidth) / 100), h: Math.floor((canvas.height * DEFAULT_RULES.boxHeight) / 100) })
363
+ const duration = to.end - from.start
364
+ const landing = revealWords(scene, state.index.words.filter((w) => w.asset === from.asset && w.start >= from.start && w.end <= to.end))
365
+ const items = scene.items.map((item, i) => ({ ...item, ...(landing[i] ? { reveal: Math.round(((landing[i].start - from.start) / FLICKS) * 1000) } : {}) }))
366
+ return blockComposition({ blockId: SCENE_BLOCK, version: SCENE_VERSION, variables: { ...scene, items }, placement: content, duration }, { output: canvas, canvas })
367
+ },
368
+
369
+ foundOf(state) {
370
+ const file = join(dirOf(state.id), "cache", "found.json")
371
+ return existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : NOTHING_FOUND
372
+ },
373
+
374
+ keepFound(state, { items = [], definitions = [] }) {
375
+ const dir = join(dirOf(state.id), "cache")
376
+ mkdirSync(dir, { recursive: true })
377
+ const known = this.foundOf(state)
378
+ const next = { items: { ...known.items, ...Object.fromEntries(items.map((item) => [item.id, item])) }, definitions: { ...known.definitions, ...Object.fromEntries(definitions.map((d) => [termId(d.term), d])) } }
379
+ atomicWrite(join(dir, "found.json"), JSON.stringify(next))
380
+ },
381
+
382
+ /** A found picture's small version for the Plan Card, fetched once. Only ids this project's plan found. */
383
+ async foundThumb(state, id, { signal } = {}) {
384
+ const item = this.foundOf(state).items[id]
385
+ if (!item || !allowedMediaUrl(item.thumb)) throw new EngineFailure("input", "unknown_media", "That picture isn't from this project's plan.")
386
+ const dir = join(dirOf(state.id), "cache", "found-thumbs")
387
+ mkdirSync(dir, { recursive: true })
388
+ const base = join(dir, sha256(id).slice(0, 24))
389
+ for (const [type, extension] of Object.entries(MEDIA_TYPES)) if (existsSync(`${base}${extension}`)) return { file: `${base}${extension}`, type }
390
+ return downloadMedia(item.thumb, base, { signal, maxBytes: 12 * 1024 * 1024 })
391
+ },
392
+
393
+ /**
394
+ * The approved pictures on disk, as assets with their credit, and the approved definitions as
395
+ * kept. A still becomes a clip with a slow move. One that can't be had is left out with a note.
396
+ */
397
+ async resolveFound(state, brief, { signal, say }) {
398
+ const found = this.foundOf(state)
399
+ const words = new Map(state.index.words.map((w) => [w.id, w]))
400
+ const shape = FORMATS[brief.format] ?? FORMATS["9:16"]
401
+ const media = join(state.folder, "media")
402
+ const pictures = []
403
+ for (const { from, to, id } of brief.pictures ?? []) {
404
+ const item = found.items[id]
405
+ const first = words.get(from)
406
+ const last = words.get(to)
407
+ if (!item || !first || !last || !allowedMediaUrl(item.url)) {
408
+ say("Left out a picture that isn't from this project's plan.")
409
+ continue
410
+ }
411
+ try {
412
+ mkdirSync(media, { recursive: true })
413
+ const tag = `found-${sha256(id).slice(0, 16)}`
414
+ const seconds = Math.min(16, Math.ceil((last.end - first.start) / FLICKS) + 2)
415
+ const clipName = `${tag}-${shape.width}x${shape.height}-${seconds}s.mp4`
416
+ const note = `${item.title} by ${item.creator}, ${item.licence}, ${item.page}`
417
+ let known = state.log.current.assets.find((a) => a.path.endsWith(item.kind === "video" ? tag : clipName) || a.path.includes(`${tag}.`))
418
+ if (!known) {
419
+ const { file } = await downloadMedia(item.url, join(media, tag), { signal })
420
+ let path = file
421
+ if (item.kind === "image") {
422
+ path = join(media, clipName)
423
+ await runTool("ffmpeg", stillClipArgs({ image: file, output: path, width: shape.width, height: shape.height, seconds, inward: pictures.length % 2 === 0 }), { signal, timeoutMs: 180_000 })
424
+ }
425
+ known = await this.addAsset(state, path, { rights: item.rights, rightsNote: note })
426
+ }
427
+ pictures.push({ asset: known.id, from, to })
428
+ } catch (error) {
429
+ if (signal?.aborted) throw error
430
+ say(`Left out the picture "${item.title}": ${error.message}`)
431
+ }
432
+ }
433
+ const terms = (brief.terms ?? []).flatMap(({ at, id }) => {
434
+ const d = found.definitions[id]
435
+ return d && words.has(at) ? [{ at, term: d.term, quote: d.quote, source: d.source, page: d.page }] : []
436
+ })
437
+ return { pictures, terms }
438
+ },
439
+
440
+ /**
441
+ * The last make this cut still descends from: its brief, story, approved plan and the
442
+ * person's edits it carried (continuity.js). Null once that make is undone or none was run.
443
+ */
444
+ lastMake(state) {
445
+ try {
446
+ const last = JSON.parse(readFileSync(join(dirOf(state.id), "last-make.json"), "utf8"))
447
+ const since = editsSince(state.log, last.head)
448
+ return since ? { ...last, edits: [...(Array.isArray(last.carried) ? last.carried : []), ...since] } : null
449
+ } catch {
450
+ return null
451
+ }
452
+ },
453
+
454
+ /** The story a make of this brief keeps from the last one; null when it's chosen again. */
455
+ keptStory(state, brief) {
456
+ return brief.fresh ? null : storyFor(this.lastMake(state), brief)
457
+ },
458
+
303
459
  /** The Director's plan for the whole cut: proposed, never made until the person approves it. */
304
460
  async plan(state, { text, history = [], previous = null, choices = {}, job = 0, signal } = {}) {
461
+ // With a cut already made, a request changes that cut: the plan it was made from is the one revised
462
+ const fresh = STARTS_OVER.test(text)
463
+ const last = fresh ? null : this.lastMake(state)
464
+ previous ??= last?.plan ?? null
305
465
  // The references in use, each only for what the person took it for; with none named, every reference, whole
306
466
  const named = cleanRefs(choices.references)
307
467
  const chosen = named.length ? named : state.log.current.assets.filter((a) => a.kind === "reference").map((a) => ({ id: a.id, aspect: "all" }))
@@ -314,9 +474,25 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
314
474
  const name = `${ref.path.split(/[\\/]/).at(-1)}${aspect === "all" ? "" : ` (only for: ${ASPECTS[aspect]})`}`
315
475
  references.push({ name, lines: taken.lines.length ? taken.lines : [`nothing measured for ${ASPECTS[aspect].toLowerCase()}`] })
316
476
  }
317
- const plan = await planCut({ ask: this.askFor(state, job), project: state.log.current, index: state.index, text, history, previous, references, choices, signal })
477
+ const { visuals, playbooks, mediaSearch, motion } = await this.features()
478
+ const device = mediaSearch ? readDevice() : null
479
+ // What was found is kept here, so an approval names an id and never carries a URL or a licence from the browser
480
+ const lookups = device ? { search: (queries) => searchMedia(device, queries), define: (terms) => defineTerms(device, terms), keep: (found) => this.keepFound(state, found) } : null
481
+ const plan = await planCut({ ask: this.askFor(state, job), project: state.log.current, index: state.index, text, history, previous, references, choices, motion: motion && !state.engine.motion().missing, visuals: visuals && !state.engine.motion().missing, playbooks, lookups, signal })
482
+ const scenes = plan.settings.scenes ?? []
483
+ const brief = briefOf(plan.settings)
318
484
  // The exact brief an approval makes, so the Studio sends back what was shown
319
- return { ...plan, brief: briefOf(plan.settings) }
485
+ return {
486
+ ...plan,
487
+ brief: { ...brief, ...(fresh ? { fresh: true } : {}) },
488
+ // Said by code from the two briefs, so the card shows what an approval changes in the cut that's there,
489
+ // and whether its story stays (the same test the make route applies, in the make's own units)
490
+ ...(last ? { revises: true, differs: last.plan ? planDiff(briefOf(last.plan.settings ?? {}), brief) : [], keepsStory: !!storyFor(last, { ...(brief.seconds ? { targetDuration: Math.round(brief.seconds * FLICKS) } : {}), ...(brief.cuts ? { cuts: brief.cuts.map((c) => ({ from: Math.round(c.from * FLICKS), to: Math.round(c.to * FLICKS) })) } : {}) }) } : {}),
491
+ // What the card may restyle each graphic to: labels only, the colours and fonts stay in code
492
+ ...(plan.settings.graphics?.length ? { graphicChoices: { kinds: Object.fromEntries(Object.entries(GRAPHIC_KINDS).map(([id, kind]) => [id, { label: kind.label, styles: kind.styles }])), styles: STYLE_LABELS, accents: Object.keys(GRAPHIC_ACCENTS), tones: Object.keys(GRAPHIC_TONES), fonts: Object.keys(GRAPHIC_FONTS) } } : {}),
493
+ // What the card may swap each scene to; code says, so it can't offer what won't draw
494
+ ...(scenes.length ? { sceneChoices: { kinds: Object.fromEntries(Object.entries(SCENE_KINDS).map(([id, kind]) => [id, kind.label])), themes: Object.fromEntries(Object.entries(SCENE_THEMES).map(([id, theme]) => [id, theme.label])), swaps: scenes.map(swapsFor) } } : {}),
495
+ }
320
496
  },
321
497
 
322
498
  /** A reference's classified analysis (reference.js), kept by its fingerprint so it's measured once. */
@@ -421,9 +597,21 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
421
597
  const bed = known ?? (await this.addAsset(state, file, { rights: "own", rightsNote: "Made by Kriya's music generator: no one else's recording." }))
422
598
  request = { ...request, brief: { ...request.brief, music: bed.id } }
423
599
  }
424
- // Sound design Kriya writes itself (sfx.js): a cut sound and an intro sound, each knowing its peak
425
- const wanted = { cut: request.brief?.cutSound, intro: request.brief?.introSound }
426
- if (!replay && (wanted.cut || wanted.intro)) {
600
+ // The pictures the person approved, downloaded now and not before, and their definitions as found
601
+ if (request.brief?.pictures?.length || request.brief?.terms?.length) {
602
+ const resolved = replay ? { pictures: [], terms: [] } : await this.resolveFound(state, request.brief, { signal, say: (line) => styled.push(line) })
603
+ request = { ...request, brief: { ...request.brief, ...resolved } }
604
+ }
605
+ // Scenes are drawn by the motion layer: without it they go, with a note, rather than fail the cut
606
+ if ((request.brief?.scenes?.length || request.brief?.terms?.length) && state.engine.motion().missing) {
607
+ request = { ...request, brief: { ...request.brief, scenes: undefined, terms: undefined } }
608
+ styled.push(`No animated scenes or definitions this time: ${state.engine.motion().missing}`)
609
+ }
610
+ // Sound design Kriya writes itself (sfx.js): a cut sound and an intro sound, each knowing its peak;
611
+ // a whoosh as a scene arrives and a pop as each of its labels lands
612
+ const sceneSound = (request.brief?.scenes?.length || request.brief?.pictures?.length) && request.brief.sceneSound !== false
613
+ const wanted = { cut: request.brief?.cutSound, intro: request.brief?.introSound, scene: sceneSound ? "whoosh" : undefined, reveal: sceneSound ? "pop" : undefined }
614
+ if (!replay && (wanted.cut || wanted.intro || wanted.scene)) {
427
615
  const media = join(state.folder, "media")
428
616
  mkdirSync(media, { recursive: true })
429
617
  const sfx = {}
@@ -461,10 +649,31 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
461
649
  const run = runTool
462
650
  const work = join(dirOf(state.id), "cache", "gates")
463
651
  const sourcePath = sourcesOf(state)
652
+ // A podcast's cameras or a montage's song: their own recipes, with the same render and gates.
653
+ // Cameras that won't sync fall back to the reel, and it says so
654
+ let planner = null
655
+ let plannerRecipe = null
656
+ const direct = { ...extra, ...request.brief }
657
+ if (!replay && direct.multicam) {
658
+ const { master, angles } = direct.multicam
659
+ const facts = (id) => state.log.current.assets.find((a) => a.id === id)?.facts
660
+ if (facts(master)?.duration && angles.every((a) => facts(a.asset))) {
661
+ const analysis = await analyseMulticam({ master: { asset: master, file: sourcePath(master), duration: facts(master).duration }, angles: angles.map((a) => ({ ...a, file: sourcePath(a.asset) })) }, { signal })
662
+ if (angles.every((a) => analysis.sync[a.asset].confidence >= PODCAST_MULTICAM.syncFloor)) {
663
+ planner = () => planProgramme({ project: state.log.current, index: state.index, brief: direct, multicam: { master, angles, analysis } })
664
+ plannerRecipe = programmeRecipe
665
+ } else styled.push("The cameras' sound didn't match well enough to sync them, so this is cut from one camera.")
666
+ }
667
+ } else if (!replay && direct.montage && direct.music) {
668
+ planner = () => planMontage({ project: state.log.current, index: state.index, brief: direct })
669
+ }
464
670
  const runtime = activeRuntime(home)
465
671
  const ask = replay ? replayAsk(replay.answers) : this.askFor(state, job)
466
672
  const parent = state.log.head
673
+ // The person's edits to the last cut go onto this one, unless they asked to start over
674
+ const last = replay || request.brief?.fresh ? null : this.lastMake(state)
467
675
  const result = await makeReel({
676
+ edits: last?.edits ?? [],
468
677
  project: state.log.current,
469
678
  head: state.log.head,
470
679
  index: state.index,
@@ -474,6 +683,8 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
474
683
  render: (project, deliverable, abort) => state.engine.render({ quality: "master", deliverable, project, job, signal: abort }),
475
684
  sourcePath,
476
685
  signal,
686
+ planner,
687
+ plannerRecipe,
477
688
  onStage: (stage) => onStep(stages.indexOf(stage) + 1, stages.length + 1),
478
689
  gateKit: {
479
690
  tilePath: state.engine.tilePath,
@@ -492,11 +703,15 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
492
703
  const planHash = result.best.plan ? sha256(canonical(result.best.plan)) : null
493
704
  const repairs = result.best.repairs ?? []
494
705
  const person = result.best.person ?? []
495
- const notes = [...result.notes, ...person.map((p) => `${p.gate}: ${p.message} This is yours to decide.`)]
706
+ const carried = result.best.carried ?? []
707
+ const lost = result.best.dropped ?? []
708
+ const notes = [...result.notes, ...(carried.length ? [`Kept ${carried.length} of your own edit${carried.length === 1 ? "" : "s"} to the last cut.`] : []), ...(lost.length ? [`${lost.length} of your edits no longer fit this cut and ${lost.length === 1 ? "was" : "were"} left out: ${lost.map((d) => describe(d.op, state.index)).join("; ")}.`] : []), ...person.map((p) => `${p.gate}: ${p.message} This is yours to decide.`)]
496
709
  if (replay) return { replayOf: replay.of, verdict: gates?.verdict ?? "not_checked", gates: gates?.gates ?? [], planHash, notes, repairs, calls: result.calls, stop: result.outcome.stop }
497
710
  const { ops, dropped } = state.log.head === result.head ? { ops: result.best.ops, dropped: [] } : rebase(state.log.current, result.best.ops, state.index)
498
711
  const landed = change(state, { ops, author: "agent" })
499
712
  if (!landed.ok) throw new EngineFailure("plan", "refused", landed.diagnostics[0].message)
713
+ // What the next change to this cut starts from
714
+ atomicWrite(join(dirOf(state.id), "last-make.json"), JSON.stringify({ head: state.log.head, brief: request.brief ?? {}, story: result.best.story ?? null, carried, plan: request.plan ?? (request.brief?.fresh ? null : (last?.plan ?? null)) }))
500
715
  // A caption per spoken line is one change to a person: said once, with the count
501
716
  const captioned = ops.filter((op) => op.op === "caption_style" && op.words?.length)
502
717
  const changes = [...usedRules, ...ops.filter((op) => !["ripple_delete", "reframe", "caption_style"].includes(op.op) || (op.op === "caption_style" && !op.words?.length)).map((op) => describe(op, state.index)), ...(captioned.length ? [`Captioned ${captioned.length} line${captioned.length === 1 ? "" : "s"} (${captioned[0].look})`] : [])]
@@ -504,8 +719,10 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
504
719
  const delivery = result.best.file
505
720
  ? await writeDelivery({ file: result.best.file, title: state.log.current.name, project: result.best.project, parent, plan: result.best.plan, sourcePath, tools: { engine: ENGINE_VERSION, ffmpeg: version, runtime: runtime?.version ?? null }, gates: gates?.gates ?? [], verdict: gates?.verdict ?? "not_checked", calls: state.journal.calls(job), changes, notes, repairs, beforeFrom: sourcePath(asset), run, work })
506
721
  : null
722
+ if (delivery?.credits) changes.push(`Credits for your description are in ${delivery.credits.split(/[\\/]/).at(-1)}`)
507
723
  return {
508
724
  verdict: gates?.verdict ?? "not_checked",
725
+ credits: delivery?.credits ?? null,
509
726
  file: result.best.file ?? null,
510
727
  head: state.log.head, // the version this file shows, so the Studio can say when it's out of date
511
728
  receipt: delivery?.receipt ?? null,
@@ -519,7 +736,7 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
519
736
  slots: result.slots,
520
737
  stop: result.outcome.stop,
521
738
  attempts,
522
- dropped: dropped.map((d) => ({ change: describe(d.op, state.index), reason: d.reason })),
739
+ dropped: [...dropped, ...lost].map((d) => ({ change: describe(d.op, state.index), reason: d.reason })),
523
740
  }
524
741
  },
525
742
 
@@ -12,6 +12,9 @@ import { solve } from "../core/solver.js"
12
12
  import { LOOKS } from "../engine/captions.js"
13
13
  import { ENGINE_VERSION, guardPath } from "../engine/index.js"
14
14
  import { cleanRefs } from "../engine/reference.js"
15
+ import { cleanScene } from "../engine/scenes.js"
16
+ import { cleanGraphic } from "../engine/graphics.js"
17
+ import { TRANSITIONS } from "../core/transitions.js"
15
18
  import { EngineFailure } from "../engine/tool.js"
16
19
  import { activeRuntime } from "../runtime/setup.js"
17
20
  import { recogniser } from "../index/layers/words.js"
@@ -76,6 +79,8 @@ function page(res, type, body) {
76
79
  }
77
80
 
78
81
  const refuse = (res, status, message) => json(res, status, { error: status, message })
82
+ /** A plan as the Studio sends it back (one being revised, or the one just approved): bounded text and a settings object the Director re-checks. */
83
+ const cleanPlan = (plan) => (plan && typeof plan === "object" ? { say: String(plan.say ?? "").slice(0, 900), steps: Array.isArray(plan.steps) ? plan.steps.slice(0, 10).map((s) => String(s).slice(0, 240)) : [], settings: plan.settings && typeof plan.settings === "object" && !Array.isArray(plan.settings) && JSON.stringify(plan.settings).length <= 20_000 ? plan.settings : {} } : null)
79
84
 
80
85
  async function readJson(req) {
81
86
  const chunks = []
@@ -352,7 +357,7 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
352
357
  return say(200, { ...result, ...projectView(state) })
353
358
  }
354
359
  if (parts[2] === "make" && parts.length === 3 && method === "POST") {
355
- const { asset, brief } = await readJson(req)
360
+ const { asset, brief, plan } = await readJson(req)
356
361
  const clean = {}
357
362
  if (brief && typeof brief === "object") {
358
363
  if (Number.isFinite(brief.seconds) && brief.seconds >= 5 && brief.seconds <= 600) clean.targetDuration = Math.round(brief.seconds * 705_600_000)
@@ -377,9 +382,41 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
377
382
  if (brief.broll === "own") clean.broll = "own"
378
383
  // The person's trims from an approved plan, in seconds of the take: up to eight, in order, checked
379
384
  if (Array.isArray(brief.cuts)) clean.cuts = brief.cuts.filter((c) => c && Number.isFinite(c.from) && Number.isFinite(c.to) && c.from >= 0 && c.to > c.from && c.to <= 86_400).slice(0, 8).map((c) => ({ from: Math.round(c.from * 705_600_000), to: Math.round(c.to * 705_600_000) }))
385
+ const allowed = await projects.features()
386
+ if (Number.isInteger(brief.soundEvery) && brief.soundEvery >= 2 && brief.soundEvery <= 8 && allowed.playbooks) clean.soundEvery = brief.soundEvery
387
+ if (allowed.playbooks) {
388
+ clean.holdCaptions = true
389
+ if (brief.montage === true) clean.montage = true
390
+ if (brief.multicam && safeId(brief.multicam.master) && Array.isArray(brief.multicam.angles) && brief.multicam.angles.length >= 2 && brief.multicam.angles.length <= 6 && brief.multicam.angles.every((a, i) => safeId(a?.asset) && a.speaker === i)) clean.multicam = { master: brief.multicam.master, angles: brief.multicam.angles.map((a) => ({ asset: a.asset, speaker: a.speaker })) }
391
+ const style = brief.captionStyle
392
+ if (style && typeof style === "object" && /^#[0-9a-f]{6}$/i.test(style.accent ?? "")) clean.captionStyle = { accent: style.accent }
393
+ }
394
+ // Only ids this project's plan found: the Host holds their URLs and licences, so a browser can't supply one
395
+ if (allowed.mediaSearch) {
396
+ const foundId = (id) => typeof id === "string" && /^[A-Za-z0-9:_. -]{3,160}$/.test(id)
397
+ if (Array.isArray(brief.pictures)) clean.pictures = brief.pictures.filter((p) => p && foundId(p.id) && safeId(p.from) && safeId(p.to)).slice(0, 8).map(({ id, from, to }) => ({ id, from, to }))
398
+ if (Array.isArray(brief.terms)) clean.terms = brief.terms.filter((t) => t && foundId(t.id) && safeId(t.at)).slice(0, 4).map(({ id, at }) => ({ id, at }))
399
+ }
400
+ // A transition from an approved plan: a kind from the fixed list, under the same switch
401
+ if (allowed.motion && Object.hasOwn(TRANSITIONS, brief.transition ?? "")) {
402
+ clean.transition = brief.transition
403
+ if (brief.transitionAll === true) clean.transitionAll = true
404
+ }
405
+ // Motion graphics from an approved plan, only while the server's switch is on; each cleaned to the kit's shape
406
+ if (Array.isArray(brief.graphics) && brief.graphics.length && allowed.motion) clean.graphics = brief.graphics.slice(0, 12).map(cleanGraphic).filter(Boolean)
407
+ // Animated scenes from an approved plan, only while the server's switch is on; the recipe checks each again against the speech
408
+ if (Array.isArray(brief.scenes) && brief.scenes.length && (await projects.features()).visuals) {
409
+ clean.scenes = brief.scenes.slice(0, 12).map(cleanScene).filter(Boolean)
410
+ clean.sceneSound = brief.sceneSound !== false
411
+ }
380
412
  }
381
413
  if (asset !== undefined && typeof asset !== "string") return refuse(res, 400, "Name the take.")
382
- return say(200, jobs.start(state, { kind: "make", ...(asset ? { asset } : {}), brief: clean }))
414
+ if (brief?.fresh === true) clean.fresh = true
415
+ // The last make's story, set here by the Host (never taken from the browser) so a replay of this job has it too
416
+ const story = projects.keptStory(state, clean)
417
+ if (story) clean.story = story
418
+ const approved = cleanPlan(plan)
419
+ return say(200, jobs.start(state, { kind: "make", ...(asset ? { asset } : {}), brief: clean, ...(approved ? { plan: approved } : {}) }))
383
420
  }
384
421
  // The person fixes a word the recogniser misheard (UX_SPEC §5)
385
422
  if (parts[2] === "words" && parts.length === 4 && method === "POST") {
@@ -387,12 +424,44 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
387
424
  if (typeof text !== "string" || text.length > 60 || /[\n\r<>]/.test(text)) return refuse(res, 400, "Give the word as it should read, in up to 60 characters.")
388
425
  return say(200, { word: projects.correctWord(state, decodeURIComponent(parts[3]), text) })
389
426
  }
427
+ // A found picture's small version for the Plan Card
428
+ if (parts[2] === "found-thumb" && parts.length === 3 && method === "GET") {
429
+ const { file, type } = await projects.foundThumb(state, url.searchParams.get("id") ?? "")
430
+ res.writeHead(200, { ...HEADERS, "content-type": type, "cross-origin-resource-policy": "same-origin" })
431
+ return createReadStream(file).pipe(res)
432
+ }
433
+ // One scene on the Plan Card, as the render will draw it. A document of its own, sandboxed, with no network
434
+ if (parts[2] === "scene-preview" && parts.length === 3 && method === "GET") {
435
+ if (!(await projects.features()).visuals) return refuse(res, 404, "Animated scenes aren't on.")
436
+ let scene = null
437
+ try {
438
+ scene = JSON.parse(url.searchParams.get("scene") ?? "null")
439
+ } catch {
440
+ return refuse(res, 400, "That isn't a scene.")
441
+ }
442
+ const html = projects.scenePreview(state, scene, url.searchParams.get("format"))
443
+ res.writeHead(200, { ...HEADERS, "content-type": "text/html; charset=utf-8", "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; frame-ancestors 'self'; sandbox allow-scripts" })
444
+ return res.end(html)
445
+ }
446
+ // One motion graphic on the Plan Card, as the render will draw it: its own sandboxed document, no network
447
+ if (parts[2] === "graphic-preview" && parts.length === 3 && method === "GET") {
448
+ if (!(await projects.features()).motion) return refuse(res, 404, "Motion graphics aren't on.")
449
+ let graphic = null
450
+ try {
451
+ graphic = JSON.parse(url.searchParams.get("graphic") ?? "null")
452
+ } catch {
453
+ return refuse(res, 400, "That isn't a graphic.")
454
+ }
455
+ const html = projects.graphicPreview(state, graphic, url.searchParams.get("format"))
456
+ res.writeHead(200, { ...HEADERS, "content-type": "text/html; charset=utf-8", "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; frame-ancestors 'self'; sandbox allow-scripts" })
457
+ return res.end(html)
458
+ }
390
459
  // The Director's plan: proposed in words with its settings; nothing is made here
391
460
  if (parts[2] === "plan" && parts.length === 3 && method === "POST") {
392
461
  const { text, history, previous, choices } = await readJson(req)
393
462
  if (typeof text !== "string" || !text.trim() || text.length > 2000) return refuse(res, 400, "Say what you want, in up to 2,000 characters.")
394
463
  const turns = Array.isArray(history) ? history.filter((h) => h && (h.who === "you" || h.who === "kriya") && typeof h.text === "string").slice(-6).map((h) => ({ who: h.who, text: h.text.slice(0, 400) })) : []
395
- const prior = previous && typeof previous === "object" ? { say: String(previous.say ?? "").slice(0, 900), steps: Array.isArray(previous.steps) ? previous.steps.slice(0, 10).map((s) => String(s).slice(0, 240)) : [], settings: previous.settings && typeof previous.settings === "object" ? previous.settings : {} } : null
464
+ const prior = cleanPlan(previous)
396
465
  return say(200, await projects.plan(state, { text, history: turns, previous: prior, choices: choices && typeof choices === "object" ? choices : {} }))
397
466
  }
398
467
  // A reference's classified analysis, measured once and kept