@kriya-ai/harness 0.2.2 → 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.
@@ -2,7 +2,7 @@
2
2
  // person's folder; its history and cache stay in ~/.kriya/edit/<id>/, never synced.
3
3
 
4
4
  import { randomBytes } from "node:crypto"
5
- import { appendFileSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, writeSync } from "node:fs"
5
+ import { appendFileSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeSync } from "node:fs"
6
6
  import { dirname, extname, isAbsolute, join, relative, sep } from "node:path"
7
7
 
8
8
  import { checkout, commit, createLog, parseEntry, undo, versions } from "../core/history.js"
@@ -28,7 +28,10 @@ import { createIndexer, layersFor } from "../index/index.js"
28
28
  import { activeRuntime } from "../runtime/setup.js"
29
29
  import { editHome } from "./paths.js"
30
30
  import { createTaste } from "./taste.js"
31
- import { extractDna } from "../engine/dna.js"
31
+ import { ASPECTS, analyseReference, cleanRefs, takeFrom } from "../engine/reference.js"
32
+ import { briefOf, planCut } from "../director/plan.js"
33
+ import { MOODS, writeMusicBed } from "../engine/music-bed.js"
34
+ import { SFX, writeSfx } from "../engine/sfx.js"
32
35
 
33
36
  function atomicWrite(file, text) {
34
37
  const part = `${file}.${process.pid}.tmp`
@@ -170,6 +173,26 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
170
173
  persist(state)
171
174
  },
172
175
 
176
+ /**
177
+ * Removes a project from the Studio: its history, cache, index and journal in
178
+ * ~/.kriya/edit/<id>/ go. The person's folder (the project file, footage, exports)
179
+ * is theirs and is never touched. A project with work running is refused.
180
+ */
181
+ remove(id, { running = () => false } = {}) {
182
+ const known = entry(id)
183
+ if (!known) throw new EngineFailure("input", "no_project", "There is no such project.")
184
+ if (running(id)) throw new EngineFailure("input", "busy", "This project has work running. Let it finish or stop it first.")
185
+ const state = open.get(id)
186
+ if (state) {
187
+ state.journal.close()
188
+ state.indexDb.close()
189
+ open.delete(id)
190
+ }
191
+ atomicWrite(registry, JSON.stringify(list().filter((item) => item.id !== id)))
192
+ rmSync(dirOf(id), { recursive: true, force: true })
193
+ return { removed: id, kept: dirname(known.file) }
194
+ },
195
+
173
196
  /** @param {{ name: string, folder: string, offered?: boolean }} input offered: the person offered this folder on this computer (CC-D2) */
174
197
  async create({ name, folder, offered = false }) {
175
198
  const real = guardPath(folder, offered ? [folder] : roots)
@@ -186,7 +209,7 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
186
209
  },
187
210
 
188
211
  /** Brings a file in by reference: probed, fingerprinted, never copied or written. */
189
- async addAsset(state, path, { reference = false } = {}) {
212
+ async addAsset(state, path, { reference = false, rights = "unknown", rightsNote, extraFacts = {} } = {}) {
190
213
  const real = guardPath(path, [...roots, state.folder])
191
214
  // A .cube is a LUT (ED13): read and checked here, before FFmpeg ever sees it, never probed as media
192
215
  const lut = extname(real).toLowerCase() === ".cube"
@@ -197,13 +220,14 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
197
220
  throw new EngineFailure("input", "refused", error.message)
198
221
  }
199
222
  }
200
- const { facts } = lut ? { facts: {} } : await probe(real)
223
+ const { facts: probed } = lut ? { facts: {} } : await probe(real)
224
+ const facts = { ...probed, ...extraFacts }
201
225
  const id = `a${state.log.current.assets.length + 1}`
202
226
  const within = relative(state.folder, real)
203
227
  const stored = within.startsWith("..") || isAbsolute(within) ? real : within.split(sep).join("/")
204
228
  // A reference is measured for its style only (EDD-23); the person confirmed they may use it
205
- if (reference && !facts.width) throw new EngineFailure("input", "refused", "A reference needs to be a video.")
206
- const op = { op: "add_asset", id, kind: reference ? "reference" : lut ? "lut" : kindOf(facts), fingerprint: await fingerprint(real), path: stored, linked: true, rights: "unknown", ...(reference ? { rightsNote: "The person confirmed they may use it as a style reference." } : {}), facts }
229
+ if (reference && !facts.width && !facts.hasAudio) throw new EngineFailure("input", "refused", "A reference needs to be a video, an image or a piece of music.")
230
+ const op = { op: "add_asset", id, kind: reference ? "reference" : lut ? "lut" : kindOf(facts), fingerprint: await fingerprint(real), path: stored, linked: true, rights: reference ? "unknown" : rights, ...(reference ? { rightsNote: "The person confirmed they may use it as a style reference." } : rightsNote ? { rightsNote } : {}), facts }
207
231
  const result = change(state, { ops: [op], author: "code" })
