@kriya-ai/harness 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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"
@@ -17,7 +17,7 @@ import { openJournal } from "../graph/journal.js"
17
17
  import { solve } from "../core/solver.js"
18
18
  import { createAsk } from "../director/ask.js"
19
19
  import { LOOKS } from "../engine/captions.js"
20
- import { cleanSelection, describe, noteWord, revise } from "../director/revise.js"
20
+ import { cleanSelection, cleanWord, describe, noteWord, revise } from "../director/revise.js"
21
21
  import { openIndexDb } from "../index/db.js"
22
22
  import { makeReel, rebase } from "../loop/make.js"
23
23
  import { runGates } from "../gates/index.js"
@@ -28,6 +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 { 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"
31
35
 
32
36
  function atomicWrite(file, text) {
33
37
  const part = `${file}.${process.pid}.tmp`
@@ -69,6 +73,7 @@ const kindOf = ({ width, hasAudio }) => (width ? "video" : hasAudio ? "audio" :
69
73
  /**
70
74
  * @param {{ home: string, roots: string[], scheduler: object, tools: () => Promise<{ capabilities: object, version: string }> }} options
71
75
  */
76
+ const FLICKS = 705_600_000
72
77
  // Director model calls a job may make (DIRECTOR_AND_AGENT §13, short form)
73
78
  const JOB_CALLS = 40
74
79
 
@@ -168,6 +173,26 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
168
173
  persist(state)
169
174
  },
170
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
+
171
196
  /** @param {{ name: string, folder: string, offered?: boolean }} input offered: the person offered this folder on this computer (CC-D2) */
172
197
  async create({ name, folder, offered = false }) {
173
198
  const real = guardPath(folder, offered ? [folder] : roots)
@@ -184,7 +209,7 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
184
209
  },
185
210
 
186
211
  /** Brings a file in by reference: probed, fingerprinted, never copied or written. */
187
- async addAsset(state, path) {
212
+ async addAsset(state, path, { reference = false, rights = "unknown", rightsNote, extraFacts = {} } = {}) {
188
213
  const real = guardPath(path, [...roots, state.folder])
189
214
  // A .cube is a LUT (ED13): read and checked here, before FFmpeg ever sees it, never probed as media
190
215
  const lut = extname(real).toLowerCase() === ".cube"
@@ -195,11 +220,14 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
195
220
  throw new EngineFailure("input", "refused", error.message)
196
221
  }
197
222
  }
198
- const { facts } = lut ? { facts: {} } : await probe(real)
223
+ const { facts: probed } = lut ? { facts: {} } : await probe(real)
224
+ const facts = { ...probed, ...extraFacts }
199
225
  const id = `a${state.log.current.assets.length + 1}`
200
226
  const within = relative(state.folder, real)
201
227
  const stored = within.startsWith("..") || isAbsolute(within) ? real : within.split(sep).join("/")
202
- const op = { op: "add_asset", id, kind: lut ? "lut" : kindOf(facts), fingerprint: await fingerprint(real), path: stored, linked: true, rights: "unknown", facts }
228
+ // A reference is measured for its style only (EDD-23); the person confirmed they may use it
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 }
203
231
  const result = change(state, { ops: [op], author: "code" })
204
232
  if (!result.ok) throw new EngineFailure("input", "refused", result.diagnostics[0].message)
205
233
  return state.log.current.assets.at(-1)
@@ -240,14 +268,17 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
240
268
  },
241
269
 
242
270
  /** The console: words → a proposal, applied to a copy, nothing landing yet (UX_SPEC §4, §5). */
243
- async ask(state, { text, selection, job = 0 }) {
271
+ async ask(state, { text, selection, history = [], job = 0 }) {
244
272
  const chosen = cleanSelection(selection, state.log.current, state.index)
245
- const result = await revise({ ask: this.askFor(state, job), project: state.log.current, index: state.index, text, selection: chosen })
246
- if (!result.ops.length) return { proposal: null, source: result.source, reason: result.reason ?? "Kriya couldn't turn that into an edit. Try saying it another way." }
273
+ const result = await revise({ ask: this.askFor(state, job), project: state.log.current, index: state.index, text, selection: chosen, history })
274
+ // A request about the whole video goes to the Director's make job; the Studio offers it
275
+ const direct = result.direct ? { brief: { ...(result.direct.seconds ? { seconds: result.direct.seconds } : {}), ...(result.direct.captions ? { captions: result.direct.captions } : {}) } } : null
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.") }
247
277
  const id = randomBytes(6).toString("hex")
248
- state.proposals.set(id, { ops: result.ops, head: state.log.head })
249
- const { picture, duration } = solve(result.project, state.index)
250
- return { proposal: { id, ops: result.ops, changes: result.changes, timeline: { picture, duration } }, source: result.source, ...(result.reason ? { reason: result.reason } : {}) }
278
+ state.proposals.set(id, { ops: result.ops, corrections: result.corrections, head: state.log.head })
279
+ const { picture, duration } = solve(result.project ?? state.log.current, state.index)
280
+ // Changes in one list, operations first, then corrections: "Only this" counts across both
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 } : {}) }
251
282
  },