208
232
  if (!result.ok) throw new EngineFailure("input", "refused", result.diagnostics[0].message)
209
233
  return state.log.current.assets.at(-1)
@@ -244,17 +268,17 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
244
268
  },
245
269
 
246
270
  /** The console: words → a proposal, applied to a copy, nothing landing yet (UX_SPEC §4, §5). */
247
- async ask(state, { text, selection, job = 0 }) {
271
+ async ask(state, { text, selection, history = [], job = 0 }) {
248
272
  const chosen = cleanSelection(selection, state.log.current, state.index)
249
- const result = await revise({ ask: this.askFor(state, job), project: state.log.current, index: state.index, text, selection: chosen })
273
+ const result = await revise({ ask: this.askFor(state, job), project: state.log.current, index: state.index, text, selection: chosen, history })
250
274
  // A request about the whole video goes to the Director's make job; the Studio offers it
251
275
  const direct = result.direct ? { brief: { ...(result.direct.seconds ? { seconds: result.direct.seconds } : {}), ...(result.direct.captions ? { captions: result.direct.captions } : {}) } } : null
252
- if (!result.ops.length && !result.corrections.length) return { proposal: null, direct, source: result.source, reason: direct ? null : (result.reason ?? "Kriya couldn't turn that into an edit. Try saying it another way.") }
276
+ 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.") }
253
277
  const id = randomBytes(6).toString("hex")
254
278
  state.proposals.set(id, { ops: result.ops, corrections: result.corrections, head: state.log.head })
255
279
  const { picture, duration } = solve(result.project ?? state.log.current, state.index)
256
280
  // Changes in one list, operations first, then corrections: "Only this" counts across both
257
- return { proposal: { id, ops: result.ops, changes: [...result.changes, ...result.corrections.map((c) => c.change)], timeline: result.ops.length ? { picture, duration } : null }, direct, source: result.source, ...(result.reason ? { reason: result.reason } : {}) }
281
+ return { proposal: { id, ops: result.ops, changes: [...result.changes, ...result.corrections.map((c) => c.change)], timeline: result.ops.length ? { picture, duration } : null }, direct, say: result.say, source: result.source, ...(result.reason ? { reason: result.reason } : {}) }
258
282
  },
259
283
 
260
284
  /** Accept all, accept some, or reject a proposal. Rebased onto HEAD; the person's own edits never move. */
@@ -276,6 +300,39 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
276
300
  return { applied: ops.length + fixes.length, dropped: dropped.map((d) => ({ change: describe(d.op, state.index), reason: d.reason })) }
277
301
  },
278
302
 
303
+ /** The Director's plan for the whole cut: proposed, never made until the person approves it. */
304
+ async plan(state, { text, history = [], previous = null, choices = {}, job = 0, signal } = {}) {
305
+ // The references in use, each only for what the person took it for; with none named, every reference, whole
306
+ const named = cleanRefs(choices.references)
307
+ const chosen = named.length ? named : state.log.current.assets.filter((a) => a.kind === "reference").map((a) => ({ id: a.id, aspect: "all" }))
308
+ const references = []
309
+ for (const { id, aspect } of chosen) {
310
+ const ref = state.log.current.assets.find((a) => a.id === id && a.kind === "reference")
311
+ const found = ref && (await this.referenceAnalysis(state, ref.id, { signal }).catch(() => null))
312
+ if (!found) continue
313
+ const taken = takeFrom(found, aspect)
314
+ const name = `${ref.path.split(/[\\/]/).at(-1)}${aspect === "all" ? "" : ` (only for: ${ASPECTS[aspect]})`}`
315
+ references.push({ name, lines: taken.lines.length ? taken.lines : [`nothing measured for ${ASPECTS[aspect].toLowerCase()}`] })
316
+ }
317
+ const plan = await planCut({ ask: this.askFor(state, job), project: state.log.current, index: state.index, text, history, previous, references, choices, signal })
318
+ // The exact brief an approval makes, so the Studio sends back what was shown
319
+ return { ...plan, brief: briefOf(plan.settings) }
320
+ },
321
+
322
+ /** A reference's classified analysis (reference.js), kept by its fingerprint so it's measured once. */
323
+ async referenceAnalysis(state, assetId, { signal } = {}) {
324
+ const asset = state.log.current.assets.find((a) => a.id === assetId && a.kind === "reference")
325
+ if (!asset) throw new EngineFailure("input", "unknown_asset", "There is no such reference in this project.")
326
+ const dir = join(dirOf(state.id), "cache", "refs")
327
+ // .2: a video's soundtrack is measured too, and each line is kept under its aspect
328
+ const file = join(dir, `${asset.fingerprint}.2.json`)
329
+ if (existsSync(file)) return JSON.parse(readFileSync(file, "utf8"))
330
+ const found = await analyseReference(sourcesOf(state)(assetId), asset.facts, { signal })
331
+ mkdirSync(dir, { recursive: true })
332
+ atomicWrite(file, JSON.stringify(found))
333
+ return found
334
+ },
335
+
279
336
  /** The person's fix of a misheard word; captions, the transcript and the Director read it from now on. */