252
283
 
253
284
  /** Accept all, accept some, or reject a proposal. Rebased onto HEAD; the person's own edits never move. */
@@ -257,6 +288,8 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
257
288
  state.proposals.delete(id)
258
289
  if (!accept) return { applied: 0, dropped: [] }
259
290
  const chosen = Array.isArray(only) ? proposal.ops.filter((_, i) => only.includes(i)) : proposal.ops
291
+ const fixes = (proposal.corrections ?? []).filter((_, i) => !Array.isArray(only) || only.includes(proposal.ops.length + i))
292
+ for (const fix of fixes) this.correctWord(state, fix.word, fix.text)
260
293
  const { ops, dropped } = rebase(state.log.current, chosen, state.index)
261
294
  if (ops.length) {
262
295
  const result = change(state, { ops, author: "agent" })
@@ -264,7 +297,50 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
264
297
  // Accepting a proposal is the person's choice
265
298
  taste.note(state.id, ops, state.log.head)
266
299
  }
267
- return { applied: ops.length, dropped: dropped.map((d) => ({ change: describe(d.op, state.index), reason: d.reason })) }
300
+ return { applied: ops.length + fixes.length, dropped: dropped.map((d) => ({ change: describe(d.op, state.index), reason: d.reason })) }
301
+ },
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
+
336
+ /** The person's fix of a misheard word; captions, the transcript and the Director read it from now on. */
337
+ correctWord(state, word, text) {
338
+ const clean = cleanWord(text)
339
+ const asset = typeof word === "string" ? word.split(":w")[0] : ""
340
+ if (!state.index.words.some((w) => w.id === word) || !state.indexDb.correct(asset, word, clean)) throw new EngineFailure("input", "unknown_word", "There's no such word in this project's transcript.")
341
+ state.index = state.indexDb.read()
342
+ state.engine.load(state.log.current, state.index)
343
+ return state.index.words.find((w) => w.id === word)
268
344
  },
269
345
 
270
346
  /** A make job: the reel recipe through the Edit Loop, checked by the gates. */
@@ -277,6 +353,89 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
277
353
  const asset = request.asset ?? video[0]?.id
278
354
  if (!asset || !video.some((a) => a.id === asset)) throw new EngineFailure("input", "no_take", "Add a video first.")
279
355
  if (!state.index.words.some((w) => w.asset === asset)) await this.indexAsset(state, asset, { signal })
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
358
+ const styled = []
359
+ let captionsFromReference = false
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)
369
+ try {
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.`)
372
+ const seconds = (request.brief.targetDuration ?? REEL_TALKING_HEAD.target.default) / FLICKS
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`)
383
+ }
384
+ if (found.captions && !request.brief.captions && !state.engine.motion().missing && claim("captions")) {
385
+ fromRefs.captions = "clean"
386
+ captionsFromReference = true
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` : ""}`)
404
+ }
405
+ } catch (error) {
406
+ if (signal?.aborted) throw error
407
+ styled.push(`${name} couldn't be measured (${error.message}), so its style wasn't used.`)
408
+ }
409
+ }
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
+ }
280
439
  // The song's beats, so the music can be fitted on its downbeats
281
440
  const song = request.brief?.music && state.log.current.assets.find((a) => a.id === request.brief.music && a.kind === "audio")
282
441
  if (song && !state.index.beats?.some((b) => b.asset === song.id)) await this.indexAsset(state, song.id, { signal })
@@ -286,9 +445,18 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
286
445
  // replay uses what the job really used. Captions only where they can render
287
446
  const recorded = replay?.answers.find((a) => a.task === "brief_extra")
288
447
  const extra = recorded ? JSON.parse(recorded.value) : { ...taste.defaults(), ...(picks && { picks }) }
289
- if (extra.captions && (!Object.hasOwn(LOOKS, extra.captions) || !state.engine.motion())) delete extra.captions
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
+ }
290
458
  if (!replay && Object.keys(extra).length) state.journal.answer({ job, task: "brief_extra", source: "person", value: extra })
291
- const usedRules = [...(extra.captions && !request.brief?.captions ? [`Used your rule: ${extra.captions} captions`] : []), ...(extra.zoom && !request.brief?.zoom ? [`Used your rule: ${extra.zoom.toFixed(2)}× zoom`] : [])]
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`] : [])]
292
460
  const stages = ["story", "check", "repair"]
293
461
  const run = runTool
294
462
  const work = join(dirOf(state.id), "cache", "gates")
@@ -329,7 +497,9 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
329
497
  const { ops, dropped } = state.log.head === result.head ? { ops: result.best.ops, dropped: [] } : rebase(state.log.current, result.best.ops, state.index)
330
498
  const landed = change(state, { ops, author: "agent" })
331
499
  if (!landed.ok) throw new EngineFailure("plan", "refused", landed.diagnostics[0].message)
332
- 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})`] : [])]
333
503
  const { version } = await tools()
334
504
  const delivery = result.best.file
335
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 })
@@ -337,6 +507,7 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
337
507
  return {
338
508
  verdict: gates?.verdict ?? "not_checked",
339
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
340
511
  receipt: delivery?.receipt ?? null,
341
512
  report: delivery?.report ?? null,
342
513
  planHash,
@@ -389,7 +560,7 @@ export function createProjects({ home, roots, scheduler, tools, governor = null
389
560
  const { version } = await tools()
390
561
  const mentions = gates.gates.filter((g) => g.status === "not_checked" || (g.status === "failed" && g.severity === "note")).map((g) => g.id)
391
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 })
392
- 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 }
393
564
  },
394
565
 
395
566
  /** `kriya edit replay`: a make job again from its recording; it compares, and lands nothing. */
@@ -4,15 +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"
17
+ import { recogniser } from "../index/layers/words.js"
18
+ import { FORMATS, GRADES } from "../recipes/reel.js"
16
19
 
17
20
  const HEADERS = {
18
21
  "cross-origin-opener-policy": "same-origin",
@@ -90,9 +93,11 @@ async function readJson(req) {
90
93
  }
91
94
  }
92
95
 
93
- function sendFile(req, res, file) {
96
+ function sendFile(req, res, file, { download = false } = {}) {
94
97
  const { size } = statSync(file)
95
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, "_")}"`)
96
101
  const range = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range ?? "")
97
102
  if (req.headers.range && !range) return refuse(res, 416, "Bad range.")