280
337
  correctWord(state, word, text) {
281
338
  const clean = cleanWord(text)
@@ -296,39 +353,108 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
296
353
  const asset = request.asset ?? video[0]?.id
297
354
  if (!asset || !video.some((a) => a.id === asset)) throw new EngineFailure("input", "no_take", "Add a video first.")
298
355
  if (!state.index.words.some((w) => w.asset === asset)) await this.indexAsset(state, asset, { signal })
299
- // The song's beats, so the music can be fitted on its downbeats
300
- const song = request.brief?.music && state.log.current.assets.find((a) => a.id === request.brief.music && a.kind === "audio")
301
- if (song && !state.index.beats?.some((b) => b.asset === song.id)) await this.indexAsset(state, song.id, { signal })
302
- // A real choice goes to the person before the story is planned (TAVI_INTEGRATION §5)
303
- const picks = !replay && beforeStory ? await beforeStory(state, asset, { signal, sourcePath: sourcesOf(state) }) : null
304
- // The person's confirmed rules, under anything the brief says, and their choices. A
305
- // replay uses what the job really used. Captions only where they can render
306
- const recorded = replay?.answers.find((a) => a.task === "brief_extra")
307
- const extra = recorded ? JSON.parse(recorded.value) : { ...taste.defaults(), ...(picks && { picks }) }
308
- // A style reference (EDD-23): measured to numbers only, never placed on a track. Its
309
- // pace sets how often the picture changes (punch-ins), and its captions turn ours on
356
+ // References, classified (reference.js), numbers only and never placed on a track
357
+ // (EDD-23): a video's pace and captions, an image's or video's colour, music's tempo and mood
310
358
  const styled = []
311
359
  let captionsFromReference = false
312
- const reference = request.brief?.reference && state.log.current.assets.find((a) => a.id === request.brief.reference && a.kind === "reference")
313
- if (reference && !replay) {
360
+ const fromRefs = {}
361
+ // Each reference gives only what the person took it for (editing, sound, colour, graphics, or
362
+ // all); one taken for an aspect goes first, so it wins that aspect over one taken for everything
363
+ const refs = cleanRefs([request.brief?.reference, ...(request.brief?.references ?? [])].filter(Boolean)).sort((a, b) => (a.aspect === "all") - (b.aspect === "all"))
364
+ const aspectOf = new Map()
365
+ for (const { id, aspect } of replay ? [] : refs) {
366
+ const ref = state.log.current.assets.find((a) => a.id === id && a.kind === "reference")
367
+ if (!ref) continue
368
+ const name = ref.path.split(/[\\/]/).at(-1)
314
369
  try {
315
- const dna = await extractDna(sourcesOf(state)(reference.id), { signal })
370
+ const found = takeFrom(await this.referenceAnalysis(state, id, { signal }), aspect)
371
+ if (aspect !== "all" && !found.lines.length) styled.push(`${name} has nothing Kriya can measure for ${ASPECTS[aspect].toLowerCase()}, so it wasn't used.`)
316
372
  const seconds = (request.brief.targetDuration ?? REEL_TALKING_HEAD.target.default) / FLICKS
317
- if (dna.pace.median) {
318
- extra.punches = Math.min(8, Math.max(1, Math.round(seconds / dna.pace.median / 2)))
319
- styled.push(`Took the pace of your reference: its picture changes every ${dna.pace.median.toFixed(1)} s, so ${extra.punches} punch-ins`)
373
+ // The first reference to give an aspect sets it. One the person took for that aspect
374
+ // is their explicit choice, so it outranks the brief's own setting there; one taken
375
+ // for everything sits under the brief, as before
376
+ const claim = (key) => !aspectOf.has(key) && (aspectOf.set(key, aspect), true)
377
+ const explicit = aspect !== "all"
378
+ if (found.pace?.every && claim("pace")) {
379
+ const punches = Math.min(8, Math.max(1, Math.round(seconds / found.pace.every / 2)))
380
+ if (explicit) request = { ...request, brief: { ...request.brief, punches } }
381
+ else fromRefs.punches = punches
382
+ styled.push(`Took the pace of ${name}: its picture changes every ${found.pace.every.toFixed(1)} s, so ${punches} punch-ins`)
320
383
  }
321
- if (dna.captions.present && !request.brief.captions && !extra.captions && state.engine.motion()) {
322
- extra.captions = "clean"
384
+ if (found.captions && !request.brief.captions && !state.engine.motion().missing && claim("captions")) {
385
+ fromRefs.captions = "clean"
323
386
  captionsFromReference = true
324
- styled.push("Your reference has captions, so this cut has them too")
387
+ styled.push(`${name} has captions, so this cut has them too`)
388
+ }
389
+ // An image says the most about colour, so it wins over a video's taken the same way
390
+ const colourBy = aspectOf.get("colour")
391
+ const colourFree = explicit ? colourBy === undefined || (colourBy !== "all" && found.kind === "image" && fromRefs.colourKind !== "image") : !request.brief.grade && (colourBy === undefined || (colourBy === "all" && found.kind === "image" && fromRefs.colourKind !== "image"))
392
+ if (found.colour && colourFree) {
393
+ aspectOf.set("colour", aspect)
394
+ fromRefs.customGrade = found.colour.grade
395
+ fromRefs.colourKind = found.kind
396
+ if (explicit && request.brief.grade) request = { ...request, brief: { ...request.brief, grade: undefined } }
397
+ styled.push(`Took the colour of ${name}: ${found.colour.words.join(", ")}`)
398
+ }
399
+ // A song the person chose stays; a reference taken for its sound replaces a generated bed
400
+ const musicFree = explicit ? !request.brief.music || /^generated:/.test(request.brief.music) : !request.brief.music
401
+ if (found.music && musicFree && claim("music")) {
402
+ request = { ...request, brief: { ...request.brief, music: `generated:${found.music.mood}`, musicBpm: found.music.bpm ?? undefined } }
403
+ styled.push(`Music follows ${name}: ${/^[aeiou]/.test(found.music.mood) ? "an" : "a"} ${found.music.mood} bed${found.music.bpm ? ` at ${found.music.bpm} bpm` : ""}`)
325
404
  }
326
405
  } catch (error) {
327
406
  if (signal?.aborted) throw error
328
- styled.push(`Your reference couldn't be measured (${error.message}), so its style wasn't used.`)
407
+ styled.push(`${name} couldn't be measured (${error.message}), so its style wasn't used.`)
329
408
  }
330
409
  }
331
- if (extra.captions && (!Object.hasOwn(LOOKS, extra.captions) || !state.engine.motion())) delete extra.captions
410
+ // "generated:<mood>": a bed Kriya writes itself (music-bed.js), so a cut can have music with no file to find
411
+ const mood = /^generated:(\w+)$/.exec(request.brief?.music ?? "")?.[1]
412
+ if (mood && Object.hasOwn(MOODS, mood) && !replay) {
413
+ const seconds = Math.ceil((request.brief.targetDuration ?? REEL_TALKING_HEAD.target.default) / FLICKS) + 15
414
+ const media = join(state.folder, "media")
415
+ mkdirSync(media, { recursive: true })
416
+ const bpm = request.brief.musicBpm
417
+ const tag = `kriya-music-${mood}${bpm ? `-${bpm}bpm` : ""}-${seconds}s.wav`
418
+ const file = join(media, tag)
419
+ const known = state.log.current.assets.find((a) => a.kind === "audio" && a.path.endsWith(tag))
420
+ if (!existsSync(file)) writeMusicBed(file, { mood, seconds, bpm })
421
+ const bed = known ?? (await this.addAsset(state, file, { rights: "own", rightsNote: "Made by Kriya's music generator: no one else's recording." }))
422
+ request = { ...request, brief: { ...request.brief, music: bed.id } }
423
+ }
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)) {
427
+ const media = join(state.folder, "media")
428
+ mkdirSync(media, { recursive: true })
429
+ const sfx = {}
430
+ for (const [slot, kind] of Object.entries(wanted)) {
431
+ if (!kind || !Object.hasOwn(SFX, kind)) continue
432
+ const file = join(media, `kriya-sfx-${kind}.wav`)
433
+ const made = writeSfx(file, kind)
434
+ const known = state.log.current.assets.find((a) => a.kind === "audio" && a.path.endsWith(`kriya-sfx-${kind}.wav`))
435
+ sfx[slot] = (known ?? (await this.addAsset(state, file, { rights: "own", rightsNote: "Made by Kriya's sound generator: no one else's recording.", extraFacts: { peak: made.peak } }))).id
436
+ }
437
+ request = { ...request, brief: { ...request.brief, sfx } }
438
+ }
439
+ // The song's beats, so the music can be fitted on its downbeats
440
+ const song = request.brief?.music && state.log.current.assets.find((a) => a.id === request.brief.music && a.kind === "audio")
441
+ if (song && !state.index.beats?.some((b) => b.asset === song.id)) await this.indexAsset(state, song.id, { signal })
442
+ // A real choice goes to the person before the story is planned (TAVI_INTEGRATION §5)
443
+ const picks = !replay && beforeStory ? await beforeStory(state, asset, { signal, sourcePath: sourcesOf(state) }) : null
444
+ // The person's confirmed rules, under anything the brief says, and their choices. A
445
+ // replay uses what the job really used. Captions only where they can render
446
+ const recorded = replay?.answers.find((a) => a.task === "brief_extra")
447
+ const extra = recorded ? JSON.parse(recorded.value) : { ...taste.defaults(), ...(picks && { picks }) }
448
+ const { colourKind: _kind, ...fromRefBrief } = fromRefs
449
+ Object.assign(extra, fromRefBrief)
450
+ // Captions only where they can render: a missing runtime or Chrome drops them with a note,
451
+ // rather than failing the whole cut at render (found in use: every render failed)
452
+ const motionMissing = state.engine.motion().missing
453
+ if (extra.captions && (!Object.hasOwn(LOOKS, extra.captions) || motionMissing)) delete extra.captions
454
+ if (motionMissing && request.brief?.captions) {
455
+ request = { ...request, brief: { ...request.brief, captions: undefined } }
456
+ styled.push(`No captions this time: ${motionMissing}`)
457
+ }
332
458
  if (!replay && Object.keys(extra).length) state.journal.answer({ job, task: "brief_extra", source: "person", value: extra })
333
459
  const usedRules = [...styled, ...(extra.captions && !request.brief?.captions && !captionsFromReference ? [`Used your rule: ${extra.captions} captions`] : []), ...(extra.zoom && !request.brief?.zoom ? [`Used your rule: ${extra.zoom.toFixed(2)}× zoom`] : [])]
334
460
  const stages = ["story", "check", "repair"]
@@ -371,7 +497,9 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
371
497
  const { ops, dropped } = state.log.head === result.head ? { ops: result.best.ops, dropped: [] } : rebase(state.log.current, result.best.ops, state.index)
372
498
  const landed = change(state, { ops, author: "agent" })
373
499
  if (!landed.ok) throw new EngineFailure("plan", "refused", landed.diagnostics[0].message)
374
- const changes = [...usedRules, ...ops.filter((op) => !["ripple_delete", "reframe"].includes(op.op)).map((op) => describe(op, state.index))]
500
+ // A caption per spoken line is one change to a person: said once, with the count
501
+ const captioned = ops.filter((op) => op.op === "caption_style" && op.words?.length)
502
+ 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})`] : [])]
375
503
  const { version } = await tools()
376
504
  const delivery = result.best.file
377
505
  ? 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 })
@@ -379,6 +507,7 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
379
507
  return {
380
508
  verdict: gates?.verdict ?? "not_checked",
381
509
  file: result.best.file ?? null,
510
+ head: state.log.head, // the version this file shows, so the Studio can say when it's out of date
382
511
  receipt: delivery?.receipt ?? null,
383
512
  report: delivery?.report ?? null,
384
513
  planHash,
@@ -431,7 +560,7 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
431
560
  const { version } = await tools()
432
561
  const mentions = gates.gates.filter((g) => g.status === "not_checked" || (g.status === "failed" && g.severity === "note")).map((g) => g.id)
433
562
  const delivery = await writeDelivery({ file, title: project.name, project, parent, plan, sourcePath, tools: { engine: ENGINE_VERSION, ffmpeg: version, runtime: runtime?.version ?? null }, gates: gates.gates, verdict: gates.verdict, calls: state.journal.calls(job), changes: [], notes: mentions, repairs: [], beforeFrom: null, run, work })
434
- return { verdict: gates.verdict, file, receipt: delivery?.receipt ?? null, report: delivery?.report ?? null, planHash: sha256(canonical(plan)), gates: gates.gates, notes: mentions, applied, skipped }
563
+ return { verdict: gates.verdict, file, head: state.log.head, receipt: delivery?.receipt ?? null, report: delivery?.report ?? null, planHash: sha256(canonical(plan)), gates: gates.gates, notes: mentions, applied, skipped }
435
564
  },
436
565
 
437
566
  /** `kriya edit replay`: a make job again from its recording; it compares, and lands nothing. */
@@ -4,16 +4,18 @@
4
4
 
5
5
  import { createHash, createHmac, randomBytes } from "node:crypto"
6
6
  import { createReadStream, createWriteStream, existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs"
7
- import { basename, extname, isAbsolute, join } from "node:path"
7
+ import { basename, dirname, extname, isAbsolute, join } from "node:path"
8
8
  import { pipeline } from "node:stream/promises"
9
9
 
10
10
  import { compile } from "../core/plan.js"
11
11
  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
+ import { cleanRefs } from "../engine/reference.js"
14
15
  import { EngineFailure } from "../engine/tool.js"
15
16
  import { activeRuntime } from "../runtime/setup.js"
16
17
  import { recogniser } from "../index/layers/words.js"
18
+ import { FORMATS, GRADES } from "../recipes/reel.js"
17
19
 
18
20
  const HEADERS = {
19
21
  "cross-origin-opener-policy": "same-origin",
@@ -91,9 +93,11 @@ async function readJson(req) {
91
93
  }
92
94
  }
93
95
 
94
- function sendFile(req, res, file) {
96
+ function sendFile(req, res, file, { download = false } = {}) {
95
97
  const { size } = statSync(file)
96
98
  const type = TYPES[extname(file).toLowerCase()] ?? "application/octet-stream"
99
+ // A download keeps the export's own name (made by the Engine: letters, digits, dashes)
100
+ if (download) res.setHeader("content-disposition", `attachment; filename="${basename(file).replace(/[^\w.-]/g, "_")}"`)
97
101
  const range = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range ?? "")
98
102
  if (req.headers.range && !range) return refuse(res, 416, "Bad range.")
99
103
  if (!range) {
@@ -110,14 +114,14 @@ function sendFile(req, res, file) {
110
114
  createReadStream(file, { start, end }).pipe(res)
111
115
  }
112
116
 
113
- const statusOf = (error) => ({ outside_project: 403, missing_file: 404, exists: 409, too_large: 413, empty: 409 })[error.reason] ?? 400
117
+ const statusOf = (error) => ({ outside_project: 403, missing_file: 404, exists: 409, too_large: 413, empty: 409, busy: 409, no_project: 404 })[error.reason] ?? 400
114
118
 
115
119
  /**
116
120
  * @param {{ home: string, roots: string[], projects: object, jobs: object, tools: () => Promise<object>, tokenTtlMs: number, port: () => number, onActivity: (inFlight?: number) => void, onStop: () => void, sse: Set<object>, log: (line: string) => void, pid: number }} options
117
121
  */
118
122
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
119
123
 
120
- export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenTtlMs, port, onActivity, onStop, onLive = () => {}, sse, log, pid }) {
124
+ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenTtlMs, port, onActivity, onStop, onLive = () => {}, sse, log, pid, stamp = null, busy = () => 0 }) {
121
125
  const tokens = new Map() // sha256 of a launch token → { expires, back }
122
126
  const sessions = new Set()
123
127
  const mediaSecret = randomBytes(32)
@@ -250,7 +254,25 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
250
254
  const entries = readdirSync(root, { withFileTypes: true })
251
255
  .filter((item) => !item.name.startsWith("."))
252
256
  .map((item) => ({ name: item.name, kind: item.isDirectory() ? "folder" : item.isFile() ? "file" : "other" }))
253
- return say(200, { root, entries })
257
+ .sort((a, b) => (a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === "folder" ? -1 : 1))
258
+ // The Studio's folder picker: up, while still inside the allowed folders
259
+ let parent = null
260
+ try {
261
+ if (dirname(root) !== root) parent = guardPath(dirname(root), roots)
262
+ } catch {
263
+ // Above the allowed folders: no way up
264
+ }
265
+ return say(200, { root, parent, roots, entries })
266
+ }
267
+ // A new folder for a project, inside the allowed folders only
268
+ if (method === "POST" && pathname === "/browse/folder") {
269
+ const { parent, name } = await readJson(req)
270
+ const clean = typeof name === "string" ? name.trim().replace(/[^\p{L}\p{N} _.-]+/gu, "-").replace(/^\.+/, "") : ""
271
+ if (!clean || clean.length > 80 || typeof parent !== "string") return refuse(res, 400, "Give the new folder a name.")
272
+ const at = join(guardPath(parent, roots), clean)
273
+ if (existsSync(at)) return refuse(res, 409, "A folder with that name is already there.")
274
+ mkdirSync(at)
275
+ return say(200, { folder: guardPath(at, roots) })
254
276
  }
255
277
 
256
278
  // The person's own screen. Never on the socket, so nothing but a Studio session can
@@ -287,6 +309,7 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
287
309
  const state = await needProject(res, parts[1])
288
310
  if (!state) return
289
311
  if (parts.length === 2 && method === "GET") return say(200, projectView(state))
312
+ if (parts.length === 2 && method === "DELETE") return say(200, projects.remove(state.id, { running: (id) => jobs.runningIn(id) }))
290
313
  if (parts.length === 2 && method === "PATCH") {
291
314
  const { ops, undo } = await readJson(req)
292
315
  if (undo === true) {
@@ -302,6 +325,13 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
302
325
  return say(200, withMedia(state, await projects.addAsset(state, path)))
303
326
  }
304
327
  if (parts[2] === "upload" && method === "POST") return upload(req, res, state, url)
328
+ // The finished films, to watch in Finish before downloading: listed, then streamed by job number
329
+ if (parts[2] === "renders" && parts.length === 3 && method === "GET") return say(200, { renders: jobs.renders(state) })
330
+ if (parts[2] === "renders" && parts.length === 4 && method === "GET") {
331
+ const file = /^\d{1,9}$/.test(parts[3]) ? jobs.renderFile(state, Number(parts[3])) : null
332
+ if (!file) return refuse(res, 404, "That film isn't there any more.")
333
+ return sendFile(req, res, file, { download: url.searchParams.get("download") === "1" })
334
+ }
305
335
  if (parts[2] === "plan" && method === "GET") {
306
336
  const { version } = await tools()
307
337
  // The solver's timeline too: the Studio's monitor and timeline place clips from it
@@ -309,9 +339,11 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
309
339
  return say(200, { ...compile(state.log.current, state.index, { engineVersion: ENGINE_VERSION, runtimeVersion: version }), timeline: { picture, audio, overlays, captions, duration } })
310
340
  }
311
341
  if (parts[2] === "ask" && parts.length === 3 && method === "POST") {
312
- const { text, selection } = await readJson(req)
342
+ const { text, selection, history } = await readJson(req)
313
343
  if (typeof text !== "string" || !text.trim() || text.length > 2000) return refuse(res, 400, "Say what you want changed, in up to 2,000 characters.")
314
- return say(200, await projects.ask(state, { text, selection }))
344
+ // The chat's last turns, short and text only: nothing else of the browser's reaches the model
345
+ 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) })) : []
346
+ return say(200, await projects.ask(state, { text, selection, history: turns }))
315
347
  }
316
348
  if (parts[2] === "proposals" && parts.length === 4 && method === "POST") {
317
349
  const { accept, only } = await readJson(req)
@@ -329,6 +361,22 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
329
361
  if (typeof brief.captions === "string" && Object.hasOwn(LOOKS, brief.captions)) clean.captions = brief.captions
330
362
  if (typeof brief.music === "string" && /^[A-Za-z0-9:_-]{1,64}$/.test(brief.music)) clean.music = brief.music
331
363
  if (typeof brief.reference === "string" && /^[A-Za-z0-9:_-]{1,64}$/.test(brief.reference)) clean.reference = brief.reference
364
+ if (Object.hasOwn(FORMATS, brief.format)) clean.format = brief.format
365
+ if (Object.hasOwn(GRADES, brief.grade)) clean.grade = brief.grade
366
+ if (brief.cleanVoice === true) clean.cleanVoice = true
367
+ // From the Director's approved plan: checked again in the recipe against the index
368
+ const safeId = (v) => typeof v === "string" && /^[A-Za-z0-9:_-]{1,64}$/.test(v)
369
+ // Each as an id (everything it shows) or { id, aspect }: editing, sound, colour or graphics only
370
+ if (Array.isArray(brief.references)) clean.references = cleanRefs(brief.references)
371
+ if (safeId(brief.hook)) clean.hook = brief.hook
372
+ if (brief.coldOpen && safeId(brief.coldOpen.from) && safeId(brief.coldOpen.to)) clean.coldOpen = { from: brief.coldOpen.from, to: brief.coldOpen.to, mono: brief.coldOpen.mono !== false }
373
+ if (["whoosh", "pop"].includes(brief.cutSound)) clean.cutSound = brief.cutSound
374
+ if (["riser", "hit"].includes(brief.introSound)) clean.introSound = brief.introSound
375
+ if (Number.isInteger(brief.punches) && brief.punches >= 0 && brief.punches <= 8) clean.punches = brief.punches
376
+ for (const flag of ["angles", "titles", "ramps"]) if (brief[flag] === true) clean[flag] = true
377
+ if (brief.broll === "own") clean.broll = "own"
378
+ // The person's trims from an approved plan, in seconds of the take: up to eight, in order, checked
379
+ 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) }))
332
380
  }
333
381
  if (asset !== undefined && typeof asset !== "string") return refuse(res, 400, "Name the take.")
334
382
  return say(200, jobs.start(state, { kind: "make", ...(asset ? { asset } : {}), brief: clean }))
@@ -339,6 +387,16 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
339
387
  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.")
340
388
  return say(200, { word: projects.correctWord(state, decodeURIComponent(parts[3]), text) })
341
389
  }
390
+ // The Director's plan: proposed in words with its settings; nothing is made here
391
+ if (parts[2] === "plan" && parts.length === 3 && method === "POST") {
392
+ const { text, history, previous, choices } = await readJson(req)
393
+ if (typeof text !== "string" || !text.trim() || text.length > 2000) return refuse(res, 400, "Say what you want, in up to 2,000 characters.")
394
+ 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
396
+ return say(200, await projects.plan(state, { text, history: turns, previous: prior, choices: choices && typeof choices === "object" ? choices : {} }))
397
+ }
398
+ // A reference's classified analysis, measured once and kept
399
+ if (parts[2] === "references" && parts.length === 4 && method === "GET") return say(200, await projects.referenceAnalysis(state, decodeURIComponent(parts[3])))
342
400
  if (parts[2] === "export" && parts[3] === "handoff" && parts.length === 4 && method === "POST") return say(200, projects.handoff(state))
343
401
  if (parts[2] === "index" && parts.length === 3 && method === "GET") {
344
402
  const { words, sentences, takes, shots } = state.index
@@ -385,7 +443,7 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
385
443
  const url = new URL(req.url, "http://host")
386
444
  try {
387
445
  if (overSocket) {
388
- if (url.pathname === "/internal/info") return json(res, 200, { pid, port: port() })
446
+ if (url.pathname === "/internal/info") return json(res, 200, { pid, port: port(), stamp, busy: busy() })
389
447
  if (url.pathname === "/internal/launch" && req.method === "POST") {
390
448
  const token = mintToken((await readJson(req)).back)
391
449
  return json(res, 200, { token, url: `http://127.0.0.1:${port()}/launch#${token}` })