98
103
  if (!range) {
@@ -109,14 +114,14 @@ function sendFile(req, res, file) {
109
114
  createReadStream(file, { start, end }).pipe(res)
110
115
  }
111
116
 
112
- 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
113
118
 
114
119
  /**
115
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
116
121
  */
117
122
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
118
123
 
119
- 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 }) {
120
125
  const tokens = new Map() // sha256 of a launch token → { expires, back }
121
126
  const sessions = new Set()
122
127
  const mediaSecret = randomBytes(32)
@@ -133,6 +138,39 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
133
138
  const NOTICES = { index: "This project's index was damaged and set aside. Index the footage again.", journal: "This project's job record was damaged and set aside. Finished renders will be made again." }
134
139
  const projectView = (state) => ({ project: state.log.current, head: state.log.head, assets: state.log.current.assets.map((asset) => withMedia(state, asset)), ...(state.damaged?.length ? { notices: state.damaged.map((part) => ({ kind: part === "index" ? "reindex" : "rerender", message: NOTICES[part] })) } : {}) })
135
140
 
141
+ // The Media Runtime, installed from the Studio with its progress shown (the same signed
142
+ // manifest and checks as `kriya edit setup`): a first Index no longer looks like nothing happening
143
+ let setup = null
144
+ const runtimeView = () => {
145
+ const runtime = activeRuntime(home)
146
+ return { version: runtime?.version ?? null, speech: recogniser(runtime).missing ?? null, setup }
147
+ }
148
+ function startSetup() {
149
+ if (setup && !setup.finished) return runtimeView()
150
+ setup = { step: null, done: null, total: null, line: "Asking Kriya for the Media Runtime", error: null, finished: false }
151
+ const tell = () => {
152
+ for (const res of sse) res.write(`event: setup\ndata: ${JSON.stringify(setup)}\n\n`)
153
+ }
154
+ let told = 0
155
+ const run = async () => {
156
+ const [{ readDevice }, { fetchManifest }, { install }] = await Promise.all([import("../../store.js"), import("../runtime/fetch.js"), import("../runtime/setup.js")])
157
+ const device = readDevice()
158
+ if (!device) throw new Error("This computer isn't signed in to Kriya. Run kriya login, then try again.")
159
+ const say = (line) => ((setup.line = line), tell())
160
+ const progress = (at) => {
161
+ Object.assign(setup, at)
162
+ if (Date.now() - told > 250 || at.done === at.total) ((told = Date.now()), tell())
163
+ }
164
+ await install(await fetchManifest(device), { home, say, progress })
165
+ }
166
+ onActivity(1)
167
+ run().then(
168
+ () => Object.assign(setup, { finished: true, step: null, line: "The Media Runtime is ready." }),
169
+ (error) => Object.assign(setup, { finished: true, error: error.message }),
170
+ ).finally(() => (tell(), onActivity(-1)))
171
+ return runtimeView()
172
+ }
173
+
136
174
  function fenced(req) {
137
175
  const allowed = [`127.0.0.1:${port()}`, `localhost:${port()}`]
138
176
  if (!allowed.includes(req.headers.host)) return false
@@ -175,7 +213,8 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
175
213
  const file = join(dir, name)
176
214
  if (existsSync(file)) return refuse(res, 409, "A file with that name is already in this project.")
177
215
  await pipeline(req, createWriteStream(file, { flags: "wx" }))
178
- json(res, 200, withMedia(state, await projects.addAsset(state, file)))
216
+ // ?as=reference: the person confirmed in the Studio they may use it as a style reference
217
+ json(res, 200, withMedia(state, await projects.addAsset(state, file, { reference: url.searchParams.get("as") === "reference" })))
179
218
  }
180
219
 
181
220
  function events(res) {
@@ -215,11 +254,31 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
215
254
  const entries = readdirSync(root, { withFileTypes: true })
216
255
  .filter((item) => !item.name.startsWith("."))
217
256
  .map((item) => ({ name: item.name, kind: item.isDirectory() ? "folder" : item.isFile() ? "file" : "other" }))
218
- 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) })
219
276
  }
220
277
 
221
278
  // The person's own screen. Never on the socket, so nothing but a Studio session can
222
279
  // say yes to a rule (ET-TST-01): no tool, no daemon, no job
280
+ if (parts[0] === "runtime" && parts.length === 1 && method === "GET") return say(200, runtimeView())
281
+ if (parts[0] === "runtime" && parts[1] === "setup" && parts.length === 2 && method === "POST") return say(202, startSetup())
223
282
  if (parts[0] === "taste" && parts.length === 1 && method === "GET") return say(200, projects.taste.list())
224
283
  if (parts[0] === "taste" && parts.length === 3 && method === "POST") {
225
284
  const key = decodeURIComponent(parts[1])
@@ -250,6 +309,7 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
250
309
  const state = await needProject(res, parts[1])
251
310
  if (!state) return
252
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) }))
253
313
  if (parts.length === 2 && method === "PATCH") {
254
314
  const { ops, undo } = await readJson(req)
255
315
  if (undo === true) {
@@ -265,6 +325,13 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
265
325
  return say(200, withMedia(state, await projects.addAsset(state, path)))
266
326
  }
267
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
+ }
268
335
  if (parts[2] === "plan" && method === "GET") {
269
336
  const { version } = await tools()
270
337
  // The solver's timeline too: the Studio's monitor and timeline place clips from it
@@ -272,9 +339,11 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
272
339
  return say(200, { ...compile(state.log.current, state.index, { engineVersion: ENGINE_VERSION, runtimeVersion: version }), timeline: { picture, audio, overlays, captions, duration } })
273
340
  }
274
341
  if (parts[2] === "ask" && parts.length === 3 && method === "POST") {
275
- const { text, selection } = await readJson(req)
342
+ const { text, selection, history } = await readJson(req)
276
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.")
277
- 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 }))
278
347
  }
279
348
  if (parts[2] === "proposals" && parts.length === 4 && method === "POST") {
280
349
  const { accept, only } = await readJson(req)
@@ -291,10 +360,43 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
291
360
  if (brief.effort === "fast" || brief.effort === "best") clean.effort = brief.effort
292
361
  if (typeof brief.captions === "string" && Object.hasOwn(LOOKS, brief.captions)) clean.captions = brief.captions
293
362
  if (typeof brief.music === "string" && /^[A-Za-z0-9:_-]{1,64}$/.test(brief.music)) clean.music = brief.music
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) }))
294
380
  }
295
381
  if (asset !== undefined && typeof asset !== "string") return refuse(res, 400, "Name the take.")
296
382
  return say(200, jobs.start(state, { kind: "make", ...(asset ? { asset } : {}), brief: clean }))
297
383
  }
384
+ // The person fixes a word the recogniser misheard (UX_SPEC §5)
385
+ if (parts[2] === "words" && parts.length === 4 && method === "POST") {
386
+ const { text } = await readJson(req)
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.")
388
+ return say(200, { word: projects.correctWord(state, decodeURIComponent(parts[3]), text) })
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])))
298
400
  if (parts[2] === "export" && parts[3] === "handoff" && parts.length === 4 && method === "POST") return say(200, projects.handoff(state))
299
401
  if (parts[2] === "index" && parts.length === 3 && method === "GET") {
300
402
  const { words, sentences, takes, shots } = state.index
@@ -341,7 +443,7 @@ export function createHandler({ home, roots, projects, jobs, tavi, tools, tokenT
341
443
  const url = new URL(req.url, "http://host")
342
444
  try {
343
445
  if (overSocket) {
344
- 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() })
345
447
  if (url.pathname === "/internal/launch" && req.method === "POST") {
346
448
  const token = mintToken((await readJson(req)).back)
347
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));
@@ -69,15 +71,40 @@ export function openIndexDb(file) {
69
71
  })
70
72
  },
71
73
 
74
+ /**
75
+ * The person's fix of a misheard word. Kept by word id beside the recogniser's rows,
76
+ * which a re-index replaces; the word's original text is kept too, so a re-index
77
+ * that moves the words never lands a fix on a different word.
78
+ * Text equal to the recogniser's, or empty, removes the fix.
79
+ */
80
+ correct(asset, word, text) {
81
+ const media = mediaOf(asset)
82
+ const n = Number(word.slice(`${asset}:w`.length))
83
+ const row = media && word.startsWith(`${asset}:w`) && Number.isInteger(n) ? db.prepare("select text from words where media = ? and n = ?").get(media, n) : null
84
+ if (!row) return false
85
+ tx(() => {
86
+ db.prepare("delete from corrections where asset = ? and word = ?").run(asset, word)
87
+ if (text && text !== row.text) db.prepare("insert into corrections (asset, word, text, at) values (?, ?, ?, ?)").run(asset, word, JSON.stringify({ text, was: row.text }), new Date().toISOString())
88
+ })
89
+ return true
90
+ },
91
+
72
92
  /** Rows for Edit Core and the views, for these assets (DATA_MODEL §3.1 shapes, ids per asset). */
73
93
  read(assets = db.prepare("select asset from assets order by asset").all().map((row) => row.asset)) {
74
94
  const raw = { words: [], sentences: [], takes: [], shots: [], faces: [], silences: [], beats: [], bars: [], timestamps: {}, subjects: {} }
75
95
  for (const asset of assets) {
76
96
  const media = mediaOf(asset)
77
97
  if (!media) continue
98
+ const fixes = new Map(db.prepare("select word, text from corrections where asset = ?").all(asset).map((c) => [c.word, JSON.parse(c.text)]))
78
99
  for (const w of db.prepare('select * from words where media = ? order by n').all(media)) {
79
- raw.words.push({ id: `${asset}:w${w.n}`, asset, start: w.start, end: w.end, text: w.text, conf: w.conf, flags: flagList(w.flags) })
100
+ const id = `${asset}:w${w.n}`
101
+ const fix = fixes.get(id)
102
+ const fixed = fix && fix.was === w.text
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 } : {}) })
80
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")))
81
108
  for (const s of db.prepare('select * from sentences where media = ? order by n').all(media)) {
82
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 })
83
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 = {}