@@ -5,6 +5,8 @@
5
5
 
6
6
  import { DatabaseSync } from "node:sqlite"
7
7
 
8
+ import { decimalSplit } from "./layers/retakes.js"
9
+
8
10
  const SCHEMA = `
9
11
  create table if not exists assets (asset text primary key, media text not null, kind text not null);
10
12
  create table if not exists layers (media text not null, layer text not null, model_version text not null, status text not null, notice text, data text, updated_at text not null, primary key (media, layer));
@@ -100,6 +102,9 @@ export function openIndexDb(file) {
100
102
  const fixed = fix && fix.was === w.text
101
103
  raw.words.push({ id, asset, start: w.start, end: w.end, text: fixed ? fix.text : w.text, conf: fixed ? 1 : w.conf, flags: flagList(w.flags).filter((f) => !fixed || f !== "low_confidence"), ...(fixed ? { heard: w.text } : {}) })
102
104
  }
105
+ // An index made before decimalSplit flagged "5" in "5 .5" as a stutter: unflagged on read, so it isn't cut
106
+ const spoken = raw.words.filter((w) => w.asset === asset)
107
+ spoken.forEach((w, i) => w.flags.includes("stutter") && decimalSplit(w, spoken[i + 1]) && (w.flags = w.flags.filter((f) => f !== "stutter")))
103
108
  for (const s of db.prepare('select * from sentences where media = ? order by n').all(media)) {
104
109
  raw.sentences.push({ id: `${asset}:s${s.n}`, asset, start: s.start, end: s.end, firstWord: `${asset}:w${s.first_word}`, lastWord: `${asset}:w${s.last_word}`, takeGroup: s.take_group === null ? null : `${asset}:g${s.take_group}`, score: s.score })
105
110
  }
@@ -37,6 +37,12 @@ function prefixOf(short, long) {
37
37
  return a.length >= 3 && a.length < b.length && a.every((token, i) => token === b[i])
38
38
  }
39
39
 
40
+ /**
41
+ * "4.5" heard as "5" then ".5" (found in use: "Opus 4.5"): the same digits after punctuation are
42
+ * one number split in two, not a stutter, and cutting the first half cuts inside the word (QG-05).
43
+ */
44
+ export const decimalSplit = (word, next) => /^\d+$/.test(bare(word.text)) && /^[.,:]\d/.test(String(next?.text ?? "").trim())
45
+
40
46
  /** Word flags: filler, stutter, low_confidence. Times decide a soft filler, not the word alone. */
41
47
  export function flagWords(words, language = "en") {
42
48
  const soft = new Set(SOFT_FILLERS[language.split("-")[0]] ?? SOFT_FILLERS.en)
@@ -49,7 +55,7 @@ export function flagWords(words, language = "en") {
49
55
  const setApart = (before >= FILLER_PAUSE || ends(words[i - 1]?.text ?? ".") || /,$/.test(words[i - 1]?.text ?? "")) && (after >= FILLER_PAUSE || /[,.!?]$/.test(word.text))
50
56
  if (HESITATIONS.has(token) || (soft.has(token) && setApart)) flags.push("filler")
51
57
  const next = words[i + 1]
52
- if (next && token && (bare(next.text) === token || (word.text.endsWith("-") && bare(next.text).startsWith(token)))) flags.push("stutter")
58
+ if (next && token && !decimalSplit(word, next) && (bare(next.text) === token || (word.text.endsWith("-") && bare(next.text).startsWith(token)))) flags.push("stutter")
53
59
  if (typeof word.conf === "number" && word.conf < LOW_CONFIDENCE) flags.push("low_confidence")
54
60
  return flags
55
61
  })
@@ -8,7 +8,7 @@
8
8
  import { apply } from "../core/ops.js"
9
9
  import { compile } from "../core/plan.js"
10
10
  import { runGates } from "../gates/index.js"
11
- import { planReel, REEL_TALKING_HEAD } from "../recipes/reel.js"
11
+ import { planReel, recipeFor } from "../recipes/reel.js"
12
12
  import { search } from "./loop.js"
13
13
  import { repairLadder } from "./repair.js"
14
14
 
@@ -39,7 +39,7 @@ export function planVerdict(project, index, recipe, { engineVersion = "f0", runt
39
39
  * }} input
40
40
  */
41
41
  export async function makeReel({ project, head, index, asset, brief = {}, ask, render, sourcePath, signal, onStage = () => {}, run, gateKit = {} }) {
42
- const recipe = REEL_TALKING_HEAD
42
+ const recipe = recipeFor(brief)
43
43
  let calls = 0
44
44
  const notes = []
45
45
  const slots = {}